diff --git a/CMakeLists.txt b/CMakeLists.txt index 4b12b760f..99ffba8a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,8 +31,8 @@ project(cegui) ################################################################################ # Set up version information ################################################################################ -set( CEGUI_VERSION_MAJOR 0) -set( CEGUI_VERSION_MINOR 9999) +set( CEGUI_VERSION_MAJOR 9999) +set( CEGUI_VERSION_MINOR 0) set( CEGUI_VERSION_PATCH 0) set( CEGUI_VERSION ${CEGUI_VERSION_MAJOR}.${CEGUI_VERSION_MINOR}.${CEGUI_VERSION_PATCH} ) @@ -70,26 +70,32 @@ if ((WIN32 OR APPLE) AND NOT CMAKE_PREFIX_PATH) set (CMAKE_FIND_FRAMEWORK LAST) endif() +if(ANDROID) + set(CMAKE_FIND_ROOT_PATH ${CEGUI_DEPENDENCIES_DIR} "${CMAKE_FIND_ROOT_PATH}") + set (CMAKE_LIBRARY_ARCHITECTURE ${ANDROID_ABI}) +endif() + # Look for packages find_package(PCRE) find_package(Freetype) find_package(Minizip) find_package(Fribidi) -if (NOT WIN32) +if (NOT WIN32 AND NOT ANDROID) find_package(Iconv REQUIRED) endif() find_package(OpenGL) find_package(GLEW) -find_package(GLM) +find_package(GLM REQUIRED) find_package(GLFW) find_package(DirectXSDK) -find_package(D3DX11Effects) find_package(Irrlicht) find_package(Ogre) find_package(OIS) find_package(DirectFB) find_package(OpenGLES) +find_package(OpenGLES2) +find_package(OpenGLES3) find_package(EXPAT) find_package(XercesC) @@ -126,33 +132,29 @@ be mindful of which C/C++ runtime setting has been used to compile the various components - they must all match or you will get crashes, heap corruption and/or other issues." FALSE "WIN32 OR APPLE" FALSE) option( CEGUI_BUILD_STATIC_CONFIGURATION "Specifies whether the static configs will be built. (NB: Shared configs are always built)" FALSE) +option( CEGUI_BUILD_DYNAMIC_CONFIGURATION "Dynamic libs to be built. Always true except for Android" TRUE) option( CEGUI_BUILD_STATIC_FACTORY_MODULE "For static CEGUI builds, specifies whether to include the getWindoFactoryModule method. When false, the developer must provide a custom implementation of the method" FALSE) # sanity check on static build option for factory method if (CEGUI_BUILD_STATIC_FACTORY_MODULE AND NOT CEGUI_BUILD_STATIC_CONFIGURATION) - message(SEND_ERROR "You may not enable CEGUI_BUILD_STATIC_FACTORY_MODULE without CEGUI_BUILD_STATIC_CONFIGURATION enabled. CEGUI needs to be built statically if building the static factory method.") + message(SEND_ERROR "You may not enable CEGUI_BUILD_STATIC_FACTORY_MODULE without CEGUI_BUILD_STATIC_CONFIGURATION enabled. CEGUI needs to be built statically if building the static factory method.") +endif() +if (NOT CEGUI_BUILD_DYNAMIC_CONFIGURATION AND NOT ANDROID) + message(SEND_ERROR "You may not disable CEGUI_BUILD_DYNAMIC_CONFIGURATION in any scenario except android builds.") endif() -option( CEGUI_CUSTOM_ALLOCATORS "If checked, CEGUI can use custom allocation. (for experienced developers only!)" FALSE ) -cmake_dependent_option( CEGUI_CUSTOM_ALLOCATORS_DEBUG "If checked, CEGUI allocations will pass debug info to allocators. (only used if CEGUI_CUSTOM_ALLOCATORS is checked)" FALSE "CEGUI_CUSTOM_ALLOCATORS" FALSE ) -set( CEGUI_CUSTOM_ALLOCATORS_INCLUDE "CEGUI/MemoryStdAllocator.h" CACHE STRING "Which include file contains memory allocators and allocation configuration. (only used if CEGUI_CUSTOM_ALLOCATORS is checked) -We have bundled 2 allocators, mostly for demonstrational purposes. -CEGUI/MemoryStdAllocator.h contains malloc allocator, use it as a starting point for your own allocators -CEGUI/MemoryOgreAllocator.h delegates allocation to Ogre, which may be useful to Ogre users (you will have to manually change linking options of CEGUIBase!)" ) set( CEGUI_STRING_CLASS 1 CACHE INT "Which string class should CEGUI use 1 - utf8 and utf32 aware inbuilt string, -2 - std::string without custom allocation, -3 - std::basic_string allocated according to allocator config" ) +2 - regular std::string" +) -# sanity check std::basic_string and allocator and allocators actually being used -if (${CEGUI_STRING_CLASS} MATCHES 3 AND NOT CEGUI_CUSTOM_ALLOCATORS) - message(SEND_ERROR "You requested std::basic_string allocated according to allocator as CEGUI::String even though CEGUI is not being built with custom allocators enabled!") -endif() option( CEGUI_HAS_FREETYPE "Specifies whether to include Freetype font support" ${FREETYPE_FOUND} ) option( CEGUI_HAS_PCRE_REGEX "Specifies whether to include PCRE regexp matching for editbox string validation" ${PCRE_FOUND} ) option( CEGUI_HAS_MINIZIP_RESOURCE_PROVIDER "Specifies whether to build the minizip based resource provider" ${MINIZIP_FOUND} ) option( CEGUI_HAS_DEFAULT_LOGGER "Specifies whether to build the DefaultLogger implementation" TRUE) +option( CEGUI_BUILD_COMMON_DIALOGS "Specifies whether to build the CommonDialogs library, which contains the code for the ColourPicker and other dialogs" TRUE) + option( CEGUI_BUILD_XMLPARSER_EXPAT "Specifies whether to build the Expat based XMLParser module" ${EXPAT_FOUND} ) option( CEGUI_BUILD_XMLPARSER_XERCES "Specifies whether to build the Xerces-C++ based XMLParser module" ${XERCESC_FOUND} ) option( CEGUI_BUILD_XMLPARSER_LIBXML2 "Specifies whether to build the libxml2 based XMLParser module" ${LIBXML2_FOUND} ) @@ -167,16 +169,16 @@ option( CEGUI_BUILD_IMAGECODEC_STB "Specifies whether to build the STB based Ima option( CEGUI_BUILD_IMAGECODEC_TGA "Specifies whether to build the based TGA only ImageCodec module" FALSE ) option( CEGUI_BUILD_IMAGECODEC_PVR "Specifies whether to build the PVR only ImageCodec module" ${PVRTOOLS_FOUND} ) -cegui_dependent_option( CEGUI_BUILD_RENDERER_OPENGL "Specifies whether to build the OpenGL renderer module" "OPENGL_FOUND;GLM_FOUND;GLEW_FOUND" ) -cegui_dependent_option( CEGUI_BUILD_RENDERER_OPENGL3 "Specifies whether to build the OpenGL 3+ (core profile) renderer module" "OPENGL_FOUND;GLM_FOUND;GLEW_FOUND") +cegui_dependent_option( CEGUI_BUILD_RENDERER_OPENGL "Specifies whether to build the OpenGL renderer module" "OPENGL_FOUND;GLEW_FOUND" ) +cegui_dependent_option( CEGUI_BUILD_RENDERER_OPENGL3 "Specifies whether to build the OpenGL 3+ (core profile) renderer module" "OPENGL_FOUND;GLEW_FOUND") option( CEGUI_BUILD_RENDERER_OGRE "Specifies whether to build the Ogre renderer module" ${OGRE_FOUND} ) option( CEGUI_BUILD_RENDERER_IRRLICHT "Specifies whether to build the Irrlicht renderer module" ${IRRLICHT_FOUND} ) option( CEGUI_BUILD_RENDERER_DIRECTFB "Specifies whether to build the DirectFB renderer module (not supported!)" FALSE ) -cegui_dependent_option( CEGUI_BUILD_RENDERER_DIRECT3D9 "Specifies whether to build the Direct3D 9 renderer module" "DIRECTXSDK_FOUND;NOT DIRECTXSDK_MAX_D3D LESS 9" ) -cegui_dependent_option( CEGUI_BUILD_RENDERER_DIRECT3D10 "Specifies whether to build the Direct3D 10 renderer module" "DIRECTXSDK_FOUND;NOT DIRECTXSDK_MAX_D3D LESS 10" ) -cegui_dependent_option( CEGUI_BUILD_RENDERER_DIRECT3D11 "Specifies whether to build the Direct3D 11 renderer module" "DIRECTXSDK_FOUND;D3DX11EFFECTS_FOUND;NOT DIRECTXSDK_MAX_D3D LESS 11" ) +cegui_dependent_option( CEGUI_BUILD_RENDERER_DIRECT3D11 "Specifies whether to build the Direct3D 11 renderer module" "DIRECTXSDK_FOUND;NOT DIRECTXSDK_MAX_D3D LESS 11" ) option( CEGUI_BUILD_RENDERER_NULL "Specifies whether to build the null renderer module" FALSE ) option( CEGUI_BUILD_RENDERER_OPENGLES "Specifies whether to build the OpenGLES renderer module" ${OPENGLES_FOUND} ) +option( CEGUI_BUILD_RENDERER_OPENGLES2 "Specifies whether to build the OpenGLES2 renderer module" ${OPENGLES2_FOUND}) +option( CEGUI_BUILD_RENDERER_OPENGLES2_WITH_GLES3_SUPPORT "Build the OpenGLES2 renderer module with GLES3 features" ${OPENGLES3_FOUND}) cegui_dependent_option( CEGUI_BUILD_LUA_MODULE "Specifies whether to build the Lua based script module" "LUA51_FOUND;TOLUAPP_FOUND" ) cegui_dependent_option( CEGUI_BUILD_LUA_GENERATOR "Specifies whether to build the custom tolua binding generator 'toluappcegui'" "LUA51_FOUND;TOLUAPP_FOUND" ) @@ -216,19 +218,23 @@ else() endif() set (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE ${CEGUI_BUILD_RENDERER_OGRE}) set (CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE ${CEGUI_BUILD_RENDERER_IRRLICHT}) -set (CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE ${CEGUI_BUILD_RENDERER_DIRECT3D9}) -set (CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE ${CEGUI_BUILD_RENDERER_DIRECT3D10}) set (CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE ${CEGUI_BUILD_RENDERER_DIRECT3D11}) set (CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE ${CEGUI_BUILD_RENDERER_DIRECTFB}) +set (CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE ${CEGUI_BUILD_RENDERER_OPENGLES2}) + +#Only build the opengles2 sample renderer for Android +if (NOT ANDROID) + set (CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE FALSE) +endif() -# Ogre and OpenGL have dependencies for the sample browser, if these are not available then the SampleBrowser won't support the respective Renderers and the option to choose them won't show up +# Ogre and OpenGL have dependencies for the sample browser, if these are not available then the samples will be OFF by default if (CEGUI_BUILD_RENDERER_OGRE AND NOT CEGUI_OGRE_DEPS_AVAILABLE) + set (_CEGUI_SAMPLES_ENABLED_DEFAULT FALSE) if (NOT OIS_FOUND) - message(STATUS "Info: The OgreRenderer is disabled in the SampleBrowser because of missing dependencies (OIS not found). Please add the dependencies and run 'Configure' in CMake again, in case you want to run the SampleBrowser using OgreRenderer.") + message(STATUS "The SampleFramework is deactivated due to missing Ogre dependencies (OIS not found)") else() - message(STATUS "Info: The OgreRenderer is disabled in the SampleBrowser because of missing dependencies (boost libraries). Please add the dependencies and run 'Configure' in CMake again, in case you want to run the SampleBrowser using OgreRenderer.") + message(STATUS "The SampleFramework is deactivated due to missing Ogre dependencies (boost libraries)") endif() - set (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE FALSE) endif() if (CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE) @@ -239,7 +245,7 @@ if (CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE) endif() # If we use a Renderer then our samples should be ON by default -if (CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE OR CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE OR CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE) +if (CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE OR CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE OR CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE OR CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE) set (_CEGUI_SAMPLES_ENABLED_DEFAULT TRUE) else() set (_CEGUI_SAMPLES_ENABLED_DEFAULT FALSE) @@ -252,6 +258,16 @@ if (UNIX AND NOT APPLE AND NOT WIN32) option( CEGUI_SAMPLES_USE_GTK2 "Specifies whether the sample applications will make use of the GTK2 UI for renderer selection." FALSE ) endif() +if (ANDROID) + set(CEGUI_BUILD_STATIC_CONFIGURATION TRUE CACHE BOOL "Forcing static build for Android" FORCE) + set(CEGUI_BUILD_STATIC_FACTORY_MODULE TRUE CACHE BOOL "Forcing static factory module for Android" FORCE) + set(CEGUI_BUILD_DYNAMIC_CONFIGURATION FALSE CACHE BOOL "Disable dynamic build for Android" FORCE) + set(CEGUI_BUILD_RENDERER_OPENGLES FALSE CACHE BOOL "Disable OpenGL ES 1 RenderSystem for Android" FORCE) + if (CEGUI_BUILD_RENDERER_OPENGLES2 AND CEGUI_BUILD_RENDERER_OGRE) + message(SEND_ERROR "Either OpenGLES2 Renderer or Ogre Renderer can be built for android at once. Please disable one of the renderers.") + endif() +endif() + if (WIN32 OR APPLE) set (CEGUI_BUILD_SUFFIX "_d" CACHE STRING "String holding a suffix appended to the name of output binaries (under CMake build, only used for debug).") else() @@ -298,11 +314,10 @@ cegui_set_library_name( CEGUI_OPENGL_RENDERER_LIBNAME CEGUIOpenGLRenderer ) cegui_set_library_name( CEGUI_OPENGL3_RENDERER_LIBNAME CEGUIOpenGL3Renderer ) cegui_set_library_name( CEGUI_OGRE_RENDERER_LIBNAME CEGUIOgreRenderer) cegui_set_library_name( CEGUI_IRRLICHT_RENDERER_LIBNAME CEGUIIrrlichtRenderer ) -cegui_set_library_name( CEGUI_DIRECT3D9_RENDERER_LIBNAME CEGUIDirect3D9Renderer ) -cegui_set_library_name( CEGUI_DIRECT3D10_RENDERER_LIBNAME CEGUIDirect3D10Renderer ) cegui_set_library_name( CEGUI_DIRECT3D11_RENDERER_LIBNAME CEGUIDirect3D11Renderer ) cegui_set_library_name( CEGUI_NULL_RENDERER_LIBNAME CEGUINullRenderer ) cegui_set_library_name( CEGUI_OPENGLES_RENDERER_LIBNAME CEGUIOpenGLESRenderer ) +cegui_set_library_name( CEGUI_OPENGLES2_RENDERER_LIBNAME CEGUIOpenGLES2Renderer ) cegui_set_library_name( CEGUI_DIRECTFB_RENDERER_LIBNAME CEGUIDirectFBRenderer ) # XML parser module names @@ -334,7 +349,7 @@ set( CEGUI_PYCEGUI_OGRE_RENDERER_LIBNAME PyCEGUIOgreRenderer ) set( CEGUI_PYCEGUI_NULL_RENDERER_LIBNAME PyCEGUINullRenderer ) # SampleFramework executable related names -cegui_set_executable_name( CEGUI_SAMPLEFRAMEWORK_EXENAME CEGUISampleFramework ) +cegui_set_executable_name( CEGUI_SAMPLEFRAMEWORK_EXENAME CEGUISampleBrowser ) # Additional lib names cegui_set_library_name( CEGUI_COMMON_DIALOGS_LIBNAME CEGUICommonDialogs ) @@ -430,6 +445,12 @@ include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/cegui/include ) +################################################################################ +# Add GLM header locations (global dependency, required) +################################################################################ +include_directories( + ${GLM_H_PATH} +) ################################################################################ # Adjust configuration based on option settings @@ -539,10 +560,11 @@ add_subdirectory(cegui/src/ImageCodecModules) add_subdirectory(cegui/src/WindowRendererSets) add_subdirectory(cegui/src/ScriptModules) -add_subdirectory(cegui/src/CommonDialogs) +if(CEGUI_BUILD_COMMON_DIALOGS) + add_subdirectory(cegui/src/CommonDialogs) +endif() if (CEGUI_SAMPLES_ENABLED) - add_subdirectory(samples_framework) add_subdirectory(samples) endif() diff --git a/README.md b/README.md index a628d17cf..b841afe5f 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ If you have no installed system-wide, it's a bit more involved and complicated. ```bash cd $cegui_folder cd build/bin/ -CEGUI_SAMPLE_DATAPATH=../../datafiles ./CEGUISampleFramework-0 ../datafiles/samples/samples.xml +CEGUI_SAMPLE_DATAPATH=../../datafiles ./CEGUISampleFramework-0 ``` ## We want to clarify some common misconceptions about CEGUI: diff --git a/cegui/include/CEGUI/Affector.h b/cegui/include/CEGUI/Affector.h index b9ee474ba..32b82948a 100644 --- a/cegui/include/CEGUI/Affector.h +++ b/cegui/include/CEGUI/Affector.h @@ -52,7 +52,7 @@ namespace CEGUI \todo moveKeyFrame, this will be vital for any animation editing tools */ -class CEGUIEXPORT Affector : public AllocatedObject +class CEGUIEXPORT Affector { public: //! enumerates the possible methods of application @@ -257,8 +257,7 @@ class CEGUIEXPORT Affector : public AllocatedObject //! curently used interpolator (has to be set for the Affector to work!) Interpolator* d_interpolator; - typedef std::map - CEGUI_MAP_ALLOC(float, KeyFrame*)> KeyFrameMap; + typedef std::map > KeyFrameMap; /** keyframes of this affector (if there are no keyframes, this affector * won't do anything!) */ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D9/ViewportTarget.h b/cegui/include/CEGUI/AndroidUtils.h similarity index 56% rename from cegui/include/CEGUI/RendererModules/Direct3D9/ViewportTarget.h rename to cegui/include/CEGUI/AndroidUtils.h index 8a03da1ed..a0ac4e261 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D9/ViewportTarget.h +++ b/cegui/include/CEGUI/AndroidUtils.h @@ -1,6 +1,8 @@ /*********************************************************************** - created: Fri Feb 13 2009 - author: Paul D Turner + created: 25/9/2014 + author: David Reepmeyer + + purpose: holds the global android_app instance of an android app *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team @@ -24,45 +26,64 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIDirect3D9ViewportTarget_h_ -#define _CEGUIDirect3D9ViewportTarget_h_ +#ifndef _AndroidUtils_h_ +#define _AndroidUtils_h_ + +#ifndef __ANDROID__ +# error "do not include AndroidUtils.h unless compiling for android" +#endif + +#include +#include -#include "CEGUI/RendererModules/Direct3D9/RenderTarget.h" -#include "../../Rect.h" -// Start of CEGUI namespace section +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + namespace CEGUI { +//----------------------------------------------------------------------------// + /*! \brief - Direct3D9 RenderTarget that represents a screen viewport. + All android applictions starts up with a global struct type + of android_app that is passed in to the main method. this + is needed in various andriod functionality by CEGUI */ -class DIRECT3D9_GUIRENDERER_API Direct3D9ViewportTarget : - public Direct3D9RenderTarget<> +class AndroidUtils { public: /*! \brief - Construct a default Direct3D9ViewportTarget that uses the current - Direct3D9 viewport as it's initial area. + Returns the android app struct + + \return + android app struct */ - Direct3D9ViewportTarget(Direct3D9Renderer& owner); + static android_app* getAndroidApp(); /*! \brief - Construct a Direct3D9ViewportTarget that uses the specified Rect as it's - initial area. + sets the global android app struct. this should + be called once and used via CEGUI throughout + the lifetime of the app - \param area - Rect object describing the initial viewport area that should be used for - the RenderTarget. + \param androidapp + global android app struct */ - Direct3D9ViewportTarget(Direct3D9Renderer& owner, const Rectf& area); - - // implementations of RenderTarget interface - bool isImageryCache() const; + static void setAndroidApp(android_app* androidapp); +private: + static struct android_app* app; }; -} // End of CEGUI namespace section +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif + -#endif // end of guard _CEGUIDirect3D9ViewportTarget_h_ diff --git a/cegui/include/CEGUI/Animation.h b/cegui/include/CEGUI/Animation.h index 35d9312cb..d1f770625 100644 --- a/cegui/include/CEGUI/Animation.h +++ b/cegui/include/CEGUI/Animation.h @@ -61,7 +61,7 @@ namespace CEGUI \see AnimationInstance, Affector */ -class CEGUIEXPORT Animation : public AllocatedObject +class CEGUIEXPORT Animation { public: //! enumerates possible replay modes @@ -283,13 +283,11 @@ class CEGUIEXPORT Animation : public AllocatedObject */ bool d_autoStart; - typedef std::vector AffectorList; + typedef std::vector AffectorList; //! list of affectors defined in this animation AffectorList d_affectors; - typedef std::multimap - CEGUI_MAP_ALLOC(String, String)> SubscriptionMap; + typedef std::multimap > SubscriptionMap; /** holds pairs of 2 strings, the left string is the Event that we will * subscribe to, the right string is the action that will be invoked to the * instance if the event is fired on target window diff --git a/cegui/include/CEGUI/AnimationInstance.h b/cegui/include/CEGUI/AnimationInstance.h index 3beae82b3..e36ac914f 100644 --- a/cegui/include/CEGUI/AnimationInstance.h +++ b/cegui/include/CEGUI/AnimationInstance.h @@ -70,8 +70,7 @@ class CEGUIEXPORT AnimationEventArgs : public EventArgs \see Animation */ -class CEGUIEXPORT AnimationInstance : - public AllocatedObject +class CEGUIEXPORT AnimationInstance { public: //! Namespace for animation instance events @@ -435,15 +434,13 @@ class CEGUIEXPORT AnimationInstance : //! true if auto stepping is enabled bool d_autoSteppingEnabled; - typedef std::map - CEGUI_MAP_ALLOC(String, String)> PropertyValueMap; + typedef std::map > PropertyValueMap; /** cached saved values, used for relative application method * and keyframe property source, see Affector and KeyFrame classes */ PropertyValueMap d_savedPropertyValues; - typedef std::vector ConnectionTracker; + typedef std::vector ConnectionTracker; //! tracks auto event connections we make. ConnectionTracker d_autoConnections; }; diff --git a/cegui/include/CEGUI/AnimationManager.h b/cegui/include/CEGUI/AnimationManager.h index efc8fd375..1f730cbee 100644 --- a/cegui/include/CEGUI/AnimationManager.h +++ b/cegui/include/CEGUI/AnimationManager.h @@ -44,8 +44,7 @@ namespace CEGUI { class CEGUIEXPORT AnimationManager : - public Singleton, - public AllocatedObject + public Singleton { public: //! Name of the schema used for loading animation xml files. @@ -300,14 +299,12 @@ class CEGUIEXPORT AnimationManager : } private: - typedef std::map - CEGUI_MAP_ALLOC(String, Interpolator*)> InterpolatorMap; + typedef std::map > InterpolatorMap; String generateUniqueAnimationName(); //! stores available interpolators InterpolatorMap d_interpolators; - typedef std::vector BasicInterpolatorList; + typedef std::vector BasicInterpolatorList; //! stores interpolators that are inbuilt in CEGUI BasicInterpolatorList d_basicInterpolators; @@ -315,8 +312,7 @@ class CEGUIEXPORT AnimationManager : //! all defined animations AnimationMap d_animations; - typedef std::multimap - CEGUI_MULTIMAP_ALLOC(Animation*, AnimationInstance*)> AnimationInstanceMap; + typedef std::multimap > AnimationInstanceMap; //! all instances of animations AnimationInstanceMap d_animationInstances; //! Default resource group used when loading animation xml files. diff --git a/cegui/include/CEGUI/Base.h b/cegui/include/CEGUI/Base.h index 43dfaf44c..df87c6212 100644 --- a/cegui/include/CEGUI/Base.h +++ b/cegui/include/CEGUI/Base.h @@ -189,6 +189,5 @@ typedef std::ostream OutStream; //!< Output stream class. Bring in forward references to all GUI base system classes *************************************************************************/ #include "CEGUI/ForwardRefs.h" -#include "CEGUI/MemoryAllocation.h" #endif // end of guard _CEGUIBase_h_ diff --git a/cegui/include/CEGUI/BasicImage.h b/cegui/include/CEGUI/BasicImage.h deleted file mode 100644 index d95f8f241..000000000 --- a/cegui/include/CEGUI/BasicImage.h +++ /dev/null @@ -1,106 +0,0 @@ -/*********************************************************************** - created: Wed Feb 16 2011 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIBasicImage_h_ -#define _CEGUIBasicImage_h_ - -#include "CEGUI/Image.h" -#include "CEGUI/String.h" -#include "CEGUI/Rect.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -class CEGUIEXPORT BasicImage : public Image -{ -public: - BasicImage(const String& name); - BasicImage(const XMLAttributes& attributes); - - BasicImage(const String& name, Texture* texture, - const Rectf& tex_area, const Vector2f& offset, - const AutoScaledMode autoscaled, const Sizef& native_res); - - void setTexture(Texture* texture); - void setArea(const Rectf& pixel_area); - void setOffset(const Vector2f& pixel_offset); - void setAutoScaled(const AutoScaledMode autoscaled); - void setNativeResolution(const Sizef& native_res); - - // Implement CEGUI::Image interface - const String& getName() const; - const Sizef& getRenderedSize() const; - const Vector2f& getRenderedOffset() const; - void render(GeometryBuffer& buffer, - const Rectf& dest_area, - const Rectf* clip_area, - const ColourRect& colours) const; - - //! Notifies the class that the display size of the renderer has changed so that - // the window can adapt to the new display size accordingly - void notifyDisplaySizeChanged(const Sizef& renderer_display_size); - -protected: - //! Updates the scaled size and offset values according to the new display size of the renderer - void updateScaledSizeAndOffset(const Sizef& renderer_display_size); - //! Updates only the scaled size values according to the new display size of the renderer - void updateScaledSize(const Sizef& renderer_display_size); - //! Updates only the scaled offset values according to the new display size of the renderer - void updateScaledOffset(const Sizef& renderer_display_size); - - //! name used when the BasicImage was created. - String d_name; - //! Texture used by this image. - Texture* d_texture; - //! Actual pixel size. - Sizef d_pixelSize; - //! Rect defining texture co-ords for this image. - Rectf d_area; - //! Defined pixel offset - Vector2f d_pixelOffset; - //! Whether image is auto-scaled or not and how. - AutoScaledMode d_autoScaled; - //! Native resolution used for autoscaling. - Sizef d_nativeResolution; - //! Size after having autoscaling applied. - Sizef d_scaledSize; - //! Offset after having autoscaling applied. - Vector2f d_scaledOffset; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIBasicImage_h_ - diff --git a/cegui/include/CEGUI/BidiVisualMapping.h b/cegui/include/CEGUI/BidiVisualMapping.h index 78723b99c..331b61130 100644 --- a/cegui/include/CEGUI/BidiVisualMapping.h +++ b/cegui/include/CEGUI/BidiVisualMapping.h @@ -47,13 +47,11 @@ enum BidiCharType }; //! Abstract class to wrap a Bidi visual mapping of a text string. -class CEGUIEXPORT BidiVisualMapping : - public AllocatedObject +class CEGUIEXPORT BidiVisualMapping { public: //! type definition for collection used to hold mapping index lists. - typedef std::vector StrIndexList; + typedef std::vector StrIndexList; //! Destructor. virtual ~BidiVisualMapping(); diff --git a/cegui/include/CEGUI/RendererModules/Direct3D10/ViewportTarget.h b/cegui/include/CEGUI/BitmapImage.h similarity index 55% rename from cegui/include/CEGUI/RendererModules/Direct3D10/ViewportTarget.h rename to cegui/include/CEGUI/BitmapImage.h index 479d1be9c..7c1361f41 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D10/ViewportTarget.h +++ b/cegui/include/CEGUI/BitmapImage.h @@ -1,6 +1,6 @@ /*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) + created: Wed Feb 16 2011 + author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team @@ -24,41 +24,63 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIDirect3D10ViewportTarget_h_ -#define _CEGUIDirect3D10ViewportTarget_h_ +#ifndef _CEGUIBitmapImage_h_ +#define _CEGUIBitmapImage_h_ -#include "CEGUI/RendererModules/Direct3D10/RenderTarget.h" +#include "CEGUI/Image.h" +#include "CEGUI/String.h" +#include "CEGUI/Rect.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif // Start of CEGUI namespace section namespace CEGUI { -//! Direct3D10 based RenderTarget that represents the screen or a portion of it. -class D3D10_GUIRENDERER_API Direct3D10ViewportTarget : public Direct3D10RenderTarget<> +class CEGUIEXPORT BitmapImage : public Image { public: + BitmapImage(const String& name); + BitmapImage(const XMLAttributes& attributes); + + BitmapImage(const String& name, Texture* texture, + const Rectf& tex_area, const glm::vec2& offset, + const AutoScaledMode autoscaled, const Sizef& native_res); + + // Implement CEGUI::Image interface + void render(std::vector& geometry_buffers, + const ImageRenderSettings& render_settings) const; + /*! \brief - Construct a default Direct3D10ViewportTarget that uses the current - Direct3D10 viewport as it's initial area. + Sets the Texture object of this Image. + + \param texture + The pointer to the Texture of this Image. */ - Direct3D10ViewportTarget(Direct3D10Renderer& owner); + void setTexture(Texture* texture); /*! \brief - Construct a Direct3D10ViewportTarget that uses the specified Rect as - it's initial area. + Returns the pointer to the Texture object used by this image. - \param area - Rect object describing the initial viewport area that should be used for - the RenderTarget. + \return + The pointer to the Texture object used by this image. */ - Direct3D10ViewportTarget(Direct3D10Renderer& owner, const Rectf& area); + const Texture* getTexture() const; - // implementations of RenderTarget interface - bool isImageryCache() const; +protected: + //! Texture used by this image. + Texture* d_texture; }; - } // End of CEGUI namespace section -#endif // end of guard _CEGUIDirect3D10ViewportTarget_h_ +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIBitmapImage_h_ + diff --git a/cegui/include/CEGUI/BoundSlot.h b/cegui/include/CEGUI/BoundSlot.h index 2f47bca25..4dd8505ff 100644 --- a/cegui/include/CEGUI/BoundSlot.h +++ b/cegui/include/CEGUI/BoundSlot.h @@ -41,8 +41,7 @@ namespace CEGUI reference counted pointer. When a BoundSlot is deleted, the connection is unsubscribed and the SubscriberSlot is deleted. */ -class CEGUIEXPORT BoundSlot : - public AllocatedObject +class CEGUIEXPORT BoundSlot { public: typedef unsigned int Group; diff --git a/cegui/include/CEGUI/CEGUI.h b/cegui/include/CEGUI/CEGUI.h index 20cef87e4..b36ccdb2c 100644 --- a/cegui/include/CEGUI/CEGUI.h +++ b/cegui/include/CEGUI/CEGUI.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 21/2/2004 author: Paul D Turner - + purpose: Main system include for client code *************************************************************************/ /*************************************************************************** @@ -34,7 +34,7 @@ #include "CEGUI/Animation.h" #include "CEGUI/AnimationInstance.h" #include "CEGUI/AnimationManager.h" -#include "CEGUI/BasicImage.h" +#include "CEGUI/BitmapImage.h" #include "CEGUI/BasicRenderedStringParser.h" #include "CEGUI/BidiVisualMapping.h" #include "CEGUI/BoundSlot.h" @@ -66,13 +66,16 @@ #include "CEGUI/ImageCodec.h" #include "CEGUI/ImageManager.h" #include "CEGUI/InputEvent.h" +#include "CEGUI/InputEvents.h" +#include "CEGUI/InputEventReceiver.h" +#include "CEGUI/InputAggregator.h" #include "CEGUI/Interpolator.h" #include "CEGUI/JustifiedRenderedString.h" #include "CEGUI/KeyFrame.h" #include "CEGUI/LeftAlignedRenderedString.h" #include "CEGUI/LinkedEvent.h" #include "CEGUI/Logger.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/NamedElement.h" #include "CEGUI/Property.h" #include "CEGUI/PropertyHelper.h" @@ -98,12 +101,12 @@ #include "CEGUI/Scheme.h" #include "CEGUI/SchemeManager.h" #include "CEGUI/ScriptModule.h" +#include "CEGUI/SemanticInputEvent.h" #include "CEGUI/SimpleTimer.h" #include "CEGUI/Size.h" #include "CEGUI/String.h" #include "CEGUI/StringTranscoder.h" #include "CEGUI/System.h" -#include "CEGUI/SystemKeys.h" #include "CEGUI/Texture.h" #include "CEGUI/TextureTarget.h" #include "CEGUI/TextUtils.h" @@ -125,6 +128,9 @@ #include "CEGUI/XMLParser.h" #include "CEGUI/XMLSerializer.h" +// Model-view +#include "CEGUI/views/All.h" + // Falagard core system include #include "CEGUI/falagard/WidgetLookManager.h" diff --git a/cegui/include/CEGUI/CentredRenderedString.h b/cegui/include/CEGUI/CentredRenderedString.h index 2dade974f..0ebf14026 100644 --- a/cegui/include/CEGUI/CentredRenderedString.h +++ b/cegui/include/CEGUI/CentredRenderedString.h @@ -51,16 +51,15 @@ class CEGUIEXPORT CentredRenderedString : public FormattedRenderedString // implementation of base interface void format(const Window* ref_wnd, const Sizef& area_size); - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const; size_t getFormattedLineCount() const; float getHorizontalExtent(const Window* ref_wnd) const; float getVerticalExtent(const Window* ref_wnd) const; protected: - std::vector d_offsets; + std::vector d_offsets; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/ChainedXMLHandler.h b/cegui/include/CEGUI/ChainedXMLHandler.h index ff815a58f..0a145b6d3 100644 --- a/cegui/include/CEGUI/ChainedXMLHandler.h +++ b/cegui/include/CEGUI/ChainedXMLHandler.h @@ -63,7 +63,7 @@ class CEGUIEXPORT ChainedXMLHandler : public XMLHandler //! is the chained handler completed. bool d_completed; //! should the chained handler be deleted by us? - bool d_deleteChaniedHandler; + bool d_deleteChainedHandler; }; diff --git a/cegui/include/CEGUI/Clipboard.h b/cegui/include/CEGUI/Clipboard.h index dff38cb41..3533d1d7e 100644 --- a/cegui/include/CEGUI/Clipboard.h +++ b/cegui/include/CEGUI/Clipboard.h @@ -44,8 +44,7 @@ namespace CEGUI \brief Lightweight interface providing access to the system-wide native clipboard */ -class CEGUIEXPORT NativeClipboardProvider : - public AllocatedObject +class CEGUIEXPORT NativeClipboardProvider { public: virtual ~NativeClipboardProvider(); @@ -79,8 +78,7 @@ class CEGUIEXPORT NativeClipboardProvider : in the future, however for X11 this is really hard and would introduce dependency -lX11 to CEGUIBase which is something we would really hate. */ -class CEGUIEXPORT Clipboard : - public AllocatedObject +class CEGUIEXPORT Clipboard { public: /*! diff --git a/cegui/include/CEGUI/Colour.h b/cegui/include/CEGUI/Colour.h index e9cdc72d1..39ca395ea 100644 --- a/cegui/include/CEGUI/Colour.h +++ b/cegui/include/CEGUI/Colour.h @@ -41,8 +41,7 @@ typedef uint32 argb_t; //!< 32 bit ARGB representation of a colour. \brief Class representing colour values within the system. */ -class CEGUIEXPORT Colour : - public AllocatedObject +class CEGUIEXPORT Colour { public: /************************************************************************* diff --git a/cegui/include/CEGUI/ColourRect.h b/cegui/include/CEGUI/ColourRect.h index 76b06e11c..5bbdbcc7e 100644 --- a/cegui/include/CEGUI/ColourRect.h +++ b/cegui/include/CEGUI/ColourRect.h @@ -40,8 +40,7 @@ namespace CEGUI \brief Class that holds details of colours for the four corners of a rectangle. */ -class CEGUIEXPORT ColourRect : - public AllocatedObject +class CEGUIEXPORT ColourRect { public: /*! diff --git a/cegui/include/CEGUI/CommonDialogs/ColourPicker/Controls.h b/cegui/include/CEGUI/CommonDialogs/ColourPicker/Controls.h index c3f794c7b..39c44f3dc 100644 --- a/cegui/include/CEGUI/CommonDialogs/ColourPicker/Controls.h +++ b/cegui/include/CEGUI/CommonDialogs/ColourPicker/Controls.h @@ -177,7 +177,7 @@ class CEGUI_COMMONDIALOGS_API ColourPickerControls : public Window RGB_Colour getAlphaSliderPositionColour(int x, int y); - Vector2f getColourPickingColourPosition(); + glm::vec2 getColourPickingColourPosition(); void getColourPickingColourPositionHSV(float& x, float& y); // Handlers to relay child widget events so they appear to come from us @@ -193,18 +193,18 @@ class CEGUI_COMMONDIALOGS_API ColourPickerControls : public Window bool handleAlphaEditboxTextChanged(const EventArgs& args); - bool handleColourPickerStaticImageMouseLeaves(const EventArgs& args); - bool handleColourPickerStaticImageMouseButtonUp(const EventArgs& args); - bool handleColourPickerStaticImageMouseButtonDown(const EventArgs& args); - bool handleColourPickerStaticImageMouseMove(const EventArgs& args); + bool handleColourPickerStaticImagePointerLeaves(const EventArgs& args); + bool handleColourPickerStaticImagePointerActivate(const EventArgs& args); + bool handleColourPickerStaticImagePointerPressHold(const EventArgs& args); + bool handleColourPickerStaticImagePointerMove(const EventArgs& args); virtual void onCancelButtonClicked(WindowEventArgs& e); virtual void onAcceptButtonClicked(WindowEventArgs& e); - void onColourCursorPositionChanged(); + void onColourIndicatorPositionChanged(); void onColourSliderChanged(); - void refreshColourPickerCursorPosition(const MouseEventArgs& mouseEventArgs); + void refreshColourPickerIndicatorPosition(const CursorInputEventArgs& pointerEventArgs); void refreshAlpha(); void refreshOnlyColourSliderImage(); @@ -214,15 +214,15 @@ class CEGUI_COMMONDIALOGS_API ColourPickerControls : public Window void refreshEditboxesAndColourRects(); void refreshColourRects(); - void positionColourPickerCursorAbsolute(float x, float y); - void positionColourPickerCursorRelative(float x, float y); + void positionColourPickerIndicatorAbsolute(float x, float y); + void positionColourPickerIndicatorRelative(float x, float y); void setColours(const Lab_Colour& newColourLAB); void setColours(const RGB_Colour& newColourRGB); void setColours(const HSV_Colour& newColourHSV); void setColourAlpha(float alphaValue); - void refreshColourPickerCursorPosition(); + void refreshColourPickerIndicatorPosition(); void refreshColourSliderPosition(); void initColourPicker(); @@ -260,7 +260,7 @@ class CEGUI_COMMONDIALOGS_API ColourPickerControls : public Window Window* getColourPickerCursorStaticImage(); ColourPicker* d_callingColourPicker; - Window* d_colourPickerCursor; + Window* d_colourPickerIndicator; SliderMode d_sliderMode; @@ -294,7 +294,7 @@ class CEGUI_COMMONDIALOGS_API ColourPickerControls : public Window int d_colourPickerControlsTextureSize; - bool d_draggingColourPickerCursor; + bool d_draggingColourPickerIndicator; RGB_Colour* d_colourPickingTexture; diff --git a/cegui/include/CEGUI/CommonDialogs/ColourPicker/Types.h b/cegui/include/CEGUI/CommonDialogs/ColourPicker/Types.h index 3a1891278..45dd05665 100644 --- a/cegui/include/CEGUI/CommonDialogs/ColourPicker/Types.h +++ b/cegui/include/CEGUI/CommonDialogs/ColourPicker/Types.h @@ -41,27 +41,12 @@ namespace CEGUI { -/*! -\brief - Enum defining the ColourPicker Slider mode - -\deprecated - This enum is deprecated and has been marked for removal. -*/ -enum ColourPickerSliderMode -{ - ColourPickerSliderMode_L, - ColourPickerSliderMode_A, - ColourPickerSliderMode_B -}; - class CEGUI_COMMONDIALOGS_API Lab_Colour; class CEGUI_COMMONDIALOGS_API RGB_Colour; class CEGUI_COMMONDIALOGS_API HSV_Colour; //! Class representing an RGB colour using unsigned chars -class CEGUI_COMMONDIALOGS_API RGB_Colour : - public AllocatedObject +class CEGUI_COMMONDIALOGS_API RGB_Colour { public: RGB_Colour(unsigned char red, unsigned char green, unsigned char blue) : @@ -85,8 +70,7 @@ class CEGUI_COMMONDIALOGS_API RGB_Colour : }; //! Class representing a Colour according to the L*a*b* standard -class CEGUI_COMMONDIALOGS_API Lab_Colour : - public AllocatedObject +class CEGUI_COMMONDIALOGS_API Lab_Colour { public: Lab_Colour(float LValue, float aValue, float bValue) : @@ -108,8 +92,7 @@ class CEGUI_COMMONDIALOGS_API Lab_Colour : }; //! Class representing an HSV (hue, saturation and value) colour using floats. -class CEGUI_COMMONDIALOGS_API HSV_Colour : - public AllocatedObject +class CEGUI_COMMONDIALOGS_API HSV_Colour { public: HSV_Colour(float HValue, float SValue, float VValue) : diff --git a/cegui/include/CEGUI/CompositeResourceProvider.h b/cegui/include/CEGUI/CompositeResourceProvider.h index c67cca091..64236c415 100644 --- a/cegui/include/CEGUI/CompositeResourceProvider.h +++ b/cegui/include/CEGUI/CompositeResourceProvider.h @@ -28,7 +28,6 @@ Author: Hans Mackowiak (Hanmac) hanmac@gmx.de #define _CEGUICompositeResourceProvider_h_ #include "CEGUI/Base.h" #include "CEGUI/IteratorBase.h" -#include "CEGUI/MemoryAllocation.h" #include "CEGUI/ResourceProvider.h" #include @@ -74,7 +73,7 @@ class CEGUIEXPORT CompositeResourceProvider : public ResourceProvider */ templatevoid add(const String& name) { - add(CEGUI_NEW_AO T,name); + add(new T,name); } /*! \brief diff --git a/cegui/include/CEGUI/Config.h.in b/cegui/include/CEGUI/Config.h.in index 11b2533cc..072a4fd1d 100644 --- a/cegui/include/CEGUI/Config.h.in +++ b/cegui/include/CEGUI/Config.h.in @@ -51,26 +51,13 @@ setting CMake options and regenerating, rather than editing directly. # endif #endif -////////////////////////////////////////////////////////////////////////// -// CEGUI supports custom memory allocation (optional) -////////////////////////////////////////////////////////////////////////// -// if this is defined, allocation can be customised -#cmakedefine CEGUI_CUSTOM_ALLOCATORS -// if this is defined, allocations will pass debug info to allocators -#cmakedefine CEGUI_CUSTOM_ALLOCATORS_DEBUG -// the file that contains allocators and allocation config -// (not used if CEGUI_CUSTOM_ALLOCATORS isn't defined) -#define CEGUI_CUSTOM_ALLOCATORS_INCLUDE "@CEGUI_CUSTOM_ALLOCATORS_INCLUDE@" - ////////////////////////////////////////////////////////////////////////// // CEGUI allows 3 different string class configurations ////////////////////////////////////////////////////////////////////////// // Inbuilt Unicode (utf8 and utf32 aware) #define CEGUI_STRING_CLASS_UNICODE 1 -// plain std::string without allocators (makes pass by reference easy) +// plain std::string #define CEGUI_STRING_CLASS_STD 2 -// std::basic_string allocated according to allocator config -#define CEGUI_STRING_CLASS_STD_AO 3 #define CEGUI_STRING_CLASS @CEGUI_STRING_CLASS@ diff --git a/cegui/include/CEGUI/Config_xmlHandler.h b/cegui/include/CEGUI/Config_xmlHandler.h index 13dbec5da..cb4426c63 100644 --- a/cegui/include/CEGUI/Config_xmlHandler.h +++ b/cegui/include/CEGUI/Config_xmlHandler.h @@ -57,7 +57,7 @@ class Config_xmlHandler : public XMLHandler static const String XMLParserElement; static const String ImageCodecElement; static const String DefaultFontElement; - static const String DefaultMouseCursorElement; + static const String DefaultCursorElement; static const String DefaultTooltipElement; // xml attribute names static const String FilenameAttribute; @@ -91,8 +91,8 @@ class Config_xmlHandler : public XMLHandler void loadAutoResources() const; //! initialise the system default font according to the config. void initialiseDefaultFont() const; - //! initialise the system default mouse cursor image according to the config. - void initialiseDefaultMouseCursor() const; + //! initialise the system default cursor image according to the config. + void initialiseDefaultCursor() const; //! initialise the system default tooltip according to the config. void initialiseDefaulTooltip() const; //! execute the init script as specified in the config. @@ -155,7 +155,7 @@ class Config_xmlHandler : public XMLHandler void handleImageCodecElement(const XMLAttributes& attr); void handleDefaultTooltipElement(const XMLAttributes& attr); void handleDefaultFontElement(const XMLAttributes& attr); - void handleDefaultMouseCursorElement(const XMLAttributes& attr); + void handleDefaultCursorElement(const XMLAttributes& attr); //! helper to convert resource type string to something more useful. ResourceType stringToResourceType(const String& type) const; @@ -165,14 +165,11 @@ class Config_xmlHandler : public XMLHandler void autoLoadImagesets(const String& pattern, const String& group) const; //! type of collection holding resource group directory specifications. - typedef std::vector ResourceDirVector; + typedef std::vector ResourceDirVector; //! type of collection holding default resource group specifications. - typedef std::vector DefaultGroupVector; + typedef std::vector DefaultGroupVector; //! type of collection holding specifications of resources to auto-load. - typedef std::vector AutoResourceVector; + typedef std::vector AutoResourceVector; //! The name to use for the CEGUI log file. String d_logFileName; //! The logging level to be set. @@ -183,15 +180,15 @@ class Config_xmlHandler : public XMLHandler String d_imageCodecName; //! The name of the default font to be set. String d_defaultFont; - //! The name of the default mouse cursor image to use. - String d_defaultMouseImage; + //! The name of the default cursor image to use. + String d_defaultPointerImage; //! The name of the default tooltip window type. String d_defaultTooltipType; //! name of the initialisation script. String d_scriptingInitScript; //! name of the termination script. String d_scriptingTerminateScript; - //! Collection of resouce group directories to be set. + //! Collection of resource group directories to be set. ResourceDirVector d_resourceDirectories; //! Collection of default resource groups to be set. DefaultGroupVector d_defaultResourceGroups; diff --git a/cegui/include/CEGUI/CoordConverter.h b/cegui/include/CEGUI/CoordConverter.h index bc350f64e..c6b2aea02 100644 --- a/cegui/include/CEGUI/CoordConverter.h +++ b/cegui/include/CEGUI/CoordConverter.h @@ -84,20 +84,20 @@ class CEGUIEXPORT CoordConverter /*! \brief - converts given Vector2 to absolute Vector2f + converts given Vector2 to absolute glm::vec2 */ - inline static Vector2f asAbsolute(const Vector2& v, const Sizef& base, bool pixelAlign = true) + inline static glm::vec2 asAbsolute(const Vector2& v, const Sizef& base, bool pixelAlign = true) { - return Vector2f(asAbsolute(v.d_x, base.d_width, pixelAlign), asAbsolute(v.d_y, base.d_height, pixelAlign)); + return glm::vec2(asAbsolute(v.d_x, base.d_width, pixelAlign), asAbsolute(v.d_y, base.d_height, pixelAlign)); } /*! \brief - converts given Vector2 to relative Vector2f + converts given Vector2 to relative glm::vec2 */ - inline static Vector2f asRelative(const Vector2& v, const Sizef& base) + inline static glm::vec2 asRelative(const Vector2& v, const Sizef& base) { - return Vector2f(asRelative(v.d_x, base.d_width), asRelative(v.d_y, base.d_height)); + return glm::vec2(asRelative(v.d_x, base.d_width), asRelative(v.d_y, base.d_height)); } /*! @@ -218,10 +218,10 @@ class CEGUIEXPORT CoordConverter UVector2 object describing the point to be converted \return - Vector2 object describing a window co-ordinate point that is equivalent + glm::vec2 object describing a window co-ordinate point that is equivalent to screen based UVector2 point \a vec. */ - static Vector2f screenToWindow(const Window& window, const UVector2& vec); + static glm::vec2 screenToWindow(const Window& window, const UVector2& vec); /*! \brief @@ -235,10 +235,10 @@ class CEGUIEXPORT CoordConverter Vector2 object describing the point to be converted. \return - Vector2 object describing a window co-ordinate point that is equivalent + glm::vec2 object describing a window co-ordinate point that is equivalent to screen based Vector2 point \a vec. */ - static Vector2f screenToWindow(const Window& window, const Vector2f& vec); + static glm::vec2 screenToWindow(const Window& window, const glm::vec2& vec); /*! \brief @@ -310,10 +310,10 @@ class CEGUIEXPORT CoordConverter Window object to return base position for. \return - Vector2 value indicating the base on-screen pixel location of the window + glm::vec2 value indicating the base on-screen pixel location of the window object. (i.e. The screen co-ord of the window's top-left corner). */ - static Vector2f getBaseValue(const Window& window); + static glm::vec2 getBaseValue(const Window& window); }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/Cursor.h b/cegui/include/CEGUI/Cursor.h new file mode 100644 index 000000000..96f7630b9 --- /dev/null +++ b/cegui/include/CEGUI/Cursor.h @@ -0,0 +1,448 @@ +/*********************************************************************** + created: 21/2/2004 + author: Paul D Turner + + purpose: Defines interface for the Cursor class +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUICursor_h_ +#define _CEGUICursor_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/String.h" +#include "CEGUI/Vector.h" +#include "CEGUI/Rect.h" +#include "CEGUI/EventSet.h" +#include "CEGUI/InputEvent.h" +#include "CEGUI/UDim.h" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4275) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +//! Class that provides cursor support. +class CEGUIEXPORT Cursor : public EventSet +{ +public: + //! Namespace for global events. + static const String EventNamespace; + + /** Name of Event fired when the cursor image is changed. + * Handlers are passed a const CursorEventArgs reference with + * CursorEventArgs::d_cursor set to the Cursor that has + * had it's image changed, and CursorEventArgs::image set to the + * Image that is now set for the Cursor (may be 0). + */ + static const String EventImageChanged; + + /** Name of Event fired when the Image to be used as a default cursor + * image is changed. + * Handlers are passed a const CursorEventArgs reference with + * CursorEventArgs::Cursor set to the Cursor that has + * had it's default image changed, and CursorEventArgs::image set to + * the Image that is now set as the default (may be 0). + */ + static const String EventDefaultImageChanged; + + /*! + \brief + Constructor for Cursor objects + */ + Cursor(void); + + + /*! + \brief + Destructor for Cursor objects + */ + ~Cursor(void); + + /*! + \brief + Set the current cursor image + + \param name + String object holding the name of the desired Image. + + \return + Nothing. + + \exception UnknownObjectException thrown if Image \a name is not known. + */ + void setImage(const String& name); + + + /*! + \brief + Set the current cursor image + */ + void setImage(const Image* image); + + + /*! + \brief + Get the current cursor image + \return + The current image used to draw cursor. + */ + const Image* getImage(void) const {return d_indicatorImage;} + + /*! + \brief + Set the image to be used as the default cursor. + + \param image + Pointer to an image object that is to be used as the default cursor + indicator. To have no indicator rendered by default, you can specify 0 here. + */ + void setDefaultImage(const Image* image); + + /*! + \brief + Set the image to be used as the default cursor. + + \param name + String object that contains the name of the Image that is to be used. + + \exception + UnknownObjectException thrown if no Image named \a name exists. + */ + void setDefaultImage(const String& name); + + /*! + \brief + Return the currently set default cursor image + + \return + Pointer to the current default image used for the cursor. May + return 0 if default cursor has not been set, or has intentionally + been set to 0 - which results in a blank default cursor. + */ + const Image* getDefaultImage() const; + + + /*! + \brief + Makes the indicator draw itself + + */ + void draw(void); + + + /*! + \brief + Set the current cursor position + + \param position + Point object describing the new location for the cursor. This will + be clipped to within the renderer screen area. + */ + void setPosition(const glm::vec2& position); + + + /*! + \brief + Offset the cursor position by the deltas specified in \a offset. + + \param offset + Point object which describes the amount to move the indicator in each axis. + + \return + Nothing. + */ + void offsetPosition(const glm::vec2& offset); + + + /*! + \brief + Set the area that the cursor is constrained to. + + \param area + Pointer to a Rect object that describes the area of the display that + the cursor is allowed to occupy. The given area will be clipped to + the current Renderer screen area - it is never possible for the cursor + to leave this area. If this parameter is NULL, the constraint is set + to the size of the current Renderer screen area. + + \return + Nothing. + */ + void setConstraintArea(const Rectf* area); + + + /*! + \brief + Set the area that the cursor is constrained to. + + \param area + Pointer to a URect object that describes the area of the display that + the cursor is allowed to occupy. The given area will be clipped to the + current Renderer screen area - it is never possible for the cursor to + leave this area. If this parameter is NULL, the constraint is set to + the size of the current Renderer screen area. + + \return + Nothing. + */ + void setUnifiedConstraintArea(const URect* area); + + + /*! + \brief + Hides the cursor. + + \return + Nothing. + */ + void hide(void) {d_visible = false;} + + + /*! + \brief + Shows the cursor. + + \return + Nothing. + */ + void show(void) {d_visible = true;} + + + /*! + \brief + Set the visibility of the cursor. + + \param visible + 'true' to show the cursor, 'false' to hide it. + + \return + Nothing. + */ + void setVisible(bool visible) {d_visible = visible;} + + + /*! + \brief + return whether the cursor is visible. + + \return + true if the cursor is visible, false if the cursor is hidden. + */ + bool isVisible(void) const {return d_visible;} + + + /*! + \brief + Return the current cursor position as a pixel offset from + the top-left corner of the display. + + \return + Point object describing the cursor position in screen pixels. + */ + inline glm::vec2 getPosition() const + { + return d_position; + } + + /*! + \brief + Return the current constraint area of the cursor. + + \return + Rect object describing the active area that the cursor is constrained to. + */ + Rectf getConstraintArea(void) const; + + + /*! + \brief + Return the current constraint area of the cursor. + + \return + URect object describing the active area that the cursor is constrained to. + */ + const URect& getUnifiedConstraintArea(void) const; + + + /*! + \brief + Return the current cursor position as display resolution + independent values. + + \return + Point object describing the current cursor position as + resolution independent values that anges from 0.0f to 1.0f, where 0.0f + represents the left-most and top-most positions, and 1.0f represents + the right-most and bottom-most positions. + */ + glm::vec2 getDisplayIndependantPosition(void) const; + + /*! + \brief + Function used to notify the Cursor of changes in the display size. + + You normally would not call this directly; rather you would call the + function System::notifyDisplaySizeChanged and that will then call this + function for you. + + \param new_size + Size object describing the new display size in pixels. + */ + void notifyDisplaySizeChanged(const Sizef& new_size); + + /*! + \brief + Set an explicit size for the cursor image to be drawn at. + + This will override the size that is usually obtained directly from the + cursor image and will stay in effect across changes to the + cursor image. + + Setting this size to (0, 0) will revert back to using the size as + obtained from the Image itself. + + \param size + Reference to a Size object that describes the size at which the indicator + image should be drawn in pixels. + */ + void setExplicitRenderSize(const Sizef& size); + + /*! + \brief + Return the explicit render size currently set. A return size of (0, 0) + indicates that the real image size will be used. + */ + const Sizef& getExplicitRenderSize() const; + + /*! + \brief + Static function to pre-initialise the cursor position (prior to + Cursor instantiation). + + Calling this function prior to instantiating Cursor will prevent + the cursor having it's position set to the middle of the initial view. + Calling this function after the Cursor is instantiated will have + no effect. + + \param position + vec2 object describing the initial pixel position to + be used for the cursor. + */ + static void setInitialPointerPosition(const glm::vec2& position); + + /*! + \brief + Mark the cached geometry as invalid so it will be recached next time the + cursor is drawn. + */ + void invalidate(); + +protected: + /************************************************************************* + New event handlers + *************************************************************************/ + //! Event triggered internally when cursor image is changed. + virtual void onImageChanged(CursorEventArgs& e); + //! Event triggered internally when cursor default image is changed. + virtual void onDefaultImageChanged(CursorEventArgs& e); + +private: + /************************************************************************* + Implementation Methods + *************************************************************************/ + /*! + \brief + Checks the cursor position is within the current 'constrain' + Rect and adjusts as required. + */ + void constrainPosition(void); + + //! updates the cached geometry. + void cacheGeometry(); + + //! calculate offset for custom image size so 'hot spot' is maintained. + void calculateCustomOffset() const; + + /*! + \brief + Destroys the geometry buffers of this Cursor. + */ + void destroyGeometryBuffers(); + + /*! + \brief + Updates the translation of the geometry buffers of this Cursor. + */ + void updateGeometryBuffersTranslation(); + + /*! + \brief + Updates the clipping area of the geometry buffers of this Cursor. + + \param clipping_area + The clipping area that will be applied to the geometry buffers of this Cursor. + */ + void updateGeometryBuffersClipping(const Rectf& clipping_area); + + + /************************************************************************* + Implementation Data + *************************************************************************/ + //! Image that is currently set as the cursor. + const Image* d_indicatorImage; + //! Image that will be used as the default image for this cursor. + const Image* d_defaultIndicatorImage; + //! Current location of the indicator + glm::vec2 d_position; + //! true if the indicator will be drawn, else false. + bool d_visible; + //! Specifies the area (in screen pixels) that the indicator can move around in. + URect d_constraints; + //! buffer to hold geometry for cursor imagery. + std::vector d_geometryBuffers; + //! custom explicit size to render the indicator image at + Sizef d_customSize; + //! correctly scaled offset used when using custom image size. + mutable glm::vec2 d_customOffset; + //! true if the cursor initial position has been pre-set + static bool s_initialPositionSet; + //! value set as initial position (if any) + static glm::vec2 s_initialPosition; + //! boolean indicating whether cached cursor geometry is valid. + mutable bool d_cachedGeometryValid; +}; + +} // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUICursor_h_ diff --git a/cegui/include/CEGUI/DataContainer.h b/cegui/include/CEGUI/DataContainer.h index c2f08560c..304932978 100644 --- a/cegui/include/CEGUI/DataContainer.h +++ b/cegui/include/CEGUI/DataContainer.h @@ -39,8 +39,7 @@ namespace CEGUI \brief Class used as the databuffer for loading files throughout the library. */ -class CEGUIEXPORT RawDataContainer : - public AllocatedObject +class CEGUIEXPORT RawDataContainer { public: /************************************************************************* diff --git a/cegui/include/CEGUI/DefaultLogger.h b/cegui/include/CEGUI/DefaultLogger.h index b02b4f105..512a41acf 100644 --- a/cegui/include/CEGUI/DefaultLogger.h +++ b/cegui/include/CEGUI/DefaultLogger.h @@ -56,6 +56,7 @@ class CEGUIEXPORT DefaultLogger : public Logger void logEvent(const String& message, LoggingLevel level = Standard); void setLogFilename(const String& filename, bool append = false); +#ifndef __ANDROID__ protected: //! Stream used to implement the logger std::ofstream d_ostream; @@ -63,12 +64,12 @@ class CEGUIEXPORT DefaultLogger : public Logger std::ostringstream d_workstream; typedef std::pair CacheItem; - typedef std::vector Cache; + typedef std::vector Cache; //! Used to cache log entries before log file is created. Cache d_cache; //! true while log entries are beign cached (prior to logfile creation) bool d_caching; +#endif }; } diff --git a/cegui/include/CEGUI/DynamicModule.h b/cegui/include/CEGUI/DynamicModule.h index 5868e0056..013aed753 100644 --- a/cegui/include/CEGUI/DynamicModule.h +++ b/cegui/include/CEGUI/DynamicModule.h @@ -38,8 +38,7 @@ namespace CEGUI Class that wraps and gives access to a dynamically linked module (.dll, .so, etc...) */ -class CEGUIEXPORT DynamicModule : - public AllocatedObject +class CEGUIEXPORT DynamicModule { public: /*! diff --git a/cegui/include/CEGUI/Element.h b/cegui/include/CEGUI/Element.h index 650b7d805..e2ecd15b1 100644 --- a/cegui/include/CEGUI/Element.h +++ b/cegui/include/CEGUI/Element.h @@ -241,8 +241,7 @@ class directly. You most likely want to use CEGUI::Window. */ class CEGUIEXPORT Element : public PropertySet, - public EventSet, - public AllocatedObject + public EventSet { public: //! Namespace for global events @@ -805,11 +804,13 @@ class CEGUIEXPORT Element : Return the element's absolute (or screen, depending on the type of the element) position in pixels. \return - Vector2f object describing this element's absolute position in pixels. + glm::vec2 object describing this element's absolute position in pixels. */ - inline const Vector2f& getPixelPosition() const + inline glm::vec2 getPixelPosition() const { - return getUnclippedOuterRect().get().d_min; + // FIXME: Temporary because of transition to glm::vec2 + const Vector2 min = getUnclippedOuterRect().get().d_min; + return glm::vec2(min.d_x, min.d_y); } /*! @@ -857,16 +858,16 @@ class CEGUIEXPORT Element : CEGUI used Euler angles previously. While these are easy to use and seem intuitive they cause Gimbal locks when animating and are overall the worse solution than using Quaternions. You can still use Euler angles, see - the CEGUI::Quaternion class for more info about that. + the glm::quat class for more info about that. */ - void setRotation(const Quaternion& rotation); + void setRotation(const glm::quat& rotation); /*! \brief retrieves rotation of this widget \see Element::setRotation */ - inline const Quaternion& getRotation() const + inline const glm::quat& getRotation() const { return d_rotation; } @@ -1291,8 +1292,7 @@ class CEGUIEXPORT Element : Implementation Data *************************************************************************/ //! definition of type used for the list of attached child elements. - typedef std::vector ChildList; + typedef std::vector ChildList; //! The list of child element objects attached to this. ChildList d_children; @@ -1321,7 +1321,7 @@ class CEGUIEXPORT Element : //! Current constrained pixel size of the element. Sizef d_pixelSize; //! Rotation of this element (relative to the parent) - Quaternion d_rotation; + glm::quat d_rotation; //! outer area rect in screen pixels CachedRectf d_unclippedOuterRect; diff --git a/cegui/include/CEGUI/Event.h b/cegui/include/CEGUI/Event.h index af23c0da2..fef0430f8 100644 --- a/cegui/include/CEGUI/Event.h +++ b/cegui/include/CEGUI/Event.h @@ -54,8 +54,7 @@ namespace CEGUI \note An Event object may not be copied. */ -class CEGUIEXPORT Event : - public AllocatedObject +class CEGUIEXPORT Event { public: /*! @@ -221,8 +220,7 @@ class CEGUIEXPORT Event : return *this; } - typedef std::multimap - CEGUI_MULTIMAP_ALLOC(Group, Connection)> SlotContainer; + typedef std::multimap > SlotContainer; SlotContainer d_slots; //!< Collection holding ref-counted bound slots const String d_name; //!< Name of this event }; diff --git a/cegui/include/CEGUI/EventArgs.h b/cegui/include/CEGUI/EventArgs.h index ee401d8f2..955544850 100644 --- a/cegui/include/CEGUI/EventArgs.h +++ b/cegui/include/CEGUI/EventArgs.h @@ -46,8 +46,7 @@ namespace CEGUI the event system does not look at this value, code at a higher level can use it to determine how far to propagate an event. */ -class CEGUIEXPORT EventArgs : - public AllocatedObject +class CEGUIEXPORT EventArgs { public: /************************************************************************* diff --git a/cegui/include/CEGUI/EventSet.h b/cegui/include/CEGUI/EventSet.h index abdde3f9c..bc79ee68e 100644 --- a/cegui/include/CEGUI/EventSet.h +++ b/cegui/include/CEGUI/EventSet.h @@ -433,8 +433,7 @@ class CEGUIEXPORT EventSet return *this; } - typedef std::map EventMap; + typedef std::map EventMap; EventMap d_events; bool d_muted; //!< true if events for this EventSet have been muted. diff --git a/cegui/include/CEGUI/Exceptions.h b/cegui/include/CEGUI/Exceptions.h index 9cf464904..6aebfff57 100644 --- a/cegui/include/CEGUI/Exceptions.h +++ b/cegui/include/CEGUI/Exceptions.h @@ -38,8 +38,7 @@ namespace CEGUI { //! Root exception class used within the GUI system. class CEGUIEXPORT Exception : - public std::exception, - public AllocatedObject + public std::exception { public: //! Virtual destructor. @@ -765,6 +764,63 @@ class CEGUIEXPORT ScriptException : public Exception #define ScriptException(message) \ ScriptException(message, __FILE__, __LINE__, CEGUI_FUNCTION_NAME) +//----------------------------------------------------------------------------// + +//! Exception class used for issues in scripting subsystem. +class CEGUIEXPORT SVGParsingException : public Exception +{ +public: + /*! + \brief + Constructor that is responsible for logging the script exception by + calling the base class. + + \param message + String object describing the reason for the script exception being + thrown. + + \param filename + String object containing the name of the file where the script exception + occurred. + + \param line + Integer representing the line number where the script exception + occurred. + + \param function + String object containing the name of the function where the exception + occurred. + + \remarks + The script exception name is automatically passed to the base class as + "CEGUI::ScriptException". + */ + SVGParsingException(const String& message, + const String& file = "unknown", int line = 0, + const String& function = "unknown") : + Exception(message, "CEGUI::SVGParsingException", file, line, function) + {} +}; + +/*! +\brief + This helper macro ensures the correct filename and line number where the + script exception occurred are passed to the exception itself. + +\remarks + There's a bug in Visual Studio 7.1 + (see http://support.microsoft.com/kb/199057/en) and lower which leads to + incorrect __LINE__ macro expansion if used inside a function and compiled + with "Program Database for Edit & Continue" (/ZI) where instead of a + constant expressing line number you'll get the following: + (__LINE__Var+constant). The workaround consists in using compiler option + "Program Database" (/Zi) instead --> Project Properties\C/C++\General\Debug + Information Format\Program Database (/Zi). Visual Studio 2005 corrects the + problem. Premake files were modified to contemplate this for VS2002 and + VS2003. +*/ +#define SVGParsingException(message) \ + SVGParsingException(message, __FILE__, __LINE__, CEGUI_FUNCTION_NAME) //----------------------------------------------------------------------------// diff --git a/cegui/include/CEGUI/FactoryModule.h b/cegui/include/CEGUI/FactoryModule.h index f21a02cd6..3b73bbfad 100644 --- a/cegui/include/CEGUI/FactoryModule.h +++ b/cegui/include/CEGUI/FactoryModule.h @@ -41,8 +41,7 @@ namespace CEGUI { class FactoryRegisterer; -class CEGUIEXPORT FactoryModule : - public AllocatedObject +class CEGUIEXPORT FactoryModule { public: //! Destructor. @@ -58,8 +57,7 @@ class CEGUIEXPORT FactoryModule : protected: //! Collection type that holds pointers to the factory registerer objects. - typedef std::vector FactoryRegistry; + typedef std::vector FactoryRegistry; //! The collection of factorty registerer object pointers. FactoryRegistry d_registry; }; diff --git a/cegui/include/CEGUI/FactoryRegisterer.h b/cegui/include/CEGUI/FactoryRegisterer.h index b7eae6065..5fb940f87 100644 --- a/cegui/include/CEGUI/FactoryRegisterer.h +++ b/cegui/include/CEGUI/FactoryRegisterer.h @@ -38,8 +38,7 @@ namespace CEGUI Base class encapsulating a type name and common parts of factory registration. */ -class CEGUIEXPORT FactoryRegisterer : - public AllocatedObject +class CEGUIEXPORT FactoryRegisterer { public: //! Destructor. diff --git a/cegui/include/CEGUI/Font.h b/cegui/include/CEGUI/Font.h index 362395e9f..fc5522655 100644 --- a/cegui/include/CEGUI/Font.h +++ b/cegui/include/CEGUI/Font.h @@ -34,8 +34,6 @@ #include "CEGUI/XMLSerializer.h" #include "CEGUI/FontGlyph.h" -#include - #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) @@ -57,8 +55,7 @@ namespace CEGUI */ class CEGUIEXPORT Font : public PropertySet, - public EventSet, - public AllocatedObject + public EventSet { public: //! Colour value used whenever a colour is not specified. @@ -103,8 +100,9 @@ class CEGUIEXPORT Font : \brief Draw text into a specified area of the display. - \param buffer - GeometryBuffer object where the geometry for the text be queued. + \param geom_buffers + List of GeometryBuffer objects that will be used to add Font geometry in + a batch-saving way. \param text String object containing the text to be drawn. @@ -138,10 +136,11 @@ class CEGUIEXPORT Font : positioning (which is not possible to determine accurately by using the extent measurement functions). */ - float drawText(GeometryBuffer& buffer, const String& text, - const Vector2f& position, const Rectf* clip_rect, - const ColourRect& colours, const float space_extra = 0.0f, - const float x_scale = 1.0f, const float y_scale = 1.0f) const; + float drawText(std::vector& geom_buffers, const String& text, + const glm::vec2& position, const Rectf* clip_rect, + const bool clipping_enabled, const ColourRect& colours, + const float space_extra = 0.0f, const float x_scale = 1.0f, + const float y_scale = 1.0f) const; /*! \brief @@ -497,8 +496,7 @@ class CEGUIEXPORT Font : uint* d_glyphPageLoaded; //! Definition of CodepointMap type. - typedef std::map - CEGUI_MAP_ALLOC(utf32, FontGlyph)> CodepointMap; + typedef std::map > CodepointMap; //! Contains mappings from code points to Image objects mutable CodepointMap d_cp_map; }; diff --git a/cegui/include/CEGUI/FontGlyph.h b/cegui/include/CEGUI/FontGlyph.h index 32dcd065b..e7224d130 100644 --- a/cegui/include/CEGUI/FontGlyph.h +++ b/cegui/include/CEGUI/FontGlyph.h @@ -39,8 +39,7 @@ namespace CEGUI For TrueType fonts initially all FontGlyph's are empty (getImage() will return 0), but they are filled by demand. */ -class CEGUIEXPORT FontGlyph: - public AllocatedObject +class CEGUIEXPORT FontGlyph { public: //! Constructor. @@ -75,7 +74,7 @@ class CEGUIEXPORT FontGlyph: */ float getRenderedAdvance(float x_scale) const { return (d_image->getRenderedSize().d_width + - d_image->getRenderedOffset().d_x) * x_scale; } + d_image->getRenderedOffset().x) * x_scale; } /*! \brief diff --git a/cegui/include/CEGUI/FontManager.h b/cegui/include/CEGUI/FontManager.h index 69c178dc9..f868e7a69 100644 --- a/cegui/include/CEGUI/FontManager.h +++ b/cegui/include/CEGUI/FontManager.h @@ -56,8 +56,7 @@ class PixmapFont; */ class CEGUIEXPORT FontManager : public Singleton, - public NamedXMLResourceManager, - public AllocatedObject + public NamedXMLResourceManager { public: //! Constructor. diff --git a/cegui/include/CEGUI/FormattedRenderedString.h b/cegui/include/CEGUI/FormattedRenderedString.h index 9d1137bf7..c13c56dcd 100644 --- a/cegui/include/CEGUI/FormattedRenderedString.h +++ b/cegui/include/CEGUI/FormattedRenderedString.h @@ -37,16 +37,15 @@ namespace CEGUI Root of a class hierarchy that wrap RenderedString objects and render them with additional formatting. */ -class CEGUIEXPORT FormattedRenderedString : - public AllocatedObject +class CEGUIEXPORT FormattedRenderedString { public: //! Destructor. virtual ~FormattedRenderedString(); virtual void format(const Window* ref_wnd, const Sizef& area_size) = 0; - virtual void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + virtual void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const = 0; virtual size_t getFormattedLineCount() const = 0; virtual float getHorizontalExtent(const Window* ref_wnd) const = 0; diff --git a/cegui/include/CEGUI/ForwardRefs.h b/cegui/include/CEGUI/ForwardRefs.h index c6183596b..fe10664fa 100644 --- a/cegui/include/CEGUI/ForwardRefs.h +++ b/cegui/include/CEGUI/ForwardRefs.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 21/2/2004 author: Paul D Turner - + purpose: Forward declares all core system classes *************************************************************************/ /*************************************************************************** @@ -70,13 +70,15 @@ class ImageCodec; class ImageManager; class ImagerySection; class Interpolator; +class InputAggregator; +class InputEvent; class JustifiedRenderedString; class KeyFrame; class LeftAlignedRenderedString; class LinkedEvent; class LinkedEventArgs; class Logger; -class MouseCursor; +class Cursor; class NamedElement; class NamedElementEventArgs; class NativeClipboardProvider; @@ -84,7 +86,6 @@ class Property; template class PropertyHelper; class PropertyReceiver; class PropertySet; -class Quaternion; class RawDataContainer; template class Rect; class RegexMatcher; @@ -111,17 +112,17 @@ class ScriptFunctor; class ScriptModule; template class Size; class SimpleTimer; +class SVGImage; class StringTranscoder; class System; -class SystemKeys; class Texture; class TextureTarget; class TextUtils; class UBox; class UDim; template class Vector2; -template class Vector3; -struct Vertex; +struct TexturedColouredVertex; +struct ColouredVertex; class WidgetLookFeel; class Window; class WindowFactory; @@ -139,7 +140,6 @@ class XMLSerializer; Forward declare window / widget classes. *************************************************************************/ class ButtonBase; -class ClippedContainer; class Combobox; class ComboDropList; class DefaultWindow; @@ -150,9 +150,7 @@ class GridLayoutContainer; class HorizontalLayoutContainer; class ItemEntry; class ItemListBase; -class ItemListbox; class LayoutContainer; -class Listbox; class ListboxItem; class ListboxTextItem; class ListHeader; @@ -169,7 +167,6 @@ class RadioButton; class ScrollablePane; class Scrollbar; class ScrolledContainer; -class ScrolledItemListBase; class SequentialLayoutContainer; class Slider; class Spinner; @@ -179,10 +176,20 @@ class Thumb; class Titlebar; class ToggleButton; class Tooltip; -class Tree; -class TreeItem; class VerticalLayoutContainer; +/************************************************************************* + Forward declare model-view classes. +*************************************************************************/ +class ItemModel; +class ListView; +class ListWidget; +class ModelIndex; +class StandardItemModel; +class StandardItem; +class TreeView; +class TreeWidget; + /************************************************************************* Forward declare EventArg based classes. *************************************************************************/ @@ -192,17 +199,34 @@ class DragDropEventArgs; class FontEventArgs; class GUIContextEventArgs; class HeaderSequenceEventArgs; +class ItemViewEventArgs; class KeyEventArgs; -class MouseCursorEventArgs; -class MouseEventArgs; +class ModelEventARgs; +class CursorEventArgs; class RegexMatchStateArgs; class RenderQueueEventArgs; class RenderTargetEventArgs; class ResourceEventArgs; -class TreeEventArgs; class UpdateEventArgs; class WindowEventArgs; +/************************************************************************* + Forward declare SVG based classes. +*************************************************************************/ +class SVGData; +class SVGDataManager; +class SVGTesselator; + +class SVGBasicShape; +class SVGCircle; +class SVGLine; +class SVGPolyline; +class SVGRect; + +class SVGPaint; +class SVGPaintStyle; + + } // End of CEGUI namespace section #endif // end of guard _CEGUIForwardRefs_h_ diff --git a/cegui/include/CEGUI/FreeFunctionSlot.h b/cegui/include/CEGUI/FreeFunctionSlot.h index 90adf04bc..c972ada56 100644 --- a/cegui/include/CEGUI/FreeFunctionSlot.h +++ b/cegui/include/CEGUI/FreeFunctionSlot.h @@ -36,7 +36,7 @@ namespace CEGUI \brief Slot functor class that calls back via a free function pointer. */ -class FreeFunctionSlot : public SlotFunctorBase +class FreeFunctionSlot : public SlotFunctorBase { public: //! Slot function type. diff --git a/cegui/include/CEGUI/FreeTypeFont.h b/cegui/include/CEGUI/FreeTypeFont.h index c025ee41e..d540e3bb9 100644 --- a/cegui/include/CEGUI/FreeTypeFont.h +++ b/cegui/include/CEGUI/FreeTypeFont.h @@ -31,7 +31,7 @@ #include "CEGUI/Font.h" #include "CEGUI/DataContainer.h" -#include "CEGUI/BasicImage.h" +#include "CEGUI/BitmapImage.h" #include #include FT_FREETYPE_H @@ -171,12 +171,10 @@ class FreeTypeFont : public Font //! Font file data RawDataContainer d_fontData; //! Type definition for TextureVector. - typedef std::vector TextureVector; + typedef std::vector TextureVector; //! Textures that hold the glyph imagery for this font. mutable TextureVector d_glyphTextures; - typedef std::vector ImageVector; + typedef std::vector ImageVector; //! collection of images defined for this font. mutable ImageVector d_glyphImages; }; diff --git a/cegui/include/CEGUI/FunctorCopySlot.h b/cegui/include/CEGUI/FunctorCopySlot.h index 42b82793e..4fd876e59 100644 --- a/cegui/include/CEGUI/FunctorCopySlot.h +++ b/cegui/include/CEGUI/FunctorCopySlot.h @@ -38,7 +38,7 @@ namespace CEGUI functor object. */ template -class FunctorCopySlot : public SlotFunctorBase +class FunctorCopySlot : public SlotFunctorBase { public: FunctorCopySlot(const T& functor) : diff --git a/cegui/include/CEGUI/FunctorPointerSlot.h b/cegui/include/CEGUI/FunctorPointerSlot.h index 854c4bbfd..290f1ec49 100644 --- a/cegui/include/CEGUI/FunctorPointerSlot.h +++ b/cegui/include/CEGUI/FunctorPointerSlot.h @@ -38,7 +38,7 @@ namespace CEGUI object pointer. */ template -class FunctorPointerSlot : public SlotFunctorBase +class FunctorPointerSlot : public SlotFunctorBase { public: FunctorPointerSlot(T* functor) : diff --git a/cegui/include/CEGUI/FunctorReferenceSlot.h b/cegui/include/CEGUI/FunctorReferenceSlot.h index c76b4d8d2..79a2f991f 100644 --- a/cegui/include/CEGUI/FunctorReferenceSlot.h +++ b/cegui/include/CEGUI/FunctorReferenceSlot.h @@ -38,7 +38,7 @@ namespace CEGUI object reference. */ template -class FunctorReferenceSlot : public SlotFunctorBase +class FunctorReferenceSlot : public SlotFunctorBase { public: FunctorReferenceSlot(T& functor) : diff --git a/cegui/include/CEGUI/GUIContext.h b/cegui/include/CEGUI/GUIContext.h index b69b83deb..5050d4a80 100644 --- a/cegui/include/CEGUI/GUIContext.h +++ b/cegui/include/CEGUI/GUIContext.h @@ -28,9 +28,12 @@ #define _CEGUIGUIContext_h_ #include "CEGUI/RenderingSurface.h" -#include "CEGUI/InjectedInputReceiver.h" -#include "CEGUI/MouseCursor.h" -#include "CEGUI/SystemKeys.h" +#include "CEGUI/InputEventReceiver.h" +#include "CEGUI/SemanticInputEvent.h" +#include "CEGUI/Cursor.h" +#include "CEGUI/WindowNavigator.h" + +#include #if defined (_MSC_VER) # pragma warning(push) @@ -39,8 +42,6 @@ namespace CEGUI { -struct MouseClickTracker; - //! EventArgs class passed to subscribers for (most) GUIContext events. class CEGUIEXPORT GUIContextEventArgs : public EventArgs { @@ -66,13 +67,9 @@ class CEGUIEXPORT GUIContextRenderTargetEventArgs : public GUIContextEventArgs }; class CEGUIEXPORT GUIContext : public RenderingSurface, - public InjectedInputReceiver + public InputEventReceiver { public: - static const float DefaultMouseButtonClickTimeout; - static const float DefaultMouseButtonMultiClickTimeout; - static const Sizef DefaultMouseButtonMultiClickTolerance; - /** Name of Event fired when the root window is changed to a different * Window. * Handlers are passed a const WindowEventArgs reference with @@ -80,23 +77,6 @@ class CEGUIEXPORT GUIContext : public RenderingSurface, * obtained by calling GUIContext::getRootWindow). */ static const String EventRootWindowChanged; - /** Name of Event fired when the mouse movement scaling factor is changed. - * Handlers are passed a const reference to a GUIContextEventArgs struct. - */ - static const String EventMouseMoveScalingFactorChanged; - /** Name of Event fired when the mouse click timeout is changed. - * Handlers are passed a const reference to a GUIContextEventArgs struct. - */ - static const String EventMouseButtonClickTimeoutChanged; - /** Name of Event fired when the mouse multi-click timeout is changed. - * Handlers are passed a const reference to a GUIContextEventArgs struct. - */ - static const String EventMouseButtonMultiClickTimeoutChanged; - /** Name of Event fired when the mouse multi-click movement tolerance area - * size is changed. - * Handlers are passed a const reference to a GUIContextEventArgs struct. - */ - static const String EventMouseButtonMultiClickToleranceChanged; /** Name of Event fired when the RenderTarget for the GUIContext is changed. * Handlers are passed a const GUIContextRenderTargetEventArgs struct, with * the renderTarget member set to the old RenderTarget. @@ -126,74 +106,31 @@ class CEGUIEXPORT GUIContext : public RenderingSurface, //! Return a pointer to the Window that is currently set as modal. Window* getModalWindow() const; - Window* getWindowContainingMouse() const; + Window* getWindowContainingCursor() const; const Sizef& getSurfaceSize() const; - const SystemKeys& getSystemKeys() const; - //! call to indicate that some redrawing is required. void markAsDirty(); bool isDirty() const; /*! \brief - Retrieves MouseCursor used in this GUIContext + Retrieves Cursor used in this GUIContext \note - Please note that each GUIContext has exactly one MouseCursor. The MouseCursor + Please note that each GUIContext has exactly one Cursor. The Cursor class holds position, as well as other properties. If you want to modify - the MouseCursor (for example change its default image), you can retrieve + the Cursor (for example change its default image), you can retrieve a reference via this method and call a method on the reference (in our example that's setDefaultImage). */ - MouseCursor& getMouseCursor(); - const MouseCursor& getMouseCursor() const; - - void setMouseMoveScalingFactor(float factor); - float getMouseMoveScalingFactor() const; - - void setMouseButtonClickTimeout(float seconds); - float getMouseButtonClickTimeout() const; - - void setMouseButtonMultiClickTimeout(float seconds); - float getMouseButtonMultiClickTimeout() const; - - void setMouseButtonMultiClickTolerance(const Sizef& sz); - const Sizef& getMouseButtonMultiClickTolerance() const; - - /*! - \brief - Set whether automatic mouse button click and multi-click (i.e. - double-click and treble-click) event generation will occur. - - \param enable - - true to have mouse button click and multi-click events automatically - generated by the system from the basic button up and down event - injections. - - false if no automatic generation of events should occur. In this - instance the user may wish to use the additional event injectors to - manually inform the system of such events. - */ - void setMouseClickEventGenerationEnabled(const bool enable); - - /*! - \brief - Return whether automatic mouse button click and multi-click (i.e. - double-click and treble-click) event generation is enabled. + Cursor& getCursor(); + const Cursor& getCursor() const; - \return - - true if mouse button click and multi-click events will be - automatically generated by the system from the basic button up and down - event injections. - - false if no automatic generation of events will occur. In this - instance the user may wish to use the additional event injectors to - manually inform the system of such events. - */ - bool isMouseClickEventGenerationEnabled() const; - //! Tell the context to reconsider which window it thinks the mouse is in. - void updateWindowContainingMouse(); + //! Tell the context to reconsider which window it thinks the cursor is in. + void updateWindowContainingCursor(); Window* getInputCaptureWindow() const; void setInputCaptureWindow(Window* window); @@ -209,7 +146,7 @@ class CEGUIEXPORT GUIContext : public RenderingSurface, Tooltip is required. \note - When passing a pointer to a Tooltip object, ownership of the Tooltip + When passing a cursor to a Tooltip object, ownership of the Tooltip does not pass to the GUIContext. */ void setDefaultTooltipObject(Tooltip* tooltip); @@ -261,27 +198,34 @@ class CEGUIEXPORT GUIContext : public RenderingSurface, */ Font* getDefaultFont() const; - // Implementation of InjectedInputReceiver interface - bool injectMouseMove(float delta_x, float delta_y); - bool injectMouseLeaves(void); - bool injectMouseButtonDown(MouseButton button); - bool injectMouseButtonUp(MouseButton button); - bool injectKeyDown(Key::Scan scan_code); - bool injectKeyUp(Key::Scan scan_code); - bool injectChar(String::value_type code_point); - bool injectMouseWheelChange(float delta); - bool injectMousePosition(float x_pos, float y_pos); + /*! + \brief + Function to inject time pulses into the receiver. + + \param timeElapsed + float value indicating the amount of time passed, in seconds, since the last time this method was called. + + \return + Currently, this method always returns true unless there is no root + window or it is not effectively visible + */ bool injectTimePulse(float timeElapsed); - bool injectMouseButtonClick(const MouseButton button); - bool injectMouseButtonDoubleClick(const MouseButton button); - bool injectMouseButtonTripleClick(const MouseButton button); - bool injectCopyRequest(); - bool injectCutRequest(); - bool injectPasteRequest(); + + // Implementation of InputEventReceiver interface + bool injectInputEvent(const InputEvent& event); + + bool injectUndoRequest(); + bool injectRedoRequest(); // public overrides void draw(); + /*! + \brief + Sets a window navigator to be used for navigating in this context + */ + void setWindowNavigator(WindowNavigator* navigator); + protected: void updateRootWindowAreaRects() const; void drawWindowContentToTarget(); @@ -293,47 +237,49 @@ class CEGUIEXPORT GUIContext : public RenderingSurface, //! notify windows in a hierarchy using default font, when font changes. void notifyDefaultFontChanged(Window* hierarchy_root) const; - bool mouseMoveInjection_impl(MouseEventArgs& ma); - Window* getTargetWindow(const Vector2f& pt, const bool allow_disabled) const; - Window* getKeyboardTargetWindow() const; + Window* getTargetWindow(const glm::vec2& pt, const bool allow_disabled) const; + //! returns the window used as input target + Window* getInputTargetWindow() const; Window* getCommonAncestor(Window* w1, Window* w2) const; //! call some function for a chain of windows: (top, bottom] - void notifyMouseTransition(Window* top, Window* bottom, - void (Window::*func)(MouseEventArgs&), - MouseEventArgs& args) const; + void notifyCursorTransition(Window* top, Window* bottom, + void (Window::*func)(CursorInputEventArgs&), + CursorInputEventArgs& args) const; bool areaChangedHandler(const EventArgs& args); bool windowDestroyedHandler(const EventArgs& args); - - //! returns whether the window containing the mouse had changed. - bool updateWindowContainingMouse_impl() const; - void resetWindowContainingMouse(); + + //! returns whether the window containing the cursor had changed. + bool updateWindowContainingCursor_impl() const; + void resetWindowContainingCursor(); // event trigger functions. virtual void onRootWindowChanged(WindowEventArgs& args); - virtual void onMouseMoveScalingFactorChanged(GUIContextEventArgs& args); - virtual void onMouseButtonClickTimeoutChanged(GUIContextEventArgs& args); - virtual void onMouseButtonMultiClickTimeoutChanged(GUIContextEventArgs& args); - virtual void onMouseButtonMultiClickToleranceChanged(GUIContextEventArgs& args); virtual void onRenderTargetChanged(GUIContextRenderTargetEventArgs& args); virtual void onDefaultFontChanged(EventArgs& args); // protected overrides void drawContent(); + // Input event handlers + void initializeSemanticEventHandlers(); + void deleteSemanticEventHandlers(); + + bool handleTextInputEvent(const TextInputEvent& event); + bool handleSemanticInputEvent(const SemanticInputEvent& event); + bool handleCopyRequest(const SemanticInputEvent& event); + bool handleCutRequest(const SemanticInputEvent& event); + bool handlePasteRequest(const SemanticInputEvent& event); + bool handleScrollEvent(const SemanticInputEvent& event); + bool handleCursorMoveEvent(const SemanticInputEvent& event); + bool handleCursorMove_impl(CursorInputEventArgs& pa); + bool handleCursorLeave(const SemanticInputEvent& event); + bool handleCursorActivateEvent(const SemanticInputEvent& event); + bool handleCursorPressHoldEvent(const SemanticInputEvent& event); + Window* d_rootWindow; bool d_isDirty; - MouseCursor d_mouseCursor; - //! Scaling factor applied to injected mouse move deltas. - float d_mouseMovementScalingFactor; - //! should mouse click/multi-click events be automatically generated. - bool d_generateMouseClickEvents; - //! Timeout used to when detecting a single-click. - float d_mouseButtonClickTimeout; - //! Timeout used when detecting multi-click events. - float d_mouseButtonMultiClickTimeout; - //! Movement tolerance used when detecting multi-click events. - Sizef d_mouseButtonMultiClickTolerance; + Cursor d_cursor; mutable Tooltip* d_defaultTooltipObject; mutable bool d_weCreatedTooltipObject; @@ -344,16 +290,19 @@ class CEGUIEXPORT GUIContext : public RenderingSurface, //! a cache of the target surface size, allows returning by ref. Sizef d_surfaceSize; - mutable Window* d_windowContainingMouse; - mutable bool d_windowContainingMouseIsUpToDate; + mutable Window* d_windowContainingCursor; + mutable bool d_windowContainingCursorIsUpToDate; Window* d_modalWindow; Window* d_captureWindow; - SystemKeys d_systemKeys; - MouseClickTracker* d_mouseClickTrackers; + CursorsState d_cursorsState; Event::ScopedConnection d_areaChangedEventConnection; Event::ScopedConnection d_windowDestroyedEventConnection; + std::map*> d_semanticEventHandlers; + + //! the window navigator (if any) used to navigate the GUI + WindowNavigator* d_windowNavigator; }; } diff --git a/cegui/include/CEGUI/GUILayout_xmlHandler.h b/cegui/include/CEGUI/GUILayout_xmlHandler.h index 204585de5..2d4da551a 100644 --- a/cegui/include/CEGUI/GUILayout_xmlHandler.h +++ b/cegui/include/CEGUI/GUILayout_xmlHandler.h @@ -183,8 +183,7 @@ class GUILayout_xmlHandler : public XMLHandler Implementation Data *************************************************************************/ typedef std::pair WindowStackEntry; //!< Pair used as datatype for the window stack. second is false if the window is an autowindow. - typedef std::vector WindowStack; + typedef std::vector WindowStack; Window* d_root; //!< Will point to first window created. WindowStack d_stack; //!< Stack used to keep track of what we're doing to which window. PropertyCallback* d_propertyCallback; //!< Callback for every property loaded diff --git a/cegui/include/CEGUI/GeometryBuffer.h b/cegui/include/CEGUI/GeometryBuffer.h index 3d580b7ab..6106f8f86 100644 --- a/cegui/include/CEGUI/GeometryBuffer.h +++ b/cegui/include/CEGUI/GeometryBuffer.h @@ -1,9 +1,10 @@ /*********************************************************************** created: Thu Jan 8 2009 author: Paul D Turner + edited by Lukas Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -30,20 +31,73 @@ #include "CEGUI/Base.h" #include "CEGUI/Renderer.h" #include "CEGUI/Rect.h" +#include "CEGUI/RefCounted.h" +#include "CEGUI/RenderMaterial.h" + +#include +#include + +#include +#include //size_t + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + // Start of CEGUI namespace section namespace CEGUI { + +class RenderMaterial; + +//----------------------------------------------------------------------------// + +/*! +\brief + Enumerated type that contains the valid options to specify a vertex attribute + of a vertex used in CEGUI +*/ +enum VertexAttributeType +{ + //! Position 0 attribute + VAT_POSITION0, + //! Colour 0 attribute + VAT_COLOUR0, + //! Texture coordinate 0 attribute + VAT_TEXCOORD0 +}; + +//----------------------------------------------------------------------------// + +/*! +\brief + Enumerated type that contains the valid options for the fill rule mode. The + fill rule defines how overlaps of the polygon defined by this GeometryBuffer + should be rendered. For further information see "fill-rule" in the SVG + standard: http://www.w3.org/TR/SVGTiny12/painting.html#FillRuleProperty +*/ +enum PolygonFillRule +{ + //! Draw the polygon normally - without a fill-rule. + PFR_NONE, + //! Uses the nonzero rule to determine how the polygon is to be filled. + PFR_NON_ZERO, + //! Uses the evenodd rule to determine how the polygon is to be filled. + PFR_EVEN_ODD +}; + +//----------------------------------------------------------------------------// + /*! \brief Abstract class defining the interface for objects that buffer geometry for later rendering. */ -class CEGUIEXPORT GeometryBuffer : - public AllocatedObject +class CEGUIEXPORT GeometryBuffer { public: - //! Destructor virtual ~GeometryBuffer(); /*! @@ -57,20 +111,40 @@ class CEGUIEXPORT GeometryBuffer : Set the translation to be applied to the geometry in the buffer when it is subsequently rendered. - \param v + \param translation Vector3 describing the three axis translation vector to be used. */ - virtual void setTranslation(const Vector3f& v) = 0; + virtual void setTranslation(const glm::vec3& translation); /*! \brief Set the rotations to be applied to the geometry in the buffer when it is subsequently rendered. - \param r + \param rotationQuat Quaternion describing the rotation to be used. */ - virtual void setRotation(const Quaternion& r) = 0; + virtual void setRotation(const glm::quat& rotationQuat); + + /*! + \brief + Set the scaling to be applied to the geometry in the buffer when it is + subsequently rendered. + + \param scale + Vector3 describing the scale to be used. + */ + virtual void setScale(const glm::vec3& scale); + + /*! + \brief + Set the scaling to be applied to the geometry in the buffer when it is + subsequently rendered. + + \param scale + Vector2 describing the x and y scale to be used. + */ + void setScale(const glm::vec2& scale); /*! \brief @@ -80,7 +154,17 @@ class CEGUIEXPORT GeometryBuffer : Vector3 describing the location of the pivot point to be used when applying the rotation to the geometry. */ - virtual void setPivot(const Vector3f& p) = 0; + void setPivot(const glm::vec3& p); + + /*! + \brief + Set a custom transformation matrix that will be applied to the + geometry in the buffer after all the other transformations. + + \param transformation + 3x3 Matrix that describes the transformation. + */ + void setCustomTransform(const glm::mat4x4& transformation); /*! \brief @@ -88,6 +172,46 @@ class CEGUIEXPORT GeometryBuffer : */ virtual void setClippingRegion(const Rectf& region) = 0; + /*! + \brief + Sets the fill rule that should be used when rendering the geometry. + + \param fill_rule + The fill rule that should be used when rendering the geometry. + */ + void setStencilRenderingActive(PolygonFillRule fill_rule); + + /*! + \brief + Sets the number of vertices that should be rendered after the stencil buffer was filled. + + \param vertex_count + The number of vertices that should be rendered after the stencil buffer was filled. + */ + void setStencilPostRenderingVertexCount(unsigned int vertex_count); + + /*! + \brief + Append the geometry data to the existing data + + \param vertex_data + Pointer to an array of floats containing the geometry data that + should be added to the GeometryBuffer. + + \param array_size + The number of elements in the passed array. + */ + virtual void appendGeometry(const float* vertex_data, std::size_t array_size); + + /*! + \brief + Append a single vertex to the buffer. + + \param vertex + Vertex object describing the vertex to be added to the GeometryBuffer. + */ + virtual void appendVertex(const TexturedColouredVertex& vertex); + /*! \brief Append a single vertex to the buffer. @@ -95,75 +219,98 @@ class CEGUIEXPORT GeometryBuffer : \param vertex Vertex object describing the vertex to be added to the GeometryBuffer. */ - virtual void appendVertex(const Vertex& vertex) = 0; + virtual void appendVertex(const ColouredVertex& vertex); + + /*! + \brief + Appends vertices with colour attributes from an std::vector to the GeometryBuffer. + \param coloured_vertices + The vector of ColouredVertices. + */ + void appendGeometry(const std::vector& coloured_vertices); + + /*! + \brief + Append a number of vertices with colour attributes from an array to the GeometryBuffer. + + \param vertex_array + Pointer to an array of Vertex objects that describe the vertices that + are to be added to the GeometryBuffer. + + \param vertex_count + The number of Vertex objects from the array \a vertex_array that are to be + added to the GeometryBuffer. + */ + virtual void appendGeometry(const ColouredVertex* vertex_array, std::size_t vertex_count); + + /*! + \brief + Appends vertices with texture coordinate and colour attributes from an std::vector to + the GeometryBuffer. + \param textured_vertices + The vector of TexturedColouredVertices. + */ + void appendGeometry(const std::vector& textured_vertices); /*! \brief - Append a number of vertices from an array to the GeometryBuffer. + Append a number of vertices, with texture coordinate and colour attributes, + from an array to the GeometryBuffer. - \param vbuff + \param vertex_array Pointer to an array of Vertex objects that describe the vertices that are to be added to the GeometryBuffer. \param vertex_count - The number of Vertex objects from the array \a vbuff that are to be + The number of Vertex objects from the array \a vertex_array that are to be added to the GeometryBuffer. */ - virtual void appendGeometry(const Vertex* const vbuff, uint vertex_count)=0; + virtual void appendGeometry(const TexturedColouredVertex* vertex_array, std::size_t vertex_count); /*! \brief - Set the active texture to be used with all subsequently added vertices. + A helper function that sets a texture parameter of the RenderMaterial of this + Geometrybuffer. + + \param parameterName + Name of the parameter as used inside the shader program. The regular CEGUI + texture-parameter that is used inside CEGUI's materials is called "texture0". \param texture Pointer to a Texture object that shall be used for subsequently added vertices. This may be 0, in which case texturing will be disabled for subsequently added vertices. */ - virtual void setActiveTexture(Texture* texture) = 0; + virtual void setTexture(const std::string& parameterName, const Texture* texture); /*! \brief Clear all buffered data and reset the GeometryBuffer to the default - state. + state. This excludes resettings the vertex attributes. */ - virtual void reset() = 0; + virtual void reset(); /*! \brief - Return a pointer to the currently active Texture object. This may - return 0 if no texture is set. - - \return - Pointer the Texture object that is currently active, or 0 if texturing - is not being used. - */ - virtual Texture* getActiveTexture() const = 0; - - /*! - \brief - Return the total number of vertices currently held by this - GeometryBuffer object. + Returns the vertex count of this GeometryBuffer, which is determined based + on the the used vertex layout and the size of the vertex data \return The number of vertices that have been appended to this GeometryBuffer. */ - virtual uint getVertexCount() const = 0; + virtual std::size_t getVertexCount() const; /*! \brief - Return the number of batches of geometry that this GeometryBuffer has - split the vertices into. - - \note - How batching is done will be largely implementation specific, although - it would be reasonable to expect that you will have at least - one batch of geometry per texture switch. + Returns the total number of floats used by the attributes of the + current vertex layout. \return - The number of batches of geometry held by the GeometryBuffer. + The total number of floats used by the attributes of the current vertex + layout. */ - virtual uint getBatchCount() const = 0; + virtual int getVertexAttributeElementCount() const; + /*! \brief @@ -179,14 +326,14 @@ class CEGUIEXPORT GeometryBuffer : you need to be careful not to delete the RenderEffect if it might still be in use! */ - virtual void setRenderEffect(RenderEffect* effect) = 0; + virtual void setRenderEffect(RenderEffect* effect); /*! \brief Return the RenderEffect object that is assigned to this GeometryBuffer or 0 if none. */ - virtual RenderEffect* getRenderEffect() = 0; + virtual RenderEffect* getRenderEffect(); /*! \brief @@ -223,7 +370,7 @@ class CEGUIEXPORT GeometryBuffer : - false if vertices added after this call should not be clipped (other than to the edges of rendering target. */ - virtual void setClippingActive(const bool active) = 0; + virtual void setClippingActive(const bool active); /* \brief @@ -233,19 +380,157 @@ class CEGUIEXPORT GeometryBuffer : \return - true if vertices subsequently added to the GeometryBuffer will be clipped to the clipping region defined for this GeometryBuffer. - - false if vertices subsequently added will not be clippled (other than + - false if vertices subsequently added will not be clipped (other than to the edges of the rendering target). */ - virtual bool isClippingActive() const = 0; + virtual bool isClippingActive() const; + + /* + \brief + Resets the vertex attributes that were set for the vertices of this + GeometryBuffer. + */ + void resetVertexAttributes(); + + /* + \brief + Adds a vertex attributes to the list of vertex attributes. The vertex + attributes are used to describe the layout of the verrex data. The + order in which the attributes are added is the same order in which the + data has to be aligned for the vertex. This has be done before adding + actual vertex data to the GeometryBuffer. + + \param attribute + The attribute that should be added to the list of vertex attributes + describing the vertices of this GeometryBuffer. + */ + void addVertexAttribute(VertexAttributeType attribute); + + /* + \brief + Returns the RenderMaterial that is currently used by this GeometryBuffer. + + \return + A reference to the RenderMaterial that is used by this GeometryBuffer. + */ + RefCounted getRenderMaterial() const; + + /* + \brief + Set a new RenderMaterial to be used by this GeometryBuffer. + + \param render_material + A reference to the RenderMaterial that will be set to be used by this + GeometryBuffer. + */ + void setRenderMaterial(RefCounted render_material); + + /*! + \brief + Sets the alpha for this window + \param alpha The new alpha value in the range 0.f-1.f + */ + void setAlpha(float alpha); + + /*! + \brief + Gets the current alpha value + */ + float getAlpha() const; + + /*! + \brief + Invalidates the local matrix. This should be called whenever anything extraordinary + that requires to recalculate the matrix has occured + */ + void invalidateMatrix(); + + //TODO DOCU + const RenderTarget* getLastRenderTarget() const; + + /*! + \brief + Returns if the data (matrix etc) from the RenderTarget that was last used is still valid or not. + + \return + True if still valid. False if invalid. + */ + bool isRenderTargetDataValid(const RenderTarget* activeRenderTarget) const; + + //TODO DOCU + void updateRenderTargetData(const RenderTarget* activeRenderTarget) const; + + /* + \brief + Calculates and returns the model matrix for this GeometryBuffer. + + \return + The model matrix for this GeometryBuffer. + */ + glm::mat4 getModelMatrix() const; + protected: - //! Constructor. - GeometryBuffer(); + GeometryBuffer(RefCounted renderMaterial); + //! Reference to the RenderMaterial used for this GeometryBuffer + RefCounted d_renderMaterial; + + //! type of container used to store the geometry's vertex data + typedef std::vector VertexData; + //! The container in which the vertex data is stored. + VertexData d_vertexData; + //! The vertex count which is determined based on the used vertex layout + unsigned int d_vertexCount; + /* + \brief + A vector of the attributes of the vertices of this GeometryBuffer. The order + in which they were added to the vector is used to define the alignment of the + vertex data. + */ + std::vector d_vertexAttributes; + + + //! translation vector + glm::vec3 d_translation; + //! rotation quaternion + glm::quat d_rotation; + //! scaling vector + glm::vec3 d_scale; + //! pivot point for rotation + glm::vec3 d_pivot; + //! custom transformation matrix + glm::mat4x4 d_customTransform; + /* + \brief + true, when there have been no translations, rotations or other transformations applied to the GeometryBuffer, + as well as when it is guaranteed that the view projection matrix of the RenderTarget has been unchanged + since the last update. + */ + mutable bool d_matrixValid; + //! The RenderTarget that this GeometryBuffer's matrix was last updated for + mutable const RenderTarget* d_lastRenderTarget; + //! The activation number of the RenderTarget that this GeometryBuffer's matrix was last updated for + mutable unsigned int d_lastRenderTargetActivationCount; //! The BlendMode to use when rendering this GeometryBuffer. - BlendMode d_blendMode; + BlendMode d_blendMode; + //! The fill rule that should be used when rendering the geometry. + PolygonFillRule d_polygonFillRule; + //! The amount of vertices that need to be rendered after rendering to the stencil buffer. + unsigned int d_postStencilVertexCount; + //! RenderEffect that will be used by the GeometryBuffer + RenderEffect* d_effect; + //! True if clipping will be active for the current batch + bool d_clippingActive; + //! The alpha value which will be applied to the whole buffer when rendering + float d_alpha; + }; -} // End of CEGUI namespace section +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif -#endif // end of guard _CEGUIGeometryBuffer_h_ +#endif diff --git a/cegui/include/CEGUI/GlobalEventSet.h b/cegui/include/CEGUI/GlobalEventSet.h index 1e61b360b..130eb2bd7 100644 --- a/cegui/include/CEGUI/GlobalEventSet.h +++ b/cegui/include/CEGUI/GlobalEventSet.h @@ -48,8 +48,7 @@ namespace CEGUI */ class CEGUIEXPORT GlobalEventSet : public EventSet, - public Singleton, - public AllocatedObject + public Singleton { public: GlobalEventSet(); diff --git a/cegui/include/CEGUI/Image.h b/cegui/include/CEGUI/Image.h index 695e6ab58..c7192c625 100644 --- a/cegui/include/CEGUI/Image.h +++ b/cegui/include/CEGUI/Image.h @@ -32,6 +32,13 @@ #include "CEGUI/ColourRect.h" #include "CEGUI/Rect.h" +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + // Start of CEGUI namespace section namespace CEGUI { @@ -156,57 +163,211 @@ class PropertyHelper quad, or something more complex. */ class CEGUIEXPORT Image : - public AllocatedObject, public ChainedXMLHandler { public: + + /*! + \brief + A struct that contains the render settings for the Image class. + */ + struct ImageRenderSettings + { + //! Constructor + ImageRenderSettings(const Rectf& dest_area, + const Rectf* clip_area, + bool clipping_enabled, + const ColourRect& multiplication_colours = ColourRect(0XFFFFFFFF), + float alpha = 1.0f) : + d_destArea(dest_area), + d_clipArea(clip_area), + d_clippingEnabled(clipping_enabled), + d_multiplyColours(multiplication_colours), + d_alpha(alpha) + { + } + + ImageRenderSettings(const ImageRenderSettings& source) : + d_destArea(source.d_destArea), + d_clipArea(source.d_clipArea), + d_clippingEnabled(source.d_clippingEnabled), + d_multiplyColours(source.d_multiplyColours), + d_alpha(source.d_alpha) + { + } + + //! The destination area for the Image. + Rectf d_destArea; + //! The clipping area of the Image. + const Rectf* d_clipArea; + //! True of clipping should be enabled for the geometry of this Image. + bool d_clippingEnabled; + //! The colour rectangle set for this Image. The colours of the rectangle will be multiplied with + //! the Image's colours when rendered, i.e. if the colours are all '0xFFFFFFFF' no effect will be seen. + //! If this will be used depends on the underlying image. + ColourRect d_multiplyColours; + //! The alpha value for this image, should be set as the GeometryBuffer's + //! alpha by the underlying image class + float d_alpha; + }; + + + + //! Constructor + Image(const String& name); + Image(const String& name, const glm::vec2& pixel_offset, + const Rectf& image_area, AutoScaledMode auto_scaled, + const Sizef& native_resolution); + virtual ~Image(); - virtual const String& getName() const = 0; + /*! + \brief + Creates a GeometryBuffer from the Image, providing the data + needed for rendering. - virtual const Sizef& getRenderedSize() const = 0; - virtual const Vector2f& getRenderedOffset() const = 0; + \param geometry_buffers + The GeometryBuffer list to which the new geometry of this Image will be added to. + \param render_settings + The ImageRenderSettings that contain render settings for new GeometryBuffers. + */ + virtual void render(std::vector& geometry_buffers, + const ImageRenderSettings& render_settings) const = 0; + + /*! + \brief + Returns the name of the Image. - virtual void render(GeometryBuffer& buffer, - const Rectf& dest_area, - const Rectf* clip_area, - const ColourRect& colours) const = 0; + \return + The name of the Image. + */ + virtual const String& getName() const; + + /*! + \brief + Returns the rendered size of this Image considering the autoscale + options that were set. + + \return + The rendered size of this Image. + */ + virtual const Sizef& getRenderedSize() const; + + + /*! + \brief + Returns the rendered offset of this Image considering the autoscale + options that were set. + + \return + The rendered offset of this Image. + */ + virtual const glm::vec2& getRenderedOffset() const; + + /*! + \brief + Notifies the class that the display size of the renderer has changed so that + the window can adapt to the new display size accordingly. + + \param size + The new display size. + */ + virtual void notifyDisplaySizeChanged(const Sizef& renderer_display_size); + + /*! + \brief + Sets the rectangular image area of this Image. + + \param image_area + The rectangular image area of this Image. + */ + void setImageArea(const Rectf& image_area); + + /*! + \brief + Sets the pixel offset of this Image. + + \param pixel_offset + The pixel offset of this Image. + */ + void setOffset(const glm::vec2& pixel_offset); + + + /*! + \brief + Sets the autoscale mode of this Image. + + \param autoscaled + The autoscale mode of this Image. + */ + void setAutoScaled(const AutoScaledMode autoscaled); + + /*! + \brief + Sets the autoscale native resolution of this Image. + + \param autoscaled + The autoscale native resolution of this Image. + */ + void setNativeResolution(const Sizef& native_res); - virtual void notifyDisplaySizeChanged(const Sizef& size) = 0; // Standard Image::render overloads - void render(GeometryBuffer& buffer, - const Vector2f& position, - const Rectf* clip_area = 0) const + void render(std::vector& geometry_buffers, + const Rectf& dest_area, + const Rectf* clip_area, + bool clipping_enabled, + const ColourRect& multiplication_colours = ColourRect(0XFFFFFFFF), + float alpha = 1.0f) const + { + ImageRenderSettings render_settings(dest_area, clip_area, clipping_enabled, + multiplication_colours, alpha); + render(geometry_buffers, render_settings); + } + + void render(std::vector& geometry_buffers, + const glm::vec2& position, + const Rectf* clip_area = 0, + const bool clipping_enabled = false) const { - const ColourRect colours(0XFFFFFFFF); - render(buffer, Rectf(position, getRenderedSize()), clip_area, colours); + ImageRenderSettings render_settings(Rectf(position, getRenderedSize()), clip_area, clipping_enabled); + render(geometry_buffers, render_settings); } - void render(GeometryBuffer& buffer, - const Vector2f& position, + void render(std::vector& geometry_buffers, + const glm::vec2& position, const Rectf* clip_area, - const ColourRect& colours) const + const bool clipping_enabled, + const ColourRect& colours, + float alpha = 1.0f) const { - render(buffer, Rectf(position, getRenderedSize()), clip_area, colours); + ImageRenderSettings render_settings(Rectf(position, getRenderedSize()), + clip_area, clipping_enabled, colours, alpha); + render(geometry_buffers, render_settings); } - void render(GeometryBuffer& buffer, - const Vector2f& position, + void render(std::vector& geometry_buffers, + const glm::vec2& position, const Sizef& size, - const Rectf* clip_area = 0) const + const Rectf* clip_area = 0, + const bool clipping_enabled = false) const { - const ColourRect colours(0XFFFFFFFF); - render(buffer, Rectf(position, size), clip_area, colours); + ImageRenderSettings render_settings(Rectf(position, size), clip_area, clipping_enabled); + render(geometry_buffers, render_settings); } - void render(GeometryBuffer& buffer, - const Vector2f& position, + + void render(std::vector& geometry_buffers, + const glm::vec2& position, const Sizef& size, const Rectf* clip_area, - const ColourRect& colours) const + const bool clipping_enabled, + const ColourRect& colours, + float alpha = 1.0f) const { - render(buffer, Rectf(position, size), clip_area, colours); + ImageRenderSettings render_settings(Rectf(position, size), clip_area, + clipping_enabled, colours, alpha); + render(geometry_buffers, render_settings); } /*! @@ -228,9 +389,38 @@ class CEGUIEXPORT Image : void elementStartLocal(const String& element, const XMLAttributes& attributes); void elementEndLocal(const String& element); + + //! Updates the scaled size and offset values according to the new display size of the renderer + void updateScaledSizeAndOffset(const Sizef& renderer_display_size); + //! Updates only the scaled size values according to the new display size of the renderer + void updateScaledSize(const Sizef& renderer_display_size); + //! Updates only the scaled offset values according to the new display size of the renderer + void updateScaledOffset(const Sizef& renderer_display_size); + + //! Name used for the Image as defined during creation. + String d_name; + //! The rectangular area defined for this Image defining position and size of it in relation to + //! the underlying data of the Image. + Rectf d_imageArea; + //! The pixel offset of the Image. It defines ??? + glm::vec2 d_pixelOffset; + //! Whether image is auto-scaled or not and how. + AutoScaledMode d_autoScaled; + //! Native resolution used for autoscaling. + Sizef d_nativeResolution; + //! The size in pixels after having autoscaling applied. + Sizef d_scaledSize; + //! The offset in pixels after having autoscaling applied. + glm::vec2 d_scaledOffset; + }; } // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + #endif // end of guard _CEGUIImage_h_ diff --git a/cegui/include/CEGUI/ImageCodec.h b/cegui/include/CEGUI/ImageCodec.h index f65dfe524..1540919e5 100644 --- a/cegui/include/CEGUI/ImageCodec.h +++ b/cegui/include/CEGUI/ImageCodec.h @@ -42,8 +42,7 @@ namespace CEGUI This class define the loading of an abstract */ -class CEGUIEXPORT ImageCodec : - public AllocatedObject +class CEGUIEXPORT ImageCodec { public: /*! diff --git a/cegui/include/CEGUI/ImageFactory.h b/cegui/include/CEGUI/ImageFactory.h index 21013707d..eb2681841 100644 --- a/cegui/include/CEGUI/ImageFactory.h +++ b/cegui/include/CEGUI/ImageFactory.h @@ -40,8 +40,7 @@ namespace CEGUI \note This interface is intended for internal use only. */ -class ImageFactory : public - AllocatedObject +class ImageFactory { public: //! base class virtual destructor. @@ -74,21 +73,21 @@ class TplImageFactory : public ImageFactory template Image& TplImageFactory::create(const String& name) { - return *CEGUI_NEW_AO T(name); + return *new T(name); } //---------------------------------------------------------------------------// template Image& TplImageFactory::create(const XMLAttributes& attributes) { - return *CEGUI_NEW_AO T(attributes); + return *new T(attributes); } //---------------------------------------------------------------------------// template void TplImageFactory::destroy(Image& image) { - CEGUI_DELETE_AO ℑ + delete ℑ } //---------------------------------------------------------------------------// diff --git a/cegui/include/CEGUI/ImageManager.h b/cegui/include/CEGUI/ImageManager.h index 23129f99d..98fdf3c10 100644 --- a/cegui/include/CEGUI/ImageManager.h +++ b/cegui/include/CEGUI/ImageManager.h @@ -47,7 +47,6 @@ namespace CEGUI { class CEGUIEXPORT ImageManager : public Singleton, - public AllocatedObject, public ChainedXMLHandler { public: @@ -148,7 +147,7 @@ class CEGUIEXPORT ImageManager : void destroyImageCollection(const String& prefix, const bool delete_texture = true); - void addFromImageFile(const String& name, + void addBitmapImageFromFile(const String& name, const String& filename, const String& resource_group = ""); @@ -190,9 +189,7 @@ class CEGUIEXPORT ImageManager : typedef std::pair ImagePair; //! container type used to hold the images. - typedef std::map ImageMap; + typedef std::map ImageMap; //! ConstBaseIterator type definition. typedef ConstMapIterator ImageIterator; @@ -210,14 +207,20 @@ class CEGUIEXPORT ImageManager : void elementEndLocal(const String& element); //! container type used to hold the registered Image types. - typedef std::map ImageFactoryRegistry; + typedef std::map ImageFactoryRegistry; //! helper to delete an image given an map iterator. void destroy(ImageMap::iterator& iter); // XML parsing helper functions. void elementImagesetStart(const XMLAttributes& attributes); + + // Get or create the Imageset's texture + void retrieveImagesetTexture(const String& name, const String& filename, const String &resource_group); + + // Get or create the Imageset's SVGData + void retrieveImagesetSVGData(const String& name, const String& filename, const String &resource_group); + void elementImageStart(const XMLAttributes& attributes); //! throw exception if file version is not supported. void validateImagesetFileVersion(const XMLAttributes& attrs); @@ -239,7 +242,7 @@ void ImageManager::addImageType(const String& name) CEGUI_THROW(AlreadyExistsException( "Image type already exists: " + name)); - d_factories[name] = CEGUI_NEW_AO TplImageFactory; + d_factories[name] = new TplImageFactory; Logger::getSingleton().logEvent( "[CEGUI::ImageManager] Registered Image type: " + name); diff --git a/cegui/include/CEGUI/InjectedInputReceiver.h b/cegui/include/CEGUI/InjectedInputReceiver.h index 63aa02e10..00e5cc995 100644 --- a/cegui/include/CEGUI/InjectedInputReceiver.h +++ b/cegui/include/CEGUI/InjectedInputReceiver.h @@ -32,7 +32,7 @@ namespace CEGUI { -//! Input injection interface to be inplemented by classes that take raw inputs +//! Input injection interface to be implemented by classes that take raw inputs class CEGUIEXPORT InjectedInputReceiver { public: @@ -159,22 +159,10 @@ class CEGUIEXPORT InjectedInputReceiver */ virtual bool injectMousePosition(float x_pos, float y_pos) = 0; - /*! - \brief - Function to inject time pulses into the receiver. - - \param timeElapsed - float value indicating the amount of time passed, in seconds, since the last time this method was called. - - \return - Currently, this method always returns true. - */ - virtual bool injectTimePulse(float timeElapsed) = 0; - /*! \brief Function to directly inject a mouse button click event. - + Here 'click' means a mouse button down event followed by a mouse button up event. @@ -190,7 +178,7 @@ class CEGUIEXPORT InjectedInputReceiver \param button One of the MouseButton enumerated values. - + \return - true if some window or handler reported that it handled the event. - false if nobody handled the event. @@ -200,7 +188,7 @@ class CEGUIEXPORT InjectedInputReceiver /*! \brief Function to directly inject a mouse button double-click event. - + Here 'double-click' means a single mouse button had the sequence down, up, down within a predefined period of time. @@ -216,7 +204,7 @@ class CEGUIEXPORT InjectedInputReceiver \param button One of the MouseButton enumerated values. - + \return - true if some window or handler reported that it handled the event. - false if nobody handled the event. @@ -226,7 +214,7 @@ class CEGUIEXPORT InjectedInputReceiver /*! \brief Function to directly inject a mouse button triple-click event. - + Here 'triple-click' means a single mouse button had the sequence down, up, down, up, down within a predefined period of time. @@ -242,37 +230,37 @@ class CEGUIEXPORT InjectedInputReceiver \param button One of the MouseButton enumerated values. - + \return - true if some window or handler reported that it handled the event. - false if nobody handled the event. */ virtual bool injectMouseButtonTripleClick(const MouseButton button) = 0; - + /*! \brief Tells the receiver to perform a clipboard copy operation. - + \return - true if the copy was successful - false if the copy was denied */ virtual bool injectCopyRequest() = 0; - + /*! \brief Tells the system to perform a clipboard cut operation. - + \return - true if the cut was successful - false if the cut was denied */ virtual bool injectCutRequest() = 0; - + /*! \brief Tells the system to perform a clipboard paste operation. - + \return - true if the paste was successful - false if the paste was denied diff --git a/cegui/include/CEGUI/InputAggregator.h b/cegui/include/CEGUI/InputAggregator.h new file mode 100644 index 000000000..6af45e9e7 --- /dev/null +++ b/cegui/include/CEGUI/InputAggregator.h @@ -0,0 +1,269 @@ +/*********************************************************************** + created: 10/7/2013 + author: Timotei Dolean + + purpose: Generates input events from injected input +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIInputAggregator_h_ +#define _CEGUIInputAggregator_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/Event.h" +#include "CEGUI/EventSet.h" +#include "CEGUI/InjectedInputReceiver.h" +#include "CEGUI/InputEventReceiver.h" +#include "CEGUI/SemanticInputEvent.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +struct MouseClickTracker; + +//! EventArgs class passed to subscribers for (most) InputAggregator events. +class CEGUIEXPORT InputAggregatorEventArgs : public EventArgs +{ +public: + InputAggregatorEventArgs(InputAggregator* aggregator): + d_aggregator(aggregator) + {} + + //! pointer to the InputAggregator that triggered the event. + InputAggregator* d_aggregator; +}; + +/*! +\brief + Aggregates the input from multiple input devices and processes it to generate + input events which are then fed to the (optional) \ref InputEventReceiver. +*/ +class CEGUIEXPORT InputAggregator : public InjectedInputReceiver, + public EventSet +{ +public: + static const float DefaultMouseButtonClickTimeout; + static const float DefaultMouseButtonMultiClickTimeout; + static const Sizef DefaultMouseButtonMultiClickTolerance; + + /** Name of Event fired when the mouse click timeout is changed. + * Handlers are passed a const reference to a GUIContextEventArgs struct. + */ + static const String EventMouseButtonClickTimeoutChanged; + /** Name of Event fired when the mouse multi-click timeout is changed. + * Handlers are passed a const reference to a GUIContextEventArgs struct. + */ + static const String EventMouseButtonMultiClickTimeoutChanged; + /** Name of Event fired when the mouse multi-click movement tolerance area + * size is changed. + * Handlers are passed a const reference to a GUIContextEventArgs struct. + */ + static const String EventMouseButtonMultiClickToleranceChanged; + /** Name of Event fired when the mouse movement scaling factor is changed. + * Handlers are passed a const reference to a GUIContextEventArgs struct. + */ + static const String EventMouseMoveScalingFactorChanged; + + InputAggregator(InputEventReceiver* input_receiver); + virtual ~InputAggregator(); + + /*! + \brief + Initialises this InputAggregator with some default simple-key mappings + \param handle_on_keyup + When set to true semantic actions will be registered on key up + otherwise semantic actions are handled on key down. If false + it is recommended to call setModifierKeys before any injectKeyDown + calls to make sure that modifiers are properly set. + */ + virtual void initialise(bool handle_on_keyup = true); + + /*! + \brief + Set whether automatic mouse button click and multi-click (i.e. + double-click and treble-click) event generation will occur. + + \param enable + - true to have mouse button click and multi-click events automatically + generated by the system from the basic button up and down event + injections. + - false if no automatic generation of events should occur. In this + instance the user may wish to use the additional event injectors to + manually inform the system of such events. + */ + void setMouseClickEventGenerationEnabled(const bool enable); + + /*! + \brief + Return whether automatic mouse button click and multi-click (i.e. + double-click and treble-click) event generation is enabled. + + \return + - true if mouse button click and multi-click events will be + automatically generated by the system from the basic button up and down + event injections. + - false if no automatic generation of events will occur. In this + instance the user may wish to use the additional event injectors to + manually inform the system of such events. + */ + bool isMouseClickEventGenerationEnabled() const; + + void setMouseButtonClickTimeout(float seconds); + float getMouseButtonClickTimeout() const; + + void setMouseButtonMultiClickTimeout(float seconds); + float getMouseButtonMultiClickTimeout() const; + + /*! + \brief + Sets the mouse multi-click tolerance size + + \param sz + The size of the tolerance in percent of the display's size + */ + void setMouseButtonMultiClickTolerance(const Sizef& sz); + + /*! + \brief + Returns the mouse multi-click tolerance size + + \return + A size structure with the zone's width and height in percent of the + display's size + */ + const Sizef& getMouseButtonMultiClickTolerance() const; + + void setMouseMoveScalingFactor(float factor); + float getMouseMoveScalingFactor() const; + + /*! + \brief + Returns a semantic action matching the scan_code + */ + int getSemanticAction(Key::Scan scan_code, bool shift_down, bool alt_down, + bool ctrl_down) const; + + /*! + \brief + Gets semantic action for scan_code and sends the event + \return + True if the semantic action was handled + */ + bool handleScanCode(Key::Scan scan_code, bool shift_down, bool alt_down, + bool ctrl_down); + + /*! + \brief + Sets the status of modifier keys to the specified values. + + Call this before injectKeyDown if InputAggregator is set to handle + actions on keydown. + */ + void setModifierKeys(bool shift_down, bool alt_down, bool ctrl_down); + + /************************************************************************/ + /* InjectedInputReceiver interface implementation */ + /************************************************************************/ + virtual bool injectMouseMove(float delta_x, float delta_y); + virtual bool injectMouseLeaves(); + + virtual bool injectMouseButtonDown(MouseButton button); + virtual bool injectMouseButtonUp(MouseButton button); + + /*! + \return + True if set to handle keys on key down and the input was consumed. + When not to set handle actions on key down will always return true. + */ + virtual bool injectKeyDown(Key::Scan scan_code); + /*! + \return + True if set to handle keys on key up and the input was consumed. + When not to set handle actions on key up will always return true. + */ + virtual bool injectKeyUp(Key::Scan scan_code); + + virtual bool injectChar(String::value_type code_point); + virtual bool injectMouseWheelChange(float delta); + virtual bool injectMousePosition(float x_pos, float y_pos); + + virtual bool injectMouseButtonClick(const MouseButton button); + virtual bool injectMouseButtonDoubleClick(const MouseButton button); + virtual bool injectMouseButtonTripleClick(const MouseButton button); + + virtual bool injectCopyRequest(); + virtual bool injectCutRequest(); + virtual bool injectPasteRequest(); + +protected: + virtual void onMouseButtonClickTimeoutChanged(InputAggregatorEventArgs& args); + virtual void onMouseButtonMultiClickTimeoutChanged(InputAggregatorEventArgs& args); + virtual void onMouseButtonMultiClickToleranceChanged(InputAggregatorEventArgs& args); + virtual void onMouseMoveScalingFactorChanged(InputAggregatorEventArgs& args); + + virtual bool isControlPressed(); + virtual bool isAltPressed(); + virtual bool isShiftPressed(); + + void recomputeMultiClickAbsoluteTolerance(); + virtual bool onDisplaySizeChanged(const EventArgs& args); + + Event::Connection d_displaySizeChangedConnection; + + InputEventReceiver* d_inputReceiver; + + //! Timeout used to when detecting a single-click. + float d_mouseButtonClickTimeout; + //! Timeout used when detecting multi-click events. + float d_mouseButtonMultiClickTimeout; + //! Movement tolerance (percent) used when detecting multi-click events. + Sizef d_mouseButtonMultiClickTolerance; + //! Movement tolerance (absolute) used when detecting multi-click events. + Sizef d_mouseButtonMultiClickAbsoluteTolerance; + //! should mouse click/multi-click events be automatically generated. + bool d_generateMouseClickEvents; + MouseClickTracker* d_mouseClickTrackers; + + //! When set to true will handle semantic actions on key up + bool d_handleInKeyUp; + + //! Scaling factor applied to injected cursor move deltas. + float d_mouseMovementScalingFactor; + + glm::vec2 d_pointerPosition; + int d_keyValuesMappings[0xFF]; //!< Mapping from a key to its semantic + bool d_keysPressed[0xFF]; +}; + +} // End of CEGUI namespace section + +#if defined (_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIInputEvents_h_ diff --git a/cegui/include/CEGUI/InputEvent.h b/cegui/include/CEGUI/InputEvent.h index de9447f44..c4d528fc1 100644 --- a/cegui/include/CEGUI/InputEvent.h +++ b/cegui/include/CEGUI/InputEvent.h @@ -34,6 +34,7 @@ #include "CEGUI/String.h" #include "CEGUI/Vector.h" #include "CEGUI/Size.h" +#include "CEGUI/SemanticInputEvent.h" #if defined(_MSC_VER) # pragma warning(push) @@ -201,7 +202,6 @@ struct CEGUIEXPORT Key }; - /*! \brief Enumeration of mouse buttons @@ -224,6 +224,19 @@ enum MouseButton NoButton }; +static CursorInputSource convertToCursorInputSource(MouseButton button) +{ + if (button == LeftButton) + return CIS_Left; + + if (button == RightButton) + return CIS_Right; + + if (button == MiddleButton) + return CIS_Middle; + + return CIS_None; +} /*! \brief @@ -256,6 +269,19 @@ class CEGUIEXPORT WindowEventArgs : public EventArgs Window* window; //!< pointer to a Window object of relevance to the event. }; +/*! +\brief + Event arguments used by semantic input event handlers +*/ +class CEGUIEXPORT SemanticEventArgs : public WindowEventArgs +{ +public: + SemanticEventArgs(Window* wnd) : WindowEventArgs(wnd) {} + + int d_semanticValue; //!< The type of the semantic value + SemanticPayload d_payload; //!< The payload of the event +}; + /*! \brief WindowEventArgs class that is primarily used by lua scripts @@ -271,57 +297,56 @@ class CEGUIEXPORT UpdateEventArgs : public WindowEventArgs float d_timeSinceLastFrame; //!< Time since the last frame update }; - /*! \brief - EventArgs based class that is used for objects passed to input event handlers - concerning mouse input. + EventArgs based class that is used for objects passed to input event handlers + concerning cursor input. */ -class CEGUIEXPORT MouseEventArgs : public WindowEventArgs +class CEGUIEXPORT CursorInputEventArgs : public WindowEventArgs { public: - MouseEventArgs(Window* wnd) : WindowEventArgs(wnd) {} - - Vector2f position; //!< holds current mouse position. - Vector2f moveDelta; //!< holds variation of mouse position from last mouse input - MouseButton button; //!< one of the MouseButton enumerated values describing the mouse button causing the event (for button inputs only) - uint sysKeys; //!< current state of the system keys and mouse buttons. - float wheelChange; //!< Holds the amount the scroll wheel has changed. - uint clickCount; //!< Holds number of mouse button down events currently counted in a multi-click sequence (for button inputs only). + CursorInputEventArgs(Window* wnd) : WindowEventArgs(wnd) {} + + //!< holds current cursor position. + glm::vec2 position; + //!< holds variation of cursor position from last cursor input + glm::vec2 moveDelta; + // one of the CursorInputSource enumerated values describing the source causing the event + CursorInputSource source; + // holds the amount of the scroll + float scroll; + + // current state (hold: true/false) of cursors sources. Addressable by members of \ref CursorInputSource + CursorsState state; }; - /*! \brief - EventArgs based class that is used for objects passed to input event handlers - concerning mouse cursor events. + EventArgs based class that is used for objects passed to input event handlers + concerning cursor events. */ -class CEGUIEXPORT MouseCursorEventArgs : public EventArgs +class CEGUIEXPORT CursorEventArgs : public EventArgs { public: - MouseCursorEventArgs(MouseCursor* cursor) : mouseCursor(cursor) {} + CursorEventArgs(Cursor* cursor) : d_cursor(cursor) {} - MouseCursor* mouseCursor; //!< pointer to a MouseCursor object of relevance to the event. - const Image* image; //!< pointer to an Image object of relevance to the event. + Cursor* d_cursor; //!< pointer to a Cursor object of relevance to the event. + const Image* d_image; //!< pointer to an Image object of relevance to the event. }; - /*! \brief EventArgs based class that is used for objects passed to input event handlers - concerning keyboard input. + concerning text input. */ -class CEGUIEXPORT KeyEventArgs : public WindowEventArgs +class CEGUIEXPORT TextEventArgs : public WindowEventArgs { public: - KeyEventArgs(Window* wnd) : WindowEventArgs(wnd) {} + TextEventArgs(Window* wnd) : WindowEventArgs(wnd) {} - String::value_type codepoint; //!< utf32 or char (depends on used String class) codepoint for the key (only used for Character inputs). - Key::Scan scancode; //!< Scan code of key that caused event (only used for key up & down inputs. - uint sysKeys; //!< current state of the system keys and mouse buttons. + String::value_type character; //!< utf32 or char (depends on used String class) codepoint for the character of the text. }; - /*! \brief EventArgs based class that is used for Activated and Deactivated window events diff --git a/cegui/include/CEGUI/InputEventReceiver.h b/cegui/include/CEGUI/InputEventReceiver.h new file mode 100644 index 000000000..10088813f --- /dev/null +++ b/cegui/include/CEGUI/InputEventReceiver.h @@ -0,0 +1,61 @@ +/*********************************************************************** + created: 10/7/2013 + author: Timotei Dolean + + purpose: Provides an interface for injecting input events +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIInputEventReceiver_h_ +#define _CEGUIInputEventReceiver_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/InputEvents.h" + +// Start of CEGUI namespace section +namespace CEGUI +{ + +//! Interface to be implemented by classes that handle input events +class CEGUIEXPORT InputEventReceiver +{ +public: + virtual ~InputEventReceiver() {} + + /*! + \brief + Injects a new input event. + + \param event + The input event to be injected. + + \return + - true if the input was processed by the input receiver. + - false if the input was not processed by the input receiver. + */ + virtual bool injectInputEvent(const InputEvent& event) = 0; +}; + +} // End of CEGUI namespace section + +#endif // end of guard _CEGUIInputEventReceiver_h_ diff --git a/cegui/include/CEGUI/InputEvents.h b/cegui/include/CEGUI/InputEvents.h new file mode 100644 index 000000000..dfc7c4fae --- /dev/null +++ b/cegui/include/CEGUI/InputEvents.h @@ -0,0 +1,124 @@ +/*********************************************************************** + created: 10/7/2013 + author: Timotei Dolean + + purpose: Holds the input events which are used by the Input Aggregator +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIInputEvents_h_ +#define _CEGUIInputEvents_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/EventArgs.h" +#include "CEGUI/SlotFunctorBase.h" +#include "CEGUI/String.h" +#include "CEGUI/Vector.h" +#include "CEGUI/Size.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +/*! +\brief + The default input events used inside CEGUI +*/ +enum InputEventType +{ + IET_TextInputEventType = 0x0001, //!< Text was inputted. + IET_SemanticInputEventType = 0x0002, //!< An event with a certain semantic + + IET_UserDefinedInputEventType = 0x5000, //!< This marks the beginning of user-defined events. +}; + +/*! +\brief + The base class for all input events. +*/ +class CEGUIEXPORT InputEvent +{ +public: + InputEvent(int event_type) : d_eventType(event_type) {} + virtual ~InputEvent() {} + + int d_eventType; //!< The type of the input event +}; + +/*! +\brief + Represents the input of a character +*/ +class CEGUIEXPORT TextInputEvent : public InputEvent +{ +public: + TextInputEvent() : InputEvent(IET_TextInputEventType) {} + + char d_character; //!< The character inputted +}; + +/*! +\brief + Slot template class that creates a functor that calls back via a class + member function and send a casted input event subclass as the parameter. + +\tparam T + The type of the class the contains the handler + +\tparam TInput + A subclass of InputEvent or InputEvent itself to cast the input event to + before calling the functor +*/ +template +class InputEventHandlerSlot : public SlotFunctorBase +{ +public: + //! Member function slot type. + typedef bool(T::*MemberFunctionType)(const TInput&); + + InputEventHandlerSlot(MemberFunctionType func, T* obj) : + d_function(func), + d_object(obj) + {} + + virtual bool operator()(const InputEvent& arg) + { + return (d_object->*d_function)(static_cast(arg)); + } + +private: + MemberFunctionType d_function; + T* d_object; +}; + +} // End of CEGUI namespace section + +#if defined (_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIInputEvents_h_ diff --git a/cegui/include/CEGUI/Interpolator.h b/cegui/include/CEGUI/Interpolator.h index 4ca7dfc1b..96a4e36a1 100644 --- a/cegui/include/CEGUI/Interpolator.h +++ b/cegui/include/CEGUI/Interpolator.h @@ -50,8 +50,7 @@ namespace CEGUI \see AnimationManager */ -class CEGUIEXPORT Interpolator : - public AllocatedObject +class CEGUIEXPORT Interpolator { public: //! destructor diff --git a/cegui/include/CEGUI/JustifiedRenderedString.h b/cegui/include/CEGUI/JustifiedRenderedString.h index a2aaaf368..a18d6cb63 100644 --- a/cegui/include/CEGUI/JustifiedRenderedString.h +++ b/cegui/include/CEGUI/JustifiedRenderedString.h @@ -51,8 +51,8 @@ class CEGUIEXPORT JustifiedRenderedString : public FormattedRenderedString // implementation of base interface void format(const Window* ref_wnd, const Sizef& area_size); - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const; size_t getFormattedLineCount() const; float getHorizontalExtent(const Window* ref_wnd) const; @@ -60,8 +60,7 @@ class CEGUIEXPORT JustifiedRenderedString : public FormattedRenderedString protected: //! space extra size for each line to achieve justified formatting. - std::vector d_spaceExtras; + std::vector d_spaceExtras; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/KeyFrame.h b/cegui/include/CEGUI/KeyFrame.h index b8e209cf4..d33eb6c93 100644 --- a/cegui/include/CEGUI/KeyFrame.h +++ b/cegui/include/CEGUI/KeyFrame.h @@ -46,8 +46,7 @@ namespace CEGUI \see Affector */ -class CEGUIEXPORT KeyFrame : - public AllocatedObject +class CEGUIEXPORT KeyFrame { public: //! enumerates possible progression methods, IE how the value progresses diff --git a/cegui/include/CEGUI/LeftAlignedRenderedString.h b/cegui/include/CEGUI/LeftAlignedRenderedString.h index f8ac2f2fd..6c6af5936 100644 --- a/cegui/include/CEGUI/LeftAlignedRenderedString.h +++ b/cegui/include/CEGUI/LeftAlignedRenderedString.h @@ -45,8 +45,8 @@ class CEGUIEXPORT LeftAlignedRenderedString : public FormattedRenderedString // implementation of base interface void format(const Window* ref_wnd, const Sizef& area_size); - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const; size_t getFormattedLineCount() const; float getHorizontalExtent(const Window* ref_wnd) const; diff --git a/cegui/include/CEGUI/LinkedEvent.h b/cegui/include/CEGUI/LinkedEvent.h index 0b8cdd3f4..a1dde7733 100644 --- a/cegui/include/CEGUI/LinkedEvent.h +++ b/cegui/include/CEGUI/LinkedEvent.h @@ -86,8 +86,7 @@ class CEGUIEXPORT LinkedEvent : public Event LinkedEvent(const LinkedEvent& e) : Event(e) {} - typedef std::vector LinkedConnections; + typedef std::vector LinkedConnections; //! collection of connection to the linked Events. LinkedConnections d_connections; //! reference to the event set that we added ourself to diff --git a/cegui/include/CEGUI/Logger.h b/cegui/include/CEGUI/Logger.h index 1c7db74af..959a74c51 100644 --- a/cegui/include/CEGUI/Logger.h +++ b/cegui/include/CEGUI/Logger.h @@ -70,8 +70,7 @@ enum LoggingLevel a object of that type before you create the CEGUI::System singleton. */ class CEGUIEXPORT Logger : - public Singleton, - public AllocatedObject + public Singleton { public: /*! diff --git a/cegui/include/CEGUI/MemberFunctionSlot.h b/cegui/include/CEGUI/MemberFunctionSlot.h index 6ab481922..7faf46749 100644 --- a/cegui/include/CEGUI/MemberFunctionSlot.h +++ b/cegui/include/CEGUI/MemberFunctionSlot.h @@ -38,7 +38,7 @@ namespace CEGUI member function. */ template -class MemberFunctionSlot : public SlotFunctorBase +class MemberFunctionSlot : public SlotFunctorBase { public: //! Member function slot type. diff --git a/cegui/include/CEGUI/MemoryAllocatedObject.h b/cegui/include/CEGUI/MemoryAllocatedObject.h deleted file mode 100644 index bddc75589..000000000 --- a/cegui/include/CEGUI/MemoryAllocatedObject.h +++ /dev/null @@ -1,120 +0,0 @@ -/*********************************************************************** - created: 28/10/2010 - author: Martin Preisler (inspired by Ogre3D) - - purpose: Overrides new an delete operators and uses given Allocator -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIMemoryAllocatedObject_h_ -#define _CEGUIMemoryAllocatedObject_h_ - -#ifndef _CEGUIMemoryAllocation_h_ -# error Dont include this directly! Include CEGUIBase.h instead. -#endif - -namespace CEGUI -{ - -#ifdef CEGUI_CUSTOM_ALLOCATORS - -/*! -\brief - Defines a 'allocated object' class - - This is used to allocate CEGUI classes via custom allocators. It's - basically a wrapper that calls given Allocator when new/delete is called. - This is managed via overloading of new and delete operators. -*/ -template -class AllocatedObject -{ -public: - typedef typename AllocatorConfig::Allocator Allocator; - - inline explicit AllocatedObject() - {} - -#ifndef CEGUI_CUSTOM_ALLOCATORS_DEBUG - inline void* operator new(size_t size) - { - return Allocator::allocateBytes(size); - } -#else - inline void* operator new(size_t size, const char* file, int line, const char* func) - { - return Allocator::allocateBytes(size, file, line, func); - } -#endif - - inline void operator delete(void* ptr) - { - Allocator::deallocateBytes(ptr); - } - -#ifndef CEGUI_CUSTOM_ALLOCATORS_DEBUG - inline void* operator new[] (size_t size) - { - return Allocator::allocateBytes(size); - } -#else - inline void* operator new[] (size_t size, const char* file, int line, const char* func) - { - return Allocator::allocateBytes(size, file, line, func); - } -#endif - - inline void operator delete[] (void* ptr) - { - Allocator::deallocateBytes(ptr); - } - - // todo: does debug variant even make sense with placement new? - inline void* operator new(size_t size, void* ptr) - { - (void) size; - return ptr; - } - - inline void operator delete(void* ptr, void*) - { - Allocator::deallocateBytes(ptr); - } -}; - -#else - -// allocated object is just a stub template class if custom memory allocators aren't used -template -class AllocatedObject -{ -public: - inline explicit AllocatedObject() - {} -}; - -#endif - -} - -#endif // end of guard _CEGUIMemoryAllocatedObject_h_ diff --git a/cegui/include/CEGUI/MemoryAllocation.h b/cegui/include/CEGUI/MemoryAllocation.h deleted file mode 100644 index 8d6a07101..000000000 --- a/cegui/include/CEGUI/MemoryAllocation.h +++ /dev/null @@ -1,125 +0,0 @@ -/*********************************************************************** - created: 14/10/2010 - author: Martin Preisler (inspired by Ogre3D) - - purpose: Allows custom memory allocators to be used within CEGUI -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIMemoryAllocation_h_ -#define _CEGUIMemoryAllocation_h_ - -#ifndef _CEGUIBase_h_ -# error Dont include this directly! Include CEGUIBase.h instead. -#endif - -#define CEGUI_SET_DEFAULT_ALLOCATOR(A)\ -template\ -struct AllocatorConfig\ -{\ - typedef A Allocator;\ -}; - -#define CEGUI_SET_ALLOCATOR(Class, A)\ -template<>\ -struct AllocatorConfig\ -{\ - typedef A Allocator;\ -}; - -#ifdef CEGUI_CUSTOM_ALLOCATORS - -namespace CEGUI -{ - -// stub classes uses for allocator configuration -class STLAllocator {}; -class BufferAllocator {}; - -// borrowed from Ogre, used to construct arrays -template -T* constructN(T* basePtr, size_t count) -{ - for (size_t i = 0; i < count; ++i) - { - new ((void*)(basePtr+i)) T(); - } - return basePtr; -} - -// ogre doesn't do this template but I added it because it works even for types without -// destructors where I was getting syntax errors with just the macro -template -void destructN(T* basePtr, size_t count) -{ - // iterate in reverse for consistency with delete [] - for (size_t i = count - 1; i-- > 0;) - { - basePtr[i].~T(); - } -} - -} // CEGUI namespace - -#ifndef CEGUI_CUSTOM_ALLOCATORS_DEBUG -# define CEGUI_NEW_AO new -# define CEGUI_DELETE_AO delete -// for primitive types, types not inherited from AllocatedObject -# define CEGUI_NEW_PT(T, A) new (::CEGUI::AllocatorConfig::Allocator::allocateBytes(sizeof(T))) T -# define CEGUI_NEW_ARRAY_PT(T, count, A) ::CEGUI::constructN(static_cast(::CEGUI::AllocatorConfig::Allocator::allocateBytes(sizeof(T)*(count))), count) -# define CEGUI_DELETE_PT(ptr, T, A) do{if(ptr){(ptr)->~T(); ::CEGUI::AllocatorConfig::Allocator::deallocateBytes((void*)ptr);}}while(0) -# define CEGUI_DELETE_ARRAY_PT(ptr, T, count, A) do{if(ptr){ ::CEGUI::destructN(static_cast(ptr), count); ::CEGUI::AllocatorConfig::Allocator::deallocateBytes((void*)ptr);}}while(0) -#else -# define CEGUI_NEW_AO new(__FILE__, __LINE__, __FUNCTION__) -# define CEGUI_DELETE_AO delete -// for primitive types, types not inherited from AllocatedObject -# define CEGUI_NEW_PT(T, A) new (::CEGUI::AllocatorConfig::Allocator::allocateBytes(sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T -# define CEGUI_NEW_ARRAY_PT(T, count, A) ::CEGUI::constructN(static_cast(::CEGUI::AllocatorConfig::Allocator::allocateBytes(sizeof(T)*(count), __FILE__, __LINE__, __FUNCTION__)), count) -# define CEGUI_DELETE_PT(ptr, T, A) do{if(ptr){(ptr)->~T(); ::CEGUI::AllocatorConfig::Allocator::deallocateBytes((void*)ptr);}}while(0) -# define CEGUI_DELETE_ARRAY_PT(ptr, T, count, A) do{if(ptr){for (size_t b = count; b-- > 0;){ (ptr)[b].~T();} ::CEGUI::AllocatorConfig::Allocator::deallocateBytes((void*)ptr);}}while(0) -#endif - -#ifndef CEGUI_CUSTOM_ALLOCATORS_INCLUDE -# define CEGUI_CUSTOM_ALLOCATORS_INCLUDE "CEGUI/MemoryStdAllocator.h" -#endif - -// all the wrappers have been declared, now we include the chosen memory allocator file -#include CEGUI_CUSTOM_ALLOCATORS_INCLUDE - -#else - -// dummy macros -#define CEGUI_NEW_AO new -#define CEGUI_DELETE_AO delete -// for primitive types, types not inherited from AllocatedObject -#define CEGUI_NEW_PT(T, Allocator) new T -#define CEGUI_NEW_ARRAY_PT(T, count, Allocator) new T[count] -#define CEGUI_DELETE_PT(ptr, T, Allocator) delete ptr -#define CEGUI_DELETE_ARRAY_PT(ptr, T, count, Allocator) delete [] ptr - -#endif - -#include "CEGUI/MemoryAllocatedObject.h" -#include "CEGUI/MemorySTLWrapper.h" - -#endif // end of guard _CEGUIMemoryAllocation_h_ diff --git a/cegui/include/CEGUI/MemorySTLWrapper.h b/cegui/include/CEGUI/MemorySTLWrapper.h deleted file mode 100644 index 44274e592..000000000 --- a/cegui/include/CEGUI/MemorySTLWrapper.h +++ /dev/null @@ -1,167 +0,0 @@ -/*********************************************************************** - created: 28/10/2010 - author: Martin Preisler (inspired by Ogre3D) - - purpose: Wraps CEGUI Allocators to std::allocator class -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIMemorySTLWrapper_h_ -#define _CEGUIMemorySTLWrapper_h_ - -#ifndef _CEGUIMemoryAllocation_h_ -# error Dont include this directly! Include CEGUIBase.h instead. -#endif - -namespace CEGUI -{ - -#ifdef CEGUI_CUSTOM_ALLOCATORS - -template -struct STLAllocatorWrapperBase -{ - typedef T value_type; -}; -// getting rid of const trick taken from Ogre :-) -template -struct STLAllocatorWrapperBase -{ - typedef T value_type; -}; - -template -class STLAllocatorWrapper : public STLAllocatorWrapperBase -{ -public: - typedef STLAllocatorWrapperBase Base; - typedef typename Base::value_type value_type; - - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - - template - struct rebind - { - typedef STLAllocatorWrapper other; - }; - - inline explicit STLAllocatorWrapper() - {} - - inline STLAllocatorWrapper(const STLAllocatorWrapper&) - {} - - template - inline STLAllocatorWrapper(const STLAllocatorWrapper&) - {} - - inline pointer address(reference x) const - { - return &x; - } - - inline const_pointer address(const_reference x) const - { - return &x; - } - - inline size_type max_size() const throw() - { - return Allocator::getMaxAllocationSize(); - } - - inline pointer allocate(size_type count, typename std::allocator::const_pointer ptr = 0) - { - (void)ptr; - return static_cast(Allocator::allocateBytes(count * sizeof(T))); - } - - inline void deallocate(pointer ptr, size_type /*size*/ ) - { - Allocator::deallocateBytes(ptr); - } - - inline void construct(pointer p, const T& val) - { - new(static_cast(p)) T(val); - } - - inline void destroy(pointer p) - { - p->~T(); - } -}; - -template -inline bool operator==(const STLAllocatorWrapper&, const STLAllocatorWrapper&) -{ - // same allocator, return true - return true; -} - -template -inline bool operator==(const STLAllocatorWrapper&, const OtherAllocator&) -{ - // if the template abose doesn't get matched, return false (allocators differ) - return false; -} - -template -inline bool operator!=(const STLAllocatorWrapper&, const STLAllocatorWrapper&) -{ - // same allocator, return false (they are not different) - return false; -} - -template -inline bool operator!=(const STLAllocatorWrapper&, const OtherAllocator&) -{ - // the above didn't get matched, that means the allocators differ... - return true; -} - -// STL allocator helper macros -#define CEGUI_VECTOR_ALLOC(T) , ::CEGUI::STLAllocatorWrapper::Allocator> -#define CEGUI_SET_ALLOC(T) , ::CEGUI::STLAllocatorWrapper::Allocator> -#define CEGUI_MAP_ALLOC(K, V) , ::CEGUI::STLAllocatorWrapper, ::CEGUI::AllocatorConfig< ::CEGUI::STLAllocator >::Allocator> -#define CEGUI_MULTIMAP_ALLOC(K, V) , ::CEGUI::STLAllocatorWrapper, ::CEGUI::AllocatorConfig< ::CEGUI::STLAllocator >::Allocator> - -#else - -// STL allocator helper macros -#define CEGUI_VECTOR_ALLOC(T) -#define CEGUI_SET_ALLOC(T) -#define CEGUI_MAP_ALLOC(K, V) -#define CEGUI_MULTIMAP_ALLOC(K, V) - -#endif - -} - -#endif // end of guard _CEGUIMemorySTLWrapper_h_ diff --git a/cegui/include/CEGUI/ModuleConfig.h.in b/cegui/include/CEGUI/ModuleConfig.h.in index 60bef6618..c3e863a71 100644 --- a/cegui/include/CEGUI/ModuleConfig.h.in +++ b/cegui/include/CEGUI/ModuleConfig.h.in @@ -47,8 +47,6 @@ setting CMake options and regenerating, rather than editing directly. #cmakedefine CEGUI_BUILD_RENDERER_OPENGL3 #cmakedefine CEGUI_BUILD_RENDERER_OGRE #cmakedefine CEGUI_BUILD_RENDERER_IRRLICHT -#cmakedefine CEGUI_BUILD_RENDERER_DIRECT3D9 -#cmakedefine CEGUI_BUILD_RENDERER_DIRECT3D10 #cmakedefine CEGUI_BUILD_RENDERER_DIRECT3D11 #cmakedefine CEGUI_BUILD_RENDERER_DIRECTFB #cmakedefine CEGUI_BUILD_RENDERER_OPENGLES diff --git a/cegui/include/CEGUI/MouseCursor.h b/cegui/include/CEGUI/MouseCursor.h deleted file mode 100644 index 5a3cbf746..000000000 --- a/cegui/include/CEGUI/MouseCursor.h +++ /dev/null @@ -1,418 +0,0 @@ -/*********************************************************************** - created: 21/2/2004 - author: Paul D Turner - - purpose: Defines interface for the MouseCursor class -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIMouseCursor_h_ -#define _CEGUIMouseCursor_h_ - -#include "CEGUI/Base.h" -#include "CEGUI/String.h" -#include "CEGUI/Vector.h" -#include "CEGUI/Rect.h" -#include "CEGUI/EventSet.h" -#include "CEGUI/InputEvent.h" -#include "CEGUI/UDim.h" - - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4275) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -//! Class that provides mouse cursor support. -class CEGUIEXPORT MouseCursor : - public EventSet, - public AllocatedObject -{ -public: - //! Namespace for global events. - static const String EventNamespace; - - /** Name of Event fired when the mouse cursor image is changed. - * Handlers are passed a const MouseCursorEventArgs reference with - * MouseCursorEventArgs::mouseCursor set to the MouseCursor that has - * had it's image changed, and MouseCursorEventArgs::image set to the - * Image that is now set for the MouseCursor (may be 0). - */ - static const String EventImageChanged; - - /** Name of Event fired when the Image to be used as a default mouse cursor - * image is changed. - * Handlers are passed a const MouseCursorEventArgs reference with - * MouseCursorEventArgs::mouseCursor set to the MouseCursor that has - * had it's default image changed, and MouseCursorEventArgs::image set to - * the Image that is now set as the default (may be 0). - */ - static const String EventDefaultImageChanged; - - /*! - \brief - Constructor for MouseCursor objects - */ - MouseCursor(void); - - - /*! - \brief - Destructor for MouseCursor objects - */ - ~MouseCursor(void); - - - /*! - \brief - Set the current mouse cursor image - - \param name - String object holding the name of the desired Image. - - \return - Nothing. - - \exception UnknownObjectException thrown if Image \a name is not known. - */ - void setImage(const String& name); - - - /*! - \brief - Set the current mouse cursor image - */ - void setImage(const Image* image); - - - /*! - \brief - Get the current mouse cursor image - \return - The current image used to draw mouse cursor. - */ - const Image* getImage(void) const {return d_cursorImage;} - - /*! - \brief - Set the image to be used as the default mouse cursor. - - \param image - Pointer to an image object that is to be used as the default mouse - cursor. To have no cursor rendered by default, you can specify 0 here. - */ - void setDefaultImage(const Image* image); - - /*! - \brief - Set the image to be used as the default mouse cursor. - - \param name - String object that contains the name of the Image that is to be used. - - \exception - UnknownObjectException thrown if no Image named \a name exists. - */ - void setDefaultImage(const String& name); - - /*! - \brief - Return the currently set default mouse cursor image - - \return - Pointer to the current default image used for the mouse cursor. May - return 0 if default cursor has not been set, or has intentionally - been set to 0 - which results in a blank default cursor. - */ - const Image* getDefaultImage() const; - - - /*! - \brief - Makes the cursor draw itself - - \return - Nothing - */ - void draw(void) const; - - - /*! - \brief - Set the current mouse cursor position - - \param position - Point object describing the new location for the mouse. This will be clipped to within the renderer screen area. - */ - void setPosition(const Vector2f& position); - - - /*! - \brief - Offset the mouse cursor position by the deltas specified in \a offset. - - \param offset - Point object which describes the amount to move the cursor in each axis. - - \return - Nothing. - */ - void offsetPosition(const Vector2f& offset); - - - /*! - \brief - Set the area that the mouse cursor is constrained to. - - \param area - Pointer to a Rect object that describes the area of the display that the mouse is allowed to occupy. The given area will be clipped to - the current Renderer screen area - it is never possible for the mouse to leave this area. If this parameter is NULL, the - constraint is set to the size of the current Renderer screen area. - - \return - Nothing. - */ - void setConstraintArea(const Rectf* area); - - - /*! - \brief - Set the area that the mouse cursor is constrained to. - - \param area - Pointer to a URect object that describes the area of the display that the mouse is allowed to occupy. The given area will be clipped to - the current Renderer screen area - it is never possible for the mouse to leave this area. If this parameter is NULL, the - constraint is set to the size of the current Renderer screen area. - - \return - Nothing. - */ - void setUnifiedConstraintArea(const URect* area); - - - /*! - \brief - Hides the mouse cursor. - - \return - Nothing. - */ - void hide(void) {d_visible = false;} - - - /*! - \brief - Shows the mouse cursor. - - \return - Nothing. - */ - void show(void) {d_visible = true;} - - - /*! - \brief - Set the visibility of the mouse cursor. - - \param visible - 'true' to show the mouse cursor, 'false' to hide it. - - \return - Nothing. - */ - void setVisible(bool visible) {d_visible = visible;} - - - /*! - \brief - return whether the mouse cursor is visible. - - \return - true if the mouse cursor is visible, false if the mouse cursor is hidden. - */ - bool isVisible(void) const {return d_visible;} - - - /*! - \brief - Return the current mouse cursor position as a pixel offset from the top-left corner of the display. - - \return - Point object describing the mouse cursor position in screen pixels. - */ - Vector2f getPosition(void) const - { return d_position; } - - - /*! - \brief - return the current constraint area of the mouse cursor. - - \return - Rect object describing the active area that the mouse cursor is constrained to. - */ - Rectf getConstraintArea(void) const; - - - /*! - \brief - return the current constraint area of the mouse cursor. - - \return - URect object describing the active area that the mouse cursor is constrained to. - */ - const URect& getUnifiedConstraintArea(void) const; - - - /*! - \brief - Return the current mouse cursor position as display resolution independant values. - - \return - Point object describing the current mouse cursor position as resolution independant values that - range from 0.0f to 1.0f, where 0.0f represents the left-most and top-most positions, and 1.0f - represents the right-most and bottom-most positions. - */ - Vector2f getDisplayIndependantPosition(void) const; - - /*! - \brief - Function used to notify the MouseCursor of changes in the display size. - - You normally would not call this directly; rather you would call the - function System::notifyDisplaySizeChanged and that will then call this - function for you. - - \param new_size - Size object describing the new display size in pixels. - */ - void notifyDisplaySizeChanged(const Sizef& new_size); - - /*! - \brief - Set an explicit size for the mouse cursor image to be drawn at. - - This will override the size that is usually obtained directly from the - mouse cursor image and will stay in effect across changes to the mouse - cursor image. - - Setting this size to (0, 0) will revert back to using the size as - obtained from the Image itself. - - \param size - Reference to a Size object that describes the size at which the cursor - image should be drawn in pixels. - */ - void setExplicitRenderSize(const Sizef& size); - - /*! - \brief - Return the explicit render size currently set. A return size of (0, 0) - indicates that the real image size will be used. - */ - const Sizef& getExplicitRenderSize() const; - - /*! - \brief - Static function to pre-initialise the mouse cursor position (prior to - MouseCursor instantiation). - - Calling this function prior to instantiating MouseCursor will prevent - the mouse having it's position set to the middle of the initial view. - Calling this function after the MouseCursor is instantiated will have - no effect. - - \param position - Reference to a point object describing the initial pixel position to - be used for the mouse cursor. - */ - static void setInitialMousePosition(const Vector2f& position); - - /*! - \brief - Mark the cached geometry as invalid so it will be recached next time the - mouse cursor is drawn. - */ - void invalidate(); - -protected: - /************************************************************************* - New event handlers - *************************************************************************/ - //! Event triggered internally when mouse cursor image is changed. - virtual void onImageChanged(MouseCursorEventArgs& e); - //! Event triggered internally when mouse cursor default image is changed. - virtual void onDefaultImageChanged(MouseCursorEventArgs& e); - - -private: - /************************************************************************* - Implementation Methods - *************************************************************************/ - /*! - \brief - Checks the mouse cursor position is within the current 'constrain' Rect and adjusts as required. - */ - void constrainPosition(void); - - //! updates the cached geometry. - void cacheGeometry() const; - - //! calculate offset for custom image size so 'hot spot' is maintained. - void calculateCustomOffset() const; - - /************************************************************************* - Implementation Data - *************************************************************************/ - //! Image that is currently set as the mouse cursor. - const Image* d_cursorImage; - //! Image that will be used as the default image for this mouse cursor. - const Image* d_defaultCursorImage; - Vector2f d_position; //!< Current location of the cursor - bool d_visible; //!< true if the cursor will be drawn, else false. - URect d_constraints; //!< Specifies the area (in screen pixels) that the mouse can move around in. - //! buffer to hold geometry for mouse cursor imagery. - GeometryBuffer* d_geometry; - //! custom explicit size to render the cursor image at - Sizef d_customSize; - //! correctly scaled offset used when using custom image size. - mutable Vector2f d_customOffset; - //! true if the mouse initial position has been pre-set - static bool s_initialPositionSet; - //! value set as initial position (if any) - static Vector2f s_initialPosition; - //! boolean indicating whether cached pointer geometry is valid. - mutable bool d_cachedGeometryValid; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIMouseCursor_h_ diff --git a/cegui/include/CEGUI/NamedXMLResourceManager.h b/cegui/include/CEGUI/NamedXMLResourceManager.h index 211a021f3..e539d7c6f 100644 --- a/cegui/include/CEGUI/NamedXMLResourceManager.h +++ b/cegui/include/CEGUI/NamedXMLResourceManager.h @@ -232,8 +232,7 @@ class NamedXMLResourceManager : public ResourceEventSet protected: // singleton allocator fits here, resource managers are very likely to be singletons //! type of collection used to store and manage objects - typedef std::map ObjectRegistry; + typedef std::map ObjectRegistry; //! implementation of object destruction. void destroyObject(typename ObjectRegistry::iterator ob); //! function to enforce XMLResourceExistsAction policy. @@ -369,7 +368,7 @@ void NamedXMLResourceManager::destroyObject( // Set up event args for event notification ResourceEventArgs args(d_resourceType, ob->first); - CEGUI_DELETE_AO ob->second; + delete ob->second; d_objects.erase(ob); // fire event signalling an object has been destroyed @@ -393,7 +392,7 @@ T& NamedXMLResourceManager::doExistingObjectAction( Logger::getSingleton().logEvent("---- Returning existing instance " "of " + d_resourceType + " named '" + object_name + "'."); // delete any new object we already had created - CEGUI_DELETE_AO object; + delete object; // return existing instance of object. return *d_objects[object_name]; @@ -406,13 +405,13 @@ T& NamedXMLResourceManager::doExistingObjectAction( break; case XREA_THROW: - CEGUI_DELETE_AO object; + delete object; CEGUI_THROW(AlreadyExistsException( "an object of type '" + d_resourceType + "' named '" + object_name + "' already exists in the collection.")); default: - CEGUI_DELETE_AO object; + delete object; CEGUI_THROW(InvalidRequestException( "Invalid CEGUI::XMLResourceExistsAction was specified.")); } diff --git a/cegui/include/CEGUI/Property.h b/cegui/include/CEGUI/Property.h index eeaad49b9..fcbaf155d 100644 --- a/cegui/include/CEGUI/Property.h +++ b/cegui/include/CEGUI/Property.h @@ -57,8 +57,7 @@ class CEGUIEXPORT PropertyReceiver Property objects allow (via a PropertySet) access to certain properties of objects by using simple get/set functions and the name of the property to be accessed. */ -class CEGUIEXPORT Property : - public AllocatedObject +class CEGUIEXPORT Property { public: static const String XMLElementName; diff --git a/cegui/include/CEGUI/PropertyHelper.h b/cegui/include/CEGUI/PropertyHelper.h index 74a33970f..e97b27ed4 100644 --- a/cegui/include/CEGUI/PropertyHelper.h +++ b/cegui/include/CEGUI/PropertyHelper.h @@ -32,12 +32,13 @@ #include "CEGUI/String.h" #include "CEGUI/Size.h" #include "CEGUI/Vector.h" -#include "CEGUI/Quaternion.h" #include "CEGUI/Colour.h" #include "CEGUI/ColourRect.h" #include "CEGUI/UDim.h" #include "CEGUI/Rect.h" +#include +#include #include @@ -528,25 +529,25 @@ class PropertyHelper }; template<> -class PropertyHelper +class PropertyHelper { public: - typedef Vector2f return_type; + typedef glm::vec2 return_type; typedef return_type safe_method_return_type; - typedef const Vector2f& pass_type; + typedef const glm::vec2& pass_type; typedef String string_return_type; static const String& getDataTypeName() { - static String type("Vector2f"); + static String type("vec2"); return type; } static return_type fromString(const String& str) { - Vector2f val(0, 0) ; - sscanf(str.c_str(), " x:%g y:%g", &val.d_x, &val.d_y); + glm::vec2 val(0, 0) ; + sscanf(str.c_str(), " x:%g y:%g", &val.x, &val.y); return val; } @@ -554,32 +555,32 @@ class PropertyHelper static string_return_type toString(pass_type val) { char buff[128]; - snprintf(buff, sizeof(buff), "x:%g y:%g", val.d_x, val.d_y); + snprintf(buff, sizeof(buff), "x:%g y:%g", val.x, val.y); return String(buff); } }; template<> -class PropertyHelper +class PropertyHelper { public: - typedef Vector3f return_type; + typedef glm::vec3 return_type; typedef return_type safe_method_return_type; - typedef const Vector3f& pass_type; + typedef const glm::vec3& pass_type; typedef String string_return_type; static const String& getDataTypeName() { - static String type("Vector3f"); + static String type("vec3"); return type; } static return_type fromString(const String& str) { - Vector3f val(0, 0, 0); - sscanf(str.c_str(), " x:%g y:%g z:%g", &val.d_x, &val.d_y, &val.d_z); + glm::vec3 val(0, 0, 0); + sscanf(str.c_str(), " x:%g y:%g z:%g", &val.x, &val.y, &val.z); return val; } @@ -587,24 +588,24 @@ class PropertyHelper static string_return_type toString(pass_type val) { char buff[128]; - snprintf(buff, sizeof(buff), "x:%g y:%g z:%g", val.d_x, val.d_y, val.d_z); + snprintf(buff, sizeof(buff), "x:%g y:%g z:%g", val.x, val.y, val.z); return String(buff); } }; template<> -class PropertyHelper +class PropertyHelper { public: - typedef Quaternion return_type; + typedef glm::quat return_type; typedef return_type safe_method_return_type; - typedef const Quaternion& pass_type; + typedef const glm::quat& pass_type; typedef String string_return_type; static const String& getDataTypeName() { - static String type("Quaternion"); + static String type("quat"); return type; } @@ -613,23 +614,25 @@ class PropertyHelper { if (strchr(str.c_str(), 'w') || strchr(str.c_str(), 'W')) { - Quaternion val(1, 0, 0, 0); - sscanf(str.c_str(), " w:%g x:%g y:%g z:%g", &val.d_w, &val.d_x, &val.d_y, &val.d_z); + glm::quat val(1, 0, 0, 0); + sscanf(str.c_str(), " w:%g x:%g y:%g z:%g", &val.w, &val.x, &val.y, &val.z); return val; } else { float x, y, z; + // CEGUI takes degrees because it's easier to work with sscanf(str.c_str(), " x:%g y:%g z:%g", &x, &y, &z); - return Quaternion::eulerAnglesDegrees(x, y, z); + // glm::radians converts from degrees to radians + return glm::quat(glm::vec3(glm::radians(x), glm::radians(y), glm::radians(z))); } } static string_return_type toString(pass_type val) { char buff[128]; - snprintf(buff, sizeof(buff), "w:%g x:%g y:%g z:%g", val.d_w, val.d_x, val.d_y, val.d_z); + snprintf(buff, sizeof(buff), "w:%g x:%g y:%g z:%g", val.w, val.x, val.y, val.z); return String(buff); } diff --git a/cegui/include/CEGUI/PropertySet.h b/cegui/include/CEGUI/PropertySet.h index 3436f0b98..da060c4b4 100644 --- a/cegui/include/CEGUI/PropertySet.h +++ b/cegui/include/CEGUI/PropertySet.h @@ -314,8 +314,7 @@ class CEGUIEXPORT PropertySet : public PropertyReceiver String getPropertyDefault(const String& name) const; private: - typedef std::map PropertyRegistry; + typedef std::map PropertyRegistry; PropertyRegistry d_properties; diff --git a/cegui/include/CEGUI/Quaternion.h b/cegui/include/CEGUI/Quaternion.h index 9e9202892..674cd8d89 100644 --- a/cegui/include/CEGUI/Quaternion.h +++ b/cegui/include/CEGUI/Quaternion.h @@ -26,6 +26,7 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ + #ifndef _CEGUIQuaternion_h_ #define _CEGUIQuaternion_h_ @@ -34,237 +35,14 @@ #include "CEGUI/Vector.h" #include -// Start of CEGUI namespace section -namespace CEGUI -{ - -/*! -\brief - Class to represent rotation, avoids Gimbal lock - -Most people are afraid of Quaternions, you don't have to fully understand them. -In CEGUI, you can just think of quaternions as magic opaque boxes that hold rotation -data. No need to understand how they work and why. You obviously have to -understand what degrees and radians are, I won't go into that here. +#include +#include -How to convert "human readable" rotation data to Quaternions: -1) Euler angles, 3 floating point values - x - rotation around X axis (anticlockwise) - y - rotation around Y axis (anticlockwise) - z - rotation around Z axis (anticlockwise) - - The actual rotation is performed in z, y, x order. Keep that in mind! - - For these, just use eulerAnglesDegrees or eulerAnglesRadians static methods. - -2) Rotation around axis, 1 Vector3 and one degree/radian angle - the vector represents the axis (it's length doesn't matter at all), - rotation is then performed by rotating given angle anticlockwise - around that axis. - - For these, use axisAngleDegrees or axisAngleRadians static methods. -*/ -class CEGUIEXPORT Quaternion : - public AllocatedObject +namespace CEGUI { -public: - //! verbatim constructor - inline Quaternion(float w = 1.0f, float x = 0.0f, float y = 0.0f, float z = 0.0f): - d_w(w), - d_x(x), - d_y(y), - d_z(z) - {} - - //! copy constructor - inline Quaternion(const Quaternion& v): - d_w(v.d_w), - d_x(v.d_x), - d_y(v.d_y), - d_z(v.d_z) - {} - - //! assignment operator - inline Quaternion& operator = (const Quaternion& v) - { - d_w = v.d_w; - d_x = v.d_x; - d_y = v.d_y; - d_z = v.d_z; - - return *this; - } - - /*! - \brief constructs a quaternion from euler angles in radians - - \param x - Anticlockwise rotation around X axis - \param y - Anticlockwise rotation around Y axis - \param z - Anticlockwise rotation around Z axis - - The rotation is performed around Z first, then Y and then X! - */ - static Quaternion eulerAnglesRadians(float x, float y, float z); - - /*! - \brief constructs a quaternion from euler angles in degrees - - \param x - Anticlockwise rotation around X axis - \param y - Anticlockwise rotation around Y axis - \param z - Anticlockwise rotation around Z axis - - The rotation is performed around Z first, then Y and then X! - */ - static Quaternion eulerAnglesDegrees(float x, float y, float z); - - /*! - \brief constructs a quaternion from axis and angle around it in radians - - \param axis - vector describing the axis of rotation - \param rotation - Anticlockwise rotation around given axis - */ - static Quaternion axisAngleRadians(const Vector3f& axis, float rotation); - - /*! - \brief constructs a quaternion from axis and angle around it in degrees - - \param axis - vector describing the axis of rotation - \param rotation - Anticlockwise rotation around given axis - */ - static Quaternion axisAngleDegrees(const Vector3f& axis, float rotation); - - //! equality operator - inline bool operator == (const Quaternion& v) const - { - return (d_w == v.d_w) && (d_x == v.d_x) && (d_y == v.d_y) && (d_z == v.d_z); - } - - //! inequality operator - inline bool operator != (const Quaternion& v) const - { - return (d_w != v.d_w) || (d_x != v.d_x) || (d_y != v.d_y) || (d_z != v.d_z); - } - - //! negation operator - inline Quaternion operator - () const - { - return Quaternion(-d_w, -d_x, -d_y, -d_z); - } - - //! scalar multiplication operator - inline Quaternion operator * (float v) const - { - return Quaternion(d_w * v, d_x * v, d_y * v, d_z * v); - } - - //! scalar multiplication operator - inline friend Quaternion operator * (float v, const Quaternion& q) - { - return Quaternion(v * q.d_w, v * q.d_x, v * q.d_y, v * q.d_z); - } - - //! quaternion dot product - inline float dot(const Quaternion& v) const - { - return d_w * v.d_w + d_x * v.d_x + d_y * v.d_y + d_z * v.d_z; - } - - //! addition operator - inline Quaternion operator + (const Quaternion& v) const - { - return Quaternion(d_w + v.d_w, d_x + v.d_x, d_y + v.d_y, d_z + v.d_z); - } - - /*! - \brief quaternion multiplication (not commutative!) - - Lets say we have quaternion A describing a rotation and another quaternion B. - If we write C = A * B, C is actually describing a rotation we would get if we - rotated Identity by A and then rotated the result by B - */ - inline Quaternion operator * (const Quaternion& v) const - { - return Quaternion( - d_w * v.d_w - d_x * v.d_x - d_y * v.d_y - d_z * v.d_z, - d_w * v.d_x + d_x * v.d_w + d_y * v.d_z - d_z * v.d_y, - d_w * v.d_y + d_y * v.d_w + d_z * v.d_x - d_x * v.d_z, - d_w * v.d_z + d_z * v.d_w + d_x * v.d_y - d_y * v.d_x - ); - } - - /*! - \brief computers and returns the length of this quaternion - */ - inline float length() const - { - return sqrtf((d_w * d_w) + (d_x * d_x) + (d_y * d_y) + (d_z * d_z)); - } - - /*! - \brief normalises this quaternion and returns it's length (since it has to be computed anyways) - */ - inline float normalise() - { - const float len = length(); - const float factor = 1.0f / len; - *this = *this * factor; - - return len; - } - - /*! - \brief spherical linear interpolation - - \param left - Left keyframe Quaternion - - \param right - Right keyframe Quaternion - - \param position - Number from range <0.0, 1.0), the closer this is to 1.0, the closer the interpolation is to the "right" quaternion - - \param shortestPath - If true, the interpolation is guaranteed to go through the shortest path - */ - static Quaternion slerp(const Quaternion& left, const Quaternion& right, float position, bool shortestPath = false); - - //! Quaternion(0, 0, 0, 0) - static const Quaternion ZERO; - //! Quaternion(1, 0, 0, 0) - static const Quaternion IDENTITY; - - /*! - \brief allows writing the quaternion to std ostream - */ - inline friend std::ostream& operator << (std::ostream& s, const Quaternion& v) - { - s << "CEGUI::Quaternion(" << v.d_w << ", " << v.d_x << ", " << v.d_y << ", " << v.d_z << ")"; - return s; - } - - //! imaginary part - float d_w; - //! x component of the vector part - float d_x; - //! y component of the vector part - float d_y; - //! z component of the vector part - float d_z; -}; /*! - \brief Special interpolator class for Quaternion + \brief Special interpolator class for glm::quat Quaternions can't be interpolated as floats and/or vectors, we have to use "Spherical linear interpolator" instead. @@ -272,7 +50,7 @@ class CEGUIEXPORT Quaternion : class QuaternionSlerpInterpolator : public Interpolator { public: - typedef PropertyHelper Helper; + typedef PropertyHelper Helper; //! destructor virtual ~QuaternionSlerpInterpolator() {} @@ -298,6 +76,6 @@ class QuaternionSlerpInterpolator : public Interpolator float position); }; -} // End of CEGUI namespace section +} -#endif // end of guard _CEGUIQuaternion_h_ +#endif // end of guard _CEGUIQuaternion_h_ \ No newline at end of file diff --git a/cegui/include/CEGUI/Rect.h b/cegui/include/CEGUI/Rect.h index bdc949d3f..dcc7161f6 100644 --- a/cegui/include/CEGUI/Rect.h +++ b/cegui/include/CEGUI/Rect.h @@ -32,6 +32,8 @@ #include "CEGUI/Vector.h" #include "CEGUI/Size.h" +#include + // Start of CEGUI namespace section namespace CEGUI { @@ -40,8 +42,7 @@ namespace CEGUI Class encapsulating operations on a Rectangle */ template -class Rect: - public AllocatedObject > +class Rect { public: typedef T value_type; @@ -59,11 +60,23 @@ class Rect: d_max(max) {} + // FIXME: Temporary for glm::vec2 transition + inline Rect(const glm::vec2& min, const glm::vec2& max): + d_min(min.x, min.y), + d_max(max.x, max.y) + {} + inline Rect(const Vector2& pos, const Size& size): d_min(pos), d_max(pos + Vector2(size.d_width, size.d_height)) {} + // FIXME: Temporary for glm::vec2 transition + inline Rect(const glm::vec2& pos, const Size& size): + d_min(pos.x, pos.y), + d_max(pos.x + size.d_width, pos.y + size.d_height) + {} + inline Rect(const Rect& r): d_min(r.d_min), d_max(r.d_max) @@ -128,6 +141,14 @@ class Rect: setSize(size); } + // FIXME: Temporary for glm::vec2 transition + void setPosition(const glm::vec2& min) + { + const Size size = getSize(); + d_min = Vector2(min.x, min.y); + setSize(size); + } + /*! \brief Return top-left position of Rect as a Vector2 @@ -137,6 +158,12 @@ class Rect: return d_min; } + // FIXME: Temporary for glm::vec2 transition + glm::vec2 getPositionGLM() const + { + return glm::vec2(d_min.d_x, d_min.d_y); + } + void setSize(const Size& size) { d_max = d_min + Vector2(size.d_width, size.d_height); @@ -226,7 +253,14 @@ class Rect: d_max += v; } - /*! + // FIXME: Temporary for glm::vec2 transition + inline void offset(const glm::vec2& v) + { + d_min += Vector2(v.x, v.y); + d_max += Vector2(v.x, v.y); + } + + /*! \brief Return true if the given Vector2 falls within this Rect @@ -249,6 +283,19 @@ class Rect: return true; } + // FIXME: Temporary for glm::vec2 transition + inline bool isPointInRect(const glm::vec2& v) const + { + if ((d_min.d_x > v.x) || + (d_max.d_x <= v.x) || + (d_min.d_y > v.y) || + (d_max.d_y <= v.y)) + { + return false; + } + + return true; + } /*! \brief @@ -353,6 +400,17 @@ class Rect: return Rect(d_min * scalar, d_max * scalar); } + inline Rect operator*(Vector2 vector) const + { + return Rect(d_min * vector, d_max * vector); + } + + // FIXME: Temporary for glm::vec2 transition + inline Rect operator*(glm::vec2 vector) const + { + return Rect(d_min * Vector2(vector.x, vector.y), d_max * Vector2(vector.x, vector.y)); + } + const Rect& operator*=(T scalar) { d_min *= scalar; @@ -364,6 +422,11 @@ class Rect: { return Rect(d_min + r.d_min, d_max + r.d_max); } + + Rect operator-(const Rect& r) const + { + return Rect(d_min - r.d_min, d_max - r.d_max); + } inline friend std::ostream& operator << (std::ostream& s, const Rect& v) { diff --git a/cegui/include/CEGUI/RefCounted.h b/cegui/include/CEGUI/RefCounted.h index a67511b48..6df631914 100644 --- a/cegui/include/CEGUI/RefCounted.h +++ b/cegui/include/CEGUI/RefCounted.h @@ -34,9 +34,6 @@ namespace CEGUI \brief Simple, generic, reference counted pointer class. This is primarily here for use by the Events system to track when to delete slot bindings. - -\note - Only safe to use with AllocatedObject derived classes! */ template class RefCounted @@ -186,10 +183,8 @@ class RefCounted { if (!--*d_count) { - // use CEGUI allocators for the object - CEGUI_DELETE_AO d_object; + delete d_object; - // use system heap for this! no CEGUI_DELETE_PT! delete d_count; d_object = 0; d_count = 0; diff --git a/cegui/include/CEGUI/RegexMatcher.h b/cegui/include/CEGUI/RegexMatcher.h index dbe0c103f..86ddf53ab 100644 --- a/cegui/include/CEGUI/RegexMatcher.h +++ b/cegui/include/CEGUI/RegexMatcher.h @@ -36,8 +36,7 @@ namespace CEGUI { //! Interface for Regex matching support classes -class CEGUIEXPORT RegexMatcher : - public AllocatedObject +class CEGUIEXPORT RegexMatcher { public: //! Enumeration of possible states when cosidering a regex match. diff --git a/cegui/include/CEGUI/RenderEffect.h b/cegui/include/CEGUI/RenderEffect.h index dd4891592..90090bf21 100644 --- a/cegui/include/CEGUI/RenderEffect.h +++ b/cegui/include/CEGUI/RenderEffect.h @@ -37,8 +37,7 @@ namespace CEGUI Interface for objects that hook into RenderingWindow to affect the rendering process, thus allowing various effects to be achieved. */ -class CEGUIEXPORT RenderEffect : - public AllocatedObject +class CEGUIEXPORT RenderEffect { public: virtual ~RenderEffect() {}; diff --git a/cegui/include/CEGUI/RenderEffectFactory.h b/cegui/include/CEGUI/RenderEffectFactory.h index 33efb58a5..7c0f1b12f 100644 --- a/cegui/include/CEGUI/RenderEffectFactory.h +++ b/cegui/include/CEGUI/RenderEffectFactory.h @@ -37,8 +37,7 @@ namespace CEGUI Interface for factory objects that create RenderEffect instances. Currently this interface is intended for internal use only. */ -class RenderEffectFactory : public - AllocatedObject +class RenderEffectFactory { public: //! base class virtual destructor. @@ -65,14 +64,14 @@ class TplRenderEffectFactory : public RenderEffectFactory template RenderEffect& TplRenderEffectFactory::create(Window* window) { - return *CEGUI_NEW_AO T(window); + return *new T(window); } //---------------------------------------------------------------------------// template void TplRenderEffectFactory::destroy(RenderEffect& effect) { - CEGUI_DELETE_AO &effect; + delete &effect; } //---------------------------------------------------------------------------// diff --git a/cegui/include/CEGUI/RenderEffectManager.h b/cegui/include/CEGUI/RenderEffectManager.h index 5a3d6864a..c9476670f 100644 --- a/cegui/include/CEGUI/RenderEffectManager.h +++ b/cegui/include/CEGUI/RenderEffectManager.h @@ -48,17 +48,14 @@ namespace CEGUI objects. */ class CEGUIEXPORT RenderEffectManager : - public Singleton, - public AllocatedObject + public Singleton { private: //! Collection type used for the render effect registry - typedef std::map RenderEffectRegistry; + typedef std::map RenderEffectRegistry; //! Collection type to track which effects we created with which factories - typedef std::map - CEGUI_MAP_ALLOC(RenderEffect*, RenderEffectFactory*)> EffectCreatorMap; + typedef std::map > EffectCreatorMap; //! Collection of registered render effects RenderEffectRegistry d_effectRegistry; @@ -182,7 +179,7 @@ void RenderEffectManager::addEffect(const String& name) name + "'")); // create an instance of a factory to create effects of type T - d_effectRegistry[name] = CEGUI_NEW_AO TplRenderEffectFactory; + d_effectRegistry[name] = new TplRenderEffectFactory; Logger::getSingleton().logEvent( "Registered RenderEffect named '" + name + "'"); diff --git a/cegui/include/CEGUI/RenderMaterial.h b/cegui/include/CEGUI/RenderMaterial.h new file mode 100644 index 000000000..c48048d77 --- /dev/null +++ b/cegui/include/CEGUI/RenderMaterial.h @@ -0,0 +1,83 @@ +/*********************************************************************** + created: 18th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIRenderMaterial_h_ +#define _CEGUIRenderMaterial_h_ + +#include "CEGUI/Base.h" + +namespace CEGUI +{ +class ShaderWrapper; +class ShaderParameterBindings; + +/*! +\brief + A RenderMaterial is used for rendering GeometryBuffers. It contains + a pointer to the used shader (ShaderWrapper) and owns shader parameters. +*/ +class CEGUIEXPORT RenderMaterial +{ +public: + RenderMaterial(ShaderWrapper* shaderWrapper); + ~RenderMaterial(); + + /*! + \brief + Return the ShaderParameterBindings of this Renderer. + + \return + The pointer to the ShaderParameterBindings. + */ + ShaderParameterBindings* getShaderParamBindings() const; + + /*! + \brief + Returns a pointer to the ShaderWrapper used for this Renderer. + + \return + The pointer to the ShaderWrapper used for this Renderer. + */ + const ShaderWrapper* getShaderWrapper() const; + + /*! + \brief + Applies the shader parameter bindings to the shader of this material. + */ + void prepareForRendering() const; + +protected: + //! pointer to the Shader that is used in this material. + ShaderWrapper* d_shaderWrapper; + + //! data structure that contains all the shader parameters that are + // to be sent to the shader program using the parameter's name + ShaderParameterBindings* d_shaderParamBindings; +}; + +} + +#endif diff --git a/cegui/include/CEGUI/RenderQueue.h b/cegui/include/CEGUI/RenderQueue.h index 3f88739fb..684933d2a 100644 --- a/cegui/include/CEGUI/RenderQueue.h +++ b/cegui/include/CEGUI/RenderQueue.h @@ -49,8 +49,7 @@ namespace CEGUI lifetime of the GeometryBuffer objects (and to remove them from any RenderQueue to which they may be attached prior to destoying them). */ -class CEGUIEXPORT RenderQueue : - public AllocatedObject +class CEGUIEXPORT RenderQueue { public: /*! @@ -63,13 +62,23 @@ class CEGUIEXPORT RenderQueue : /*! \brief - Add a GeometryBuffer to the RenderQueue. Ownership of the + Add a list of GeometryBuffers to the RenderQueue. Ownership of the GeometryBuffer does not pass to the RenderQueue. - \param buffer - GeometryBuffer that is to be added to the RenderQueue for later drawing. + \param geometry_buffers + List of GeometryBuffers that are to be added to the RenderQueue for later drawing. + */ + void addGeometryBuffers(const std::vector& geometry_buffers); + + /*! + \brief + Add a GeometryBuffer to the RenderQueue. Ownership of the GeometryBuffer does not + pass to the RenderQueue. + + \param geometry_buffers + The GeometryBuffer that is to be added to the RenderQueue for later drawing. */ - void addGeometryBuffer(const GeometryBuffer& buffer); + void addGeometryBuffer(const GeometryBuffer& geometry_buffer); /*! \brief @@ -92,8 +101,7 @@ class CEGUIEXPORT RenderQueue : private: //! Type to use for the GeometryBuffer collection. - typedef std::vector BufferList; + typedef std::vector BufferList; //! Collection of GeometryBuffer objects that comprise this RenderQueue. BufferList d_buffers; }; diff --git a/cegui/include/CEGUI/RenderTarget.h b/cegui/include/CEGUI/RenderTarget.h index 173bfb966..c30040920 100644 --- a/cegui/include/CEGUI/RenderTarget.h +++ b/cegui/include/CEGUI/RenderTarget.h @@ -33,6 +33,11 @@ #include "CEGUI/Vector.h" #include "CEGUI/Rect.h" +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + // Start of CEGUI namespace section namespace CEGUI { @@ -55,10 +60,13 @@ class CEGUIEXPORT RenderTargetEventArgs : public EventArgs normally created via the Renderer object. */ class CEGUIEXPORT RenderTarget : - public EventSet, - public AllocatedObject + public EventSet { public: + RenderTarget(); + + virtual ~RenderTarget(); + //! Namespace for global events static const String EventNamespace; @@ -77,7 +85,7 @@ class CEGUIEXPORT RenderTarget : GeometryBuffer object holding the geometry that should be drawn to the RenderTarget. */ - virtual void draw(const GeometryBuffer& buffer) = 0; + virtual void draw(const GeometryBuffer& buffer); /*! \brief @@ -88,7 +96,7 @@ class CEGUIEXPORT RenderTarget : RenderQueue object holding the geometry that should be drawn to the RenderTarget. */ - virtual void draw(const RenderQueue& queue) = 0; + virtual void draw(const RenderQueue& queue); /*! \brief @@ -109,7 +117,7 @@ class CEGUIEXPORT RenderTarget : May be thrown if the RenderTarget does not support setting or changing its area, or if the area change can not be satisfied for some reason. */ - virtual void setArea(const Rectf& area) = 0; + virtual void setArea(const Rectf& area); /*! \brief @@ -118,7 +126,7 @@ class CEGUIEXPORT RenderTarget : \return Rect object describing the currently defined area for this RenderTarget. */ - virtual const Rectf& getArea() const = 0; + const Rectf& getArea() const; /*! \brief @@ -140,22 +148,22 @@ class CEGUIEXPORT RenderTarget : Activate the render target and put it in a state ready to be drawn to. \note - You MUST call this before doing any rendering - if you do not call this, + This must be called before doing any rendering - if it is not called, in the unlikely event that your application actually works, it will likely stop working in some future version. */ - virtual void activate() = 0; + virtual void activate(); /*! \brief Deactivate the render target after having completed rendering. \note - You MUST call this after you finish rendering to the target - if you do - not call this, in the unlikely event that your application actually + This must be called after you have finished rendering to a target - + if it is not called, in the unlikely event that your application actually works, it will likely stop working in some future version. */ - virtual void deactivate() = 0; + virtual void deactivate(); /*! \brief @@ -163,9 +171,80 @@ class CEGUIEXPORT RenderTarget : Resulting point is local to GeometryBuffer \a buff. */ virtual void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const = 0; + const glm::vec2& p_in, glm::vec2& p_out) const = 0; + + /*! + \brief + Returns a reference to the Renderer that is the owner/creator of this RenderTarget instance. + + \return + A reference to the Renderer that is the owner/creator of this RenderTarget instance. + */ + virtual Renderer& getOwner() = 0; + + /*! + \brief + Returns the current count of activations for this RenderTarget + + \return + The current count of activations. + */ + unsigned int getActivationCounter() const; + + /*! + \brief + Creates a view projection matrix for the OpenGL graphics library (Depth Range from -1 to 1) based + on this RenderTarget's current settings. + + \return + A freshly created OpenGL view projection matrix for this RenderTarget. + */ + glm::mat4 createViewProjMatrixForOpenGL() const; + + /*! + \brief + Creates a view projection matrix for the Direct3D graphics library (Depth Range from 0 to 1) based + on this RenderTarget's current settings. + + \return + A freshly created Direct3D view projection matrix for this RenderTarget. + */ + glm::mat4 createViewProjMatrixForDirect3D() const; + + /*! + \brief + Updates the view projection matrix of this Rendertarget. + */ + void updateMatrix(const glm::mat4& matrix) const; + + +protected: + /*! + \brief + The current number of activation of this RenderTarget. This is increased on every call to activate() and + will in turn be used to remove the most common redundant matrix updates of GeometryBuffers. + */ + mutable unsigned int d_activationCounter; + + //! holds defined area for the RenderTarget + Rectf d_area; + + //! Determines if the matrix is up to date + mutable bool d_matrixValid; + //! The view projection matrix + mutable glm::mat4 d_matrix; + + //! tracks viewing distance (this is set up at the same time as d_matrix) + mutable float d_viewDistance; + //! The tangent of the y-axis FOV half-angle; used to calculate viewing distance. + static const float d_yfov_tan; }; } // End of CEGUI namespace section +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + + #endif // end of guard _CEGUIRenderTarget_h_ diff --git a/cegui/include/CEGUI/RenderedString.h b/cegui/include/CEGUI/RenderedString.h index 5cbe83b2e..427e03c0e 100644 --- a/cegui/include/CEGUI/RenderedString.h +++ b/cegui/include/CEGUI/RenderedString.h @@ -47,8 +47,7 @@ namespace CEGUI Here 'string' does not refer solely to a text string, rather a string of any renderable items. */ -class CEGUIEXPORT RenderedString : - public AllocatedObject +class CEGUIEXPORT RenderedString { public: //! Constructor. @@ -94,8 +93,8 @@ class CEGUIEXPORT RenderedString : thrown if \a line is out of range. */ void draw(const Window* ref_wnd, - const size_t line, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + const size_t line, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float space_extra) const; /*! @@ -174,15 +173,13 @@ class CEGUIEXPORT RenderedString : protected: //! Collection type used to hold the string components. - typedef std::vector ComponentList; + typedef std::vector ComponentList; //! RenderedStringComponent objects that comprise this RenderedString. ComponentList d_components; //! track info for a line. first is componetn idx, second is component count. typedef std::pair LineInfo; //! Collection type used to hold details about the lines. - typedef std::vector LineList; + typedef std::vector LineList; //! lines that make up this string. LineList d_lines; //! Make this object's component list a clone of \a list. diff --git a/cegui/include/CEGUI/RenderedStringComponent.h b/cegui/include/CEGUI/RenderedStringComponent.h index a0dd08d45..15bf3680a 100644 --- a/cegui/include/CEGUI/RenderedStringComponent.h +++ b/cegui/include/CEGUI/RenderedStringComponent.h @@ -31,6 +31,8 @@ #include "CEGUI/Rect.h" #include "CEGUI/falagard/Enums.h" +#include + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) @@ -44,8 +46,7 @@ namespace CEGUI Base class representing a part of a rendered string. The 'part' represented may be a text string, an image or some other entity. */ -class CEGUIEXPORT RenderedStringComponent : - public AllocatedObject +class CEGUIEXPORT RenderedStringComponent { public: //! Destructor. @@ -81,8 +82,8 @@ class CEGUIEXPORT RenderedStringComponent : bool getAspectLock() const; //! draw the component. - virtual void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + virtual void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float vertical_space, const float space_extra) const = 0; diff --git a/cegui/include/CEGUI/RenderedStringImageComponent.h b/cegui/include/CEGUI/RenderedStringImageComponent.h index e0b2fc131..5522e6e2c 100644 --- a/cegui/include/CEGUI/RenderedStringImageComponent.h +++ b/cegui/include/CEGUI/RenderedStringImageComponent.h @@ -31,6 +31,8 @@ #include "CEGUI/ColourRect.h" #include "CEGUI/String.h" +#include + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) @@ -66,8 +68,8 @@ class CEGUIEXPORT RenderedStringImageComponent : public RenderedStringComponent const Sizef& getSize() const; // implementation of abstract base interface - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float vertical_space, const float space_extra) const; Sizef getPixelSize(const Window* ref_wnd) const; diff --git a/cegui/include/CEGUI/RenderedStringParser.h b/cegui/include/CEGUI/RenderedStringParser.h index 21cd491c2..19011fe3f 100644 --- a/cegui/include/CEGUI/RenderedStringParser.h +++ b/cegui/include/CEGUI/RenderedStringParser.h @@ -34,8 +34,7 @@ namespace CEGUI { //! Specifies interface for classes that parse text into RenderedString objects. -class CEGUIEXPORT RenderedStringParser : - public AllocatedObject +class CEGUIEXPORT RenderedStringParser { public: /*! diff --git a/cegui/include/CEGUI/RenderedStringTextComponent.h b/cegui/include/CEGUI/RenderedStringTextComponent.h index 9482b9dbc..64f16108e 100644 --- a/cegui/include/CEGUI/RenderedStringTextComponent.h +++ b/cegui/include/CEGUI/RenderedStringTextComponent.h @@ -31,6 +31,8 @@ #include "CEGUI/ColourRect.h" #include "CEGUI/String.h" +#include + // Start of CEGUI namespace section namespace CEGUI { @@ -62,8 +64,8 @@ class CEGUIEXPORT RenderedStringTextComponent : public RenderedStringComponent const ColourRect& getColours() const; // implementation of abstract base interface - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float vertical_space, const float space_extra) const; Sizef getPixelSize(const Window* ref_wnd) const; diff --git a/cegui/include/CEGUI/RenderedStringWidgetComponent.h b/cegui/include/CEGUI/RenderedStringWidgetComponent.h index 94679813b..c43fb8ef4 100644 --- a/cegui/include/CEGUI/RenderedStringWidgetComponent.h +++ b/cegui/include/CEGUI/RenderedStringWidgetComponent.h @@ -50,8 +50,8 @@ class CEGUIEXPORT RenderedStringWidgetComponent : public RenderedStringComponent const Window* getWindow() const; // implementation of abstract base interface - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float vertical_space, const float space_extra) const; Sizef getPixelSize(const Window* ref_wnd) const; diff --git a/cegui/include/CEGUI/RenderedStringWordWrapper.h b/cegui/include/CEGUI/RenderedStringWordWrapper.h index 8c1de2947..7036e3478 100644 --- a/cegui/include/CEGUI/RenderedStringWordWrapper.h +++ b/cegui/include/CEGUI/RenderedStringWordWrapper.h @@ -51,8 +51,8 @@ class RenderedStringWordWrapper : public FormattedRenderedString // implementation of base interface void format(const Window* ref_wnd, const Sizef& area_size); - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const; size_t getFormattedLineCount() const; float getHorizontalExtent(const Window* ref_wnd) const; @@ -62,8 +62,7 @@ class RenderedStringWordWrapper : public FormattedRenderedString //! Delete the current formatters and associated RenderedStrings void deleteFormatters(); //! type of collection used to track the formatted lines. - typedef std::vector LineList; + typedef std::vector LineList; //! collection of lines. LineList d_lines; }; @@ -111,7 +110,7 @@ void RenderedStringWordWrapper::format(const Window* ref_wnd, // split rstring at width into lstring and remaining rstring rstring.split(ref_wnd, line, area_size.d_width, lstring); - frs = CEGUI_NEW_AO T(*new RenderedString(lstring)); + frs = new T(*new RenderedString(lstring)); frs->format(ref_wnd, area_size); d_lines.push_back(frs); line = 0; @@ -119,7 +118,7 @@ void RenderedStringWordWrapper::format(const Window* ref_wnd, } // last line. - frs = CEGUI_NEW_AO T(*new RenderedString(rstring)); + frs = new T(*new RenderedString(rstring)); frs->format(ref_wnd, area_size); d_lines.push_back(frs); } @@ -127,17 +126,17 @@ void RenderedStringWordWrapper::format(const Window* ref_wnd, //----------------------------------------------------------------------------// template void RenderedStringWordWrapper::draw(const Window* ref_wnd, - GeometryBuffer& buffer, - const Vector2f& position, + std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const { - Vector2f line_pos(position); + glm::vec2 line_pos(position); typename LineList::const_iterator i = d_lines.begin(); for (; i != d_lines.end(); ++i) { - (*i)->draw(ref_wnd, buffer, line_pos, mod_colours, clip_rect); - line_pos.d_y += (*i)->getVerticalExtent(ref_wnd); + (*i)->draw(ref_wnd, geometry_buffers, line_pos, mod_colours, clip_rect); + line_pos.y += (*i)->getVerticalExtent(ref_wnd); } } @@ -189,9 +188,9 @@ void RenderedStringWordWrapper::deleteFormatters() // get the rendered string back from rthe formatter const RenderedString* rs = &d_lines[i]->getRenderedString(); // delete the formatter - CEGUI_DELETE_AO d_lines[i]; + delete d_lines[i]; // delete the rendered string. - CEGUI_DELETE_AO rs; + delete rs; } d_lines.clear(); diff --git a/cegui/include/CEGUI/Renderer.h b/cegui/include/CEGUI/Renderer.h index 73a246fdd..3c6bf3907 100644 --- a/cegui/include/CEGUI/Renderer.h +++ b/cegui/include/CEGUI/Renderer.h @@ -33,10 +33,21 @@ #include "CEGUI/String.h" #include "CEGUI/Size.h" #include "CEGUI/Vector.h" +#include "CEGUI/RefCounted.h" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + -// Start of CEGUI namespace section namespace CEGUI { + class RenderMaterial; + + //----------------------------------------------------------------------------// /*! \brief @@ -68,6 +79,23 @@ enum BlendMode BM_RTT_PREMULTIPLIED }; + +//----------------------------------------------------------------------------// + +/*! +\brief + Enum for the default shader types that the Renderers have to offer +*/ +enum DefaultShaderType +{ + //! A shader for solid, coloured geometry + DS_SOLID, + //! A shader for textured geometry, used in most CEGUI widgets + DS_TEXTURED, + //! Count of types + DS_COUNT +}; + //----------------------------------------------------------------------------// /*! @@ -79,10 +107,13 @@ enum BlendMode or API to draw CEGUI imagery requires that an appropriate Renderer object be available. */ -class CEGUIEXPORT Renderer : - public AllocatedObject +class CEGUIEXPORT Renderer { public: + Renderer(); + + virtual ~Renderer() {} + /*! \brief Returns the default RenderTarget object. The default render target is @@ -95,32 +126,67 @@ class CEGUIEXPORT Renderer : /*! \brief - Create a new GeometryBuffer and return a reference to it. You should - remove the GeometryBuffer from any RenderQueues and call - destroyGeometryBuffer when you want to destroy the GeometryBuffer. + Create a GeometryBuffer for textured geometry and return a reference to it. + You should remove the GeometryBuffer from any RenderQueues and call destroyGeometryBuffer + when you want to destroy the GeometryBuffer. + + \return + GeometryBuffer object. + */ + virtual GeometryBuffer& createGeometryBufferTextured(RefCounted renderMaterial) = 0; + + /*! + \brief + Creates a GeometryBuffer for textured geometry with its default RenderMaterial and return a + reference to it. + You should remove the GeometryBuffer from any RenderQueues and call destroyGeometryBuffer + when you want to destroy the GeometryBuffer. + + \return + GeometryBuffer object. + */ + GeometryBuffer& createGeometryBufferTextured(); + + /*! + \brief + Creates a GeometryBuffer for coloured geometry and return a reference to it. + You should remove the GeometryBuffer from any RenderQueues and call destroyGeometryBuffer + when you want to destroy the GeometryBuffer. + + \return + GeometryBuffer object. + */ + virtual GeometryBuffer& createGeometryBufferColoured(RefCounted renderMaterial) = 0; + + /*! + \brief + Creates a GeometryBuffer for coloured geometry with its default RenderMaterial and return a + reference to it. + You should remove the GeometryBuffer from any RenderQueues and call destroyGeometryBuffer + when you want to destroy the GeometryBuffer. \return GeometryBuffer object. */ - virtual GeometryBuffer& createGeometryBuffer() = 0; + GeometryBuffer& createGeometryBufferColoured(); /*! \brief - Destroy a GeometryBuffer that was returned when calling the - createGeometryBuffer function. Before destroying any GeometryBuffer + Destroys a GeometryBuffer that was returned when calling one of the + createGeometryBuffer functions. Before destroying any GeometryBuffer you should ensure that it has been removed from any RenderQueue that was using it. \param buffer The GeometryBuffer object to be destroyed. */ - virtual void destroyGeometryBuffer(const GeometryBuffer& buffer) = 0; + void destroyGeometryBuffer(GeometryBuffer& buffer); /*! \brief - Destroy all GeometryBuffer objects created by this Renderer. + Destroys all GeometryBuffer objects created by this Renderer. */ - virtual void destroyAllGeometryBuffers() = 0; + void destroyAllGeometryBuffers(); /*! \brief @@ -148,13 +214,13 @@ class CEGUIEXPORT Renderer : /*! \brief - Destory all TextureTarget objects created by this Renderer. + Destroys all TextureTarget objects created by this Renderer. */ virtual void destroyAllTextureTargets() = 0; /*! \brief - Create a 'null' Texture object. + Creates a 'null' Texture object. \param name String holding the name for the new texture. Texture names must be @@ -206,7 +272,7 @@ class CEGUIEXPORT Renderer : /*! \brief - Create a Texture object with the given pixel dimensions as specified by + Creates a Texture object with the given pixel dimensions as specified by \a size. \param name @@ -233,7 +299,7 @@ class CEGUIEXPORT Renderer : /*! \brief - Destroy a Texture object that was previously created by calling the + Destroys a Texture object that was previously created by calling the createTexture functions. \param texture @@ -243,7 +309,7 @@ class CEGUIEXPORT Renderer : /*! \brief - Destroy a Texture object that was previously created by calling the + Destroys a Texture object that was previously created by calling the createTexture functions. \param name @@ -253,13 +319,13 @@ class CEGUIEXPORT Renderer : /*! \brief - Destroy all Texture objects created by this Renderer. + Destroys all Texture objects created by this Renderer. */ virtual void destroyAllTextures() = 0; /*! \brief - Return a Texture object that was previously created by calling the + Returns a Texture object that was previously created by calling the createTexture functions. \param name @@ -276,20 +342,20 @@ class CEGUIEXPORT Renderer : /*! \brief - Perform any operations required to put the system into a state ready + Performs any operations required to put the system into a state ready for rendering operations to begin. */ virtual void beginRendering() = 0; /*! \brief - Perform any operations required to finalise rendering. + Performs any operations required to finalise rendering. */ virtual void endRendering() = 0; /*! \brief - Set the size of the display or host window in pixels for this Renderer + Sets the size of the display or host window in pixels for this Renderer object. This is intended to be called by the System as part of the notification @@ -308,7 +374,7 @@ class CEGUIEXPORT Renderer : /*! \brief - Return the size of the display or host window in pixels. + Returns the size of the display or host window in pixels. \return Size object describing the pixel dimesntions of the current display or @@ -318,17 +384,17 @@ class CEGUIEXPORT Renderer : /*! \brief - Return the resolution of the display or host window in dots per inch. + Returns the resolution of the display or host window in dots per inch. \return - Vector2 object that describes the resolution of the display or host + vec2 object that describes the resolution of the display or host window in DPI. */ - virtual const Vector2f& getDisplayDPI() const = 0; + virtual const glm::vec2& getDisplayDPI() const = 0; /*! \brief - Return the pixel size of the maximum supported texture. + Returns the pixel size of the maximum supported texture. \return Size of the maximum supported texture in pixels. @@ -337,18 +403,100 @@ class CEGUIEXPORT Renderer : /*! \brief - Return identification string for the renderer module. + Returns identification string for the renderer module. \return String object holding text that identifies the Renderer in use. */ virtual const String& getIdentifierString() const = 0; - //! Destructor. - virtual ~Renderer() {} + /*! + \brief + Creates a copy of the specified default shader type. + + \param shaderType + Specifies the type of CEGUI shader that the RenderMaterial should be based on + + \return + A copy of the specified default shader type. + */ + virtual RefCounted createRenderMaterial(const DefaultShaderType shaderType) const = 0; + + /*! + \brief + Marks all matrices of all GeometryBuffers as dirty, so that they will be updated before their next usage. + This is a special function that will only be used if a RenderTarget has been rendered more than the amount + of numbers that can be stored in the counter, at which point the counter restarts at 0. This is necessary + to ensure that no Matrix will be reused although it actually would need updating (for example in the case + the Buffer was not rendered for exactly the amount of maximum countable times, and is updated again exactly at + the same count) + */ + void invalidateGeomBufferMatrices(const CEGUI::RenderTarget* renderTarget); + + /*! + \brief + Sets the active render target. + + \param renderTarget + The active RenderTarget. + */ + void setActiveRenderTarget(RenderTarget* renderTarget); + + /*! + \brief + Retruns the active render target. + + \return + The active RenderTarget. + */ + RenderTarget* getActiveRenderTarget(); + + /*! + \brief + Sets the currently active view projection matrix. + + \param viewProjectionMatrix + The view projection matrix that should be set as the new active matrix. + */ + virtual void setViewProjectionMatrix(const glm::mat4& viewProjectionMatrix); + + /*! + \brief + Returns the currently active view projection matrix. + + \return + The currently active view projection matrix. + */ + const glm::mat4& getViewProjectionMatrix() const; + +protected: + /*! + \brief + Adds a created GeometryBuffer, which was returned when calling one of the + createGeometryBuffer functions, to the list of GeometryBuffers. + + \param buffer + The GeometryBuffer object to be destroyed. + */ + void addGeometryBuffer(GeometryBuffer& buffer); + + //! The currently active RenderTarget + RenderTarget* d_activeRenderTarget; + + //! The currently active view projection matrix + glm::mat4 d_viewProjectionMatrix; +private: + //! container type used to hold GeometryBuffers created. + typedef std::set GeometryBufferSet; + //! Container used to track geometry buffers. + GeometryBufferSet d_geometryBuffers; + }; -} // End of CEGUI namespace section +} +#if defined(_MSC_VER) +# pragma warning(pop) +#endif -#endif // end of guard _CEGUIRenderer_h_ +#endif diff --git a/cegui/include/CEGUI/RendererModules/Direct3D10/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/Direct3D10/GeometryBuffer.h deleted file mode 100644 index d4a3f08ac..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D10/GeometryBuffer.h +++ /dev/null @@ -1,152 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D10GeometryBuffer_h_ -#define _CEGUIDirect3D10GeometryBuffer_h_ - -#include "../../GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D10/Renderer.h" -#include "../../Rect.h" -#include "../../Quaternion.h" - -#include - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -class Direct3D10Texture; - -//! Implementation of CEGUI::GeometryBuffer for the Direct3D 10 API. -class D3D10_GUIRENDERER_API Direct3D10GeometryBuffer : public GeometryBuffer -{ -public: - //! Constructor - Direct3D10GeometryBuffer(Direct3D10Renderer& owner); - - //! Destructor - ~Direct3D10GeometryBuffer(); - - //! return pointer to D3DXMATRIX used by this GeometryBuffer - const D3DXMATRIX* getMatrix() const; - - // Implement GeometryBuffer interface. - void draw() const; - void setTranslation(const Vector3f& v); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); - void setClippingRegion(const Rectf& region); - void appendVertex(const Vertex& vertex); - void appendGeometry(const Vertex* const vbuff, uint vertex_count); - void setActiveTexture(Texture* texture); - void reset(); - Texture* getActiveTexture() const; - uint getVertexCount() const; - uint getBatchCount() const; - void setRenderEffect(RenderEffect* effect); - RenderEffect* getRenderEffect(); - void setClippingActive(const bool active); - bool isClippingActive() const; - -protected: - //! update cached matrix - void updateMatrix() const; - //! Synchronise data in the hardware buffer with what's been added - void syncHardwareBuffer() const; - //! allocate the hardware vertex buffer large enough for \a count vertices. - void allocateVertexBuffer(const size_t count) const; - //! cleanup the hardware vertex buffer. - void cleanupVertexBuffer() const; - - //! internal Vertex structure used for Direct3D based geometry. - struct D3DVertex - { - //! The transformed position for the vertex. - FLOAT x, y, z; - //! colour of the vertex. - DWORD diffuse; - //! texture coordinates. - float tu, tv; - }; - - //! type to track info for per-texture sub batches of geometry - struct BatchInfo - { - const ID3D10ShaderResourceView* texture; - uint vertexCount; - bool clip; - }; - - // Direct3D10Renderer object that created and owns this GeometryBuffer. - Direct3D10Renderer& d_owner; - //! The D3D Device - ID3D10Device& d_device; - //! last texture that was set as active - Direct3D10Texture* d_activeTexture; - //! hardware buffer where vertices will be drawn from. - mutable ID3D10Buffer* d_vertexBuffer; - //! Size of the currently allocated vertex buffer. - mutable UINT d_bufferSize; - //! whether the h/w buffer is in sync with the added geometry - mutable bool d_bufferSynched; - //! type of container that tracks BatchInfos. - typedef std::vector BatchList; - //! list of texture batches added to the geometry buffer - BatchList d_batches; - //! type of container used to queue the geometry - typedef std::vector VertexList; - //! container where added geometry is stored. - VertexList d_vertices; - //! rectangular clip region - Rectf d_clipRect; - //! whether clipping will be active for the current batch - bool d_clippingActive; - //! translation vector - Vector3f d_translation; - //! rotation Quaternion - Quaternion d_rotation; - //! pivot point for rotation - Vector3f d_pivot; - //! RenderEffect that will be used by the GeometryBuffer - RenderEffect* d_effect; - //! model matrix cache - mutable D3DXMATRIX d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; -}; - - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D10GeometryBuffer_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D10/RenderTarget.h b/cegui/include/CEGUI/RendererModules/Direct3D10/RenderTarget.h deleted file mode 100644 index 985e31a9a..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D10/RenderTarget.h +++ /dev/null @@ -1,88 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D10RenderTarget_h_ -#define _CEGUIDirect3D10RenderTarget_h_ - -#include "../../RenderTarget.h" -#include "CEGUI/RendererModules/Direct3D10/Renderer.h" -#include "../../Rect.h" -#include - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -//! Implementation of an ntermediate RenderTarget for the Direct3D 10 API -template -class D3D10_GUIRENDERER_API Direct3D10RenderTarget : public T -{ -public: - //! Constructor - Direct3D10RenderTarget(Direct3D10Renderer& owner); - - // implement parts of RenderTarget interface - void draw(const GeometryBuffer& buffer); - void draw(const RenderQueue& queue); - void setArea(const Rectf& area); - const Rectf& getArea() const; - void activate(); - void deactivate(); - void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const; - -protected: - //! helper that initialises the cached matrix - void updateMatrix() const; - //! helper to initialise the D3D10_VIEWPORT \a vp for this target. - void setupViewport(D3D10_VIEWPORT& vp) const; - - //! Renderer that created and owns the render target. - Direct3D10Renderer& d_owner; - //! D3D10Device interface. - ID3D10Device& d_device; - //! holds defined area for the RenderTarget - Rectf d_area; - //! projection / view matrix cache - mutable D3DXMATRIX d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; - //! tracks viewing distance (this is set up at the same time as d_matrix) - mutable float d_viewDistance; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D10RenderTarget_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D10/Renderer.h b/cegui/include/CEGUI/RendererModules/Direct3D10/Renderer.h deleted file mode 100644 index 4732574e2..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D10/Renderer.h +++ /dev/null @@ -1,232 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D10Renderer_h_ -#define _CEGUIDirect3D10Renderer_h_ - -#include "../../Renderer.h" -#include "../../Size.h" -#include "../../Vector.h" -#include -#include - -#if (defined( __WIN32__ ) || defined( _WIN32 )) && !defined(CEGUI_STATIC) -# ifdef CEGUIDIRECT3D10RENDERER_EXPORTS -# define D3D10_GUIRENDERER_API __declspec(dllexport) -# else -# define D3D10_GUIRENDERER_API __declspec(dllimport) -# endif -#else -# define D3D10_GUIRENDERER_API -#endif - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// D3D forward refs -struct ID3D10Device; -struct ID3D10Effect; -struct ID3D10EffectTechnique; -struct ID3D10InputLayout; -struct ID3D10EffectShaderResourceVariable; -struct ID3D10EffectMatrixVariable; -struct ID3D10ShaderResourceView; -struct D3DXMATRIX; - -// Start of CEGUI namespace section -namespace CEGUI -{ -class Direct3D10GeometryBuffer; -class Direct3D10Texture; - -//! Renderer implementation using Direct3D 10. -class D3D10_GUIRENDERER_API Direct3D10Renderer : public Renderer -{ -public: - /*! - \brief - Convenience function that creates the required objects to initialise the - CEGUI system. - - This will create and initialise the following objects for you: - - CEGUI::Direct3D10Renderer - - CEGUI::DefaultResourceProvider - - CEGUI::System - - \param device - Pointer to the ID3D10Device interface that is to be used for CEGUI - rendering operations. - - \param abi - This must be set to CEGUI_VERSION_ABI - - \return - Reference to the CEGUI::Direct3D10Renderer object that was created. - */ - static Direct3D10Renderer& bootstrapSystem(ID3D10Device* device, - const int abi = CEGUI_VERSION_ABI); - - /*! - \brief - Convenience function to cleanup the CEGUI system and related objects - that were created by calling the bootstrapSystem function. - - This function will destroy the following objects for you: - - CEGUI::System - - CEGUI::DefaultResourceProvider - - CEGUI::Direct3D10Renderer - - \note - If you did not initialise CEGUI by calling the bootstrapSystem function, - you should \e not call this, but rather delete any objects you created - manually. - */ - static void destroySystem(); - - /*! - \brief - Create an Direct3D10Renderer object. - */ - static Direct3D10Renderer& create(ID3D10Device* device, - const int abi = CEGUI_VERSION_ABI); - - /*! - \brief - Destroy an Direct3D10Renderer object. - - \param renderer - The Direct3D10Renderer object to be destroyed. - */ - static void destroy(Direct3D10Renderer& renderer); - - //! return the ID3D10Device used by this renderer object. - ID3D10Device& getDirect3DDevice() const; - - //! low-level function that binds the technique pass ready for use - void bindTechniquePass(const BlendMode mode, const bool clipped); - //! low-level function to set the texture shader resource view to be used. - void setCurrentTextureShaderResource(ID3D10ShaderResourceView* srv); - //! low-level function to set the projection matrix to be used. - void setProjectionMatrix(D3DXMATRIX& matrix); - //! low-level function to set the world matrix to be used. - void setWorldMatrix(D3DXMATRIX& matrix); - - // Implement interface from Renderer - RenderTarget& getDefaultRenderTarget(); - GeometryBuffer& createGeometryBuffer(); - void destroyGeometryBuffer(const GeometryBuffer& buffer); - void destroyAllGeometryBuffers(); - TextureTarget* createTextureTarget(); - void destroyTextureTarget(TextureTarget* target); - void destroyAllTextureTargets(); - Texture& createTexture(const String& name); - Texture& createTexture(const String& name, - const String& filename, - const String& resourceGroup); - Texture& createTexture(const String& name, const Sizef& size); - void destroyTexture(Texture& texture); - void destroyTexture(const String& name); - void destroyAllTextures(); - Texture& getTexture(const String& name) const; - bool isTextureDefined(const String& name) const; - void beginRendering(); - void endRendering(); - void setDisplaySize(const Sizef& sz); - const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; - uint getMaxTextureSize() const; - const String& getIdentifierString() const; - -protected: - //! constructor - Direct3D10Renderer(ID3D10Device* device); - - //! destructor. - ~Direct3D10Renderer(); - - //! return size of the D3D device viewport. - Sizef getViewportSize(); - - //! helper to throw exception if name is already used. - void throwIfNameExists(const String& name) const; - //! helper to safely log the creation of a named texture - static void logTextureCreation(const String& name); - //! helper to safely log the destruction of a named texture - static void logTextureDestruction(const String& name); - - //! String holding the renderer identification text. - static String d_rendererID; - //! The D3D device we're using to render with. - ID3D10Device* d_device; - //! What the renderer considers to be the current display size. - Sizef d_displaySize; - //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; - //! The default RenderTarget - RenderTarget* d_defaultTarget; - //! container type used to hold TextureTargets we create. - typedef std::vector TextureTargetList; - //! Container used to track texture targets. - TextureTargetList d_textureTargets; - //! container type used to hold GeometryBuffers we create. - typedef std::vector GeometryBufferList; - //! Container used to track geometry buffers. - GeometryBufferList d_geometryBuffers; - //! container type used to hold Textures we create. - typedef std::map TextureMap; - //! Container used to track textures. - TextureMap d_textures; - //! Effect (shader) used when rendering. - ID3D10Effect* d_effect; - //! Rendering technique that supplies scissor clipped BM_NORMAL type rendering - ID3D10EffectTechnique* d_normalClippedTechnique; - //! Rendering technique that supplies BM_NORMAL type rendering - ID3D10EffectTechnique* d_normalUnclippedTechnique; - //! Rendering technique that supplies scissor clipped BM_RTT_PREMULTIPLIED type rendering - ID3D10EffectTechnique* d_premultipliedClippedTechnique; - //! Rendering technique that supplies BM_RTT_PREMULTIPLIED type rendering - ID3D10EffectTechnique* d_premultipliedUnclippedTechnique; - //! D3D10 input layout describing the vertex format we use. - ID3D10InputLayout* d_inputLayout; - //! Variable to access current texture (actually shader resource view) - ID3D10EffectShaderResourceVariable* d_boundTextureVariable; - //! Variable to access world matrix used in geometry transformation. - ID3D10EffectMatrixVariable* d_worldMatrixVariable; - //! Variable to access projection matrix used in geometry transformation. - ID3D10EffectMatrixVariable* d_projectionMatrixVariable; -}; - - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D10Renderer_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D10/Texture.h b/cegui/include/CEGUI/RendererModules/Direct3D10/Texture.h deleted file mode 100644 index ee5eec322..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D10/Texture.h +++ /dev/null @@ -1,154 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D10Texture_h_ -#define _CEGUIDirect3D10Texture_h_ - -#include "../../Texture.h" -#include "CEGUI/RendererModules/Direct3D10/Renderer.h" -#include "../../Size.h" -#include "../../Vector.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// d3d forward refs -struct ID3D10Device; -struct ID3D10Texture2D; -struct ID3D10ShaderResourceView; - -// Start of CEGUI namespace section -namespace CEGUI -{ -//! Texture implementation for the Direct3D10Renderer. -class D3D10_GUIRENDERER_API Direct3D10Texture : public Texture -{ -public: - /*! - \brief - set the D3D10 texture that this Texture is based on to the specified - texture. - */ - void setDirect3DTexture(ID3D10Texture2D* tex); - - /*! - \brief - Return the internal D3D10 texture used by this Texture object. - - \return - Pointer to the D3D10 texture interface that this object is using. - */ - ID3D10Texture2D* getDirect3DTexture() const; - - /*! - \brief - Return the internal D3D10 shader resource view for the texture. - - \return - Pointer to the ID3D10ShaderResourceView interface. - */ - ID3D10ShaderResourceView* getDirect3DShaderResourceView() const; - - /*! - \brief - Sets what the texture should consider as the original data size. - - \note - This also causes the texel scaling values to be updated. - */ - void setOriginalDataSize(const Sizef& sz); - - // implement abstract members from base class. - const String& getName() const; - const Sizef& getSize() const; - const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; - void loadFromFile(const String& filename, const String& resourceGroup); - void loadFromMemory(const void* buffer, const Sizef& buffer_size, - PixelFormat pixel_format); - void blitFromMemory(const void* sourceData, const Rectf& area); - void blitToMemory(void* targetData); - bool isPixelFormatSupported(const PixelFormat fmt) const; - -protected: - // Friends to allow Renderer to peform construction and destruction - friend Texture& Direct3D10Renderer::createTexture(const String&); - friend Texture& Direct3D10Renderer::createTexture(const String&, - const String&, - const String&); - friend Texture& Direct3D10Renderer::createTexture(const String&, - const Sizef&); - //friend Texture& Direct3D10Renderer::createTexture(ID3D10Texture2D* tex); - friend void Direct3D10Renderer::destroyTexture(Texture&); - friend void Direct3D10Renderer::destroyTexture(const String&); - - //! Basic constructor. - Direct3D10Texture(ID3D10Device& device, const String&); - //! Construct texture from an image file. - Direct3D10Texture(ID3D10Device& device, const String&, - const String& filename, const String& resourceGroup); - //! Construct texture with a given size. - Direct3D10Texture(ID3D10Device& device, const String&, const Sizef& sz); - //! Construct texture that wraps an existing D3D10 texture. - Direct3D10Texture(ID3D10Device& device, const String&, ID3D10Texture2D* tex); - //! Destructor. - virtual ~Direct3D10Texture(); - - //! clean up the internal texture. - void cleanupDirect3D10Texture(); - //! updates cached scale value used to map pixels to texture co-ords. - void updateCachedScaleValues(); - //! set d_size to actual texture size (d_dataSize is used if query fails) - void updateTextureSize(); - //! creates shader resource view for the current D3D texture - void initialiseShaderResourceView(); - - //! D3D device used to do the business. - ID3D10Device& d_device; - //! The D3D 10 texture we're wrapping. - ID3D10Texture2D* d_texture; - //! Shader resource view for the texture. - ID3D10ShaderResourceView* d_resourceView; - //! Size of the texture. - Sizef d_size; - //! original pixel of size data loaded into texture - Sizef d_dataSize; - //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; - //! The name used when the texture was created. - const String d_name; -}; - - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D10Texture_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D10/TextureTarget.h b/cegui/include/CEGUI/RendererModules/Direct3D10/TextureTarget.h deleted file mode 100644 index 4d732abbd..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D10/TextureTarget.h +++ /dev/null @@ -1,104 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D10TextureTarget_h_ -#define _CEGUIDirect3D10TextureTarget_h_ - -#include "CEGUI/RendererModules/Direct3D10/RenderTarget.h" -#include "../../TextureTarget.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4250) -# pragma warning(disable : 4251) -#endif - -// d3d forward refs -struct ID3D10Texture2D; -struct ID3D10RenderTargetView; -struct ID3D10DepthStencilView; - -// Start of CEGUI namespace section -namespace CEGUI -{ -class Direct3D10Texture; - -//! Direct3D10TextureTarget - allows rendering to Direct3D 10 textures. -class D3D10_GUIRENDERER_API Direct3D10TextureTarget : public Direct3D10RenderTarget -{ -public: - Direct3D10TextureTarget(Direct3D10Renderer& owner); - virtual ~Direct3D10TextureTarget(); - - // overrides from Direct3D10RenderTarget - void activate(); - void deactivate(); - // implementation of RenderTarget interface - bool isImageryCache() const; - // implementation of TextureTarget interface - void clear(); - Texture& getTexture() const; - void declareRenderSize(const Sizef& sz); - bool isRenderingInverted() const; - -protected: - //! default size of created texture objects - static const float DEFAULT_SIZE; - //! static data used for creating texture names - static uint s_textureNumber; - //! helper to generate unique texture names - static String generateTextureName(); - - //! allocate and set up the texture used for rendering. - void initialiseRenderTexture(); - //! clean up the texture used for rendering. - void cleanupRenderTexture(); - //! resize the texture - void resizeRenderTexture(); - //! switch to the texture surface & depth buffer - void enableRenderTexture(); - //! switch back to previous surface - void disableRenderTexture(); - - //! Direct3D10 texture that's rendered to. - ID3D10Texture2D* d_texture; - //! render target view for d_texture - ID3D10RenderTargetView* d_renderTargetView; - //! we use this to wrap d_texture so it can be used by the core CEGUI lib. - Direct3D10Texture* d_CEGUITexture; - //! render target view that was bound before this target was activated - ID3D10RenderTargetView* d_previousRenderTargetView; - //! depth stencil view that was bound before this target was activated - ID3D10DepthStencilView* d_previousDepthStencilView; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D10TextureTarget_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/Direct3D11/GeometryBuffer.h index 4c482fb92..d080c3965 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D11/GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/GeometryBuffer.h @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -26,126 +27,81 @@ #ifndef _CEGUIDirect3D11GeometryBuffer_h_ #define _CEGUIDirect3D11GeometryBuffer_h_ -#include "../../GeometryBuffer.h" +#include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/Direct3D11/Renderer.h" -#include "../../Rect.h" -#include "../../Quaternion.h" - - +#include "CEGUI/Rect.h" #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif -// Start of CEGUI namespace section + namespace CEGUI { class Direct3D11Texture; -//! Implementation of CEGUI::GeometryBuffer for the Direct3D 10 API. +//! Implementation of CEGUI::GeometryBuffer for the Direct3D 11 API. class D3D11_GUIRENDERER_API Direct3D11GeometryBuffer : public GeometryBuffer { public: //! Constructor - Direct3D11GeometryBuffer(Direct3D11Renderer& owner); + Direct3D11GeometryBuffer(Direct3D11Renderer& owner, CEGUI::RefCounted renderMaterial); //! Destructor ~Direct3D11GeometryBuffer(); - //! return pointer to D3DXMATRIX used by this GeometryBuffer - const D3DXMATRIX* getMatrix() const; // Implement GeometryBuffer interface. - void draw() const; - void setTranslation(const Vector3f& v); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); - void setClippingRegion(const Rectf& region); - void appendVertex(const Vertex& vertex); - void appendGeometry(const Vertex* const vbuff, uint vertex_count); - void setActiveTexture(Texture* texture); - void reset(); - Texture* getActiveTexture() const; - uint getVertexCount() const; - uint getBatchCount() const; - void setRenderEffect(RenderEffect* effect); - RenderEffect* getRenderEffect(); - void setClippingActive(const bool active); - bool isClippingActive() const; + virtual void draw() const; + virtual void appendGeometry(const float* vertex_data, std::size_t array_size); + virtual void setClippingRegion(const Rectf& region); + + /* + \brief + The update function that is to be called when all the vertex attributes + are set. + + \return Returns the created D3D input layout for the attribute layout of the used shader. + */ + void finaliseVertexAttributes(); protected: - //! update cached matrix + //! Update the cached matrices void updateMatrix() const; //! Synchronise data in the hardware buffer with what's been added - void syncHardwareBuffer() const; - //! allocate the hardware vertex buffer large enough for \a count vertices. - void allocateVertexBuffer(const size_t count) const; + void updateVertexBuffer() const; + //! Allocates a hardware vertex buffer of size 'dataSize' (size in bytes). + void allocateVertexBuffer(const UINT dataSize) const; //! cleanup the hardware vertex buffer. void cleanupVertexBuffer() const; - - //! internal Vertex structure used for Direct3D based geometry. - struct D3DVertex - { - //! The transformed position for the vertex. - FLOAT x, y, z; - //! colour of the vertex. - DWORD diffuse; - //! texture coordinates. - float tu, tv; - }; - - //! type to track info for per-texture sub batches of geometry - struct BatchInfo - { - const ID3D11ShaderResourceView* texture; - uint vertexCount; - bool clip; - }; - + //! Draws the vertex data depending on the fill rule that was set for this object. + void drawDependingOnFillRule() const; + //! Calls the D3D11 function fot setting the scissor rectangle + void setScissorRects() const; // Direct3D11Renderer object that created and owns this GeometryBuffer. Direct3D11Renderer& d_owner; //! The D3D Device - IDevice11& d_device; - //! last texture that was set as active - Direct3D11Texture* d_activeTexture; + ID3D11Device* d_device; + //! The D3D DeviceContext + ID3D11DeviceContext* d_deviceContext; //! hardware buffer where vertices will be drawn from. mutable ID3D11Buffer* d_vertexBuffer; //! Size of the currently allocated vertex buffer. mutable UINT d_bufferSize; - //! whether the h/w buffer is in sync with the added geometry - mutable bool d_bufferSynched; - //! type of container that tracks BatchInfos. - typedef std::vector BatchList; - //! list of texture batches added to the geometry buffer - BatchList d_batches; - //! type of container used to queue the geometry - typedef std::vector VertexList; - //! container where added geometry is stored. - VertexList d_vertices; //! rectangular clip region Rectf d_clipRect; - //! whether clipping will be active for the current batch - bool d_clippingActive; - //! translation vector - Vector3f d_translation; - //! rotation vector - Quaternion d_rotation; - //! pivot point for rotation - Vector3f d_pivot; - //! RenderEffect that will be used by the GeometryBuffer - RenderEffect* d_effect; - //! model matrix cache - mutable D3DXMATRIX d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; + //! Cache of the model view projection matrix + mutable glm::mat4 d_matrix; + //! D3D11 input layout describing the vertex format we use. + ID3D11InputLayout* d_inputLayout; }; -} // End of CEGUI namespace section +} #if defined(_MSC_VER) # pragma warning(pop) #endif -#endif // end of guard _CEGUIDirect3D11GeometryBuffer_h_ +#endif diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/RenderTarget.h b/cegui/include/CEGUI/RendererModules/Direct3D11/RenderTarget.h index ce04ce866..1bf83bad7 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D11/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/RenderTarget.h @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -23,13 +24,12 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIDirect3D10RenderTarget_h_ -#define _CEGUIDirect3D10RenderTarget_h_ +#ifndef _CEGUIDirect3D11RenderTarget_h_ +#define _CEGUIDirect3D11RenderTarget_h_ #include "../../RenderTarget.h" #include "CEGUI/RendererModules/Direct3D11/Renderer.h" #include "../../Rect.h" -#include #if defined(_MSC_VER) @@ -49,40 +49,32 @@ class D3D11_GUIRENDERER_API Direct3D11RenderTarget : public T Direct3D11RenderTarget(Direct3D11Renderer& owner); // implement parts of RenderTarget interface - void draw(const GeometryBuffer& buffer); - void draw(const RenderQueue& queue); - void setArea(const Rectf& area); - const Rectf& getArea() const; void activate(); - void deactivate(); void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const; + const glm::vec2& p_in, + glm::vec2& p_out) const; + // implementing the virtual function with a covariant return type + virtual Direct3D11Renderer& getOwner(); protected: //! helper that initialises the cached matrix void updateMatrix() const; - //! helper to initialise the D3D10_VIEWPORT \a vp for this target. + //! helper to initialise the viewport \a vp for this target. void setupViewport(D3D11_VIEWPORT& vp) const; //! Renderer that created and owns the render target. Direct3D11Renderer& d_owner; - //! D3D10Device interface. - IDevice11& d_device; - //! holds defined area for the RenderTarget - Rectf d_area; - //! projection / view matrix cache - mutable D3DXMATRIX d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; - //! tracks viewing distance (this is set up at the same time as d_matrix) - mutable float d_viewDistance; + + //! The D3D Device + ID3D11Device& d_device; + //! The D3D DeviceContext + ID3D11DeviceContext& d_deviceContext; }; -} // End of CEGUI namespace section +} #if defined(_MSC_VER) # pragma warning(pop) #endif -#endif // end of guard _CEGUIDirect3D10RenderTarget_h_ +#endif diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/Renderer.h b/cegui/include/CEGUI/RendererModules/Direct3D11/Renderer.h index da1523d9f..cb6cd4eac 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D11/Renderer.h +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/Renderer.h @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -29,6 +30,9 @@ #include "../../Renderer.h" #include "../../Size.h" #include "../../Vector.h" + +#include + #include #include @@ -50,35 +54,49 @@ // D3D forward refs struct ID3D11Device; struct ID3D11DeviceContext; -struct ID3DX11Effect;//D3DXEffect11 in dependences -struct ID3DX11EffectTechnique;//D3DXEffect11 in dependences struct ID3D11InputLayout; -struct ID3DX11EffectShaderResourceVariable;//D3DXEffect11 in dependences -struct ID3DX11EffectMatrixVariable;//D3DXEffect11 in dependences -struct ID3D11ShaderResourceView;//D3DXEffect11 in dependences -struct D3DXMATRIX; #include -#include -#include - - -struct IDevice11//little structure that keeps both device, in order to reduce copy & paste around module -{ - //! The D3D device context we're using to create various resources with. - ID3D11Device* d_device; - //! The D3D device context we're using to render - ID3D11DeviceContext* d_context; -}; // Start of CEGUI namespace section namespace CEGUI { class Direct3D11GeometryBuffer; class Direct3D11Texture; +class Direct3D11ShaderWrapper; + +/*! +The CEGUI Direct3D11 Renderer -//! Renderer implementation using Direct3D 10. +This Renderer is fully backwards compatible to Direct3D9 (down to D3D_FEATURE_LEVEL_9_1) +and Direct3D10. When you creating your Direct3D11 Device be sure to specify the +Feature Level(s) you can and want to support to create a device of the correct Direct3D +version. The order of submitted Feature Levels determines in which order the creation is +attempted, e.g.: + +@code{.cpp} +const D3D_FEATURE_LEVEL featureLevels[] = +{ + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1, +}; + +// initialise main parts of D3D +HRESULT result = D3D11CreateDeviceAndSwapChain(0, D3D_DRIVER_TYPE_HARDWARE, + 0, creationFlags, featureLevels, + 6, D3D11_SDK_VERSION, + pSwapChainDesc, ppSwapChain, + ppDevice, pFeatureLevel, + ppImmediateContext); +@endcode + +Click this link for more info about the Direct3D11 device creation +*/ class D3D11_GUIRENDERER_API Direct3D11Renderer : public Renderer { public: @@ -131,7 +149,7 @@ class D3D11_GUIRENDERER_API Direct3D11Renderer : public Renderer \brief Create an Direct3D11Renderer object. */ - static Direct3D11Renderer& create(ID3D11Device* device,ID3D11DeviceContext* context, + static Direct3D11Renderer& create(ID3D11Device* device, ID3D11DeviceContext* deviceContext, const int abi = CEGUI_VERSION_ABI); /*! @@ -143,29 +161,28 @@ class D3D11_GUIRENDERER_API Direct3D11Renderer : public Renderer */ static void destroy(Direct3D11Renderer& renderer); -// //! return the ID3D10Device used by this renderer object. -// ID3D11Device& getDirect3DDevice() const; -// -// //! return the ID3D11Device context used by this renderer object. -// ID3D11DeviceContext& getDirect3DDeviceContext() const; - - //returns d3d11 container for further rendering and creating - IDevice11& getDirect3DDevice(); - - //! low-level function that binds the technique pass ready for use - void bindTechniquePass(const BlendMode mode, const bool clipped); - //! low-level function to set the texture shader resource view to be used. - void setCurrentTextureShaderResource(ID3D11ShaderResourceView* srv); - //! low-level function to set the projection matrix to be used. - void setProjectionMatrix(D3DXMATRIX& matrix); - //! low-level function to set the world matrix to be used. - void setWorldMatrix(D3DXMATRIX& matrix); + //Returns Direct3D device + ID3D11Device* getDirect3DDevice(); + //Returns Direct3D context + ID3D11DeviceContext* getDirect3DDeviceContext(); + + /*! + \brief + Binds the corresponding D3D11 blend mode. + */ + void bindBlendMode(BlendMode d_blendMode); + + /*! + \brief + Binds the D3D11 RasterizerState corresponding to the scissorEnabled boolean. + */ + void bindRasterizerState(bool scissorEnabled); // Implement interface from Renderer RenderTarget& getDefaultRenderTarget(); - GeometryBuffer& createGeometryBuffer(); - void destroyGeometryBuffer(const GeometryBuffer& buffer); - void destroyAllGeometryBuffers(); + RefCounted createRenderMaterial(const DefaultShaderType shaderType) const; + GeometryBuffer& createGeometryBufferColoured(CEGUI::RefCounted renderMaterial); + GeometryBuffer& createGeometryBufferTextured(CEGUI::RefCounted renderMaterial); TextureTarget* createTextureTarget(); void destroyTextureTarget(TextureTarget* target); void destroyAllTextureTargets(); @@ -183,10 +200,9 @@ class D3D11_GUIRENDERER_API Direct3D11Renderer : public Renderer void endRendering(); void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; - protected: //! constructor Direct3D11Renderer(ID3D11Device* device,ID3D11DeviceContext* context); @@ -194,6 +210,23 @@ class D3D11_GUIRENDERER_API Direct3D11Renderer : public Renderer //! destructor. ~Direct3D11Renderer(); + //! Initialises the D3D states + void initialiseSamplerStates(); + void initialiseDepthStencilState(); + void initialiseRasterizerStates(); + void initialiseBlendStates(); + + //! Initialises the ShaderManager and the required D3D11 shaders + void initialiseShaders(); + //! Initialises the D3D11 ShaderWrapper for textured objects + void initialiseStandardTexturedShaderWrapper(); + //! Initialises the D3D11 ShaderWrapper for coloured objects + void initialiseStandardColouredShaderWrapper(); + //! Wrapper of the OpenGL shader we will use for textured geometry + Direct3D11ShaderWrapper* d_shaderWrapperTextured; + //! Wrapper of the OpenGL shader we will use for solid geometry + Direct3D11ShaderWrapper* d_shaderWrapperSolid; + //! return size of the D3D device viewport. Sizef getViewportSize(); @@ -205,48 +238,43 @@ class D3D11_GUIRENDERER_API Direct3D11Renderer : public Renderer static void logTextureDestruction(const String& name); //! String holding the renderer identification text. - static String d_rendererID; - //! The D3D device we're using to render with. - - IDevice11 d_device; + const static String d_rendererID; + //! The D3D device context we're using to create various resources with. + ID3D11Device* d_device; + //! The D3D device context we're using to render + ID3D11DeviceContext* d_deviceContext; + //! BlendState for regular blending in CEGUI + ID3D11BlendState* d_blendStateNormal; + //! BlendState for premultiplied blending in CEGUI + ID3D11BlendState* d_blendStatePreMultiplied; + //! The currently set BlendState + ID3D11BlendState* d_currentBlendState; + //! The rasterizer state for CEGUI with scissor enabled + ID3D11RasterizerState* d_rasterizerStateScissorEnabled; + //! The rasterizer state for CEGUI with scissor enabled + ID3D11RasterizerState* d_rasterizerStateScissorDisabled; + //! The current rasterizer state + ID3D11RasterizerState* d_currentRasterizerState; + //! The default depth/stencil state + ID3D11DepthStencilState* d_depthStencilStateDefault; //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. typedef std::vector TextureTargetList; //! Container used to track texture targets. TextureTargetList d_textureTargets; - //! container type used to hold GeometryBuffers we create. - typedef std::vector GeometryBufferList; - //! Container used to track geometry buffers. - GeometryBufferList d_geometryBuffers; //! container type used to hold Textures we create. - typedef std::map TextureMap; + typedef std::map TextureMap; //! Container used to track textures. TextureMap d_textures; - //! Effect (shader) used when rendering. - ID3DX11Effect* d_effect; - //! Rendering technique that supplies scissor clipped BM_NORMAL type rendering - ID3DX11EffectTechnique* d_normalClippedTechnique; - //! Rendering technique that supplies BM_NORMAL type rendering - ID3DX11EffectTechnique* d_normalUnclippedTechnique; - //! Rendering technique that supplies scissor clipped BM_RTT_PREMULTIPLIED type rendering - ID3DX11EffectTechnique* d_premultipliedClippedTechnique; - //! Rendering technique that supplies BM_RTT_PREMULTIPLIED type rendering - ID3DX11EffectTechnique* d_premultipliedUnclippedTechnique; - //! D3D11 input layout describing the vertex format we use. - ID3D11InputLayout* d_inputLayout; - //! Variable to access current texture (actually shader resource view) - ID3DX11EffectShaderResourceVariable* d_boundTextureVariable; - //! Variable to access world matrix used in geometry transformation. - ID3DX11EffectMatrixVariable* d_worldMatrixVariable; - //! Variable to access projection matrix used in geometry transformation. - ID3DX11EffectMatrixVariable* d_projectionMatrixVariable; + + //! Variable containing the sampler state for CEGUI textures + ID3D11SamplerState* d_samplerState; }; diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/Shader.h b/cegui/include/CEGUI/RendererModules/Direct3D11/Shader.h new file mode 100644 index 000000000..94f401a87 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/Shader.h @@ -0,0 +1,123 @@ +/*********************************************************************** + created: Sun, 6th April 2014 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIDirect3D11Shader_h_ +#define _CEGUIDirect3D11Shader_h_ + +#include "CEGUI/RendererModules/Direct3D11/Renderer.h" +#include "CEGUI/Exceptions.h" + +#include "D3Dcompiler.h" +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +/*! +\brief Enumerated type used when specifying the type of a shader (e.g. vertex shader, or pixel shader) + + */ +enum ShaderType +{ + /** + * The ShaderType represents a vertex shader + */ + ST_VERTEX, + /** + * The ShaderType represents a pixel shader + */ + ST_PIXEL +}; +//----------------------------------------------------------------------------// + +class D3D11_GUIRENDERER_API Direct3D11Shader +{ +public: + + /*! + \brief + Creates and loads shader programs from the two strings supplied to it + */ + Direct3D11Shader(Direct3D11Renderer& owner, + const std::string& vertexShaderSource, + const std::string& pixelShaderSource); + + ~Direct3D11Shader(); + + /*! + \brief + Binds the shader - prepares it to be used for follow-up rendering + */ + void bind() const; + + //! Returns the binding location of a texture resource variable in the shader + D3D11_SHADER_INPUT_BIND_DESC getTextureBindingDesc(const std::string& variableName, ShaderType shaderType); + //! Returns the binding location of a uniform (constant) variable in the shader + D3D11_SHADER_VARIABLE_DESC getUniformVariableDescription(const std::string& variableName, ShaderType shaderType); + //! Returns the ID3D10Blob pointer to the buffer of the vertex shader + ID3D10Blob* getVertexShaderBuffer() const; + //! Returns the ID3D11ShaderReflectionConstantBuffer pointer of the specified shader type + ID3D11ShaderReflectionConstantBuffer* getShaderReflectionConstBuffer(ShaderType shaderType); + +private: + //! Creates the vertex shader from a shader source code string + void createVertexShader(const std::string& vertexShaderSource); + //! Creates the pixel shader from a shader source code string + void createPixelShader(const std::string& pixelShaderSource); + //! Returns the highest pixel shader version available that CEGUI supports + std::string getVertexShaderVersion() const; + //! Returns the highest pixel shader version available that CEGUI supports + std::string getPixelShaderVersion() const; + + //! The D3D Device + ID3D11Device* d_device; + //! The D3D DeviceContext + ID3D11DeviceContext* d_deviceContext; + + //! The D3D VertexShader of this shader program + ID3D11VertexShader* d_vertShader; + //! The D3D Vertex Shader Buffer + mutable ID3D10Blob* d_vertexShaderBuffer; + //! The D3D VertexShader ShaderReflection of this shader program + ID3D11ShaderReflection* d_vertexShaderReflection; + //! The D3D PixelShader of this shader program + ID3D11PixelShader* d_pixelShader; + //! The D3D Vertex Shader Buffer + mutable ID3D10Blob* d_pixelShaderBuffer; + //! The D3D PixelShader ShaderReflection of this shader program + ID3D11ShaderReflection* d_pixelShaderReflection; +}; + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/ShaderWrapper.h b/cegui/include/CEGUI/RendererModules/Direct3D11/ShaderWrapper.h new file mode 100644 index 000000000..851223ca0 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/ShaderWrapper.h @@ -0,0 +1,110 @@ +/*********************************************************************** + created: Sun, 6th April 2014 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIDirect3D11ShaderWrapper_h_ +#define _CEGUIDirect3D11ShaderWrapper_h_ + +#include "CEGUI/RendererModules/Direct3D11/Renderer.h" +#include "CEGUI/RendererModules/Direct3D11/Shader.h" +#include "CEGUI/ShaderWrapper.h" +#include "CEGUI/ShaderParameterBindings.h" +#include + +#include "D3D11.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +class ShaderParameterBindings; +class ShaderParameter; +class Direct3D11Shader; + +//----------------------------------------------------------------------------// +struct Direct3D11ParamDesc +{ + UINT d_boundLocation; + UINT d_boundSize; + ShaderType d_shaderType; + ShaderParamType d_shaderParamType; +}; + +//----------------------------------------------------------------------------// +class D3D11_GUIRENDERER_API Direct3D11ShaderWrapper : public ShaderWrapper +{ +public: + Direct3D11ShaderWrapper(Direct3D11Shader& shader, Direct3D11Renderer* renderer); + + ~Direct3D11ShaderWrapper(); + + //Implementation of ShaderWrapper interface + void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings); + + //! Adds a shader uniform variable to the list of variables + void addUniformVariable(const std::string& variableName, ShaderType shaderType, ShaderParamType paramType); + + //! Creates a per-object buffer for a parameter + void createPerObjectBuffer(ShaderType shaderType); + + //! Returns the vertex shader buffer pointer + void* getVertShaderBufferPointer() const; + //! Returns the vertex shader buffer size + SIZE_T getVertShaderBufferSize() const; + +protected: + //! Prepare the uniform variable mapping + void prepareUniformVariableMapping(unsigned char*& resourceDataVS, unsigned char*& resourceDataPS); + //! Finish the uniform variable mapping + void finishUniformVariableMapping(); + + //! The D3D DeviceContext + ID3D11DeviceContext* d_deviceContext; + //! The D3D Device + ID3D11Device* d_device; + + //! The D3DBuffer used to update the uniform variables of the vertex shader + ID3D11Buffer* d_perObjectUniformVarBufferVert; + //! The D3DBuffer used to update the uniform variables of the pixel shader + ID3D11Buffer* d_perObjectUniformVarBufferPixel; + + //! The underlying HLSL shader program, consisting of a vertex and fragment shader, that this class wraps the access to + Direct3D11Shader& d_shader; + + //! A map of parameter names and the related constant variables + std::map d_uniformVariables; + //! Last states of the set shader parameters + std::map d_shaderParameterStates; +}; + + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/Texture.h b/cegui/include/CEGUI/RendererModules/Direct3D11/Texture.h index 95ba8f916..da51d86f4 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D11/Texture.h +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/Texture.h @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -51,26 +52,26 @@ class D3D11_GUIRENDERER_API Direct3D11Texture : public Texture public: /*! \brief - set the D3D10 texture that this Texture is based on to the specified + set the texture that this Texture is based on to the specified texture. */ void setDirect3DTexture(ID3D11Texture2D* tex); /*! \brief - Return the internal D3D10 texture used by this Texture object. + Return the internal texture used by this Texture object. \return - Pointer to the D3D10 texture interface that this object is using. + Pointer to the texture interface that this object is using. */ ID3D11Texture2D* getDirect3DTexture() const; /*! \brief - Return the internal D3D10 shader resource view for the texture. + Return the internal shader resource view for the texture. \return - Pointer to the ID3D10ShaderResourceView interface. + Pointer to the ShaderResourceView interface. */ ID3D11ShaderResourceView* getDirect3DShaderResourceView() const; @@ -87,7 +88,7 @@ class D3D11_GUIRENDERER_API Direct3D11Texture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); @@ -103,19 +104,18 @@ class D3D11_GUIRENDERER_API Direct3D11Texture : public Texture const String&); friend Texture& Direct3D11Renderer::createTexture(const String&, const Sizef&); - //friend Texture& Direct3D11Renderer::createTexture(ID3D10Texture2D* tex); friend void Direct3D11Renderer::destroyTexture(Texture&); friend void Direct3D11Renderer::destroyTexture(const String&); //! Basic constructor. - Direct3D11Texture(IDevice11& device, const String& name); + Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, const String& name); //! Construct texture from an image file. - Direct3D11Texture(IDevice11& device, const String& name, const String& filename, + Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, const String& name, const String& filename, const String& resourceGroup); //! Construct texture with a given size. - Direct3D11Texture(IDevice11& device, const String& name, const Sizef& sz); - //! Construct texture that wraps an existing D3D10 texture. - Direct3D11Texture(IDevice11& device, const String& name, ID3D11Texture2D* tex); + Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, const String& name, const Sizef& sz); + //! Construct texture that wraps an existing texture. + Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, const String& name, ID3D11Texture2D* tex); //! Destructor. virtual ~Direct3D11Texture(); @@ -128,8 +128,10 @@ class D3D11_GUIRENDERER_API Direct3D11Texture : public Texture //! creates shader resource view for the current D3D texture void initialiseShaderResourceView(); - //! D3D device used to do the business. - IDevice11& d_device; + //! The D3D Device + ID3D11Device& d_device; + //! The D3D DeviceContext + ID3D11DeviceContext& d_deviceContext; //! The D3D 10 texture we're wrapping. ID3D11Texture2D* d_texture; //! Shader resource view for the texture. @@ -139,7 +141,7 @@ class D3D11_GUIRENDERER_API Direct3D11Texture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! The name we were created with. const String d_name; }; diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/TextureTarget.h b/cegui/include/CEGUI/RendererModules/Direct3D11/TextureTarget.h index d2b9e9ba2..e4e320bf8 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D11/TextureTarget.h +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/TextureTarget.h @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -52,7 +53,7 @@ class D3D11_GUIRENDERER_API Direct3D11TextureTarget : public Direct3D11RenderTar Direct3D11TextureTarget(Direct3D11Renderer& owner); virtual ~Direct3D11TextureTarget(); - // overrides from Direct3D10RenderTarget + // overrides from the superclass void activate(); void deactivate(); // implementation of RenderTarget interface @@ -82,7 +83,7 @@ class D3D11_GUIRENDERER_API Direct3D11TextureTarget : public Direct3D11RenderTar //! switch back to previous surface void disableRenderTexture(); - //! Direct3D10 texture that's rendered to. + //! The texture that we will render to ID3D11Texture2D* d_texture; //! render target view for d_texture ID3D11RenderTargetView* d_renderTargetView; diff --git a/cegui/include/CEGUI/RendererModules/Direct3D11/ViewportTarget.h b/cegui/include/CEGUI/RendererModules/Direct3D11/ViewportTarget.h index 7103879e4..69a729a16 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D11/ViewportTarget.h +++ b/cegui/include/CEGUI/RendererModules/Direct3D11/ViewportTarget.h @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -23,28 +24,28 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIDirect3D10ViewportTarget_h_ -#define _CEGUIDirect3D10ViewportTarget_h_ +#ifndef _CEGUIDirect3D11ViewportTarget_h_ +#define _CEGUIDirect3D11ViewportTarget_h_ #include "CEGUI/RendererModules/Direct3D11/RenderTarget.h" // Start of CEGUI namespace section namespace CEGUI { -//! Direct3D10 based RenderTarget that represents the screen or a portion of it. +//! Direct3D11 based RenderTarget that represents the screen or a portion of it. class D3D11_GUIRENDERER_API Direct3D11ViewportTarget : public Direct3D11RenderTarget<> { public: /*! \brief - Construct a default Direct3D10ViewportTarget that uses the current - Direct3D10 viewport as it's initial area. + Construct a default Direct3D11ViewportTarget that uses the current + Direct3D11 viewport as it's initial area. */ Direct3D11ViewportTarget(Direct3D11Renderer& owner); /*! \brief - Construct a Direct3D10ViewportTarget that uses the specified Rect as + Construct a Direct3D11ViewportTarget that uses the specified Rect as it's initial area. \param area @@ -60,4 +61,4 @@ class D3D11_GUIRENDERER_API Direct3D11ViewportTarget : public Direct3D11RenderTa } // End of CEGUI namespace section -#endif // end of guard _CEGUIDirect3D10ViewportTarget_h_ +#endif diff --git a/cegui/include/CEGUI/RendererModules/Direct3D9/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/Direct3D9/GeometryBuffer.h deleted file mode 100644 index 07a0141a5..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D9/GeometryBuffer.h +++ /dev/null @@ -1,142 +0,0 @@ -/*********************************************************************** - created: Mon Feb 9 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D9GeometryBuffer_h_ -#define _CEGUIDirect3D9GeometryBuffer_h_ - -#include "../../GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" -#include "../../Rect.h" -#include "../../Quaternion.h" -#include -#include -#include - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -class Direct3D9Texture; - -/*! -\brief - Direct3D9 based implementation of the GeometryBuffer interface. -*/ -class DIRECT3D9_GUIRENDERER_API Direct3D9GeometryBuffer : public GeometryBuffer -{ -public: - //! Constructor - Direct3D9GeometryBuffer(Direct3D9Renderer& owner, LPDIRECT3DDEVICE9 device); - - //! return pointer to D3DXMATRIX used as world transform. - const D3DXMATRIX* getMatrix() const; - - // implementation of abstract members from GeometryBuffer - void draw() const; - void setTranslation(const Vector3f& t); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); - void setClippingRegion(const Rectf& region); - void appendVertex(const Vertex& vertex); - void appendGeometry(const Vertex* const vbuff, uint vertex_count); - void setActiveTexture(Texture* texture); - void reset(); - Texture* getActiveTexture() const; - uint getVertexCount() const; - uint getBatchCount() const; - void setRenderEffect(RenderEffect* effect); - RenderEffect* getRenderEffect(); - void setClippingActive(const bool active); - bool isClippingActive() const; - -protected: - //! perform batch management operations prior to adding new geometry. - void performBatchManagement(); - //! update cached matrix - void updateMatrix() const; - - //! internal Vertex structure used for Direct3D based geometry. - struct D3DVertex - { - //! The transformed position for the vertex. - FLOAT x, y, z; - //! colour of the vertex. - DWORD diffuse; - //! texture coordinates. - float tu, tv; - }; - - //! type to track info for per-texture sub batches of geometry - struct BatchInfo - { - LPDIRECT3DTEXTURE9 texture; - uint vertexCount; - bool clip; - }; - - //! Owning Direct3D9Renderer object - Direct3D9Renderer& d_owner; - //! last texture that was set as active - Direct3D9Texture* d_activeTexture; - //! type of container that tracks BatchInfos. - typedef std::vector BatchList; - //! list of texture batches added to the geometry buffer - BatchList d_batches; - //! type of container used to queue the geometry - typedef std::vector VertexList; - //! container where added geometry is stored. - VertexList d_vertices; - //! rectangular clip region - Rectf d_clipRect; - //! whether clipping will be active for the current batch - bool d_clippingActive; - //! translation vector - Vector3f d_translation; - //! rotation vector - Quaternion d_rotation; - //! pivot point for rotation - Vector3f d_pivot; - //! RenderEffect that will be used by the GeometryBuffer - RenderEffect* d_effect; - //! The D3D Device - LPDIRECT3DDEVICE9 d_device; - //! model matrix cache - mutable D3DXMATRIX d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D9GeometryBuffer_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D9/RenderTarget.h b/cegui/include/CEGUI/RendererModules/Direct3D9/RenderTarget.h deleted file mode 100644 index aee68a5af..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D9/RenderTarget.h +++ /dev/null @@ -1,91 +0,0 @@ -/*********************************************************************** - created: Tue Feb 10 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D9RenderTarget_h_ -#define _CEGUIDirect3D9RenderTarget_h_ - -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" -#include "../../RenderTarget.h" -#include "../../Rect.h" -#include - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -/*! -\brief - Intermediate Direct3D9 implementation of a RenderTarget. -*/ -template -class DIRECT3D9_GUIRENDERER_API Direct3D9RenderTarget : public T -{ -public: - //! Constructor - Direct3D9RenderTarget(Direct3D9Renderer& owner); - - // implement parts of RenderTarget interface - void draw(const GeometryBuffer& buffer); - void draw(const RenderQueue& queue); - void setArea(const Rectf& area); - const Rectf& getArea() const; - void activate(); - void deactivate(); - void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const; - -protected: - //! helper that initialises the cached matrix - void updateMatrix() const; - //! helper to initialise the D3DVIEWPORT9 \a vp for this target. - void setupViewport(D3DVIEWPORT9& vp) const; - - //! Direct3D9Renderer that created this object - Direct3D9Renderer& d_owner; - //! Direct3DDevice9 interface obtained from our owner. - LPDIRECT3DDEVICE9 d_device; - //! holds defined area for the RenderTarget - Rectf d_area; - //! projection / view matrix cache - mutable D3DXMATRIX d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; - //! tracks viewing distance (this is set up at the same time as d_matrix) - mutable float d_viewDistance; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D9RenderTarget_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D9/Renderer.h b/cegui/include/CEGUI/RendererModules/Direct3D9/Renderer.h deleted file mode 100644 index f7222f7cf..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D9/Renderer.h +++ /dev/null @@ -1,232 +0,0 @@ -/*********************************************************************** - created: Mon Feb 9 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D9Renderer_h_ -#define _CEGUIDirect3D9Renderer_h_ - -#include "../../Base.h" -#include "../../Renderer.h" -#include "../../Size.h" -#include "../../Vector.h" - -#include -#include -#include - -#if (defined( __WIN32__ ) || defined( _WIN32 )) && !defined(CEGUI_STATIC) -# ifdef CEGUIDIRECT3D9RENDERER_EXPORTS -# define DIRECT3D9_GUIRENDERER_API __declspec(dllexport) -# else -# define DIRECT3D9_GUIRENDERER_API __declspec(dllimport) -# endif -#else -# define DIRECT3D9_GUIRENDERER_API -#endif - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -class Direct3D9Texture; -class Direct3D9GeometryBuffer; - -/*! -\brief - Renderer class to interface with Direct3D 9. -*/ -class DIRECT3D9_GUIRENDERER_API Direct3D9Renderer : public Renderer -{ -public: - /*! - \brief - Convenience function that creates the required objects to initialise the - CEGUI system. - - This will create and initialise the following objects for you: - - CEGUI::Direct3D9Renderer - - CEGUI::DefaultResourceProvider - - CEGUI::System - - \param device - LPDIRECT3DDEVICE9 of the device that is to be used for CEGUI - rendering operations. - - \param abi - This must be set to CEGUI_VERSION_ABI - - \return - Reference to the CEGUI::Direct3D9Renderer object that was created. - */ - static Direct3D9Renderer& bootstrapSystem(LPDIRECT3DDEVICE9 device, - const int abi = CEGUI_VERSION_ABI); - - /*! - \brief - Convenience function to cleanup the CEGUI system and related objects - that were created by calling the bootstrapSystem function. - - This function will destroy the following objects for you: - - CEGUI::System - - CEGUI::DefaultResourceProvider - - CEGUI::Direct3D9Renderer - - \note - If you did not initialise CEGUI by calling the bootstrapSystem function, - you should \e not call this, but rather delete any objects you created - manually. - */ - static void destroySystem(); - - /*! - \brief - Create an Direct3D9Renderer object. - */ - static Direct3D9Renderer& create(LPDIRECT3DDEVICE9 device, - const int abi = CEGUI_VERSION_ABI); - - /*! - \brief - Destroy an Direct3D9Renderer object. - - \param renderer - The Direct3D9Renderer object to be destroyed. - */ - static void destroy(Direct3D9Renderer& renderer); - - //! support function to be called prior to a Reset on the Direct3DDevice9. - void preD3DReset(); - - //! support function to be called after a Reset on the Direct3DDevice9. - void postD3DReset(); - - //! return the Direct3D 9 Device interface used by this renderer object. - LPDIRECT3DDEVICE9 getDevice() const; - - //! create a CEGUI::texture from an existing D3D texture - Texture& createTexture(const String& name, LPDIRECT3DTEXTURE9 tex); - - //! return true if we can use non square textures. - bool supportsNonSquareTexture(); - - //! return true if we can use NPOT texture dimensions. - bool supportsNPOTTextures(); - - //! returns Size object from \a sz adjusted for hardware capabilities. - Sizef getAdjustedSize(const Sizef& sz); - - //! set the render states for the specified BlendMode. - void setupRenderingBlendMode(const BlendMode mode, - const bool force = false); - - // implement Renderer interface - RenderTarget& getDefaultRenderTarget(); - GeometryBuffer& createGeometryBuffer(); - void destroyGeometryBuffer(const GeometryBuffer& buffer); - void destroyAllGeometryBuffers(); - TextureTarget* createTextureTarget(); - void destroyTextureTarget(TextureTarget* target); - void destroyAllTextureTargets(); - Texture& createTexture(const String& name); - Texture& createTexture(const String& name, - const String& filename, - const String& resourceGroup); - Texture& createTexture(const String& name, const Sizef& size); - void destroyTexture(Texture& texture); - void destroyTexture(const String& name); - void destroyAllTextures(); - Texture& getTexture(const String& name) const; - bool isTextureDefined(const String& name) const; - void beginRendering(); - void endRendering(); - void setDisplaySize(const Sizef& sz); - const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; - uint getMaxTextureSize() const; - const String& getIdentifierString() const; - -private: - //! Constructor for Direct3D9 Renderer objects. - Direct3D9Renderer(LPDIRECT3DDEVICE9 device); - - //! Destructor for Direct3D9Renderer objects. - virtual ~Direct3D9Renderer(); - - //! helper to throw exception if name is already used. - void throwIfNameExists(const String& name) const; - //! helper to safely log the creation of a named texture - static void logTextureCreation(const String& name); - //! helper to safely log the destruction of a named texture - static void logTextureDestruction(const String& name); - - //! return size of device view port (if possible). - Sizef getViewportSize(); - //! returns next power of 2 size if \a size is not power of 2 - float getSizeNextPOT(float sz) const; - - //! String holding the renderer identification text. - static String d_rendererID; - //! Direct3DDevice9 interface we were given when constructed. - LPDIRECT3DDEVICE9 d_device; - //! What the renderer considers to be the current display size. - Sizef d_displaySize; - //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; - //! The default RenderTarget - RenderTarget* d_defaultTarget; - //! container type used to hold TextureTargets we create. - typedef std::vector TextureTargetList; - //! Container used to track texture targets. - TextureTargetList d_textureTargets; - //! container type used to hold GeometryBuffers we create. - typedef std::vector GeometryBufferList; - //! Container used to track geometry buffers. - GeometryBufferList d_geometryBuffers; - //! container type used to hold Textures we create. - typedef std::map TextureMap; - //! Container used to track textures. - TextureMap d_textures; - //! What the renderer thinks the max texture size is. - uint d_maxTextureSize; - //! whether the hardware supports non-power of two textures - bool d_supportNPOTTex; - //! whether the hardware supports non-square textures. - bool d_supportNonSquareTex; - //! What we think is the active blendine mode - BlendMode d_activeBlendMode; - }; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D9Renderer_h_ diff --git a/cegui/include/CEGUI/RendererModules/Direct3D9/Texture.h b/cegui/include/CEGUI/RendererModules/Direct3D9/Texture.h deleted file mode 100644 index c9781c9bf..000000000 --- a/cegui/include/CEGUI/RendererModules/Direct3D9/Texture.h +++ /dev/null @@ -1,152 +0,0 @@ -/*********************************************************************** - created: Mon Feb 9 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIDirect3D9Texture_h_ -#define _CEGUIDirect3D9Texture_h_ - -#include "../../Base.h" -#include "../../Renderer.h" -#include "../../Texture.h" -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -//! Texture implementation for the Direct3D9Renderer. -class DIRECT3D9_GUIRENDERER_API Direct3D9Texture : public Texture -{ -public: - /*! - \brief - set the D3D9 texture that this Texture is based on to the specified - texture. - */ - void setDirect3D9Texture(LPDIRECT3DTEXTURE9 tex); - - /*! - \brief - Return the internal D3D9 texture used by this Texture object. - - \return - Pointer to the D3D9 texture interface that this object is using. - */ - LPDIRECT3DTEXTURE9 getDirect3D9Texture() const; - - /*! - \brief - Sets what the texture should consider as the original data size. - - \note - This also causes the texel scaling values to be updated. - */ - void setOriginalDataSize(const Sizef& sz); - - //! auto called via the Renderer prior to Reset on the Direct3DDevice9. - void preD3DReset(); - - //! auto called via the Renderer after Reset on the Direct3DDevice9. - void postD3DReset(); - - // implement abstract members from base class. - const String& getName() const; - const Sizef& getSize() const; - const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; - void loadFromFile(const String& filename, const String& resourceGroup); - void loadFromMemory(const void* buffer, const Sizef& buffer_size, - PixelFormat pixel_format); - void blitFromMemory(const void* sourceData, const Rectf& area); - void blitToMemory(void* targetData); - bool isPixelFormatSupported(const PixelFormat fmt) const; - -protected: - // Friends (to allow construction and destruction) - friend Texture& Direct3D9Renderer::createTexture(const String&); - friend Texture& Direct3D9Renderer::createTexture(const String&, - const String&, - const String&); - friend Texture& Direct3D9Renderer::createTexture(const String&, - const Sizef&); - friend Texture& Direct3D9Renderer::createTexture(const String&, - LPDIRECT3DTEXTURE9 tex); - friend void Direct3D9Renderer::destroyTexture(Texture&); - friend void Direct3D9Renderer::destroyTexture(const String&); - - //! Basic constructor. - Direct3D9Texture(Direct3D9Renderer& owner, const String& name); - //! Construct texture from an image file. - Direct3D9Texture(Direct3D9Renderer& owner, const String& name, - const String& filename, const String& resourceGroup); - //! Construct texture with a given size. - Direct3D9Texture(Direct3D9Renderer& owner, const String& name, - const Sizef& sz); - //! Construct texture that wraps an existing D3D9 texture. - Direct3D9Texture(Direct3D9Renderer& owner, const String& name, - LPDIRECT3DTEXTURE9 tex); - //! Destructor. - virtual ~Direct3D9Texture(); - - //! create internal texture. - void createDirect3D9Texture(const Sizef sz, D3DFORMAT format); - //! clean up the internal texture. - void cleanupDirect3D9Texture(); - //! get the IDirect3DSurface9 interface for the underlying texture. - IDirect3DSurface9* getTextureSurface() const; - //! updates cached scale value used to map pixels to texture co-ords. - void updateCachedScaleValues(); - //! set d_size to actual texture size (d_dataSize is used if query fails) - void updateTextureSize(); - - //! Direct3D9Renderer object that created and owns this texture. - Direct3D9Renderer& d_owner; - //! The D3D9 texture we're wrapping. - LPDIRECT3DTEXTURE9 d_texture; - //! Size of the texture. - Sizef d_size; - //! original pixel of size data loaded into texture - Sizef d_dataSize; - //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; - //! holds info about the texture surface before we released it for reset. - D3DSURFACE_DESC d_savedSurfaceDesc; - //! true when d_savedSurfaceDesc is valid and texture can be restored. - bool d_savedSurfaceDescValid; - //! Name the texture was created with. - const String d_name; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIDirect3D9Texture_h_ diff --git a/cegui/include/CEGUI/RendererModules/DirectFB/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/DirectFB/GeometryBuffer.h index 8e7010e2a..91c836eb2 100644 --- a/cegui/include/CEGUI/RendererModules/DirectFB/GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/DirectFB/GeometryBuffer.h @@ -29,7 +29,6 @@ #include "CEGUI/GeometryBuffer.h" #include "CEGUI/Rect.h" -#include "CEGUI/Quaternion.h" #include #include @@ -51,9 +50,9 @@ class DirectFBGeometryBuffer : public GeometryBuffer // Implement GeometryBuffer interface. void draw() const; - void setTranslation(const Vector3f& v); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); + void setTranslation(const glm::vec3& v); + void setRotation(const glm::quat& r); + void setPivot(const glm::vec3& p); void setClippingRegion(const Rectf& region); void appendVertex(const Vertex& vertex); void appendGeometry(const Vertex* const vbuff, uint vertex_count); @@ -96,11 +95,11 @@ class DirectFBGeometryBuffer : public GeometryBuffer //! whether clipping will be active for the current batch bool d_clippingActive; //! translation vector - Vector3f d_translation; + glm::vec3 d_translation; //! rotation vector - Quaternion d_rotation; + glm::quat d_rotation; //! pivot point for rotation - Vector3f d_pivot; + glm::vec3 d_pivot; //! RenderEffect that will be used by the GeometryBuffer RenderEffect* d_effect; //! model matrix cache diff --git a/cegui/include/CEGUI/RendererModules/DirectFB/RenderTarget.h b/cegui/include/CEGUI/RendererModules/DirectFB/RenderTarget.h index a53c1f6a8..da6443612 100644 --- a/cegui/include/CEGUI/RendererModules/DirectFB/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/DirectFB/RenderTarget.h @@ -52,7 +52,7 @@ class DirectFBRenderTarget : public RenderTarget void activate(); void deactivate(); void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const; + const glm::vec2& p_in, glm::vec2& p_out) const; protected: //! DirectFBRenderer that created and owns this RenderTarget. diff --git a/cegui/include/CEGUI/RendererModules/DirectFB/Renderer.h b/cegui/include/CEGUI/RendererModules/DirectFB/Renderer.h index 83d738561..6e84cf4fd 100644 --- a/cegui/include/CEGUI/RendererModules/DirectFB/Renderer.h +++ b/cegui/include/CEGUI/RendererModules/DirectFB/Renderer.h @@ -79,7 +79,7 @@ class DirectFBRenderer : public Renderer void endRendering(); void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; @@ -105,7 +105,7 @@ class DirectFBRenderer : public Renderer //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. diff --git a/cegui/include/CEGUI/RendererModules/DirectFB/Texture.h b/cegui/include/CEGUI/RendererModules/DirectFB/Texture.h index 921b98478..43cc13805 100644 --- a/cegui/include/CEGUI/RendererModules/DirectFB/Texture.h +++ b/cegui/include/CEGUI/RendererModules/DirectFB/Texture.h @@ -45,7 +45,7 @@ class DirectFBTexture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); @@ -84,7 +84,7 @@ class DirectFBTexture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! The name given for this texture. const String d_name; }; diff --git a/cegui/include/CEGUI/RendererModules/Irrlicht/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/Irrlicht/GeometryBuffer.h index 99722f399..bc8417705 100644 --- a/cegui/include/CEGUI/RendererModules/Irrlicht/GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/Irrlicht/GeometryBuffer.h @@ -62,9 +62,9 @@ class IRR_GUIRENDERER_API IrrlichtGeometryBuffer : public GeometryBuffer // implement GeometryBuffer interface void draw() const; - void setTranslation(const Vector3f& v); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); + void setTranslation(const glm::vec3& v); + void setRotation(const glm::quat& r); + void setPivot(const glm::vec3& p); void setClippingRegion(const Rectf& region); void appendVertex(const Vertex& vertex); void appendGeometry(const Vertex* const vbuff, uint vertex_count); diff --git a/cegui/include/CEGUI/RendererModules/Irrlicht/RenderTarget.h b/cegui/include/CEGUI/RendererModules/Irrlicht/RenderTarget.h index 127576c02..3be82f434 100644 --- a/cegui/include/CEGUI/RendererModules/Irrlicht/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/Irrlicht/RenderTarget.h @@ -62,7 +62,7 @@ class IRR_GUIRENDERER_API IrrlichtRenderTarget : public T void activate(); void deactivate(); void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const; + const glm::vec2& p_in, glm::vec2& p_out) const; protected: //! helper that initialises the cached matrix void updateMatrix() const; diff --git a/cegui/include/CEGUI/RendererModules/Irrlicht/Renderer.h b/cegui/include/CEGUI/RendererModules/Irrlicht/Renderer.h index 43c338ce8..962b5a1f8 100644 --- a/cegui/include/CEGUI/RendererModules/Irrlicht/Renderer.h +++ b/cegui/include/CEGUI/RendererModules/Irrlicht/Renderer.h @@ -178,7 +178,7 @@ class IRR_GUIRENDERER_API IrrlichtRenderer : public Renderer void endRendering(); void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; const IrrlichtEventPusher* getEventPusher() const; @@ -205,7 +205,7 @@ class IRR_GUIRENDERER_API IrrlichtRenderer : public Renderer //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. @@ -217,8 +217,7 @@ class IRR_GUIRENDERER_API IrrlichtRenderer : public Renderer //! Container used to track geometry buffers. GeometryBufferList d_geometryBuffers; //! container type used to hold Textures we create. - typedef std::map TextureMap; + typedef std::map TextureMap; //! Container used to track textures. TextureMap d_textures; //! What the renderer thinks the max texture size is. diff --git a/cegui/include/CEGUI/RendererModules/Irrlicht/Texture.h b/cegui/include/CEGUI/RendererModules/Irrlicht/Texture.h index 0f92502f8..66d57079e 100644 --- a/cegui/include/CEGUI/RendererModules/Irrlicht/Texture.h +++ b/cegui/include/CEGUI/RendererModules/Irrlicht/Texture.h @@ -71,7 +71,7 @@ class IRR_GUIRENDERER_API IrrlichtTexture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); @@ -121,7 +121,7 @@ class IRR_GUIRENDERER_API IrrlichtTexture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! reference to the IrrlichtRenderer that created this texture IrrlichtRenderer& d_owner; //! name given when texture was created. diff --git a/cegui/include/CEGUI/RendererModules/Null/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/Null/GeometryBuffer.h index 37b4c9214..0078283d2 100644 --- a/cegui/include/CEGUI/RendererModules/Null/GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/Null/GeometryBuffer.h @@ -27,12 +27,11 @@ #ifndef _CEGUINullGeometryBuffer_h_ #define _CEGUINullGeometryBuffer_h_ -#include "../../GeometryBuffer.h" +#include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/Null/Renderer.h" -#include "../../Rect.h" -#include "../../Colour.h" -#include "../../Vertex.h" -#include "../../Quaternion.h" +#include "CEGUI/Rect.h" +#include "CEGUI/Colour.h" +#include "CEGUI/Vertex.h" #include #include @@ -50,47 +49,18 @@ class NULL_GUIRENDERER_API NullGeometryBuffer : public GeometryBuffer { public: //! Constructor - NullGeometryBuffer(); + NullGeometryBuffer(CEGUI::RefCounted renderMaterial); //! Destructor virtual ~NullGeometryBuffer(); - // implement CEGUI::GeometryBuffer interface. + // Implementation/overrides of member functions inherited from GeometryBuffer void draw() const; - void setTranslation(const Vector3f& v); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); + void appendGeometry(const std::vector& vertex_data); + void finaliseVertexAttributes(); void setClippingRegion(const Rectf& region); - void appendVertex(const Vertex& vertex); - void appendGeometry(const Vertex* const vbuff, uint vertex_count); - void setActiveTexture(Texture* texture); - void reset(); - Texture* getActiveTexture() const; - uint getVertexCount() const; - uint getBatchCount() const; - void setRenderEffect(RenderEffect* effect); - RenderEffect* getRenderEffect(); - void setClippingActive(const bool active); - bool isClippingActive() const; - protected: - //! Texture that is set as active - NullTexture* d_activeTexture; //! rectangular clip region Rectf d_clipRect; - //! whether clipping will be active for the current batch - bool d_clippingActive; - //! translation vector - Vector3f d_translation; - //! rotation quaternion - Quaternion d_rotation; - //! pivot point for rotation - Vector3f d_pivot; - //! RenderEffect that will be used by the GeometryBuffer - RenderEffect* d_effect; - //! type of container used to queue the geometry - typedef std::vector VertexList; - //! container where added geometry is stored. - VertexList d_vertices; }; diff --git a/cegui/include/CEGUI/RendererModules/Null/RenderTarget.h b/cegui/include/CEGUI/RendererModules/Null/RenderTarget.h index 7a1a04413..5179e372e 100644 --- a/cegui/include/CEGUI/RendererModules/Null/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/Null/RenderTarget.h @@ -51,21 +51,16 @@ class NULL_GUIRENDERER_API NullRenderTarget : public T virtual ~NullRenderTarget(); // implement parts of CEGUI::RenderTarget interface - void draw(const GeometryBuffer& buffer); - void draw(const RenderQueue& queue); - void setArea(const Rectf& area); - const Rectf& getArea() const; - void activate(); - void deactivate(); - void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const; - bool isImageryCache() const; + virtual void activate(); + virtual void unprojectPoint(const GeometryBuffer& buff, + const glm::vec2& p_in, glm::vec2& p_out) const; + virtual bool isImageryCache() const; + // implementing the virtual function with a covariant return type + virtual NullRenderer& getOwner(); protected: //! NullRenderer object that owns this RenderTarget NullRenderer& d_owner; - //! holds defined area for the RenderTarget - Rectf d_area; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/RendererModules/Null/Renderer.h b/cegui/include/CEGUI/RendererModules/Null/Renderer.h index 212209881..f4c10b64f 100644 --- a/cegui/include/CEGUI/RendererModules/Null/Renderer.h +++ b/cegui/include/CEGUI/RendererModules/Null/Renderer.h @@ -55,6 +55,7 @@ namespace CEGUI { class NullGeometryBuffer; class NullTexture; +class NullShaderWrapper; //! CEGUI::Renderer implementation for no particular engine class NULL_GUIRENDERER_API NullRenderer : public Renderer @@ -107,9 +108,9 @@ class NULL_GUIRENDERER_API NullRenderer : public Renderer // implement CEGUI::Renderer interface RenderTarget& getDefaultRenderTarget(); - GeometryBuffer& createGeometryBuffer(); - void destroyGeometryBuffer(const GeometryBuffer& buffer); - void destroyAllGeometryBuffers(); + RefCounted createRenderMaterial(const DefaultShaderType shaderType) const; + GeometryBuffer& createGeometryBufferTextured(RefCounted renderMaterial); + GeometryBuffer& createGeometryBufferColoured(RefCounted renderMaterial); TextureTarget* createTextureTarget(); void destroyTextureTarget(TextureTarget* target); void destroyAllTextureTargets(); @@ -127,7 +128,7 @@ class NULL_GUIRENDERER_API NullRenderer : public Renderer void endRendering(); void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; @@ -151,7 +152,7 @@ class NULL_GUIRENDERER_API NullRenderer : public Renderer //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. @@ -163,12 +164,16 @@ class NULL_GUIRENDERER_API NullRenderer : public Renderer //! Container used to track geometry buffers. GeometryBufferList d_geometryBuffers; //! container type used to hold Textures we create. - typedef std::map TextureMap; + typedef std::map TextureMap; //! Container used to track textures. TextureMap d_textures; //! What the renderer thinks the max texture size is. uint d_maxTextureSize; + + //! Shaderwrapper for textured & coloured vertices + NullShaderWrapper* d_shaderWrapperTextured; + //! Shaderwrapper for coloured vertices + NullShaderWrapper* d_shaderWrapperSolid; }; diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GlmPimpl.h b/cegui/include/CEGUI/RendererModules/Null/ShaderWrapper.h similarity index 70% rename from cegui/include/CEGUI/RendererModules/OpenGL/GlmPimpl.h rename to cegui/include/CEGUI/RendererModules/Null/ShaderWrapper.h index d4b8fd4fc..5b0af83b1 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GlmPimpl.h +++ b/cegui/include/CEGUI/RendererModules/Null/ShaderWrapper.h @@ -1,6 +1,6 @@ /*********************************************************************** -created: Mon, 13th Feb 2012 -author: Lukas E Meindl + created: 7th December 2013 + author: Lukas Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team @@ -24,20 +24,36 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ +#ifndef _CEGUINullShaderWrapper_h_ +#define _CEGUINullShaderWrapper_h_ -#ifndef _CEGUIGlmPimpl_h_ -#define _CEGUIGlmPimpl_h_ +#include "CEGUI/ShaderWrapper.h" +#include "CEGUI/RendererModules/Null/Renderer.h" +#include -#include "glm/glm.hpp" +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif namespace CEGUI { +class ShaderParameterBindings; -struct mat4Pimpl + +class NULL_GUIRENDERER_API NullShaderWrapper : public ShaderWrapper { - glm::mat4 d_matrix; +public: + NullShaderWrapper(); + + ~NullShaderWrapper(); + + //Implementation of ShaderWrapper interface + void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings); }; + } -#endif \ No newline at end of file +#endif + diff --git a/cegui/include/CEGUI/RendererModules/Null/Texture.h b/cegui/include/CEGUI/RendererModules/Null/Texture.h index 2083775be..176ed5213 100644 --- a/cegui/include/CEGUI/RendererModules/Null/Texture.h +++ b/cegui/include/CEGUI/RendererModules/Null/Texture.h @@ -46,7 +46,7 @@ class NULL_GUIRENDERER_API NullTexture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); @@ -82,7 +82,7 @@ class NULL_GUIRENDERER_API NullTexture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! Name this texture was created with. const String d_name; }; diff --git a/cegui/include/CEGUI/RendererModules/Ogre/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/Ogre/GeometryBuffer.h index e867ab759..c71edbb5c 100644 --- a/cegui/include/CEGUI/RendererModules/Ogre/GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/Ogre/GeometryBuffer.h @@ -1,6 +1,6 @@ /*********************************************************************** created: Tue Feb 17 2009 - author: Paul D Turner + author: Henri I Hyyryläinen (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team @@ -29,13 +29,13 @@ #include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/Ogre/Renderer.h" +#include "CEGUI/RendererModules/Ogre/ShaderWrapper.h" #include "CEGUI/Rect.h" -#include "CEGUI/Quaternion.h" -#include #include #include #include +#include #include #include @@ -53,98 +53,67 @@ namespace CEGUI class OGRE_GUIRENDERER_API OgreGeometryBuffer : public GeometryBuffer { public: + + enum MANUALOBJECT_TYPE + { + MT_COLOURED, + MT_TEXTURED, + MT_INVALID + }; + //! Constructor - OgreGeometryBuffer(OgreRenderer& owner, Ogre::RenderSystem& rs); + OgreGeometryBuffer(OgreRenderer& owner, Ogre::RenderSystem& rs, + CEGUI::RefCounted renderMaterial); + //! Destructor virtual ~OgreGeometryBuffer(); - //! return the transformation matrix used for this buffer. - const Ogre::Matrix4& getMatrix() const; - - // implement CEGUI::GeometryBuffer interface. virtual void draw() const; - virtual void setTranslation(const Vector3f& v); - virtual void setRotation(const Quaternion& r); - virtual void setPivot(const Vector3f& p); + virtual void appendGeometry(const float* vertex_data, std::size_t array_size); virtual void setClippingRegion(const Rectf& region); - virtual void appendVertex(const Vertex& vertex); - virtual void appendGeometry(const Vertex* const vbuff, uint vertex_count); - virtual void setActiveTexture(Texture* texture); virtual void reset(); - virtual Texture* getActiveTexture() const; - virtual uint getVertexCount() const; - virtual uint getBatchCount() const; - virtual void setRenderEffect(RenderEffect* effect); - virtual RenderEffect* getRenderEffect(); - void setClippingActive(const bool active); - bool isClippingActive() const; + virtual int getVertexAttributeElementCount() const; + + void finaliseVertexAttributes(MANUALOBJECT_TYPE type); protected: - //! convert CEGUI::colour into something Ogre can use - Ogre::RGBA colourToOgre(const Colour& col) const; - //! update cached matrix + + //! Updates the cached matrix. This should only be called after the RenderTarget was set. void updateMatrix() const; - //! Synchronise data in the hardware buffer with what's been added - void syncHardwareBuffer() const; - //! set up texture related states - void initialiseTextureStates() const; + //! Sets the current scissor rect active + void setScissorRects() const; - //! vertex structure used internally and also by Ogre. - struct OgreVertex - { - float x, y, z; - Ogre::RGBA diffuse; - float u, v; - }; + void syncVertexData() const; - //! type to track info for per-texture sub batches of geometry - struct BatchInfo - { - Ogre::TexturePtr texture; - uint vertexCount; - bool clip; - }; + void setVertexBuffer(size_t count) const; + + void cleanUpVertexAttributes(); //! Renderer object that owns this GeometryBuffer OgreRenderer& d_owner; //! Ogre render system we're to use. Ogre::RenderSystem& d_renderSystem; - //! Texture that is set as active - OgreTexture* d_activeTexture; //! rectangular clip region Rectf d_clipRect; - //! whether clipping will be active for the current batch - bool d_clippingActive; - //! translation vector - Vector3f d_translation; - //! rotation quaternion - Quaternion d_rotation; - //! pivot point for rotation - Vector3f d_pivot; - //! RenderEffect that will be used by the GeometryBuffer - RenderEffect* d_effect; - //! offset to be applied to all geometry - Vector2f d_texelOffset; + //! model matrix cache - mutable Ogre::Matrix4 d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; + mutable glm::mat4 d_matrix; + + //! The type of vertex data we expect + MANUALOBJECT_TYPE d_expectedData; + //! Render operation for this buffer. mutable Ogre::RenderOperation d_renderOp; + //! H/W buffer where the vertices are rendered from. mutable Ogre::HardwareVertexBufferSharedPtr d_hwBuffer; - //! whether the h/w buffer is in sync with the added geometry - mutable bool d_sync; - //! type of container that tracks BatchInfos. - typedef std::vector BatchList; - //! list of texture batches added to the geometry buffer - BatchList d_batches; - //! type of container used to queue the geometry - typedef std::vector VertexList; - //! container where added geometry is stored. - VertexList d_vertices; -}; + //! Marks the d_hwBuffer as being out of date + mutable bool d_dataAppended; + + //! The old alpha value + mutable float d_previousAlphaValue; +}; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/RendererModules/Ogre/RenderTarget.h b/cegui/include/CEGUI/RendererModules/Ogre/RenderTarget.h index e4d567095..d1aeb4442 100644 --- a/cegui/include/CEGUI/RendererModules/Ogre/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/Ogre/RenderTarget.h @@ -45,7 +45,7 @@ class OGRE_GUIRENDERER_API OgreRenderTarget : public T //! Destructor virtual ~OgreRenderTarget(); - + /*! \brief Set the underlying viewport area directly - bypassing what the @@ -62,14 +62,12 @@ class OGRE_GUIRENDERER_API OgreRenderTarget : public T void setOgreViewportDimensions(const Rectf& area); // implement parts of CEGUI::RenderTarget interface - void draw(const GeometryBuffer& buffer); - void draw(const RenderQueue& queue); - void setArea(const Rectf& area); - const Rectf& getArea() const; - void activate(); - void deactivate(); - void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const; + virtual void activate(); + virtual void unprojectPoint(const GeometryBuffer& buff, + const glm::vec2& p_in, glm::vec2& p_out) const; + virtual void setArea(const Rectf& area); + // implementing the virtual function with a covariant return type + virtual OgreRenderer& getOwner(); protected: //! helper that initialises the cached matrix @@ -83,22 +81,18 @@ class OGRE_GUIRENDERER_API OgreRenderTarget : public T OgreRenderer& d_owner; //! Ogre RendererSystem used to affect the rendering process Ogre::RenderSystem& d_renderSystem; - //! holds defined area for the RenderTarget - Rectf d_area; //! Ogre render target that we are effectively wrapping Ogre::RenderTarget* d_renderTarget; + //! Ogre viewport used for this target. Ogre::Viewport* d_viewport; - //! projection / view matrix cache - mutable Ogre::Matrix4 d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; - //! tracks viewing distance (this is set up at the same time as d_matrix) - mutable float d_viewDistance; - //! true when d_viewport is up to date and valid. - bool d_viewportValid; //! holds set Ogre viewport dimensions Rectf d_ogreViewportDimensions; + + //! true when d_viewport is up to date and valid. + //! \version Beginning from Ogre 2.0 this indicates whether the workspace is + //! up to date + bool d_viewportValid; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/RendererModules/Ogre/Renderer.h b/cegui/include/CEGUI/RendererModules/Ogre/Renderer.h index ae5e2664f..23707331e 100644 --- a/cegui/include/CEGUI/RendererModules/Ogre/Renderer.h +++ b/cegui/include/CEGUI/RendererModules/Ogre/Renderer.h @@ -1,6 +1,6 @@ /*********************************************************************** created: Tue Feb 17 2009 - author: Paul D Turner + author: Paul D Turner, Henri I Hyyryläinen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team @@ -54,16 +54,24 @@ namespace Ogre class Root; class RenderSystem; class RenderTarget; +class SceneManager; #if (CEGUI_OGRE_VERSION < ((1 << 16) | (9 << 8) | 0)) class TexturePtr; #else template class SharedPtr; class Texture; typedef SharedPtr TexturePtr; +class HardwareVertexBufferSharedPtr; #endif class Matrix4; } +#if (CEGUI_OGRE_VERSION >= (2 << 16)) +// The new Ogre Compositor2 system has to be used since ViewPorts +// no longer have the required functionality +#define CEGUI_USE_OGRE_COMPOSITOR2 +#endif + // Start of CEGUI namespace section namespace CEGUI { @@ -170,7 +178,14 @@ class OGRE_GUIRENDERER_API OgreRenderer : public Renderer static OgreRenderer& create(Ogre::RenderTarget& target, const int abi = CEGUI_VERSION_ABI); - //! destory an OgreRenderer object. + /*! + \brief + Creates a new renderer that can be used to create a context on a new Ogre window + */ + static OgreRenderer& registerWindow(OgreRenderer& main_window, + Ogre::RenderTarget &new_window); + + //! destroy an OgreRenderer object. static void destroy(OgreRenderer& renderer); //! function to create a CEGUI::OgreResourceProvider object @@ -185,6 +200,21 @@ class OGRE_GUIRENDERER_API OgreRenderer : public Renderer //! function to destroy a CEGUI::OgreImageCodec object. static void destroyOgreImageCodec(OgreImageCodec& ic); + //! Conversion function from Ogre to glm + static glm::mat4 ogreToGlmMatrix(const Ogre::Matrix4& matrix); + + //! Conversion function from glm to Ogre + static Ogre::Matrix4 glmToOgreMatrix(const glm::mat4& matrix); + +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + //! Function to initialize required Ogre::Compositor2 workspaces + static void createOgreCompositorResources(); + + //! Function to update the workspace render target + void updateWorkspaceRenderTarget(Ogre::RenderTarget& target); + +#endif // CEGUI_USE_OGRE_COMPOSITOR2 + //! set whether CEGUI rendering will occur void setRenderingEnabled(const bool enabled); @@ -196,7 +226,7 @@ class OGRE_GUIRENDERER_API OgreRenderer : public Renderer Create a CEGUI::Texture that wraps an existing Ogre texture. \param name - The name for tne new texture being created. + The name for the new texture being created. \param tex Ogre::TexturePtr for the texture that will be used by the created @@ -274,108 +304,83 @@ class OGRE_GUIRENDERER_API OgreRenderer : public Renderer */ void setDefaultRootRenderTarget(Ogre::RenderTarget& target); - /*! - \brief - Returns whether the OgreRenderer is currently set to use shaders when - doing its rendering operations. - - \return - - true if rendering is being done using shaders. - - false if rendering is being done using the fixed function pipeline - */ - bool isUsingShaders() const; - - /*! - \brief - Set whether the OgreRenderer shound use shaders when performing its - rendering operations. - - \param use_shaders - - true if rendering shaders should be used to perform rendering. - - false if the fixed function pipeline should be used to perform - rendering. - - \note - When compiled against Ogre 1.8 or later, shaders will automatically - be enabled if the render sytem does not support the fixed function - pipeline (such as with Direct3D 11). If you are compiling against - earlier releases of Ogre, you must explicity enable the use of - shaders by calling this function - if you are unsure what you'll be - compiling against, it is safe to call this function anyway. - */ - void setUsingShaders(const bool use_shaders); + //! \brief Sets the correct BlendMode for rendering a GeometryBuffer + void bindBlendMode(BlendMode blend); + /*! - \brief - Perform required operations to bind shaders (or unbind them) depending - on whether shader based rendering is currently enabled. - - Normally you would not need to call this function directly, although - that might be required if you are using RenderEffect objects that - also use shaders. + \brief + Initialises the states for rendering textured geometry */ - void bindShaders(); + void initialiseTextureStates(); /*! - \brief - Updates the shader constant parameters (i.e. uniforms). + \brief + Returns a vertex buffer larger than size if any exist - You do not normally need to call this function directly. Some may need - to call this function if you're doing non-standard or advanced things. + This function also cleans the pool and discards large buffers that + aren't used */ - void updateShaderParams() const; - - //! Set the current world matrix to the given matrix. - void setWorldMatrix(const Ogre::Matrix4& m); - //! Set the current view matrix to the given matrix. - void setViewMatrix(const Ogre::Matrix4& m); - //! Set the current projection matrix to the given matrix. - void setProjectionMatrix(const Ogre::Matrix4& m); - //! return a const reference to the current world matrix. - const Ogre::Matrix4& getWorldMatrix() const; - //! return a const reference to the current view matrix. - const Ogre::Matrix4& getViewMatrix() const; - //! return a const reference to the current projection matrix. - const Ogre::Matrix4& getProjectionMatrix() const; + Ogre::HardwareVertexBufferSharedPtr getVertexBuffer(size_t min_size); - /*! - \brief - Return a const reference to the final transformation matrix that - should be used when transforming geometry. + //! \brief Puts a vertex buffer back in to the pool + void returnVertexBuffer(Ogre::HardwareVertexBufferSharedPtr buffer); - \note - The projection used when building this matrix is correctly adjusted - according to whether the current Ogre::RenderTarget requires textures - to be flipped (i.e it does the right thing for both D3D and OpenGL). - */ - const Ogre::Matrix4& getWorldViewProjMatrix() const; + //! \brief Clears vertex buffer pool + void clearVertexBufferPool(); // implement CEGUI::Renderer interface - RenderTarget& getDefaultRenderTarget(); - GeometryBuffer& createGeometryBuffer(); - void destroyGeometryBuffer(const GeometryBuffer& buffer); - void destroyAllGeometryBuffers(); + virtual void setViewProjectionMatrix(const glm::mat4& viewProjMatrix); + virtual RenderTarget& getDefaultRenderTarget(); + virtual RefCounted createRenderMaterial(const DefaultShaderType shaderType) const; + virtual GeometryBuffer& createGeometryBufferColoured(CEGUI::RefCounted renderMaterial); + virtual GeometryBuffer& createGeometryBufferTextured(CEGUI::RefCounted renderMaterial); + TextureTarget* createTextureTarget(); void destroyTextureTarget(TextureTarget* target); void destroyAllTextureTargets(); + Texture& createTexture(const String& name); - Texture& createTexture(const String& name, - const String& filename, - const String& resourceGroup); + Texture& createTexture(const String& name, const String& filename, + const String& resourceGroup); Texture& createTexture(const String& name, const Sizef& size); +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + Ogre::SceneManager& getDummyScene() const; +#endif void destroyTexture(Texture& texture); void destroyTexture(const String& name); void destroyAllTextures(); + Texture& getTexture(const String& name) const; bool isTextureDefined(const String& name) const; + void beginRendering(); void endRendering(); + void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; + /*! + \brief + Returns if this OgreRenderer uses an OpenGL based RenderSystem. + + \return + True if this OgreRenderer uses an OpenGL based RenderSystem. + */ + bool usesOpenGL(); + + /*! + \brief + Returns if this OgreRenderer uses a Direct3D based RenderSystem. + + \return + True if this OgreRenderer uses a Direct3D based RenderSystem. + */ + bool usesDirect3D(); + protected: //! default constructor. OgreRenderer(); @@ -395,16 +400,19 @@ class OGRE_GUIRENDERER_API OgreRenderer : public Renderer //! common parts of constructor void constructor_impl(Ogre::RenderTarget& target); + //! Helper that switches off shader-usage + void switchShaderUsageOff(); //! helper that creates and sets up shaders void initialiseShaders(); //! helper to clean up shaders void cleanupShaders(); + //! Deletes count number of largest vertex buffers + void cleanLargestVertexBufferPool(size_t count); //! Pointer to the hidden implementation data OgreRenderer_impl* d_pimpl; }; - } // End of CEGUI namespace section #if defined(_MSC_VER) diff --git a/cegui/include/CEGUI/RendererModules/Ogre/ShaderWrapper.h b/cegui/include/CEGUI/RendererModules/Ogre/ShaderWrapper.h new file mode 100644 index 000000000..d8222f5ee --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/Ogre/ShaderWrapper.h @@ -0,0 +1,98 @@ +/*********************************************************************** + created: Fri, 4th July 2014 + author: Henri I Hyyryläinen +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIOgreShaderWrapper_h_ +#define _CEGUIOgreShaderWrapper_h_ + +#include +#include "Renderer.h" +#include "CEGUI/ShaderWrapper.h" +#include "OgreHighLevelGpuProgram.h" + +#include "glm/glm.hpp" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +class ShaderParameterBindings; +class ShaderParameter; + +//----------------------------------------------------------------------------// +class OGRE_GUIRENDERER_API OgreShaderWrapper : public ShaderWrapper +{ +public: + OgreShaderWrapper(OgreRenderer& owner, Ogre::RenderSystem& rs, + Ogre::HighLevelGpuProgramPtr vs, Ogre::HighLevelGpuProgramPtr ps); + + ~OgreShaderWrapper(); + + //Implementation of ShaderWrapper interface + void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings); + + Ogre::GpuProgramParametersSharedPtr getVertexParameters() const; + +protected: + + //! Renderer object that owns this GeometryBuffer + OgreRenderer& d_owner; + //! Ogre render system we're to use. + Ogre::RenderSystem& d_renderSystem; + + //! The GPU program that is our vertex shader + Ogre::HighLevelGpuProgramPtr d_vertexShader; + + //! Parameters for vertex shader + Ogre::GpuProgramParametersSharedPtr d_vertexParameters; + + //! The GPU program that is our pixel shader + Ogre::HighLevelGpuProgramPtr d_pixelShader; + + //! Parameters for pixel shader + Ogre::GpuProgramParametersSharedPtr d_pixelParameters; + + //! The currently active matrix + glm::mat4 d_lastMatrix; + + //! The current alpha value + float d_previousAlpha; + + //! The physical index to which the matrix will be written + size_t d_physicalIndex; + + //! Stores the index where a given type of parameter is bound + //! \note Could be using ShaderParamType but the include is avoided by using an int instead + std::map d_paramTypeToIndex; +}; + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/Ogre/Texture.h b/cegui/include/CEGUI/RendererModules/Ogre/Texture.h index ca25f2ba2..b752f5ecf 100644 --- a/cegui/include/CEGUI/RendererModules/Ogre/Texture.h +++ b/cegui/include/CEGUI/RendererModules/Ogre/Texture.h @@ -30,6 +30,7 @@ #include "../../Texture.h" #include "CEGUI/RendererModules/Ogre/Renderer.h" #include +#include // Start of CEGUI namespace section namespace CEGUI @@ -50,7 +51,7 @@ class OGRE_GUIRENDERER_API OgreTexture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); @@ -105,7 +106,7 @@ class OGRE_GUIRENDERER_API OgreTexture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! Name this texture was created with. const String d_name; }; diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GL.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL.h index 3a952f0de..dd3a796d6 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GL.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL.h @@ -27,13 +27,21 @@ #ifndef _CEGUIOpenGL_h_ #define _CEGUIOpenGL_h_ -#ifndef __APPLE__ +#ifdef __ANDROID__ +# ifdef CEGUI_GLES3_SUPPORT +# include +# else +# include +# endif +#elif !defined(__APPLE__) # if (defined( __WIN32__ ) || defined( _WIN32 )) # include # endif +# include # include # include #else +# include # include # include #endif diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h index ab0941773..8e333de88 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h @@ -42,6 +42,7 @@ namespace CEGUI { class OpenGL3Texture; class OpenGL3Renderer; +class OpenGLBaseStateChangeWrapper; //! ~OpenGL3FBOTextureTarget - allows rendering to an OpenGL texture via FBO. class OPENGL_GUIRENDERER_API OpenGL3FBOTextureTarget : public OpenGLTextureTarget @@ -73,8 +74,12 @@ class OPENGL_GUIRENDERER_API OpenGL3FBOTextureTarget : public OpenGLTextureTarge //! Frame buffer object. GLuint d_frameBuffer; + //! Stencil buffer renderbuffer object + GLuint d_stencilBufferRBO; //! Frame buffer object that was bound before we bound this one GLuint d_previousFrameBuffer; + //! OpenGL state changer + OpenGLBaseStateChangeWrapper* d_glStateChanger; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h index 120f5273e..1c553e032 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h @@ -28,47 +28,45 @@ #define _CEGUIOpenGL3GeometryBuffer_h_ #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" +#include "CEGUI/RefCounted.h" namespace CEGUI { class OpenGL3Shader; -class OpenGL3StateChangeWrapper; +class OpenGLBaseStateChangeWrapper; class OpenGL3Renderer; +class RenderMaterial; //! OpenGL3 based implementation of the GeometryBuffer interface. class OPENGL_GUIRENDERER_API OpenGL3GeometryBuffer : public OpenGLGeometryBufferBase { public: //! Constructor - OpenGL3GeometryBuffer(OpenGL3Renderer& owner); + OpenGL3GeometryBuffer(OpenGL3Renderer& owner, CEGUI::RefCounted renderMaterial); virtual ~OpenGL3GeometryBuffer(); - void initialiseOpenGLBuffers(); - void deinitialiseOpenGLBuffers(); - void updateOpenGLBuffers(); + // Overrides of virtual and abstract methods from GeometryBuffer + virtual void draw() const; + virtual void appendGeometry(const float* vertex_data, std::size_t array_size); + virtual void reset(); - // implementation/overrides of members from GeometryBuffer - void draw() const; - void appendGeometry(const Vertex* const vbuff, uint vertex_count); - void reset(); + // Implementation/overrides of member functions inherited from OpenGLGeometryBufferBase + void finaliseVertexAttributes(); protected: + void initialiseVertexBuffers(); + void deinitialiseOpenGLBuffers(); + //! Update the OpenGL buffer objects containing the vertex data. + void updateOpenGLBuffers(); + //! Draws the vertex data depending on the fill rule that was set for this object. + void drawDependingOnFillRule() const; + //! OpenGL vao used for the vertices GLuint d_verticesVAO; //! OpenGL vbo containing all vertex data GLuint d_verticesVBO; - //! Reference to the OpenGL shader inside the Renderer, that is used to render all geometry - CEGUI::OpenGL3Shader*& d_shader; - //! Position variable location inside the shader, for OpenGL - const GLint d_shaderPosLoc; - //! TexCoord variable location inside the shader, for OpenGL - const GLint d_shaderTexCoordLoc; - //! Color variable location inside the shader, for OpenGL - const GLint d_shaderColourLoc; - //! Matrix uniform location inside the shader, for OpenGL - const GLint d_shaderStandardMatrixLoc; //! Pointer to the OpenGL state changer wrapper that was created inside the Renderer - OpenGL3StateChangeWrapper* d_glStateChanger; + OpenGLBaseStateChangeWrapper* d_glStateChanger; //! Size of the buffer that is currently in use GLuint d_bufferSize; }; diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GL3Renderer.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL3Renderer.h index d6eac407f..9680c5aac 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GL3Renderer.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL3Renderer.h @@ -31,9 +31,9 @@ namespace CEGUI { - class OpenGL3Shader; - class OpenGL3ShaderManager; - class OpenGL3StateChangeWrapper; + class OpenGLBaseShaderWrapper; + class OpenGLBaseShaderManager; + class OpenGLBaseStateChangeWrapper; /*! \brief @@ -144,59 +144,6 @@ class OPENGL_GUIRENDERER_API OpenGL3Renderer : public OpenGLRendererBase */ static void destroy(OpenGL3Renderer& renderer); - /*! - \brief - Helper to return the reference to the pointer to the standard shader of - the Renderer - - \return - Reference to the pointer to the standard shader of the Renderer - */ - OpenGL3Shader*& getShaderStandard(); - - /*! - \brief - Helper to return the attribute location of the position variable in the - standard shader - - \return - Attribute location of the position variable in the standard shader - */ - GLint getShaderStandardPositionLoc(); - - - /*! - \brief - Helper to return the attribute location of the texture coordinate - variable in the standard shader - - \return - Attribute location of the texture coordinate variable in the standard - shader - */ - GLint getShaderStandardTexCoordLoc(); - - - /*! - \brief - Helper to return the attribute location of the colour variable in the - standard shader - - \return - Attribute location of the colour variable in the standard shader - */ - GLint getShaderStandardColourLoc(); - - /*! - \brief - Helper to return the uniform location of the matrix variable in the - standard shader - - \return - Uniform location of the matrix variable in the standard shader - */ - GLint getShaderStandardMatrixUniformLoc(); - /*! \brief Helper to get the wrapper used to check for redundant OpenGL state @@ -205,29 +152,28 @@ class OPENGL_GUIRENDERER_API OpenGL3Renderer : public OpenGLRendererBase \return The active OpenGL state change wrapper object. */ - OpenGL3StateChangeWrapper* getOpenGLStateChanger(); + OpenGLBaseStateChangeWrapper* getOpenGLStateChanger(); // base class overrides / abstract function implementations void beginRendering(); void endRendering(); - Sizef getAdjustedTextureSize(const Sizef& sz) const; + virtual Sizef getAdjustedTextureSize(const Sizef& sz); bool isS3TCSupported() const; void setupRenderingBlendMode(const BlendMode mode, const bool force = false); + RefCounted createRenderMaterial(const DefaultShaderType shaderType) const; -private: - OpenGLGeometryBufferBase* createGeometryBuffer_impl(); +protected: + OpenGLGeometryBufferBase* createGeometryBuffer_impl(CEGUI::RefCounted renderMaterial); TextureTarget* createTextureTarget_impl(); + //! creates a texture of GL3Texture type + virtual OpenGLTexture* createTexture_impl(const String& name); void initialiseRendererIDString(); /*! \brief Constructor for OpenGL Renderer objects - - \param tt_type - Specifies one of the TextureTargetType enumerated values indicating the - desired TextureTarget type to be used. */ OpenGL3Renderer(); @@ -237,14 +183,16 @@ class OPENGL_GUIRENDERER_API OpenGL3Renderer : public OpenGLRendererBase \param display_size Size object describing the initial display resolution. - - \param tt_type - Specifies one of the TextureTargetType enumerated values indicating the - desired TextureTarget type to be used. */ OpenGL3Renderer(const Sizef& display_size); + //! Initialises the ShaderManager and the required OpenGL shaders void initialiseOpenGLShaders(); + //! Initialises the OpenGL ShaderWrapper for textured objects + void initialiseStandardTexturedShaderWrapper(); + //! Initialises the OpenGL ShaderWrapper for coloured objects + void initialiseStandardColouredShaderWrapper(); + void initialiseGLExtensions(); /*! @@ -259,19 +207,15 @@ class OPENGL_GUIRENDERER_API OpenGL3Renderer : public OpenGLRendererBase //! init the extra GL states enabled via enableExtraStateSettings void setupExtraStates(); - //! The OpenGL shader we will use usually - OpenGL3Shader* d_shaderStandard; - //! Position variable location inside the shader, for OpenGL - GLint d_shaderStandardPosLoc; - //! TexCoord variable location inside the shader, for OpenGL - GLint d_shaderStandardTexCoordLoc; - //! Color variable location inside the shader, for OpenGL - GLint d_shaderStandardColourLoc; - //! Matrix uniform location inside the shader, for OpenGL - GLint d_shaderStandardMatrixLoc; + //! Wrapper of the OpenGL shader we will use for textured geometry + OpenGLBaseShaderWrapper* d_shaderWrapperTextured; + //! Wrapper of the OpenGL shader we will use for solid geometry + OpenGLBaseShaderWrapper* d_shaderWrapperSolid; + //! The wrapper we use for OpenGL calls, to detect redundant state changes and prevent them - OpenGL3StateChangeWrapper* d_openGLStateChanger; - OpenGL3ShaderManager* d_shaderManager; + OpenGLBaseStateChangeWrapper* d_openGLStateChanger; + //! The ShaderManager takes care of the creation of standard OpenGL Shaders and their deletion + OpenGLBaseShaderManager* d_shaderManager; //! whether S3TC texture compression is supported by the context bool d_s3tcSupported; //! pointer to a helper that creates TextureTargets supported by the system. diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/Tree.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL3Shader.h similarity index 51% rename from cegui/include/CEGUI/WindowRendererSets/Core/Tree.h rename to cegui/include/CEGUI/RendererModules/OpenGL/GL3Shader.h index ae0c9e9ea..f4b097c27 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/Tree.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL3Shader.h @@ -1,9 +1,9 @@ /*********************************************************************** -created: 5-13-07 -author: Jonathan Welch (Based on Code by David Durant) +created: Wed, 8th Feb 2012 +author: Lukas E Meindl *************************************************************************/ /*************************************************************************** -* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team +* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,59 +24,46 @@ author: Jonathan Welch (Based on Code by David Durant) * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _FalTree_h_ -#define _FalTree_h_ +#ifndef _CEGUIOpenGL3Shader_h_ +#define _CEGUIOpenGL3Shader_h_ -#include "CEGUI/WindowRendererSets/Core/Module.h" -#include "CEGUI/WindowFactory.h" -#include "CEGUI/widgets/Tree.h" +#include "CEGUI/RendererModules/OpenGL/Shader.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif // Start of CEGUI namespace section namespace CEGUI { - /*! - \brief - Tree class for the FalagardBase module. +class OpenGLBaseStateChangeWrapper; - This class requires LookNFeel to be assigned. The LookNFeel should provide the following: +class OPENGL_GUIRENDERER_API OpenGL3Shader : public OpenGLBaseShader +{ +public: - States: - - Enabled - - Disabled + /*! + \brief + Creates and loads shader programs from the two strings supplied to it + */ + OpenGL3Shader(const std::string& vertex_shader_source, + const std::string& fragment_shader_source, + OpenGLBaseStateChangeWrapper* glStateChanger); - Named Areas: - - ItemRenderingArea - - ItemRenderingAreaHScroll - - ItemRenderingAreaVScroll - - ItemRenderingAreaHVScroll + ~OpenGL3Shader(); - Child Widgets: - Scrollbar based widget with name suffix "__auto_vscrollbar__" - Scrollbar based widget with name suffix "__auto_hscrollbar__" + /*! + \brief + Defines the name of the variable inside the shader which represents the + final color for each fragment. */ - class COREWRSET_API FalagardTree : public WindowRenderer - { - public: - static const String TypeName; //!< type name for this widget. - - /*! - \brief - Constructor - */ - FalagardTree(const String& type, const String& name); - FalagardTree(const String& type); + virtual void bindFragDataLocation(const std::string &name); - /*! - \brief - Destructor - */ - ~FalagardTree(); - protected: - Rectf getTreeRenderArea(void) const; - void render(); - }; + virtual void link(); +}; -} // End of CEGUI namespace section +} +#endif -#endif // end of guard _FalTree_h_ diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GL3StateChangeWrapper.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL3StateChangeWrapper.h new file mode 100644 index 000000000..2c2c1984a --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL3StateChangeWrapper.h @@ -0,0 +1,64 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl + edited: David Reepmeyer (GLES2/3 support) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#ifndef _CEGUIOpenGL3StateChangeWrapper_h_ +#define _CEGUIOpenGL3StateChangeWrapper_h_ + +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "RendererBase.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ + +/*! +\brief +OpenGL3StateChangeWrapper - wraps OpenGL calls and checks for redundant calls beforehand +*/ +class OPENGL_GUIRENDERER_API OpenGL3StateChangeWrapper : public OpenGLBaseStateChangeWrapper +{ +public: + OpenGL3StateChangeWrapper(); + virtual ~OpenGL3StateChangeWrapper(); + + //! call to glBindVertexArray + virtual void bindVertexArray(GLuint vertexArray); +}; + +} // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/MemoryStdAllocator.h b/cegui/include/CEGUI/RendererModules/OpenGL/GL3Texture.h similarity index 58% rename from cegui/include/CEGUI/MemoryStdAllocator.h rename to cegui/include/CEGUI/RendererModules/OpenGL/GL3Texture.h index 1a07ba074..390df0727 100644 --- a/cegui/include/CEGUI/MemoryStdAllocator.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GL3Texture.h @@ -1,11 +1,9 @@ /*********************************************************************** - created: 14/10/2010 - author: Martin Preisler - - purpose: Implements the default "dummy" allocator + created: Sun Jan 11 2009 + author: Paul D Turner *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -26,42 +24,40 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIMemoryStdAllocator_h_ -#define _CEGUIMemoryStdAllocator_h_ +#ifndef _CEGUIOpenGL3Texture_h_ +#define _CEGUIOpenGL3Texture_h_ + +#include "CEGUI/RendererModules/OpenGL/GLTexture.h" +#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h" -#include -#include +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif +// Start of CEGUI namespace section namespace CEGUI { -class CEGUIEXPORT StdAllocator +//! Texture implementation for the OpenGL3Renderer. +class OPENGL_GUIRENDERER_API OpenGL3Texture : public OpenGL1Texture { -public: - static inline void* allocateBytes(size_t count) - { - return malloc(count); - } - - static inline void deallocateBytes(void* ptr) - { - free(ptr); - } +protected: + friend class OpenGL3Renderer; - // !!! IF YOU GET AN ERROR HERE: - // that says something like: "You can't call allocateBytes with 4 arguments", - // you are using StdAllocator and trying to enable CEGUI_CUSTOM_ALLOCATORS_DEBUG, you - // have to provide your own custom memory allocator if you want memory debugging. + //! Basic constructor. + OpenGL3Texture(OpenGLRendererBase& owner, const String& name); + //! Destructor. + virtual ~OpenGL3Texture(); - /// Get the maximum size of a single allocation - static inline size_t getMaxAllocationSize() - { - return std::numeric_limits::max(); - } + //! OpenGL method to set glTexEnv which is deprecated in GL 3.2 and GLES 2.0 and above + virtual void setTextureEnvironment(); }; -CEGUI_SET_DEFAULT_ALLOCATOR(StdAllocator) +} // End of CEGUI namespace section -} +#if defined(_MSC_VER) +# pragma warning(pop) +#endif -#endif // end of guard _CEGUIMemoryStdAllocator_h_ +#endif // end of guard _CEGUIOpenGL3Texture_h_ diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h new file mode 100644 index 000000000..c62ad54de --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h @@ -0,0 +1,86 @@ +/*********************************************************************** + created: 18th July 2013 + author: Lukas Meindl + edited: David Reepmeyer (GLES2/3 support) +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CEGUIOpenGLBaseShaderWrapper_h_ +#define _CEGUIOpenGLBaseShaderWrapper_h_ + +#include "RendererBase.h" + +#include "CEGUI/ShaderWrapper.h" +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ + class OpenGLBaseShader; + class ShaderParameterBindings; + class OpenGLBaseStateChangeWrapper; + class ShaderParameter; + +class OPENGL_GUIRENDERER_API OpenGLBaseShaderWrapper : public ShaderWrapper +{ +public: + OpenGLBaseShaderWrapper(OpenGLBaseShader& shader, OpenGLBaseStateChangeWrapper* stateChangeWrapper); + + ~OpenGLBaseShaderWrapper(); + + //Implementation of ShaderWrapper interface + void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings); + + //! Adds a shader attribute variable to the list of variables + void addAttributeVariable(const std::string& attributeName); + //! Adds a shader uniform variable to the list of variables + void addUniformVariable(const std::string& uniformName); + //! Adds a shader attribute variable to the list of variables + void addTextureUniformVariable(const std::string& uniformName, GLint textureUnitIndex); + + GLint getAttributeLocation(const std::string& attributeName) const; + GLint getUniformLocation(const std::string& uniformName) const; + +protected: + //! The underlying GLSL shader that this class wraps the access to + OpenGLBaseShader& d_shader; + //! A map of parameter names and the related uniform variable locations + std::map d_uniformVariables; + //! A map of parameter names and the related attribute variable locations + std::map d_attributeVariables; + //! OpenGL state change wrapper + OpenGLBaseStateChangeWrapper* d_glStateChangeWrapper; + //! Last states of the set shader parameters + std::map d_shaderParameterStates; +}; + + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/Direct3D9/TextureTarget.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h similarity index 50% rename from cegui/include/CEGUI/RendererModules/Direct3D9/TextureTarget.h rename to cegui/include/CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h index dcd33a6c3..10da4f3dd 100644 --- a/cegui/include/CEGUI/RendererModules/Direct3D9/TextureTarget.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h @@ -1,9 +1,10 @@ /*********************************************************************** - created: Fri Feb 13 2009 - author: Paul D Turner + created: Wed, 8th Feb 2012 + author: Lukas E Meindl (based on code by Paul D Turner) + David Reepmeyer (added GLES2/GLES3) *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,76 +25,62 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIDirect3D9TextureTarget_h_ -#define _CEGUIDirect3D9TextureTarget_h_ +#ifndef _CEGUIGLES2FBOTextureTarget_h_ +#define _CEGUIGLES2FBOTextureTarget_h_ + +#include "CEGUI/RendererModules/OpenGL/TextureTarget.h" +#include "CEGUI/RendererModules/OpenGL/GL.h" +#include "../../Rect.h" -#include "CEGUI/RendererModules/Direct3D9/RenderTarget.h" -#include "../../TextureTarget.h" -#include #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4250) -# pragma warning(disable : 4251) #endif // Start of CEGUI namespace section namespace CEGUI { -class Direct3D9Texture; +class GLES2Texture; +class GLES2Renderer; +class OpenGLBaseStateChangeWrapper; -//! Direct3D9TextureTarget - allows rendering to an Direct3D9 texture via . -class DIRECT3D9_GUIRENDERER_API Direct3D9TextureTarget : public Direct3D9RenderTarget +//! ~GLES2FBOTextureTarget - allows rendering to an OpenGL texture via FBO. +class OPENGL_GUIRENDERER_API GLES2FBOTextureTarget : public OpenGLTextureTarget { public: - Direct3D9TextureTarget(Direct3D9Renderer& owner); - virtual ~Direct3D9TextureTarget(); - - //! auto called via the Renderer prior to Reset on the Direct3DDevice9. - void preD3DReset(); + GLES2FBOTextureTarget(GLES2Renderer& owner); + virtual ~GLES2FBOTextureTarget(); - //! auto called via the Renderer after Reset on the Direct3DDevice9. - void postD3DReset(); - - // overrides from Direct3D9RenderTarget + // overrides from GLES2RenderTarget void activate(); void deactivate(); - // implementation of RenderTarget interface - bool isImageryCache() const; // implementation of TextureTarget interface void clear(); - Texture& getTexture() const; void declareRenderSize(const Sizef& sz); - bool isRenderingInverted() const; + // specialise functions from GLES2TextureTarget + void grabTexture(); + void restoreTexture(); protected: //! default size of created texture objects static const float DEFAULT_SIZE; - //! static data used for creating texture names - static uint s_textureNumber; - //! helper to generate unique texture names - static String generateTextureName(); - //! allocate and set up the texture used for rendering. + //! allocate and set up the texture used with the FBO. void initialiseRenderTexture(); - //! clean up the texture used for rendering. - void cleanupRenderTexture(); //! resize the texture void resizeRenderTexture(); + //! Checks for OpenGL framebuffer completeness + void checkFramebufferStatus(); - //! switch to the texture surface & depth buffer - void enableRenderTexture(); - //! switch back to previous surface - void disableRenderTexture(); - - //! Direct3D9 texture that's rendered to. - LPDIRECT3DTEXTURE9 d_texture; - //! Direct3D9 surface for the texture - LPDIRECT3DSURFACE9 d_surface; - //! we use this to wrap d_texture so it can be used by the core CEGUI lib. - Direct3D9Texture* d_CEGUITexture; - //! colour surface that was in use before this target was activated. - LPDIRECT3DSURFACE9 d_prevColourSurface; + //! Frame buffer object. + GLuint d_frameBuffer; + //! Stencil buffer renderbuffer object + GLuint d_stencilBufferRBO; + //! Frame buffer object that was bound before we bound this one + GLuint d_previousFrameBuffer; + //! OpenGL state changer + OpenGLBaseStateChangeWrapper* d_glStateChanger; }; } // End of CEGUI namespace section @@ -102,4 +89,4 @@ class DIRECT3D9_GUIRENDERER_API Direct3D9TextureTarget : public Direct3D9RenderT # pragma warning(pop) #endif -#endif // end of guard _CEGUIDirect3D9TextureTarget_h_ +#endif // end of guard _CEGUIOpenGLFBOTextureTarget_h_ diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h new file mode 100644 index 000000000..5c6c25f19 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h @@ -0,0 +1,85 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl (based on code by Paul D Turner) + David Reepmeyer (added GLES2/GLES3) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIGLES2GeometryBuffer_h_ +#define _CEGUIGLES2GeometryBuffer_h_ + +#include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" +#include "CEGUI/RefCounted.h" + +namespace CEGUI +{ +class OpenGLBaseShader; +class OpenGLBaseStateChangeWrapper; +class GLES2Renderer; +class RenderMaterial; + +//! GLES2 based implementation of the GeometryBuffer interface. +class OPENGL_GUIRENDERER_API GLES2GeometryBuffer : public OpenGLGeometryBufferBase +{ +public: + //! Constructor + GLES2GeometryBuffer(GLES2Renderer& owner, CEGUI::RefCounted renderMaterial); + virtual ~GLES2GeometryBuffer(); + + // Overrides of virtual and abstract methods from GeometryBuffer + virtual void draw() const; + virtual void appendGeometry(const float* vertex_data, std::size_t array_size); + virtual void reset(); + + // Implementation/overrides of member functions inherited from OpenGLGeometryBufferBase + void finaliseVertexAttributes(); + +protected: + void initialiseVertexBuffers(); + void deinitialiseOpenGLBuffers(); + //! Update the OpenGL buffer objects containing the vertex data. + void updateOpenGLBuffers(); + //! Draws the vertex data depending on the fill rule that was set for this object. + void drawDependingOnFillRule() const; + //! called each time before rendering if VAO's not used (GLES2) + //! called once upon setup if VAO's are used (GLES3) + void bindVertexAttributes() const; + + //! OpenGL vao used for the vertices + GLuint d_verticesVAO; + GLint d_posAttrib; + GLint d_texAttrib; + GLint d_colAttrib; + + //! OpenGL vbo containing all vertex data + GLuint d_verticesVBO; + //! Pointer to the OpenGL state changer wrapper that was created inside the Renderer + OpenGLBaseStateChangeWrapper* d_glStateChanger; + //! Size of the buffer that is currently in use + GLuint d_bufferSize; +}; + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Renderer.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Renderer.h new file mode 100644 index 000000000..8b5062a56 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Renderer.h @@ -0,0 +1,230 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl (based on code by Paul D Turner) + David Reepmeyer (added GLES2/GLES3) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIGLES2Renderer_h_ +#define _CEGUIGLES2Renderer_h_ + +#include "RendererBase.h" + +namespace CEGUI +{ + class OpenGLBaseShaderWrapper; + class OpenGLBaseShaderManager; + class OpenGLBaseStateChangeWrapper; + +/*! +\brief + Renderer class to interface with OpenGL +*/ +class OPENGL_GUIRENDERER_API GLES2Renderer : public OpenGLRendererBase +{ +public: + /*! + \brief + Convenience function that creates the required objects to initialise the + CEGUI system. + + The created Renderer will use the current OpenGL viewport as it's + default surface size. + + This will create and initialise the following objects for you: + - CEGUI::GLES2Renderer + - CEGUI::DefaultResourceProvider + - CEGUI::System + + \param abi + This must be set to CEGUI_VERSION_ABI + + \return + Reference to the CEGUI::GLES2Renderer object that was created. + */ + static GLES2Renderer& bootstrapSystem(const int abi = CEGUI_VERSION_ABI); + + /*! + \brief + Convenience function that creates the required objects to initialise the + CEGUI system. + + The created Renderer will use the current OpenGL viewport as it's + default surface size. + + This will create and initialise the following objects for you: + - CEGUI::GLES2Renderer + - CEGUI::DefaultResourceProvider + - CEGUI::System + + \param display_size + Size object describing the initial display resolution. + + \param abi + This must be set to CEGUI_VERSION_ABI + + \return + Reference to the CEGUI::GLES2Renderer object that was created. + */ + static GLES2Renderer& bootstrapSystem(const Sizef& display_size, + const int abi = CEGUI_VERSION_ABI); + + /*! + \brief + Convenience function to cleanup the CEGUI system and related objects + that were created by calling the bootstrapSystem function. + + This function will destroy the following objects for you: + - CEGUI::System + - CEGUI::DefaultResourceProvider + - CEGUI::GLES2Renderer + + \note + If you did not initialise CEGUI by calling the bootstrapSystem function, + you should \e not call this, but rather delete any objects you created + manually. + */ + static void destroySystem(); + + /*! + \brief + Create an GLES2Renderer object. + + \param tt_type + Specifies one of the TextureTargetType enumerated values indicating the + desired TextureTarget type to be used. + + \param abi + This must be set to CEGUI_VERSION_ABI + */ + static GLES2Renderer& create(const int abi = CEGUI_VERSION_ABI); + + /*! + \brief + Create an GLES2Renderer object. + + \param display_size + Size object describing the initial display resolution. + + \param tt_type + Specifies one of the TextureTargetType enumerated values indicating the + desired TextureTarget type to be used. + + \param abi + This must be set to CEGUI_VERSION_ABI + */ + static GLES2Renderer& create(const Sizef& display_size, + const int abi = CEGUI_VERSION_ABI); + + /*! + \brief + Destroy an GLES2Renderer object. + + \param renderer + The GLES2Renderer object to be destroyed. + */ + static void destroy(GLES2Renderer& renderer); + + /*! + \brief + Helper to get the wrapper used to check for redundant OpenGL state + changes. + + \return + The active OpenGL state change wrapper object. + */ + OpenGLBaseStateChangeWrapper* getOpenGLStateChanger(); + + // base class overrides / abstract function implementations + void beginRendering(); + virtual Sizef getAdjustedTextureSize(const Sizef& sz); + void endRendering(); + Sizef getAdjustedTextureSize(const Sizef& sz) const; + bool isS3TCSupported() const; + void setupRenderingBlendMode(const BlendMode mode, + const bool force = false); + RefCounted createRenderMaterial(const DefaultShaderType shaderType) const; + +protected: + OpenGLGeometryBufferBase* createGeometryBuffer_impl(CEGUI::RefCounted renderMaterial); + TextureTarget* createTextureTarget_impl(); + //! creates a texture of GLES2Texture type + virtual OpenGLTexture* createTexture_impl(const String& name); + + void initialiseRendererIDString(); + + /*! + \brief + Constructor for OpenGL Renderer objects + */ + GLES2Renderer(); + + /*! + \brief + Constructor for OpenGL Renderer objects. + + \param display_size + Size object describing the initial display resolution. + */ + GLES2Renderer(const Sizef& display_size); + + //! Initialises the ShaderManager and the required OpenGL shaders + void initialiseOpenGLShaders(); + //! Initialises the OpenGL ShaderWrapper for textured objects + void initialiseStandardTexturedShaderWrapper(); + //! Initialises the OpenGL ShaderWrapper for coloured objects + void initialiseStandardColouredShaderWrapper(); + + void initialiseGLExtensions(); + + /*! + \brief + Destructor for GLES2Renderer objects + */ + virtual ~GLES2Renderer(); + + //! initialise OGLES2TextureTargetFactory that will generate TextureTargets + void initialiseTextureTargetFactory(); + + //! init the extra GL states enabled via enableExtraStateSettings + void setupExtraStates(); + + //! Wrapper of the OpenGL shader we will use for textured geometry + OpenGLBaseShaderWrapper* d_shaderWrapperTextured; + //! Wrapper of the OpenGL shader we will use for solid geometry + OpenGLBaseShaderWrapper* d_shaderWrapperSolid; + + //! The wrapper we use for OpenGL calls, to detect redundant state changes and prevent them + OpenGLBaseStateChangeWrapper* d_openGLStateChanger; + //! The ShaderManager takes care of the creation of standard OpenGL Shaders and their deletion + OpenGLBaseShaderManager* d_shaderManager; + //! whether S3TC texture compression is supported by the context + bool d_s3tcSupported; + //! pointer to a helper that creates TextureTargets supported by the system. + OGLTextureTargetFactory* d_textureTargetFactory; +}; + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h new file mode 100644 index 000000000..8bb5e2142 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h @@ -0,0 +1,64 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl + edited: David Reepmeyer (GLES2/3 support) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#ifndef _CEGUIGLES2StateChangeWrapper_h_ +#define _CEGUIGLES2StateChangeWrapper_h_ + +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "RendererBase.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ + +/*! +\brief +GLES2StateChangeWrapper - wraps OpenGL calls and checks for redundant calls beforehand +*/ +class OPENGL_GUIRENDERER_API GLES2StateChangeWrapper : public OpenGLBaseStateChangeWrapper +{ +public: + GLES2StateChangeWrapper(); + virtual ~GLES2StateChangeWrapper(); + + //! glBindVertexArray only recognized in GLES3 (not 2) + virtual void bindVertexArray(GLuint vertexArray); +}; + +} // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Texture.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Texture.h new file mode 100644 index 000000000..b936a8d7f --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Texture.h @@ -0,0 +1,72 @@ +/*********************************************************************** + created: Sun Jan 11 2009 + author: Paul D Turner +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIGLES2Texture_h_ +#define _CEGUIGLES2Texture_h_ + +#include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +//! Texture implementation for the GLES2Renderer. +class OPENGL_GUIRENDERER_API GLES2Texture : public OpenGLTexture +{ +public: + virtual void blitToMemory(void* targetData); + + // Friends (to allow construction and destruction) + friend GLES2Renderer; +protected: + + //! Basic constructor. + GLES2Texture(OpenGLRendererBase& owner, const String& name); + //! Destructor. + virtual ~GLES2Texture(); + + //! initialise the internal format flags for the given CEGUI::PixelFormat. + virtual void initInternalPixelFormatFields(const PixelFormat fmt); + + //! internal texture resize function (does not reset format or other fields) + virtual void setTextureSize_impl(const Sizef& sz); + + virtual GLsizei getCompressedTextureSize(const Sizef& pixel_size) const; + +}; + +} // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIGLES2Texture_h_ diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h index a337fddec..38bdf96ef 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h @@ -38,7 +38,6 @@ // Start of CEGUI namespace section namespace CEGUI { -class OpenGLTexture; class OpenGLRenderer; /*! @@ -49,10 +48,19 @@ class OPENGL_GUIRENDERER_API OpenGLGeometryBuffer : public OpenGLGeometryBufferB { public: //! Constructor - OpenGLGeometryBuffer(OpenGLRenderer& owner); + OpenGLGeometryBuffer(OpenGLRenderer& owner, CEGUI::RefCounted renderMaterial); - // implementation/overrides of members from GeometryBuffer - void draw() const; + // Overrides of virtual and abstract methods inherited from GeometryBuffer + virtual void draw() const; + + // Overrides of virtual and abstract methods inherited from GeometryBufferBase + virtual void finaliseVertexAttributes(); + + /* + \brief + Updates the fixed-function vertex data pointers based on the defined vertex attributes + */ + void setupVertexDataPointers() const; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLRenderer.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLRenderer.h index cbc7d6f21..145a419a5 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GLRenderer.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLRenderer.h @@ -32,6 +32,7 @@ namespace CEGUI { + class OpenGLShaderWrapper; /*! \brief Renderer class to interface with OpenGL @@ -170,14 +171,17 @@ class OPENGL_GUIRENDERER_API OpenGLRenderer : public OpenGLRendererBase // base class overrides / abstract function implementations void beginRendering(); void endRendering(); + virtual Sizef getAdjustedTextureSize(const Sizef& sz); bool isS3TCSupported() const; void setupRenderingBlendMode(const BlendMode mode, const bool force = false); - void setViewProjectionMatrix(const mat4Pimpl* viewProjectionMatrix); + RefCounted createRenderMaterial(const DefaultShaderType shaderType) const; protected: - OpenGLGeometryBufferBase* createGeometryBuffer_impl(); + OpenGLGeometryBufferBase* createGeometryBuffer_impl(CEGUI::RefCounted renderMaterial); TextureTarget* createTextureTarget_impl(); + //! creates a texture of GLTexture type + virtual OpenGLTexture* createTexture_impl(const String& name); //! set up renderer id string. void initialiseRendererIDString(); @@ -205,6 +209,8 @@ class OPENGL_GUIRENDERER_API OpenGLRenderer : public OpenGLRendererBase */ OpenGLRenderer(const Sizef& display_size, const TextureTargetType tt_type); + void initialiseShaderWrappers(); + /*! \brief Destructor for OpenGLRenderer objects @@ -224,6 +230,12 @@ class OPENGL_GUIRENDERER_API OpenGLRenderer : public OpenGLRendererBase //! pointer to a helper that creates TextureTargets supported by the system. OGLTextureTargetFactory* d_textureTargetFactory; + + //! Shaderwrapper for textured & coloured vertices + OpenGLShaderWrapper* d_shaderWrapperTextured; + + //! Shaderwrapper for coloured vertices + OpenGLShaderWrapper* d_shaderWrapperSolid; }; } diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLShaderWrapper.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLShaderWrapper.h new file mode 100644 index 000000000..a12926b81 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLShaderWrapper.h @@ -0,0 +1,60 @@ +/*********************************************************************** + created: 23rd September 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CEGUIOpenGLShaderWrapper_h_ +#define _CEGUIOpenGLShaderWrapper_h_ + +#include "RendererBase.h" +#include "CEGUI/ShaderWrapper.h" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +class ShaderParameterBindings; + +class OPENGL_GUIRENDERER_API OpenGLShaderWrapper : public ShaderWrapper +{ +public: + OpenGLShaderWrapper(); + + ~OpenGLShaderWrapper(); + + //Implementation of ShaderWrapper interface + void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings); +}; + + +} + +#endif + diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GLTexture.h b/cegui/include/CEGUI/RendererModules/OpenGL/GLTexture.h new file mode 100644 index 000000000..9359514b5 --- /dev/null +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GLTexture.h @@ -0,0 +1,74 @@ +/*********************************************************************** + created: Sun Jan 11 2009 + author: Paul D Turner +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIOpenGL1Texture_h_ +#define _CEGUIOpenGL1Texture_h_ + +#include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/RendererModules/OpenGL/GLRenderer.h" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +//! Texture implementation for the OpenGLRenderer. +class OPENGL_GUIRENDERER_API OpenGL1Texture : public OpenGLTexture +{ +public: + virtual void blitToMemory(void* targetData); + +protected: + friend class OpenGLRenderer; + + //! Basic constructor. + OpenGL1Texture(OpenGLRendererBase& owner, const String& name); + //! Destructor. + virtual ~OpenGL1Texture(); + + //! OpenGL method to set glTexEnv which is deprecated in GL 3.2 and GLES 2.0 and above + virtual void setTextureEnvironment(); + + //! initialise the internal format flags for the given CEGUI::PixelFormat. + virtual void initInternalPixelFormatFields(const PixelFormat fmt); + + //! internal texture resize function (does not reset format or other fields) + virtual void setTextureSize_impl(const Sizef& sz); + + virtual GLsizei getCompressedTextureSize(const Sizef& pixel_size) const; + +}; + +} // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIOpenGL1Texture_h_ diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h b/cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h index 8b427bae1..ec09bef5e 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h @@ -1,7 +1,7 @@ /*********************************************************************** created: Tue Apr 30 2013 authors: Paul D Turner - Lukas E Meindl + Lukas Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team @@ -28,10 +28,11 @@ #ifndef _CEGUIGeometryBufferBase_h_ #define _CEGUIGeometryBufferBase_h_ -#include "../../GeometryBuffer.h" +#include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/OpenGL/RendererBase.h" -#include "../../Rect.h" -#include "../../Quaternion.h" +#include "CEGUI/Rect.h" + +#include "CEGUI/RefCounted.h" #include #include @@ -44,6 +45,7 @@ namespace CEGUI { class OpenGLTexture; +class RenderMaterial; /*! \brief @@ -53,80 +55,29 @@ class OPENGL_GUIRENDERER_API OpenGLGeometryBufferBase : public GeometryBuffer { public: //! Constructor - OpenGLGeometryBufferBase(OpenGLRendererBase& owner); + OpenGLGeometryBufferBase(OpenGLRendererBase& owner, CEGUI::RefCounted renderMaterial); virtual ~OpenGLGeometryBufferBase(); - // implementation of abstract members from GeometryBuffer - void setTranslation(const Vector3f& t); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); - void setClippingRegion(const Rectf& region); - void appendVertex(const Vertex& vertex); - void appendGeometry(const Vertex* const vbuff, uint vertex_count); - void setActiveTexture(Texture* texture); - void reset(); - Texture* getActiveTexture() const; - uint getVertexCount() const; - uint getBatchCount() const; - void setRenderEffect(RenderEffect* effect); - RenderEffect* getRenderEffect(); - void setClippingActive(const bool active); - bool isClippingActive() const; + // Overrides of virtual and abstract methods inherited from GeometryBuffer + virtual void setClippingRegion(const Rectf& region); - //! return the GL modelview matrix used for this buffer. - const mat4Pimpl* getMatrix() const; + /* + \brief + The update function that is to be called when all the vertex attributes + are set. + */ + virtual void finaliseVertexAttributes() = 0; protected: - //! perform batch management operations prior to adding new geometry. - void performBatchManagement(); - - //! update cached matrix + //! Update the cached matrices void updateMatrix() const; - //! internal Vertex structure used for GL based geometry. - struct GLVertex - { - float tex[2]; - float colour[4]; - float position[3]; - }; - - //! type to track info for per-texture sub batches of geometry - struct BatchInfo - { - uint texture; - uint vertexCount; - bool clip; - }; - //! OpenGLRendererBase that owns the GeometryBuffer. - OpenGLRendererBase* d_owner; - //! last texture that was set as active - OpenGLTexture* d_activeTexture; - //! type of container that tracks BatchInfos. - typedef std::vector BatchList; - //! list of texture batches added to the geometry buffer - BatchList d_batches; - //! type of container used to queue the geometry - typedef std::vector VertexList; - //! container where added geometry is stored. - VertexList d_vertices; + OpenGLRendererBase& d_owner; //! rectangular clip region Rectf d_clipRect; - //! whether clipping will be active for the current batch - bool d_clippingActive; - //! translation vector - Vector3f d_translation; - //! rotation quaternion - Quaternion d_rotation; - //! pivot point for rotation - Vector3f d_pivot; - //! RenderEffect that will be used by the GeometryBuffer - RenderEffect* d_effect; - //! model matrix cache - we use double because gluUnproject takes double - mutable mat4Pimpl* d_matrix; - //! true when d_matrix is valid and up to date - mutable bool d_matrixValid; + //! Cache of the model view projection matrix + mutable glm::mat4 d_matrix; }; } diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/RenderTarget.h b/cegui/include/CEGUI/RendererModules/OpenGL/RenderTarget.h index db8f16c6f..bc6da5025 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/RenderTarget.h @@ -51,31 +51,18 @@ class OPENGL_GUIRENDERER_API OpenGLRenderTarget : public T virtual ~OpenGLRenderTarget(); // implement parts of RenderTarget interface - void draw(const GeometryBuffer& buffer); - void draw(const RenderQueue& queue); - void setArea(const Rectf& area); - const Rectf& getArea() const; - void activate(); - void deactivate(); - void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const; + virtual void activate(); + virtual void unprojectPoint(const GeometryBuffer& buff, + const glm::vec2& p_in, glm::vec2& p_out) const; + // implementing the virtual function with a covariant return type + virtual OpenGLRendererBase& getOwner(); protected: - //! helper that initialises the cached matrix + //! helper that initialises the matrix virtual void updateMatrix() const; //! OpenGLRendererBase that created this object OpenGLRendererBase& d_owner; - //! holds defined area for the RenderTarget - Rectf d_area; - //! tangent of the y FOV half-angle; used to calculate viewing distance. - static const double d_yfov_tan; - //! saved copy of projection matrix - mutable mat4Pimpl* d_matrix; - //! true if saved matrix is up to date - mutable bool d_matrixValid; - //! tracks viewing distance (this is set up at the same time as d_matrix) - mutable double d_viewDistance; }; } diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/RendererBase.h b/cegui/include/CEGUI/RendererModules/OpenGL/RendererBase.h index e82d783a6..a7041e2ec 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/RendererBase.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/RendererBase.h @@ -34,7 +34,11 @@ #include "../../Vector.h" #include "../../Rect.h" #include "../../TextureTarget.h" +#include "../../RefCounted.h" #include "CEGUI/RendererModules/OpenGL/GL.h" + +#include "glm/glm.hpp" + #include #include @@ -57,7 +61,7 @@ namespace CEGUI { class OpenGLTexture; class OpenGLGeometryBufferBase; -struct mat4Pimpl; +class RenderMaterial; //! Common base class used for other OpenGL based renderer modules. class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer @@ -65,9 +69,8 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer public: // implement Renderer interface RenderTarget& getDefaultRenderTarget(); - GeometryBuffer& createGeometryBuffer(); - void destroyGeometryBuffer(const GeometryBuffer& buffer); - void destroyAllGeometryBuffers(); + GeometryBuffer& createGeometryBufferTextured(CEGUI::RefCounted renderMaterial); + GeometryBuffer& createGeometryBufferColoured(CEGUI::RefCounted renderMaterial); TextureTarget* createTextureTarget(); void destroyTextureTarget(TextureTarget* target); void destroyAllTextureTargets(); @@ -83,7 +86,7 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer bool isTextureDefined(const String& name) const; void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; @@ -151,7 +154,7 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer \return Size object containing - possibly different - output size. */ - virtual Sizef getAdjustedTextureSize(const Sizef& sz) const; + virtual Sizef getAdjustedTextureSize(const Sizef& sz) = 0; /*! \brief @@ -167,24 +170,6 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer //! Return whether EXT_texture_compression_s3tc is supported virtual bool isS3TCSupported() const = 0; - /*! - \brief - Helper to return view projection matrix. - - \return - The view projection matrix. - */ - virtual const mat4Pimpl* getViewProjectionMatrix(); - - /*! - \brief - Helper to set the view projection matrix. - - \param viewProjectionMatrix - The view projection matrix. - */ - virtual void setViewProjectionMatrix(const mat4Pimpl* viewProjectionMatrix); - /*! \brief Helper to get the viewport. @@ -194,24 +179,6 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer */ const CEGUI::Rectf& getActiveViewPort(); - /*! - \brief - Helper to set the active render target. - - \param renderTarget - The active RenderTarget. - */ - void setActiveRenderTarget(RenderTarget* renderTarget); - - /*! - \brief - Helper to get the active render target. - - \return - The active RenderTarget. - */ - RenderTarget* getActiveRenderTarget(); - protected: OpenGLRendererBase(); @@ -239,30 +206,28 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer void initialiseDisplaySizeWithViewportSize(); //! return some appropriate OpenGLGeometryBufferBase subclass instance. - virtual OpenGLGeometryBufferBase* createGeometryBuffer_impl() = 0; + virtual OpenGLGeometryBufferBase* createGeometryBuffer_impl(RefCounted renderMaterial) = 0; //! return some appropriate TextureTarget subclass instance. virtual TextureTarget* createTextureTarget_impl() = 0; + //! return some appropriate Texture subclass instance. + virtual OpenGLTexture* createTexture_impl(const String& name) = 0; + //! String holding the renderer identification text. static String d_rendererID; //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. typedef std::vector TextureTargetList; //! Container used to track texture targets. TextureTargetList d_textureTargets; - //! container type used to hold GeometryBuffers created. - typedef std::vector GeometryBufferList; - //! Container used to track geometry buffers. - GeometryBufferList d_geometryBuffers; //! container type used to hold Textures we create. - typedef std::map TextureMap; + typedef std::map TextureMap; //! Container used to track textures. TextureMap d_textures; //! What the renderer thinks the max texture size is. @@ -271,10 +236,6 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer bool d_initExtraStates; //! What blend mode we think is active. BlendMode d_activeBlendMode; - //! View projection matrix - mat4Pimpl* d_viewProjectionMatrix; - //! The active RenderTarget - RenderTarget* d_activeRenderTarget; }; /** @@ -284,8 +245,7 @@ class OPENGL_GUIRENDERER_API OpenGLRendererBase : public Renderer TextureTarget based on what the host system can provide - or use the default 'null' factory if no suitable TextureTargets are available. */ -class OGLTextureTargetFactory : - public AllocatedObject +class OGLTextureTargetFactory { public: OGLTextureTargetFactory() {} diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/Shader.h b/cegui/include/CEGUI/RendererModules/OpenGL/Shader.h index 91904bc9b..d2d187ab8 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/Shader.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/Shader.h @@ -24,8 +24,8 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIOpenGL3Shader_h_ -#define _CEGUIOpenGL3Shader_h_ +#ifndef _CEGUIOpenGLBaseShader_h_ +#define _CEGUIOpenGLBaseShader_h_ #include "CEGUI/Exceptions.h" #include "RendererBase.h" @@ -39,8 +39,9 @@ author: Lukas E Meindl // Start of CEGUI namespace section namespace CEGUI { -class OPENGL_GUIRENDERER_API OpenGL3Shader : - public AllocatedObject +class OpenGLBaseStateChangeWrapper; + +class OPENGL_GUIRENDERER_API OpenGLBaseShader { public: @@ -48,10 +49,11 @@ class OPENGL_GUIRENDERER_API OpenGL3Shader : \brief Creates and loads shader programs from the two strings supplied to it */ - OpenGL3Shader(const std::string& vertex_shader_source, - const std::string& fragment_shader_source); + OpenGLBaseShader(const std::string& vertex_shader_source, + const std::string& fragment_shader_source, + OpenGLBaseStateChangeWrapper* glStateChanger); - ~OpenGL3Shader(); + ~OpenGLBaseShader(); /*! \brief @@ -59,34 +61,28 @@ class OPENGL_GUIRENDERER_API OpenGL3Shader : */ void bind() const; - /*! - \brief - Unbind the shader - */ - void unbind() const; - /*! \brief Query the location of a vertex attribute inside the shader. */ - GLuint getAttribLocation(const std::string &name) const; + GLint getAttribLocation(const std::string &name) const; /*! \brief Query the location of a uniform variable inside the shader. */ - GLuint getUniformLocation(const std::string &name) const; + GLint getUniformLocation(const std::string &name) const; /*! \brief Defines the name of the variable inside the shader which represents the final color for each fragment. */ - void bindFragDataLocation(const std::string &name); + virtual void bindFragDataLocation(const std::string &name); bool isCreatedSuccessfully(); - void link(); + virtual void link(); private: GLuint compile(GLuint type, const std::string &source); @@ -94,12 +90,14 @@ class OPENGL_GUIRENDERER_API OpenGL3Shader : void outputShaderLog(GLuint shader); void outputProgramLog(GLuint program); - std::string d_shaderName; - bool d_createdSucessfully; + OpenGLBaseStateChangeWrapper* d_glStateChanger; + + bool d_createdSuccessfully; GLuint d_vertexShader; GLuint d_fragmentShader; GLuint d_geometryShader; +protected: GLuint d_program; }; diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/ShaderManager.h b/cegui/include/CEGUI/RendererModules/OpenGL/ShaderManager.h index b0cf53794..44a409237 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/ShaderManager.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/ShaderManager.h @@ -25,8 +25,8 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIOpenGL3ShaderManager_h_ -#define _CEGUIOpenGL3ShaderManager_h_ +#ifndef _CEGUIOpenGLBaseShaderManager_h_ +#define _CEGUIOpenGLBaseShaderManager_h_ #include "CEGUI/Base.h" #include "CEGUI/RendererModules/OpenGL/GL.h" @@ -42,34 +42,46 @@ // Start of CEGUI namespace section namespace CEGUI { - class OpenGL3Shader; + class OpenGLBaseShader; + class OpenGLBaseStateChangeWrapper; - enum OpenGL3ShaderID + enum OpenGLBaseShaderID { - SHADER_ID_STANDARDSHADER, + SHADER_ID_STANDARD_TEXTURED, + SHADER_ID_STANDARD_SOLID, SHADER_ID_COUNT }; - class OpenGL3ShaderManager : - public AllocatedObject + enum ShaderVersion + { + SHADER_GLSL, + SHADER_GLSLES1, + SHADER_GLSLES3 + }; + + + class OpenGLBaseShaderManager { public: - OpenGL3ShaderManager(); - virtual ~OpenGL3ShaderManager(); + OpenGLBaseShaderManager(OpenGLBaseStateChangeWrapper* glStateChanger, ShaderVersion shaderVersion); + virtual ~OpenGLBaseShaderManager(); - OpenGL3Shader* getShader(GLuint id); + OpenGLBaseShader* getShader(GLuint id); void loadShader(GLuint id, std::string vertexShader, std::string fragmentShader); void initialiseShaders(); void deinitialiseShaders(); private: - - typedef std::map shaderContainerType; + typedef std::map shaderContainerType; shaderContainerType d_shaders; + ShaderVersion d_shaderVersion; + bool d_shadersInitialised; + + OpenGLBaseStateChangeWrapper* d_glStateChanger; }; } diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/StateChangeWrapper.h b/cegui/include/CEGUI/RendererModules/OpenGL/StateChangeWrapper.h index 72f55e37a..922c89fdc 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/StateChangeWrapper.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/StateChangeWrapper.h @@ -25,11 +25,11 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIOpenGL3StateChangeWrapper_h_ -#define _CEGUIOpenGL3StateChangeWrapper_h_ +#ifndef _CEGUIOpenGLBaseStateChangeWrapper_h_ +#define _CEGUIOpenGLBaseStateChangeWrapper_h_ #include "CEGUI/RendererModules/OpenGL/GL.h" -#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h" +#include "RendererBase.h" #if defined(_MSC_VER) # pragma warning(push) @@ -40,67 +40,189 @@ namespace CEGUI { +/*! +\brief +OpenGLBaseStateChangeWrapper - wraps OpenGL calls and checks for redundant calls beforehand +*/ +class OPENGL_GUIRENDERER_API OpenGLBaseStateChangeWrapper +{ +public: /*! \brief - OpenGL3StateChangeWrapper - wraps OpenGL calls and checks for redundant calls beforehand + This has to be used for both glBlendFunc and glBlendFuncSeperate, as the second call is + just a more specific version of the first. */ - class OPENGL_GUIRENDERER_API OpenGL3StateChangeWrapper : - public AllocatedObject + struct BlendFuncSeperateParams + { + BlendFuncSeperateParams(); + void reset(); + bool equal(GLenum sFactor, GLenum dFactor); + bool equal(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); + GLenum d_sfactorRGB, d_dfactorRGB, d_sfactorAlpha, d_dfactorAlpha; + }; + struct PortParams + { + PortParams(); + void reset(); + bool equal(GLint x, GLint y, GLsizei width, GLsizei height); + GLint d_x, d_y; + GLsizei d_width, d_height; + }; + struct BindBufferParams { - protected: - struct BlendFuncParams - { - BlendFuncParams(); - void reset(); - bool equal(GLenum sFactor, GLenum dFactor); - GLenum d_sFactor, d_dFactor; - }; - struct BlendFuncSeperateParams - { - BlendFuncSeperateParams(); - void reset(); - bool equal(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); - GLenum d_sfactorRGB, d_dfactorRGB, d_sfactorAlpha, d_dfactorAlpha; - }; - struct PortParams - { - PortParams(); - void reset(); - bool equal(GLint x, GLint y, GLsizei width, GLsizei height); - GLint d_x, d_y; - GLsizei d_width, d_height; - }; - struct BindBufferParams - { - BindBufferParams(); - void reset(); - bool equal(GLenum target, GLuint buffer); - GLenum d_target; - GLuint d_buffer; - }; - - public: - //! constructor. - OpenGL3StateChangeWrapper(OpenGL3Renderer& owner); - //! destructor - virtual ~OpenGL3StateChangeWrapper(); + BindBufferParams(); + void reset(); + bool equal(GLenum target, GLuint buffer); + GLenum d_target; + GLuint d_buffer; + }; + struct BoundTexture + { + BoundTexture(); + void bindTexture(GLenum target, GLuint texture); + GLenum d_target; + GLuint d_texture; + }; + + + OpenGLBaseStateChangeWrapper(); + virtual ~OpenGLBaseStateChangeWrapper(); + + //! Due to unknown changes of states between each time CEGUI gets rendered, we will invalidate + //! all states on CPU-side so that the following calls will definitely change the states on GPU void reset(); - void bindVertexArray(GLuint vertexArray); + //! Functions wrapping the gl* function calls to improve performance by storing the parameters and + //! only calling the OpenGL functions when actual state changes are taking place. + virtual void bindVertexArray(GLuint vertexArray) = 0; + void useProgram(GLuint program); void blendFunc(GLenum sfactor, GLenum dfactor); void blendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); void viewport(GLint x, GLint y, GLsizei width, GLsizei height); void scissor(GLint x, GLint y, GLsizei width, GLsizei height); void bindBuffer(GLenum target, GLuint buffer); + void enable(GLenum capability); + void disable(GLenum capability); + void bindTexture(GLenum target, GLuint texture); + + /* + \brief + This function takes the number representing the texture position as unsigned integer, + not the actual OpenGL value for the position (GL_TEXTURE0, GL_TEXTURE1). + + \param texture_position + Value representing the texture position as integer, it will be used in the following way to get the + OpenGL Texture position: (GL_TEXTURE0 + texture_position) + */ + void activeTexture(unsigned int texture_position); + + /* + \brief + Returns the number representing the last active texture's position. This value is the one that was last + set using this wrapper. No OpenGL getter function is called to retrieve the actual state of the variable, + which means that changes resulting from OpenGL calls done outside this wrapper, will not be considered. + + \return + An unsigned int representing the currently active texture. + */ + unsigned int getActiveTexture() const; + + /* + \brief + Returns the ID of the bound vertex array. No OpenGL getter function is called to retrieve the actual state of + the variable, which means that changes resulting from OpenGL calls done outside this wrapper, will not be + considered. + + \return + An unsigned int representing the bound vertex array. + */ + GLuint getBoundVertexArray() const; + + /* + \brief + Returns the ID of the OpenGL shader program that is set to be used . No OpenGL getter function is called to + retrieve the actual state of the variable, which means that changes resulting from OpenGL calls done outside + this wrapper, will not be considered. + + \return + An unsigned int representing the ID of the OpenGL shader program. + */ + GLuint getUsedProgram() const; + + /* + \brief + Returns a struct containing the parameters that were set for the blend function. No OpenGL getter function is + called to retrieve the actual state of the variables, which means that changes resulting from OpenGL calls done + outside this wrapper, will not be considered. + + \return + A struct containing the parameters for the blend function. + */ + BlendFuncSeperateParams getBlendFuncParams() const; + + /* + \brief + Returns a struct containing the parameters that were set for the viewport function. No OpenGL getter function is + called to retrieve the actual state of the variables, which means that changes resulting from OpenGL calls done + outside this wrapper, will not be considered. + + \return + A struct containing the parameters for the viewport function. + */ + PortParams getViewportParams() const; + + /* + \brief + Returns a struct containing the parameters that were set for the scissor function. No OpenGL getter function is + called to retrieve the actual state of the variables, which means that changes resulting from OpenGL calls done + outside this wrapper, will not be considered. + + \return + A struct containing the parameters for the scissor function. + */ + PortParams getScissorParams() const; + + /* + \brief + Returns a struct containing the parameters that were set for the bindBuffer function. No OpenGL getter function is + called to retrieve the actual state of the variables, which means that changes resulting from OpenGL calls done + outside this wrapper, will not be considered. + + \return + A struct containing the parameters for the bindBuffer function. + */ + BindBufferParams getBoundBuffer() const; + + /* + \brief + Returns an integers representing if an OpenGL state was enabled, disabled or not set. No OpenGL getter function is + called to retrieve the actual state of the variables, which means that changes resulting from OpenGL calls done + outside this wrapper, will not be considered. + + \param capability + The OpenGL state's OpenGL enum. + + \return + 0 if the requested state has been disabled, + 1 if the requested state has been enabled, + -1 if the requested state has never been set using this class. + */ + int isStateEnabled(GLenum capability) const; protected: GLuint d_vertexArrayObject; - BlendFuncParams d_blendFuncParams; + GLuint d_shaderProgram; BlendFuncSeperateParams d_blendFuncSeperateParams; PortParams d_viewPortParams; PortParams d_scissorParams; BindBufferParams d_bindBufferParams; + //! List of enabled/disabled OpenGL states + std::map d_enabledOpenGLStates; + //! The active texture saved as integer and not as OpenGL enum + unsigned int d_activeTexturePosition; + //! List of bound textures, the position in the vector defines the active texture it is bound to + std::vector d_boundTextures; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/Texture.h b/cegui/include/CEGUI/RendererModules/OpenGL/Texture.h index 92ec8f4b2..5c2b4b179 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/Texture.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/Texture.h @@ -102,12 +102,12 @@ class OPENGL_GUIRENDERER_API OpenGLTexture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); void blitFromMemory(const void* sourceData, const Rectf& area); - void blitToMemory(void* targetData); + virtual void blitToMemory(void* targetData) = 0; bool isPixelFormatSupported(const PixelFormat fmt) const; protected: @@ -121,15 +121,14 @@ class OPENGL_GUIRENDERER_API OpenGLTexture : public Texture //! Basic constructor. OpenGLTexture(OpenGLRendererBase& owner, const String& name); - //! Constructor that creates a Texture from an image file. - OpenGLTexture(OpenGLRendererBase& owner, const String& name, - const String& filename, const String& resourceGroup); - //! Constructor that creates a Texture with a given size. - OpenGLTexture(OpenGLRendererBase& owner, const String& name, - const Sizef& size); + //! initliase method that creates a Texture. + void initialise(); + //! initliase method that creates a Texture from an image file. + void initialise(const String& filename, const String& resourceGroup); + //! initialise method that creates a Texture with a given size. + void initialise(const Sizef& size); //! Constructor that wraps an existing GL texture. - OpenGLTexture(OpenGLRendererBase& owner, const String& name, - GLuint tex, const Sizef& size); + void initialise(GLuint tex, const Sizef& size); //! Destructor. virtual ~OpenGLTexture(); @@ -143,10 +142,10 @@ class OPENGL_GUIRENDERER_API OpenGLTexture : public Texture void cleanupOpenGLTexture(); //! initialise the internal format flags for the given CEGUI::PixelFormat. - void initInternalPixelFormatFields(const PixelFormat fmt); + virtual void initInternalPixelFormatFields(const PixelFormat fmt) = 0; //! internal texture resize function (does not reset format or other fields) - void setTextureSize_impl(const Sizef& sz); + virtual void setTextureSize_impl(const Sizef& sz) = 0; void loadUncompressedTextureBuffer(const Rectf& dest_area, const GLvoid* buffer) const; @@ -154,7 +153,10 @@ class OPENGL_GUIRENDERER_API OpenGLTexture : public Texture void loadCompressedTextureBuffer(const Rectf& dest_area, const GLvoid* buffer) const; - GLsizei getCompressedTextureSize(const Sizef& pixel_size) const; + virtual GLsizei getCompressedTextureSize(const Sizef& pixel_size) const; + + //! OpenGL method to set glTexEnv which is deprecated in GL 3.2 and GLES 2.0 and above + virtual void setTextureEnvironment(); //! The OpenGL texture we're wrapping. GLuint d_ogltexture; @@ -165,7 +167,7 @@ class OPENGL_GUIRENDERER_API OpenGLTexture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! OpenGLRenderer that created and owns this OpenGLTexture OpenGLRendererBase& d_owner; //! The name given for this texture. diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/WGLPBTextureTarget.h b/cegui/include/CEGUI/RendererModules/OpenGL/WGLPBTextureTarget.h index e1f35d431..a09704c70 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/WGLPBTextureTarget.h +++ b/cegui/include/CEGUI/RendererModules/OpenGL/WGLPBTextureTarget.h @@ -27,13 +27,13 @@ #ifndef _CEGUIOpenGLWGLPBTextureTarget_h_ #define _CEGUIOpenGLWGLPBTextureTarget_h_ -//#include -#include -#include - #include "CEGUI/RendererModules/OpenGL/TextureTarget.h" +#include "CEGUI/RendererModules/OpenGL/GL.h" #include "../../Rect.h" +#include +#include + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4250) diff --git a/cegui/include/CEGUI/RendererModules/OpenGLES/GeometryBuffer.h b/cegui/include/CEGUI/RendererModules/OpenGLES/GeometryBuffer.h index da6c58bec..25001832f 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGLES/GeometryBuffer.h +++ b/cegui/include/CEGUI/RendererModules/OpenGLES/GeometryBuffer.h @@ -30,7 +30,6 @@ #include "CEGUI/GeometryBuffer.h" #include "CEGUI/RendererModules/OpenGLES/Renderer.h" #include "CEGUI/Rect.h" -#include "CEGUI/Quaternion.h" #include #include @@ -57,9 +56,9 @@ class OPENGLES_GUIRENDERER_API OpenGLESGeometryBuffer : public GeometryBuffer // implementation of abstract members from GeometryBuffer void draw() const; - void setTranslation(const Vector3f& t); - void setRotation(const Quaternion& r); - void setPivot(const Vector3f& p); + void setTranslation(const glm::vec3& t); + void setRotation(const glm::quat& r); + void setPivot(const glm::vec3& p); void setClippingRegion(const Rectf& region); void appendVertex(const Vertex& vertex); void appendGeometry(const Vertex* const vbuff, uint vertex_count); @@ -108,11 +107,11 @@ class OPENGLES_GUIRENDERER_API OpenGLESGeometryBuffer : public GeometryBuffer //! whether clipping will be active for the current batch bool d_clippingActive; //! translation vector - Vector3f d_translation; + glm::vec3 d_translation; //! rotation quaternion - Quaternion d_rotation; + glm::quat d_rotation; //! pivot point for rotation - Vector3f d_pivot; + glm::vec3 d_pivot; //! RenderEffect that will be used by the GeometryBuffer RenderEffect* d_effect; //! model matrix cache diff --git a/cegui/include/CEGUI/RendererModules/OpenGLES/RenderTarget.h b/cegui/include/CEGUI/RendererModules/OpenGLES/RenderTarget.h index bd8db5af9..d34aa9400 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGLES/RenderTarget.h +++ b/cegui/include/CEGUI/RendererModules/OpenGLES/RenderTarget.h @@ -53,7 +53,7 @@ class OPENGLES_GUIRENDERER_API OpenGLESRenderTarget : public T void activate(); void deactivate(); void unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const; + const glm::vec2& p_in, glm::vec2& p_out) const; protected: //! helper that initialises the cached matrix diff --git a/cegui/include/CEGUI/RendererModules/OpenGLES/Renderer.h b/cegui/include/CEGUI/RendererModules/OpenGLES/Renderer.h index 7cb074f33..41761b8f0 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGLES/Renderer.h +++ b/cegui/include/CEGUI/RendererModules/OpenGLES/Renderer.h @@ -227,7 +227,7 @@ class OPENGLES_GUIRENDERER_API OpenGLESRenderer : public Renderer void endRendering(); void setDisplaySize(const Sizef& sz); const Sizef& getDisplaySize() const; - const Vector2f& getDisplayDPI() const; + const glm::vec2& getDisplayDPI() const; uint getMaxTextureSize() const; const String& getIdentifierString() const; @@ -354,7 +354,7 @@ class OPENGLES_GUIRENDERER_API OpenGLESRenderer : public Renderer //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget RenderTarget* d_defaultTarget; //! container type used to hold TextureTargets we create. @@ -366,8 +366,7 @@ class OPENGLES_GUIRENDERER_API OpenGLESRenderer : public Renderer //! Container used to track geometry buffers. GeometryBufferList d_geometryBuffers; //! container type used to hold Textures we create. - typedef std::map TextureMap; + typedef std::map TextureMap; //! Container used to track textures. TextureMap d_textures; //! What the renderer thinks the max texture size is. diff --git a/cegui/include/CEGUI/RendererModules/OpenGLES/Texture.h b/cegui/include/CEGUI/RendererModules/OpenGLES/Texture.h index db3876771..a2ef6ab1f 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGLES/Texture.h +++ b/cegui/include/CEGUI/RendererModules/OpenGLES/Texture.h @@ -97,7 +97,7 @@ class OPENGLES_GUIRENDERER_API OpenGLESTexture : public Texture const String& getName() const; const Sizef& getSize() const; const Sizef& getOriginalDataSize() const; - const Vector2f& getTexelScaling() const; + const glm::vec2& getTexelScaling() const; void loadFromFile(const String& filename, const String& resourceGroup); void loadFromMemory(const void* buffer, const Sizef& buffer_size, PixelFormat pixel_format); @@ -162,7 +162,7 @@ class OPENGLES_GUIRENDERER_API OpenGLESTexture : public Texture //! original pixel of size data loaded into texture Sizef d_dataSize; //! cached pixel to texel mapping scale values. - Vector2f d_texelScaling; + glm::vec2 d_texelScaling; //! OpenGLESRenderer that created and owns this OpenGLESTexture OpenGLESRenderer& d_owner; //! Name of the texture given when it was created. diff --git a/cegui/include/CEGUI/RenderingContext.h b/cegui/include/CEGUI/RenderingContext.h index 40d0b458b..9ab893f84 100644 --- a/cegui/include/CEGUI/RenderingContext.h +++ b/cegui/include/CEGUI/RenderingContext.h @@ -36,15 +36,14 @@ namespace CEGUI \brief struct that holds some context relating to a RenderingSurface object. */ -struct RenderingContext : - public AllocatedObject +struct RenderingContext { //! RenderingSurface to be used for drawing RenderingSurface* surface; //! The Window object that owns the RenederingSurface (0 for default root) const Window* owner; //! The offset of the owning window on the root RenderingSurface. - Vector2f offset; + glm::vec2 offset; //! The queue that rendering should be added to. RenderQueueID queue; }; diff --git a/cegui/include/CEGUI/RenderingSurface.h b/cegui/include/CEGUI/RenderingSurface.h index e010947da..ce81f0e65 100644 --- a/cegui/include/CEGUI/RenderingSurface.h +++ b/cegui/include/CEGUI/RenderingSurface.h @@ -31,6 +31,8 @@ #include "CEGUI/EventArgs.h" #include "CEGUI/RenderQueue.h" +#include + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) @@ -106,8 +108,7 @@ class CEGUIEXPORT RenderQueueEventArgs : public EventArgs geometry. */ class CEGUIEXPORT RenderingSurface : - public EventSet, - public AllocatedObject + public EventSet { public: //! Namespace for global events from RenderingSurface objects. @@ -150,6 +151,29 @@ class CEGUIEXPORT RenderingSurface : //! Destructor for RenderingSurface objects. virtual ~RenderingSurface(); + /*! + \brief + Add the specified GeometryBuffers to the specified queue for rendering + when the RenderingSurface is drawn. + + \param queue + One of the RenderQueueID enumerated values indicating which prioritised + queue the GeometryBuffer should be added to. + + \param geometryBuffers + List of GeometryBuffers to be added to the specified rendering queue. + + \note + The RenderingSurface does not take ownership of the GeometryBuffers, and + does not destroy it when the RenderingSurface geometry is cleared. + Rather, the RenderingSurface is just maintaining a list of things to be + drawn; the actual GeometryBuffers can be re-used by whichever object + does own them, and even changed or updated while still "attached" to + a RenderingSurface. + */ + void addGeometryBuffers(const RenderQueueID queue, + const std::vector& geometry_buffers); + /*! \brief Add the specified GeometryBuffer to the specified queue for rendering @@ -159,19 +183,19 @@ class CEGUIEXPORT RenderingSurface : One of the RenderQueueID enumerated values indicating which prioritised queue the GeometryBuffer should be added to. - \param buffer - GeometryBuffer object to be added to the specified rendering queue. + \param geometry_buffers + The GeometryBuffer to be added to the specified rendering queue. \note The RenderingSurface does not take ownership of the GeometryBuffer, and does not destroy it when the RenderingSurface geometry is cleared. - Rather, the RenderingSurface is just maintaining a list of thigs to be + Rather, the RenderingSurface is just maintaining a list of things to be drawn; the actual GeometryBuffers can be re-used by whichever object - \e does own them, and even changed or updated while still "attached" to + does own them, and even changed or updated while still "attached" to a RenderingSurface. */ void addGeometryBuffer(const RenderQueueID queue, - const GeometryBuffer& buffer); + const GeometryBuffer& geometry_buffer); /*! \brief @@ -181,11 +205,11 @@ class CEGUIEXPORT RenderingSurface : One of the RenderQueueID enumerated values indicating which prioritised queue the GeometryBuffer should be removed from. - \param buffer + \param geometry_buffer GeometryBuffer object to be removed from the specified rendering queue. */ void removeGeometryBuffer(const RenderQueueID queue, - const GeometryBuffer& buffer); + const GeometryBuffer& geometry_buffer); /*! \brief @@ -345,11 +369,9 @@ class CEGUIEXPORT RenderingSurface : void attachWindow(RenderingWindow& w); //! collection type for the queues - typedef std::map RenderQueueList; + typedef std::map RenderQueueList; //! collection type for created RenderingWindow objects - typedef std::vector RenderingWindowList; + typedef std::vector RenderingWindowList; //! the collection of RenderQueue objects. RenderQueueList d_queues; //! collection of RenderingWindow object we own diff --git a/cegui/include/CEGUI/RenderingWindow.h b/cegui/include/CEGUI/RenderingWindow.h index aa7a6f670..94f83e3d8 100644 --- a/cegui/include/CEGUI/RenderingWindow.h +++ b/cegui/include/CEGUI/RenderingWindow.h @@ -29,10 +29,12 @@ #include "CEGUI/RenderingSurface.h" #include "CEGUI/Vector.h" -#include "CEGUI/Quaternion.h" #include "CEGUI/Size.h" #include "CEGUI/Rect.h" +#include +#include + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) @@ -107,7 +109,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface other root surface. It is \e not relative to the owner of the RenderingWindow. */ - void setPosition(const Vector2f& position); + void setPosition(const glm::vec2& position); /*! \brief @@ -127,7 +129,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface \param rotation Quaternion object describing the rotation. */ - void setRotation(const Quaternion& rotation); + void setRotation(const glm::quat& rotation); /*! \brief @@ -138,7 +140,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface Vector3 describing the three dimensional point around which the RenderingWindow will be rotated. */ - void setPivot(const Vector3f& pivot); + void setPivot(const glm::vec3& pivot); /*! \brief @@ -153,7 +155,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface other root surface. It is \e not relative to the owner of the RenderingWindow. */ - const Vector2f& getPosition() const; + const glm::vec2& getPosition() const; /*! \brief @@ -171,7 +173,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface \return Quaternion object describing the rotation for the RenderingWindow. */ - const Quaternion& getRotation()const; + const glm::quat& getRotation()const; /*! \brief @@ -181,7 +183,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface Vector3 object describing the current location of the pivot point used when rotating the RenderingWindow. */ - const Vector3f& getPivot() const; + const glm::vec3& getPivot() const; /*! \brief @@ -276,7 +278,7 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface Fill in Vector2 object \a p_out with an unprojected version of the point described by Vector2 \a p_in. */ - void unprojectPoint(const Vector2f& p_in, Vector2f& p_out); + void unprojectPoint(const glm::vec2& p_in, glm::vec2& p_out); // overrides from base void draw(); @@ -298,18 +300,18 @@ class CEGUIEXPORT RenderingWindow : public RenderingSurface TextureTarget& d_textarget; //! RenderingSurface that owns this object, we render back to this object. RenderingSurface* d_owner; - //! GeometryBuffer that holds geometry for drawing this window. - GeometryBuffer* d_geometry; + //! The geometry buffers that cache the geometry drawn by this Window. + GeometryBuffer& d_geometryBuffer; //! indicates whether data in GeometryBuffer is up-to-date bool d_geometryValid; //! Position of this RenderingWindow - Vector2f d_position; + glm::vec2 d_position; //! Size of this RenderingWindow Sizef d_size; //! Rotation for this RenderingWindow - Quaternion d_rotation; + glm::quat d_rotation; //! Pivot point used for the rotation. - Vector3f d_pivot; + glm::vec3 d_pivot; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/ResourceProvider.h b/cegui/include/CEGUI/ResourceProvider.h index b6dd3c154..15d72d0b1 100644 --- a/cegui/include/CEGUI/ResourceProvider.h +++ b/cegui/include/CEGUI/ResourceProvider.h @@ -44,8 +44,7 @@ namespace CEGUI A ResourceProvider is used to load both XML and binary data from an external source. This could be from a filesystem or the resource manager of a specific renderer. */ -class CEGUIEXPORT ResourceProvider : - public AllocatedObject +class CEGUIEXPORT ResourceProvider { public: /************************************************************************* diff --git a/cegui/include/CEGUI/RightAlignedRenderedString.h b/cegui/include/CEGUI/RightAlignedRenderedString.h index df0d586cc..e768fdf19 100644 --- a/cegui/include/CEGUI/RightAlignedRenderedString.h +++ b/cegui/include/CEGUI/RightAlignedRenderedString.h @@ -51,16 +51,15 @@ class CEGUIEXPORT RightAlignedRenderedString : public FormattedRenderedString // implementation of base interface void format(const Window* ref_wnd, const Sizef& area_size); - void draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, const ColourRect* mod_colours, + void draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const; size_t getFormattedLineCount() const; float getHorizontalExtent(const Window* ref_wnd) const; float getVerticalExtent(const Window* ref_wnd) const; protected: - std::vector d_offsets; + std::vector d_offsets; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/Scheme.h b/cegui/include/CEGUI/Scheme.h index 543164f19..fc2bd25c9 100644 --- a/cegui/include/CEGUI/Scheme.h +++ b/cegui/include/CEGUI/Scheme.h @@ -55,8 +55,7 @@ namespace CEGUI Imageset objects, some Font objects, and register a collection of WindowFactory objects within the system which would then be in a state to serve those elements to client code. */ -class CEGUIEXPORT Scheme : - public AllocatedObject +class CEGUIEXPORT Scheme { private: friend class Scheme_xmlHandler; @@ -306,8 +305,7 @@ class CEGUIEXPORT Scheme : private: //! \internal This is implementation specific so we keep it private! - typedef std::vector LoadableUIElementList; + typedef std::vector LoadableUIElementList; public: typedef ConstVectorIterator LoadableUIElementIterator; @@ -347,8 +345,7 @@ class CEGUIEXPORT Scheme : DynamicModule* dynamicModule; FactoryModule* factoryModule; - typedef std::vector TypeList; + typedef std::vector TypeList; TypeList types; }; @@ -377,22 +374,18 @@ class CEGUIEXPORT Scheme : LoadableUIElementList d_imagesetsFromImages; LoadableUIElementList d_fonts; - typedef std::vector UIModuleList; + typedef std::vector UIModuleList; UIModuleList d_widgetModules; - typedef std::vector WRModuleList; + typedef std::vector WRModuleList; WRModuleList d_windowRendererModules; - typedef std::vector AliasMappingList; + typedef std::vector AliasMappingList; AliasMappingList d_aliasMappings; LoadableUIElementList d_looknfeels; - typedef std::vector FalagardMappingList; + typedef std::vector FalagardMappingList; FalagardMappingList d_falagardMappings; static String d_defaultResourceGroup; //!< holds default resource group diff --git a/cegui/include/CEGUI/SchemeManager.h b/cegui/include/CEGUI/SchemeManager.h index 44ad1b02c..07f327e7c 100644 --- a/cegui/include/CEGUI/SchemeManager.h +++ b/cegui/include/CEGUI/SchemeManager.h @@ -50,8 +50,7 @@ namespace CEGUI */ class CEGUIEXPORT SchemeManager : public Singleton, - public NamedXMLResourceManager, - public AllocatedObject + public NamedXMLResourceManager { public: //! Constructor. diff --git a/cegui/include/CEGUI/ScriptModule.h b/cegui/include/CEGUI/ScriptModule.h index 4a6278a3d..0ac98516e 100644 --- a/cegui/include/CEGUI/ScriptModule.h +++ b/cegui/include/CEGUI/ScriptModule.h @@ -42,8 +42,7 @@ namespace CEGUI Abstract interface required for all scripting support modules to be used with the CEGUI system. */ -class CEGUIEXPORT ScriptModule : - public AllocatedObject +class CEGUIEXPORT ScriptModule { public: /************************************************************************* @@ -235,8 +234,7 @@ class CEGUIEXPORT ScriptModule : \brief Functor class used for binding named script functions to events */ -class CEGUIEXPORT ScriptFunctor : - public AllocatedObject +class CEGUIEXPORT ScriptFunctor { public: ScriptFunctor(const String& functionName) : scriptFunctionName(functionName) {} diff --git a/cegui/include/CEGUI/SemanticInputEvent.h b/cegui/include/CEGUI/SemanticInputEvent.h new file mode 100644 index 000000000..4914754ae --- /dev/null +++ b/cegui/include/CEGUI/SemanticInputEvent.h @@ -0,0 +1,189 @@ +/*********************************************************************** + created: 18/7/2013 + author: Timotei Dolean + + purpose: Holds the semantic input events used by the Input Aggregator +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUISemanticInputEvent_h_ +#define _CEGUISemanticInputEvent_h_ + +#include "CEGUI/InputEvents.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ + +/*! +\brief + Represents the source of an event that uses the cursor. +*/ +enum CursorInputSource +{ + CIS_None, //!< No specific cursor source + CIS_Left, //!< Left cursor source + CIS_Right, //!< Right cursor source + CIS_Middle, //!< Middle cursor source +}; + +/*! +\brief + Holds the state of the cursors (held or not) +*/ +class CursorsState +{ +public: + CursorsState() : + d_state(0) + { + } + + uint get() const { return d_state; } + + bool isHeld(CursorInputSource source) + { + return (d_state & (1 << source)) != 0; + } + + void pointerHold(CursorInputSource source) + { + d_state |= (1 << source); + } + + void pointerDeactivated(CursorInputSource source) + { + d_state &= ~(1 << source); + } + +private: + uint d_state; +}; + +/*! +\brief + Represents the value of a semantic input event, generated from a specific + operation or sequence of operations. +*/ +enum SemanticValue +{ + SV_NoValue = 0x0000, + SV_CursorActivate, + SV_PointerDeactivate, + SV_CursorPressHold, + SV_CursorMove, + SV_PointerLeave, + SV_SelectRange, + SV_SelectCumulative, + SV_SelectWord, + SV_SelectAll, + SV_SelectPreviousCharacter, + SV_SelectNextCharacter, + SV_SelectPreviousWord, + SV_SelectNextWord, + SV_SelectToStartOfLine, + SV_SelectToEndOfLine, + SV_GoToPreviousCharacter, + SV_GoToNextCharacter, + SV_GoToPreviousWord, + SV_GoToNextWord, + SV_GoToStartOfLine, + SV_GoToEndOfLine, + SV_GoToStartOfDocument, + SV_GoToEndOfDocument, + SV_GoToNextPage, + SV_GoToPreviousPage, + SV_DeleteNextCharacter, + SV_DeletePreviousCharacter, + SV_Confirm, + SV_Back, + SV_Undo, + SV_Redo, + SV_Cut, + SV_Copy, + SV_Paste, + SV_HorizontalScroll, + SV_VerticalScroll, + SV_SelectToStartOfDocument, + SV_SelectToEndOfDocument, + SV_SelectToNextPage, + SV_SelectToPreviousPage, + SV_SelectNextPage, + SV_SelectPreviousPage, + SV_GoUp, + SV_GoDown, + SV_SelectUp, + SV_SelectDown, + SV_NavigateToNext, + SV_NavigateToPrevious, + + SV_UserDefinedSemanticValue = 0x5000, //!< This marks the beginning of user-defined semantic values. +}; + +static bool isSelectionSemanticValue(int value) +{ + return (value >= SV_SelectRange && value <= SV_SelectToEndOfLine) || + (value >= SV_SelectToStartOfDocument && value <= SV_SelectToPreviousPage); +} + +/*! +\brief + The type of the payload used in the semantic input events +*/ +union SemanticPayload +{ + float array[2]; + float single; + CursorInputSource source; +}; + +/*! +\brief + Represents a semantic input event (e.g.: delete a previous character, confirm) +*/ +class CEGUIEXPORT SemanticInputEvent : public InputEvent +{ +public: + SemanticInputEvent(int value) : + InputEvent(IET_SemanticInputEventType), + d_value(value), + d_payload() + { + } + + int d_value; //!< The semantic value of this event + SemanticPayload d_payload; //!< Extra data associated to this event +}; + +} // End of CEGUI namespace section + +#if defined (_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUISemanticInputEvent_h_ diff --git a/cegui/include/CEGUI/ShaderParameterBindings.h b/cegui/include/CEGUI/ShaderParameterBindings.h new file mode 100644 index 000000000..ec710a97a --- /dev/null +++ b/cegui/include/CEGUI/ShaderParameterBindings.h @@ -0,0 +1,326 @@ +/*********************************************************************** + created: 18th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIShaderParameterBindings_h_ +#define _CEGUIShaderParameterBindings_h_ + +#include "CEGUI/Base.h" + +#include "CEGUI/ModuleConfig.h" +#include "glm/glm.hpp" + +#ifdef CEGUI_BUILD_RENDERER_OGRE +namespace Ogre +{ + class Matrix4; +} +#endif + +#include +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ +class Texture; + +//----------------------------------------------------------------------------// +/*! +\brief + Enumerated type that contains the valid types a shader parameter can have +*/ +enum ShaderParamType +{ + //! A regular integer type + SPT_INT, + //! A regular float type + SPT_FLOAT, + //! A pointer to a CEGUI Texture + SPT_TEXTURE, + //! A pointer to a 4x4 Matrix + SPT_MATRIX_4X4, + + //! Total number of shader parameter types + SPT_COUNT +}; +//----------------------------------------------------------------------------// + +/*! +\brief + The class is the abstract interface used for all shader parameters that + are added to the RenderMaterials. +*/ +class ShaderParameter +{ +public: + ShaderParameter() + {} + + virtual ~ShaderParameter() + {} + + ShaderParameter(const ShaderParameter& other) + {} + + /*! + \brief + Returns the type of the shader parameter. + + \return + The type of the shader parameter. + */ + virtual ShaderParamType getType() const = 0; + + /*! + \brief + Returns a copy of this ShaderParameter on the heap and returns the + pointer to it. The caller has to take care of memory deallocation. + + \return + A pointer to the copy of this ShaderParameter. + */ + virtual ShaderParameter* clone() const = 0; + + /*! + \brief + Checks if the ShaderParameters are equal, depending on their type + and parameter. + + \return + True if the ShaderParameters are equal. + */ + virtual bool equal(const ShaderParameter* other_parameter) const = 0; + + /*! + \brief + Copies the parameter value from the passed ShaderParameter to this + one if the classes are of the same type. + \param other_parameter + The ShaderParameter from which the parameter value should be taken over. + */ + virtual void takeOverParameterValue(const ShaderParameter* other_parameter) = 0; +}; + +/*! +\brief + The class implements the functionality of the + ShaderParameter interface for float parameters. +*/ +class ShaderParameterFloat : public ShaderParameter +{ +public: + ShaderParameterFloat(float parameterValue) + : d_parameterValue(parameterValue) + {} + + //! Implementation of the shader_parameter interface + virtual ShaderParamType getType() const + { return SPT_FLOAT; } + virtual ShaderParameterFloat* clone() const + { return new ShaderParameterFloat(*this); } + bool equal(const ShaderParameter* other_parameter) const; + void takeOverParameterValue(const ShaderParameter* other_parameter); + + //! The float parameter value + float d_parameterValue; +}; + +/*! +\brief + The class implements the functionality of the + ShaderParameter interface for int parameters. +*/ +class ShaderParameterInt : public ShaderParameter +{ +public: + ShaderParameterInt(int parameterValue) + : d_parameterValue(parameterValue) + {} + + //! Implementation of the shader_parameter interface + virtual ShaderParamType getType() const + { return SPT_INT; } + virtual ShaderParameterInt* clone() const + { return new ShaderParameterInt(*this); } + bool equal(const ShaderParameter* other_parameter) const; + void takeOverParameterValue(const ShaderParameter* other_parameter); + + //! The float parameter value + int d_parameterValue; +}; + +/*! +\brief + The class implements the functionality of the + ShaderParameter interface for Texture parameters. +*/ +class ShaderParameterTexture : public ShaderParameter +{ +public: + ShaderParameterTexture(const CEGUI::Texture* parameterValue) + : d_parameterValue(parameterValue) + {} + + //! Implementation of the shader_parameter interface + virtual ShaderParamType getType() const + { return SPT_TEXTURE; } + virtual ShaderParameterTexture* clone() const + { return new ShaderParameterTexture(*this); } + bool equal(const ShaderParameter* other_parameter) const; + void takeOverParameterValue(const ShaderParameter* other_parameter); + + //! The float parameter value + const CEGUI::Texture* d_parameterValue; +}; + +/*! +\brief + The class implements the functionality of the + ShaderParameter interface for 4x4 matrix parameters. +*/ +class ShaderParameterMatrix : public ShaderParameter +{ +public: + ShaderParameterMatrix(const glm::mat4& parameterValue) + : d_parameterValue(parameterValue) + {} + + //! Implementation of the shader_parameter interface + virtual ShaderParamType getType() const + { return SPT_MATRIX_4X4; } + virtual ShaderParameterMatrix* clone() const + { return new ShaderParameterMatrix(*this); } + bool equal(const ShaderParameter* other_parameter) const; + void takeOverParameterValue(const ShaderParameter* other_parameter); + + glm::mat4 d_parameterValue; +}; + +/*! +\brief + +*/ +class CEGUIEXPORT ShaderParameterBindings +{ +public: + typedef std::map ShaderParameterBindingsMap; + + ShaderParameterBindings(); + ~ShaderParameterBindings(); + + /*! + \brief + Adds a matrix shader parameter to the parameter bindings + + \param parameter_name + The name of the parameter as used by the shader + + \param matrix + The pointer to the matrix + */ + void setParameter(const std::string& parameter_name, + const glm::mat4& matrix); + + /*! + \brief + Adds a texture shader parameter to the parameter bindings + + \param parameter_name + The name of the parameter as used by the shader + + \param texture + The pointer to the CEGUI::Texture + */ + void setParameter(const std::string& parameter_name, + const CEGUI::Texture* texture); + + /*! + \brief + Adds a float shader parameter to the parameter bindings + + \param parameter_name + The name of the parameter as used by the shader + + \param fvalue + The value of the float parameter + */ + void setParameter(const std::string& parameter_name, + const float fvalue); + + /*! + \brief + Returns a pointer to the shader_parameter with the specified parameter name + + \param parameter_name + The name of the parameter as used by the shader + + \return + The pointer to the required shader_parameter. Will return 0 if a parameter + with the specified name was not set. + */ + ShaderParameter* getParameter(const std::string& parameter_name); + + /*! + \brief + Sets the shader_parameter in the map to 0, which means that the shader parameter + will remain unchanged during rendering + + \param parameter_name + The name of the parameter as used by the shader + */ + void removeParameter(const std::string& parameter_name); + + const ShaderParameterBindingsMap& getShaderParameterBindings() const; + +protected: + /*! + \brief + Adds a new shader parameter to the parameter bindings. If an old one exists it will be + deleted and replaced by the new one. + + \param parameter_name + The name of the parameter as used by the shader + + \param shader_parameter + The pointer to the shader_parameter + */ + void setNewParameter(const std::string& parameter_name, ShaderParameter* shader_parameter); + + //! Map of the names of the shader parameter and the respective shader parameter value + ShaderParameterBindingsMap d_shaderParameterBindings; +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/ShaderWrapper.h b/cegui/include/CEGUI/ShaderWrapper.h new file mode 100644 index 000000000..af24c703f --- /dev/null +++ b/cegui/include/CEGUI/ShaderWrapper.h @@ -0,0 +1,65 @@ +/*********************************************************************** + created: 18th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIShaderWrapper_h_ +#define _CEGUIShaderWrapper_h_ + +#include "CEGUI/Base.h" + +namespace CEGUI +{ +class ShaderParameterBindings; + +/*! +\brief + The ShaderWrapper is an abstract interface that is used in RenderMaterials + and has to be implemented by the specific Renderer. It updates all the + ShaderParameters set for a RenderMaterial before rendering. +*/ +class CEGUIEXPORT ShaderWrapper +{ +public: + ShaderWrapper() + {} + + virtual ~ShaderWrapper() + {} + + /*! + \brief + This function applies the shader parameters depending on their type, + so that they will be used during rendering + + \param ShaderParameterBindings + The ShaderParameterBindings that will be applied + + */ + virtual void prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) = 0; +}; + +} + +#endif diff --git a/cegui/include/CEGUI/SimpleTimer.h b/cegui/include/CEGUI/SimpleTimer.h index 0b09c4a73..45275a893 100644 --- a/cegui/include/CEGUI/SimpleTimer.h +++ b/cegui/include/CEGUI/SimpleTimer.h @@ -33,8 +33,7 @@ namespace CEGUI { //! Simple timer class. -class CEGUIEXPORT SimpleTimer : - public AllocatedObject +class CEGUIEXPORT SimpleTimer { double d_baseTime; diff --git a/cegui/include/CEGUI/Size.h b/cegui/include/CEGUI/Size.h index dd7cf3c02..98a46dc14 100644 --- a/cegui/include/CEGUI/Size.h +++ b/cegui/include/CEGUI/Size.h @@ -34,6 +34,8 @@ #include #include +#include + // Start of CEGUI namespace section namespace CEGUI { @@ -63,8 +65,7 @@ enum AspectMode Class that holds the size (width & height) of something. */ template -class Size: - public AllocatedObject > +class Size { public: typedef T value_type; @@ -102,9 +103,9 @@ class Size: return Size(d_width * s.d_width, d_height * s.d_height); } - inline Size operator*(const Vector2f& vec) const + inline Size operator*(const glm::vec2& vec) const { - return Size(d_width * vec.d_x, d_height * vec.d_y); + return Size(d_width * vec.x, d_height * vec.y); } inline Size operator+(const Size& s) const diff --git a/cegui/include/CEGUI/SlotFunctorBase.h b/cegui/include/CEGUI/SlotFunctorBase.h index f4b1fe541..97f6faff8 100644 --- a/cegui/include/CEGUI/SlotFunctorBase.h +++ b/cegui/include/CEGUI/SlotFunctorBase.h @@ -30,24 +30,23 @@ // Start of CEGUI namespace section namespace CEGUI { - -// forward refs -class EventArgs; - /*! \brief Defines abstract interface which will be used when constructing various functor objects that bind slots to signals (or in CEGUI terms, handlers to events). + +\tparam TArgs + The type of the argument this functor takes */ +template class SlotFunctorBase { public: virtual ~SlotFunctorBase() {}; - virtual bool operator()(const EventArgs& args) = 0; + virtual bool operator()(const TArg& arg) = 0; }; - } // End of CEGUI namespace section #endif // end of guard _CEGUISlotFunctorBase_h_ diff --git a/cegui/include/CEGUI/String.h b/cegui/include/CEGUI/String.h index 8037bc90c..89d53e601 100644 --- a/cegui/include/CEGUI/String.h +++ b/cegui/include/CEGUI/String.h @@ -59,8 +59,7 @@ typedef utf8 encoded_char; current locale, and also comparisons do not take into account the Unicode data tables, so are not 'correct' as such. */ -class CEGUIEXPORT String : - public AllocatedObject +class CEGUIEXPORT String { public: /************************************************************************* @@ -5598,10 +5597,6 @@ typedef char encoded_char; typedef std::string String; -#else // CEGUI_STRING_CLASS_STD_AO - -typedef std::basic_string, STLAllocatorWrapper::Allocator> > String; - #endif /*! diff --git a/cegui/include/CEGUI/StringTranscoder.h b/cegui/include/CEGUI/StringTranscoder.h index 334b2c8bc..bf4c16214 100644 --- a/cegui/include/CEGUI/StringTranscoder.h +++ b/cegui/include/CEGUI/StringTranscoder.h @@ -38,8 +38,7 @@ namespace CEGUI from some other character encodings not directly supported by the CEGUI::String class. */ -class CEGUIEXPORT StringTranscoder : - public AllocatedObject +class CEGUIEXPORT StringTranscoder { public: /*! diff --git a/cegui/include/CEGUI/SubscriberSlot.h b/cegui/include/CEGUI/SubscriberSlot.h index 67b3b9970..a2feb51d0 100644 --- a/cegui/include/CEGUI/SubscriberSlot.h +++ b/cegui/include/CEGUI/SubscriberSlot.h @@ -48,8 +48,7 @@ namespace CEGUI exceptions are for subscribing member functions and references to functor objects. */ -class CEGUIEXPORT SubscriberSlot : - public AllocatedObject +class CEGUIEXPORT SubscriberSlot { public: /*! @@ -137,7 +136,7 @@ class CEGUIEXPORT SubscriberSlot : private: //! Points to the internal functor object to which we are bound - SlotFunctorBase* d_functor_impl; + SlotFunctorBase* d_functor_impl; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/System.h b/cegui/include/CEGUI/System.h index ef00a430b..95c2cf866 100644 --- a/cegui/include/CEGUI/System.h +++ b/cegui/include/CEGUI/System.h @@ -64,8 +64,7 @@ namespace CEGUI */ class CEGUIEXPORT System : public Singleton, - public EventSet, - public AllocatedObject + public EventSet { public: static const String EventNamespace; //!< Namespace for global events @@ -227,9 +226,18 @@ class CEGUIEXPORT System : */ void renderAllGUIContexts(); + /*! + \brief + Renders the contexts associated with the renderer + \todo + This needs to be actually made to check if context matches the renderer + and for that to work all the contexts need to know their renderer + \see renderAllGUIContexts + */ + void renderAllGUIContextsOnTarget(Renderer* contained_in); - /*! - \brief + /*! + \brief Return a pointer to the ScriptModule being used for scripting within the GUI system. \return @@ -394,7 +402,7 @@ class CEGUIEXPORT System : returned may not actually correspond to the module in use. */ static const String getDefaultXMLParserName(); - + /*! \brief Retrieve the image codec to be used by the system. @@ -439,7 +447,7 @@ class CEGUIEXPORT System : Calling this function ensures that any other parts of the system that need to know about display size changes are notified. This affects - things such as the MouseCursor default constraint area, and also the + things such as the Cursor default constraint area, and also the auto-scale functioning of Imagesets and Fonts. \note @@ -461,7 +469,7 @@ class CEGUIEXPORT System : If this global custom RenderedStringParser is set to 0, then all windows with parsing enabled and no custom RenderedStringParser set on the - window itself will use the systems BasicRenderedStringParser. + window itself will use the systems BasicRenderedStringParser. */ RenderedStringParser* getDefaultCustomRenderedStringParser() const; @@ -477,7 +485,7 @@ class CEGUIEXPORT System : If this global custom RenderedStringParser is set to 0, then all windows with parsing enabled and no custom RenderedStringParser set on the - window itself will use the systems BasicRenderedStringParser. + window itself will use the systems BasicRenderedStringParser. */ void setDefaultCustomRenderedStringParser(RenderedStringParser* parser); @@ -487,9 +495,9 @@ class CEGUIEXPORT System : This function will invalidate the caches used for both imagery and geometry for all content that is managed by the core CEGUI manager - objects, causing a full and total redraw of that content. This + objects, causing a full and total redraw of that content. This includes Window object's cached geometry, rendering surfaces and - rendering windows and the mouse pointer geometry. + rendering windows and the pointer geometry. */ void invalidateAllCachedRendering(); @@ -598,16 +606,16 @@ class CEGUIEXPORT System : //! handle cleanup of the XML parser void cleanupXMLParser(); - //! setup image codec + //! setup image codec void setupImageCodec(const String& codecName); - //! cleanup image codec + //! cleanup image codec void cleanupImageCodec(); //! invalidate all windows and any rendering surfaces they may be using. void invalidateAllWindows(); - /************************************************************************* + /************************************************************************* Implementation Data *************************************************************************/ Renderer* d_renderer; //!< Holds the pointer to the Renderer object given to us in the constructor @@ -615,6 +623,7 @@ class CEGUIEXPORT System : bool d_ourResourceProvider; Clipboard* d_clipboard; //!< Internal clipboard with optional sync with native clipboard + NativeClipboardProvider* d_nativeClipboardProvider; //!< the default native clipboard provider (only on Win32 for now) // scripting ScriptModule* d_scriptModule; //!< Points to the scripting support module. @@ -641,7 +650,7 @@ class CEGUIEXPORT System : //! currently set global RenderedStringParser. RenderedStringParser* d_customRenderedStringParser; - typedef std::vector GUIContextCollection; + typedef std::vector GUIContextCollection; GUIContextCollection d_guiContexts; //! instance of class that can convert string encodings #if defined(__WIN32__) || defined(_WIN32) diff --git a/cegui/include/CEGUI/SystemKeys.h b/cegui/include/CEGUI/SystemKeys.h deleted file mode 100644 index 6df1c3924..000000000 --- a/cegui/include/CEGUI/SystemKeys.h +++ /dev/null @@ -1,86 +0,0 @@ -/*********************************************************************** - created: Fri Feb 17 2012 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUISystemKeys_h_ -#define _CEGUISystemKeys_h_ - -#include "CEGUI/InputEvent.h" - -namespace CEGUI -{ -class CEGUIEXPORT SystemKeys -{ -public: - enum SystemKey - { - None = 0x0000, - LeftMouse = 0x0001, - RightMouse = 0x0002, - Shift = 0x0004, - Control = 0x0008, - MiddleMouse = 0x0010, - X1Mouse = 0x0020, - X2Mouse = 0x0040, - Alt = 0x0080 - }; - - SystemKeys(); - - void reset(); - - uint get() const; - bool isPressed(SystemKey key) const; - - //! notify that the given key was presed - void keyPressed(Key::Scan key); - //! notify that the given key was released. - void keyReleased(Key::Scan key); - //! notify that the given mouse button was pressed. - void mouseButtonPressed(MouseButton button); - //! notify that the given mouse button was released. - void mouseButtonReleased(MouseButton button); - - static SystemKey mouseButtonToSystemKey(MouseButton button); - static SystemKey keyCodeToSystemKey(Key::Scan key); - -private: - void updatePressedStateForKey(Key::Scan key, bool state); - void updateSystemKeyState(SystemKey syskey); - - uint d_current; - - bool d_leftShift; - bool d_rightShift; - bool d_leftCtrl; - bool d_rightCtrl; - bool d_leftAlt; - bool d_rightAlt; -}; - -} - -#endif - diff --git a/cegui/include/CEGUI/TextUtils.h b/cegui/include/CEGUI/TextUtils.h index 1d74254df..90957e056 100644 --- a/cegui/include/CEGUI/TextUtils.h +++ b/cegui/include/CEGUI/TextUtils.h @@ -82,7 +82,7 @@ class CEGUIEXPORT TextUtils \brief Return the index of the first character of the word at \a idx. - /note + \note This currently uses DefaultWhitespace and DefaultAlphanumerical to determine groupings for what constitutes a 'word'. \param str @@ -101,7 +101,7 @@ class CEGUIEXPORT TextUtils \brief Return the index of the first character of the word after the word at \a idx. - /note + \note This currently uses DefaultWhitespace and DefaultAlphanumerical to determine groupings for what constitutes a 'word'. \param str diff --git a/cegui/include/CEGUI/Texture.h b/cegui/include/CEGUI/Texture.h index 64fecbccb..9ee363be5 100644 --- a/cegui/include/CEGUI/Texture.h +++ b/cegui/include/CEGUI/Texture.h @@ -49,8 +49,7 @@ namespace CEGUI for the rest of the system to work. Texture objects are only created through the Renderer object's texture creation functions. */ -class CEGUIEXPORT Texture : - public AllocatedObject +class CEGUIEXPORT Texture { public: /*! @@ -126,7 +125,7 @@ class CEGUIEXPORT Texture : Reference to a Vector2 object that describes the scaling values required to accurately map pixel positions to texture co-ordinates. */ - virtual const Vector2f& getTexelScaling() const = 0; + virtual const glm::vec2& getTexelScaling() const = 0; /*! \brief @@ -134,7 +133,7 @@ class CEGUIEXPORT Texture : as required to hold the image. \param filename - The filename of the image file that is to be loaded into the texture + The filename of the image file that is to be loaded into the texture. \param resourceGroup Resource group identifier to be passed to the resource provider when diff --git a/cegui/include/CEGUI/TextureTarget.h b/cegui/include/CEGUI/TextureTarget.h index 3e400ffba..a5b9f5881 100644 --- a/cegui/include/CEGUI/TextureTarget.h +++ b/cegui/include/CEGUI/TextureTarget.h @@ -90,6 +90,19 @@ class CEGUIEXPORT TextureTarget : public RenderTarget textures. */ virtual bool isRenderingInverted() const = 0; + + /*! + \brief + Return whether this TextureTarget has a stencil buffer attached or not. + \return + - true if a stencil buffer is attached + - false if no stencil buffer is attached + */ + bool getUsesStencil() const {return d_usesStencil;} + +protected: + //! Determines if the instance has a stencil buffer attached or not + bool d_usesStencil; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/TplWindowFactory.h b/cegui/include/CEGUI/TplWindowFactory.h index ec0a3ba4d..02db2a6c4 100644 --- a/cegui/include/CEGUI/TplWindowFactory.h +++ b/cegui/include/CEGUI/TplWindowFactory.h @@ -71,14 +71,14 @@ TplWindowFactory::TplWindowFactory() : template Window* TplWindowFactory::createWindow(const String& name) { - return CEGUI_NEW_AO T(d_type, name); + return new T(d_type, name); } //----------------------------------------------------------------------------// template void TplWindowFactory::destroyWindow(Window* window) { - CEGUI_DELETE_AO window; + delete window; } //----------------------------------------------------------------------------// diff --git a/cegui/include/CEGUI/TplWindowProperty.h b/cegui/include/CEGUI/TplWindowProperty.h index 5dcfa181d..530282eb2 100644 --- a/cegui/include/CEGUI/TplWindowProperty.h +++ b/cegui/include/CEGUI/TplWindowProperty.h @@ -49,7 +49,7 @@ class TplWindowProperty : public TplProperty virtual Property* clone() const { - return CEGUI_NEW_AO TplWindowProperty(*this); + return new TplWindowProperty(*this); } protected: diff --git a/cegui/include/CEGUI/TplWindowRendererFactory.h b/cegui/include/CEGUI/TplWindowRendererFactory.h index b9e0b258d..375eb8ce8 100644 --- a/cegui/include/CEGUI/TplWindowRendererFactory.h +++ b/cegui/include/CEGUI/TplWindowRendererFactory.h @@ -71,14 +71,14 @@ TplWindowRendererFactory::TplWindowRendererFactory() : template WindowRenderer* TplWindowRendererFactory::create() { - return CEGUI_NEW_AO T(T::TypeName); + return new T(T::TypeName); } //----------------------------------------------------------------------------// template void TplWindowRendererFactory::destroy(WindowRenderer* wr) { - CEGUI_DELETE_AO wr; + delete wr; } //----------------------------------------------------------------------------// diff --git a/cegui/include/CEGUI/TplWindowRendererProperty.h b/cegui/include/CEGUI/TplWindowRendererProperty.h index aba7a7e68..33f81897a 100644 --- a/cegui/include/CEGUI/TplWindowRendererProperty.h +++ b/cegui/include/CEGUI/TplWindowRendererProperty.h @@ -53,7 +53,7 @@ class TplWindowRendererProperty : public TplProperty virtual Property* clone() const { - return CEGUI_NEW_AO TplWindowRendererProperty(*this); + return new TplWindowRendererProperty(*this); } protected: diff --git a/cegui/include/CEGUI/UDim.h b/cegui/include/CEGUI/UDim.h index 985174898..89b6896e8 100644 --- a/cegui/include/CEGUI/UDim.h +++ b/cegui/include/CEGUI/UDim.h @@ -89,8 +89,7 @@ namespace CEGUI \see CEGUI::USize \see CEGUI::URect */ -class CEGUIEXPORT UDim : - public AllocatedObject +class CEGUIEXPORT UDim { public: inline UDim() @@ -244,8 +243,7 @@ class CEGUIEXPORT UDim : \note Name taken from W3 'box model' */ -class CEGUIEXPORT UBox : - public AllocatedObject +class CEGUIEXPORT UBox { public: UBox(): diff --git a/cegui/include/CEGUI/UndoHandler.h b/cegui/include/CEGUI/UndoHandler.h new file mode 100644 index 000000000..816f44960 --- /dev/null +++ b/cegui/include/CEGUI/UndoHandler.h @@ -0,0 +1,154 @@ +/*********************************************************************** + created: 15/07/2013 + author: Erihel + + purpose: Class for handling undo/redo of windows +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIUndoHandler_h_ +#define _CEGUIUndoHandler_h_ + +#include "Base.h" +#include "Window.h" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + + +// Start of CEGUI namespace section +namespace CEGUI +{ +/*! +\brief + Handler class for undo support + +*/ + +class CEGUIEXPORT UndoHandler +{ +public: + UndoHandler(Window *window); + + /*! + \brief + enum representing undo type (insert, delete) + */ + enum UndoActionType + { + UAT_INSERT = 1, + UAT_DELETE = 2 + }; + + /*! + \brief + Struct used to store information about undo actions + */ + struct UndoAction + { + UndoActionType d_type; //!< Undo type + size_t d_startIdx; //!< Starting index for this line. + String d_text; + }; + + typedef std::deque UndoList; //!< Type for collection of UndoActions. + + /*! + \brief + Perform undo + + \param cursor + - new cursor position + */ + bool undo(size_t &cursor); + + /*! + \brief + Perform redo + + \param cursor + - new cursor position + */ + bool redo(size_t &cursor); + + /*! + \brief + Add a single record to undo history + */ + void addUndoHistory(UndoAction &action); + + /*! + \brief + Clear undo history + */ + void clearUndoHistory(); + + /*! + \brief + Set maximum number of undo steps to store. + + \param limit + - size of undo list + */ + void setUndoLimit(int limit); + + /*! + \brief + Get count of undo actions in queue + */ + size_t count(); + + /*! + \brief + Checks if undo action is possible + */ + bool canUndo(); + + /*! + \brief + Checks if redo action is possible + */ + bool canRedo(); + + UndoAction getLastAction(); + +private: + UndoList d_undoList; //!< Holds the undo history + size_t d_undoLimit; //!< Maximum numer of undo entries + int d_undoPosition; //!< Position in undo list + Window* d_attachedWindow; //!< Pointer to window that we will handle + bool d_lastUndo; //!< True if last function called was undo +}; + + +} // End of CEGUI namespace section + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIUndoHandler_h_ diff --git a/cegui/include/CEGUI/Vector.h b/cegui/include/CEGUI/Vector.h index 9d8580ea6..be686a7a7 100644 --- a/cegui/include/CEGUI/Vector.h +++ b/cegui/include/CEGUI/Vector.h @@ -44,14 +44,9 @@ namespace CEGUI \par This class is templated now, this allows us to use it as a Vector2 of floats, ints or even UDims without replicating the code all over the place. - -\par - For a simple Vector2 of floats (what was called Vector2 before), use Vector2f - as the T template parameter defaults to float to save fingertips. */ template -class Vector2: - public AllocatedObject > +class Vector2 { public: typedef T value_type; @@ -139,6 +134,14 @@ class Vector2: return Vector2(d_x / c, d_y / c); } + inline Vector2 operator/=(const T c) + { + d_x /= c; + d_y /= c; + + return *this; + } + inline bool operator==(const Vector2& vec) const { return ((d_x == vec.d_x) && (d_y == vec.d_y)); @@ -186,9 +189,6 @@ class Vector2: T d_y; }; -// the main reason for this is to keep C++ API in sync with other languages -typedef Vector2 Vector2f; - // we need to allow UVector2 to be multiplied by floats, this is the most elegant way to do that inline Vector2 operator * (const Vector2& v, const float c) { @@ -197,118 +197,6 @@ inline Vector2 operator * (const Vector2& v, const float c) typedef Vector2 UVector2; -/*! -\brief - Class used as a three dimensional vector - -\par - This class is templated now, this allows us to use it as a Vector3 of floats, - ints or even UDims without replicating the code all over the place. - -\par - For a simple Vector3 of floats (what was called Vector3 before), use Vector3f - as the T template parameter defaults to float to save fingertips. -*/ -template -class Vector3: - public AllocatedObject > -{ -public: - typedef T value_type; - - inline Vector3() - {} - - inline Vector3(const T x, const T y, const T z): - d_x(x), - d_y(y), - d_z(z) - {} - - inline explicit Vector3(const Vector2& v, const T z): - d_x(v.d_x), - d_y(v.d_y), - d_z(z) - {} - - inline Vector3(const Vector3& v): - d_x(v.d_x), - d_y(v.d_y), - d_z(v.d_z) - {} - - inline bool operator==(const Vector3& vec) const - { - return ((d_x == vec.d_x) && (d_y == vec.d_y) && (d_z == vec.d_z)); - } - - inline bool operator!=(const Vector3& vec) const - { - return !(operator==(vec)); - } - - inline Vector3 operator*(const T c) const - { - return Vector3(d_x * c, d_y * c, d_z * c); - } - - inline Vector3 operator+(const Vector3& v) const - { - return Vector3(d_x + v.d_x, d_y + v.d_y, d_z + v.d_z); - } - - inline Vector3 operator-(const Vector3& v) const - { - return Vector3(d_x - v.d_x, d_y - v.d_y, d_z - v.d_z); - } - - /*! - \brief allows writing the vector3 to std ostream - */ - inline friend std::ostream& operator << (std::ostream& s, const Vector3& v) - { - s << "CEGUI::Vector3<" << typeid(T).name() << ">(" << v.d_x << ", " << v.d_y << ", " << v.d_z << ")"; - return s; - } - - //! \brief finger saving alias for Vector3(0, 0, 0) - inline static Vector3 zero() - { - return Vector3(TypeSensitiveZero(), TypeSensitiveZero(), TypeSensitiveZero()); - } - - //! \brief finger saving alias for Vector3(1, 1, 1) - inline static Vector3 one() - { - return Vector3(TypeSensitiveOne(), TypeSensitiveOne(), TypeSensitiveOne()); - } - - //! \brief finger saving alias for Vector3(1, 0, 0) - inline static Vector3 one_x() - { - return Vector3(TypeSensitiveOne(), TypeSensitiveZero(), TypeSensitiveZero()); - } - - //! \brief finger saving alias for Vector3(0, 1, 0) - inline static Vector3 one_y() - { - return Vector3(TypeSensitiveZero(), TypeSensitiveOne(), TypeSensitiveZero()); - } - - //! \brief finger saving alias for Vector3(0, 0, 1) - inline static Vector3 one_z() - { - return Vector3(TypeSensitiveZero(), TypeSensitiveZero(), TypeSensitiveOne()); - } - - T d_x; - T d_y; - T d_z; -}; - -// the main reason for this is to keep C++ API in sync with other languages -typedef Vector3 Vector3f; - } // End of CEGUI namespace section #endif // end of guard _CEGUIVector_h_ diff --git a/cegui/include/CEGUI/Vertex.h b/cegui/include/CEGUI/Vertex.h index 682a10412..e786e8409 100644 --- a/cegui/include/CEGUI/Vertex.h +++ b/cegui/include/CEGUI/Vertex.h @@ -27,27 +27,80 @@ #ifndef _CEGUIVertex_h_ #define _CEGUIVertex_h_ -#include "CEGUI/Vector.h" #include "CEGUI/Colour.h" -// Start of CEGUI namespace section +#include "glm/glm.hpp" + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + + namespace CEGUI { /*! \brief - structure that is used to hold details of a single vertex in 3D space. + Structure that is used to hold the attributes of a vertex for coloured and + textured geometry in 3D space. */ -struct Vertex : - public AllocatedObject +struct CEGUIEXPORT TexturedColouredVertex { + //! Constructor + TexturedColouredVertex() + {} + + TexturedColouredVertex(const glm::vec3& position, + const glm::vec4& colour, + const glm::vec2& texCoords) : + d_position(position), + d_colour(colour), + d_texCoords(texCoords) + {} + + //! Sets the colour of the struct + void setColour(const Colour& colour); + //! Position of the vertex in 3D space. - Vector3f position; - //! Texture co-ords to be applied to the vertex. - Vector2f tex_coords; - //! colour to be applied to the vertex. - Colour colour_val; + glm::vec3 d_position; + //! Multiplicative-colour attribute of the vertex. + glm::vec4 d_colour; + //! Texture coordinates of the vertex. + glm::vec2 d_texCoords; }; -} // End of CEGUI namespace section +/*! +\brief + Structure that is used to hold the attributes of coloured geometry + in 3D space. +*/ +struct CEGUIEXPORT ColouredVertex +{ + //! Constructor + ColouredVertex() + {} + + ColouredVertex(const glm::vec3& position, + const glm::vec4& colour) : + d_position(position), + d_colour(colour) + {} + + //! Sets the colour of the struct + void setColour(const Colour& colour); + + //! Position of the vertex in 3D space. + glm::vec3 d_position; + + //! Colour attribute of the vertex. + glm::vec4 d_colour; +}; + + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif #endif // end of guard _CEGUIVertex_h_ diff --git a/cegui/include/CEGUI/Win32ClipboardProvider.h b/cegui/include/CEGUI/Win32ClipboardProvider.h new file mode 100644 index 000000000..ac0fe5fb5 --- /dev/null +++ b/cegui/include/CEGUI/Win32ClipboardProvider.h @@ -0,0 +1,57 @@ +/*********************************************************************** + created: 19/09/2013 + author: Alexander Gladis + + purpose: Implement a clipboard provider for Windows +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIWin32ClipboardProvider_h_ +#define _CEGUIWin32ClipboardProvider_h_ + +#include "CEGUI/Clipboard.h" + +namespace CEGUI +{ + +class Win32ClipboardProvider : public NativeClipboardProvider +{ +public: + Win32ClipboardProvider(); + ~Win32ClipboardProvider(); + + // NativeClipboardProvider implementation + void sendToClipboard(const String& mime_type, void* buffer, size_t size); + void retrieveFromClipboard(String& mime_type, void*& buffer, size_t& size); + +private: + char* d_buffer; + size_t d_bufferSize; + + void allocateBuffer(size_t size); + void deallocateBuffer(); +}; + +} + +#endif diff --git a/cegui/include/CEGUI/Window.h b/cegui/include/CEGUI/Window.h index ecfbdc7d5..a11b52ec9 100644 --- a/cegui/include/CEGUI/Window.h +++ b/cegui/include/CEGUI/Window.h @@ -33,7 +33,6 @@ #include "CEGUI/Base.h" #include "CEGUI/NamedElement.h" #include "CEGUI/Vector.h" -#include "CEGUI/Quaternion.h" #include "CEGUI/Rect.h" #include "CEGUI/Size.h" #include "CEGUI/EventSet.h" @@ -95,7 +94,7 @@ class PropertyHelper static return_type fromString(const String& str) { - + if (str == "Always") { return WUM_ALWAYS; @@ -161,7 +160,7 @@ class CEGUIEXPORT Window : * Handlers are passed a const UpdateEventArgs reference. */ static const String EventUpdated; - + /** Event fired when the text string for the Window has changed. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the Window whose text was changed. @@ -241,23 +240,23 @@ class CEGUIEXPORT Window : * was changed. */ static const String EventAlwaysOnTopChanged; - /** Event fired when the Window gains capture of mouse inputs. + /** Event fired when the Window gains capture of cursor inputs. * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Window that has captured mouse inputs. + * WindowEventArgs::window set to the Window that has captured cursor inputs. */ static const String EventInputCaptureGained; - /** Event fired when the Window loses capture of mouse inputs. + /** Event fired when the Window loses capture of cursor inputs. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to either: - * - the Window that has lost capture of mouse inputs if that event was + * - the Window that has lost capture of cursor inputs if that event was * caused by the window itself releasing the capture. - * - the Window that is @gaining capture of mouse inputs if that is the + * - the Window that is @gaining capture of cursor inputs if that is the * cause of the previous window with capture losing that capture. */ static const String EventInputCaptureLost; /** Event fired when the Window has been invalidated. * When a window is invalidated its cached rendering geometry is cleared, - * the rendering surface that recieves the window's output is invalidated + * the rendering surface that receives the window's output is invalidated * and the window's target GUIContext is marked as dirty; this causes all * objects involved in the display of the window to be refreshed the next * time that the GUIContext::draw function is called. @@ -267,7 +266,7 @@ class CEGUIEXPORT Window : static const String EventInvalidated; /** Event fired when rendering of the Window has started. In this context * 'rendering' is the population of the GeometryBuffer with geometry for the - * window, not the actual rendering of that GeometryBuffer content to the + * window, not the actual rendering of that GeometryBuffer content to the * display. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the Window whose rendering has started. @@ -275,7 +274,7 @@ class CEGUIEXPORT Window : static const String EventRenderingStarted; /** Event fired when rendering of the Window has ended. In this context * 'rendering' is the population of the GeometryBuffer with geometry for the - * window, not the actual rendering of that GeometryBuffer content to the + * window, not the actual rendering of that GeometryBuffer content to the * display. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the Window whose rendering has ended. @@ -336,96 +335,58 @@ class CEGUIEXPORT Window : static const String EventMarginChanged; // generated externally (inputs) - /** Event fired when the mouse cursor has entered the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields + /** Event fired when the cursor has entered the Window's area. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ - static const String EventMouseEntersArea; - /** Event fired when the mouse cursor has left the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields + static const String EventCursorEntersArea; + /** Event fired when the cursor has left the Window's area. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ - static const String EventMouseLeavesArea; - /** Event fired when the mouse cursor enters the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields + static const String EventCursorLeavesArea; + /** Event fired when the cursor enters the Window's area. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. - *\note This event is fired if - and only if - the mouse cursor is actually + *\note This event is fired if - and only if - the cursor is actually * over some part of this Window's surface area, and will not fire for - * example if the location of the mouse is over some child window (even - * though the mouse is technically also within the area of this Window). + * example if the location of the cursor is over some child window (even + * though the cursor is technically also within the area of this Window). * For an alternative version of this event see the - * Window::EventMouseEntersArea event. + * Window::EventCursorEntersArea event. */ - static const String EventMouseEntersSurface; - /** Event fired when the mouse cursor is no longer over the Window's surface + static const String EventCursorEntersSurface; + /** Event fired when the cursor is no longer over the Window's surface * area. - * Handlers are passed a const MouseEventArgs reference with all fields + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. - *\note This event will fire whenever the mouse is no longer actually over - * some part of this Window's surface area, for example if the mouse is - * moved over some child window (even though technically the mouse has not + *\note This event will fire whenever the cursor is no longer actually over + * some part of this Window's surface area, for example if the cursor is + * moved over some child window (even though technically the cursor has not * actually 'left' this Window's area). For an alternative version of this - * event see the Window::EventMouseLeavesArea event. + * event see the Window::EventCursorLeavesArea event. */ - static const String EventMouseLeavesSurface; - /** Event fired when the mouse cursor moves within the area of the Window. - * Handlers are passed a const MouseEventArgs reference with all fields + static const String EventCursorLeavesSurface; + /** Event fired when the cursor moves within the area of the Window. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ - static const String EventMouseMove; - /** Event fired when the mouse wheel is scrolled when the mouse cursor is - * within the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields + static const String EventCursorMove; + /** Event fired when there is a scroll event within the Window's area. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ - static const String EventMouseWheel; - /** Event fired when a mouse button is pressed down within the Window. - * Handlers are passed a const MouseEventArgs reference with all fields + static const String EventScroll; + /** Event fired when a cursor is pressed and held down within the Window. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ - static const String EventMouseButtonDown; - /** Event fired when a mouse button is released within the Window. - * Handlers are passed a const MouseEventArgs reference with all fields + static const String EventCursorPressHold; + /** Event fired when the cursor is activated within the Window. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ - static const String EventMouseButtonUp; - /** Event fired when a mouse button is clicked - that is, pressed down and - * released within a specific time interval - while the mouse cursor is - * within the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields - * valid. - */ - static const String EventMouseClick; - /** Event fired when a mouse button is double-clicked while the mouse cursor - * is within the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields - * valid. - */ - static const String EventMouseDoubleClick; - /** Event fired when a mouse button is triple-clicked while the mouse cursor - * is within the Window's area. - * Handlers are passed a const MouseEventArgs reference with all fields - * valid. - */ - static const String EventMouseTripleClick; - /** Event fired when a key on the keyboard was pressed down while the window - * had input focus. - * Handlers are passed a const KeyEventArgs reference with - * WindowEventArgs::window set to the Window receiving the key press, - * KeyEventArgs::scancode set to the Key::Scan value of the key that was - * pressed, and KeyEventArgs::sysKeys set to the combination of ::SystemKey - * values active when the key was pressed. - */ - static const String EventKeyDown; - /** Event fired when a key on the keyboard was released while the window - * had input focus. - * Handlers are passed a const KeyEventArgs reference with - * WindowEventArgs::window set to the Window receiving the key release, - * KeyEventArgs::scancode set to the Key::Scan value of the key that was - * released, and KeyEventArgs::sysKeys set to the combination of ::SystemKey - * values active when the key was released. - */ - static const String EventKeyUp; + static const String EventCursorActivate; /** Event fired when the Window receives a character key input event. * Handlers are passed a const KeyEventArgs reference with * WindowEventArgs::window set to the Window receiving the character input, @@ -434,6 +395,11 @@ class CEGUIEXPORT Window : * values active when the character input was received. */ static const String EventCharacterKey; + /** Event fired when the Window receives a semantic input event. + * Handler are passed a const SemanticEventArgs reference with the details + * of what semantic event was received + */ + static const String EventSemanticEvent; /************************************************************************* Child Widget name suffix constants @@ -569,10 +535,10 @@ class CEGUIEXPORT Window : return true if this is the active Window. An active window is a window that may receive user inputs. - Mouse events are always sent to the window containing the mouse cursor - regardless of what this function reports (unless a window has captured - inputs). The active state mainly determines where send other, for - example keyboard, inputs. + Cursor events are always sent to the window containing the cursor + regardless of what this function reports (unless a window has + captured inputs). The active state mainly determines where send other, + for example keyboard inputs. \return - true if the window is active and may be sent inputs by the system. @@ -660,7 +626,7 @@ class CEGUIEXPORT Window : { return static_cast(getChildElementAtIdx(idx)); } - + /*! \brief return the attached child window that the given name path references. @@ -967,7 +933,7 @@ class CEGUIEXPORT Window : check if the given pixel position would hit this window. \param position - Vector2 object describing the position to check. The position + vec2 object describing the position to check. The position describes a pixel offset from the top-left corner of the display. \param allow_disabled @@ -978,7 +944,7 @@ class CEGUIEXPORT Window : - true if \a position hits this Window. - false if \a position does not hit this window. */ - virtual bool isHit(const Vector2f& position, + virtual bool isHit(const glm::vec2& position, const bool allow_disabled = false) const; /*! @@ -986,22 +952,22 @@ class CEGUIEXPORT Window : return the child Window that is hit by the given pixel position \param position - Vector2 object describing the position to check. The position + vec2 object describing the position to check. The position describes a pixel offset from the top-left corner of the display. \return Pointer to the child Window that was hit according to the location \a position, or 0 if no child of this window was hit. */ - Window* getChildAtPosition(const Vector2f& position) const; + Window* getChildAtPosition(const glm::vec2& position) const; /*! \brief return the child Window that is 'hit' by the given position, and is - allowed to handle mouse events. + allowed to handle cursor events. \param position - Vector2 object describing the position to check. The position + vec2 object describing the position to check. The position describes a pixel offset from the top-left corner of the display. \param allow_disabled @@ -1012,7 +978,7 @@ class CEGUIEXPORT Window : Pointer to the child Window that was hit according to the location \a position, or 0 if no child of this window was hit. */ - Window* getTargetChildAtPosition(const Vector2f& position, + Window* getTargetChildAtPosition(const glm::vec2& position, const bool allow_disabled = false) const; /*! @@ -1030,19 +996,19 @@ class CEGUIEXPORT Window : /*! \brief - Return a pointer to the mouse cursor image to use when the mouse cursor - is within this window's area. + Return a pointer to the cursor image to use when the cursor + indicator is within this window's area. \param useDefault - Sepcifies whether to return the default mouse cursor image if this - window specifies no preferred mouse cursor image. + Specifies whether to return the default cursor image if this + window specifies no preferred cursor image. \return - Pointer to the mouse cursor image that will be used when the mouse - enters this window's area. May return NULL indicating no cursor will + Pointer to the cursor image that will be used when the cursor + enters this window's area. May return NULL indicating no indicator will be drawn for this window. */ - const Image* getMouseCursor(bool useDefault = true) const; + const Image* getCursor(bool useDefault = true) const; /*! \brief @@ -1080,8 +1046,8 @@ class CEGUIEXPORT Window : \note This is distinguished from the is/setRiseOnClickEnabled setting in that if rise on click is disabled it only affects the users ability to affect - the z order of the Window by clicking the mouse; is still possible to - programatically alter the Window z-order by calling the moveToFront, + the z order of the Window by clicking the cursor; is still possible to + programmatic alter the Window z-order by calling the moveToFront, moveToBack, moveInFront and moveBehind member functions. Whereas if z ordering is disabled those functions are also precluded from affecting the Window z position. @@ -1096,36 +1062,24 @@ class CEGUIEXPORT Window : /*! \brief - Return whether this window will receive multi-click events or multiple - 'down' events instead. - - \return - - true if the Window will receive double-click and triple-click events. - - false if the Window will receive multiple mouse button down events - instead of double/triple click events. - */ - bool wantsMultiClickEvents(void) const; - - /*! - \brief - Return whether mouse button down event autorepeat is enabled for this + Return whether cursor press event autorepeat is enabled for this window. \return - - true if autorepeat of mouse button down events is enabled for this + - true if autorepeat of cursor press events is enabled for this window. - - false if autorepeat of mouse button down events is not enabled for + - false if autorepeat of cursor press events is not enabled for this window. */ - bool isMouseAutoRepeatEnabled(void) const; + bool isCursorAutoRepeatEnabled(void) const; /*! \brief Return the current auto-repeat delay setting for this window. \return - float value indicating the delay, in seconds, defore the first repeat - mouse button down event will be triggered when autorepeat is enabled. + float value indicating the delay, in seconds, before the first repeat + cursor press event will be triggered when autorepeat is enabled. */ float getAutoRepeatDelay(void) const; @@ -1134,9 +1088,8 @@ class CEGUIEXPORT Window : Return the current auto-repeat rate setting for this window. \return - float value indicating the rate, in seconds, at which repeat mouse - button down events will be generated after the initial delay has - expired. + float value indicating the rate, in seconds, at which repeat cursor press + events will be generated after the initial delay has expired. */ float getAutoRepeatRate(void) const; @@ -1208,33 +1161,33 @@ class CEGUIEXPORT Window : /*! \brief Return whether this window will rise to the top of the z-order when - clicked with the left mouse button. + activated with the left cursor source. \note This is distinguished from the is/setZOrderingEnabled setting in that if rise on click is disabled it only affects the users ability to affect - the z order of the Window by clicking the mouse; is still possible to - programatically alter the Window z-order by calling the moveToFront, + the z order of the Window by activating the cursor; is still possible to + programmatic alter the Window z-order by calling the moveToFront, moveToBack, moveInFront and moveBehind member functions. Whereas if z ordering is disabled those functions are also precluded from affecting the Window z position. \return - true if the window will come to the top of other windows when the left - mouse button is pushed within its area. + cursor source is activated within its area. - false if the window does not change z-order position when the left - mouse button is pushed within its area. + cursor source is activated within its area. */ - bool isRiseOnClickEnabled(void) const { return d_riseOnClick; } + bool isRiseOnPointerActivationEnabled(void) const { return d_riseOnPointerActivation; } /*! \brief - Return the GeometryBuffer object for this Window. + Return the list of GeometryBuffer objects for this Window. \return - Reference to the GeometryBuffer object for this Window. + Reference to the list of GeometryBuffer objects for this Window. */ - GeometryBuffer& getGeometryBuffer(); + std::vector& getGeometryBuffers(); /*! \brief @@ -1303,15 +1256,15 @@ class CEGUIEXPORT Window : /*! \brief - Returns whether this window should ignore mouse event and pass them + Returns whether this window should ignore cursor event and pass them through to and other windows behind it. In effect making the window - transparent to the mouse. + transparent to the cursor. \return - true if mouse pass through is enabled. - false if mouse pass through is not enabled. + true if cursor pass through is enabled. + false if cursor pass through is not enabled. */ - bool isMousePassThroughEnabled(void) const {return d_mousePassThroughEnabled;} + bool isCursorPassThroughEnabled(void) const {return d_cursorPassThroughEnabled;} /*! \brief @@ -1586,11 +1539,11 @@ class CEGUIEXPORT Window : \brief Insert the text string \a text into the current text string for the Window object at the position specified by \a position. - + \param text String object holding the text that is to be inserted into the Window object's current text string. - + \param position The characted index position where the string \a text should be inserted. @@ -1601,7 +1554,7 @@ class CEGUIEXPORT Window : \brief Append the string \a text to the currect text string for the Window object. - + \param text String object holding the text that is to be appended to the Window object's current text string. @@ -1656,7 +1609,7 @@ class CEGUIEXPORT Window : /*! \brief Creates a child window attached to this window. - + \param type String that describes the type of Window to be created. A valid WindowFactory for the specified type must be registered. @@ -1687,7 +1640,7 @@ class CEGUIEXPORT Window : Name path that references the window to destroy */ void destroyChild(const String& name_path); - + /*! \brief Move the Window to the top of the z order. @@ -1749,11 +1702,11 @@ class CEGUIEXPORT Window : The sibling window that this window will be moved behind. */ void moveBehind(const Window* const window); - + /*! \brief Return the (visual) z index of the window on it's parent. - + The z index is a number that indicates the order that windows will be drawn (but is not a 'z co-ordinate', as such). Higher numbers are in front of lower numbers. @@ -1862,19 +1815,6 @@ class CEGUIEXPORT Window : */ void setInheritsAlpha(bool setting); - /*! - \brief - Invalidate this window causing at least this window to be redrawn during - the next rendering pass. - - \return - Nothing - - \deprecated - This function is deprecated in favour of the version taking a boolean. - */ - void invalidate(void); - /*! \brief Invalidate this window and - dependant upon \a recursive - all child @@ -1886,28 +1826,25 @@ class CEGUIEXPORT Window : invalidated. - true will cause all child content to be invalidated also. - false will just invalidate this single window. - - \return - Nothing */ - void invalidate(const bool recursive); + void invalidate(const bool recursive = false); /*! \brief - Set the mouse cursor image to be used when the mouse enters this window. + Set the cursor image to be used when the cursor enters this window. \param image - Pointer to the Image object to use as the mouse cursor image when the - mouse enters the area for this Window. + Pointer to the Image object to use as the cursor image when the + cursor enters the area for this Window. \return Nothing. */ - void setMouseCursor(const Image* image); + void setCursor(const Image* image); /*! \brief - Set the mouse cursor image to be used when the mouse enters this window. + Set the cursor image to be used when the cursor enters this window. \param imageset String object that contains the name of the Imageset that contains the @@ -1922,7 +1859,7 @@ class CEGUIEXPORT Window : \exception UnknownObjectException thrown if no Image named \a name exists. */ - void setMouseCursor(const String& name); + void setCursor(const String& name); /*! \brief @@ -1939,7 +1876,7 @@ class CEGUIEXPORT Window : Nothing. */ void setUserData(void* user_data) {d_userData = user_data;} - + /*! \brief Set whether z-order changes are enabled or disabled for this Window. @@ -1947,8 +1884,8 @@ class CEGUIEXPORT Window : \note This is distinguished from the is/setRiseOnClickEnabled setting in that if rise on click is disabled it only affects the users ability to affect - the z order of the Window by clicking the mouse; is still possible to - programatically alter the Window z-order by calling the moveToFront, + the z order of the Window by activating the cursor; is still possible to + programmatic alter the Window z-order by calling the moveToFront, moveToBack, moveInFront and moveBehind member functions. Whereas if z ordering is disabled those functions are also precluded from affecting the Window z position. @@ -1963,43 +1900,28 @@ class CEGUIEXPORT Window : Nothing. */ void setZOrderingEnabled(bool setting); - - /*! - \brief - Set whether this window will receive multi-click events or multiple - 'down' events instead. - - \param setting - - true if the Window will receive double-click and triple-click events. - - false if the Window will receive multiple mouse button down events - instead of double/triple click events. - - \return - Nothing. - */ - void setWantsMultiClickEvents(bool setting); /*! \brief - Set whether mouse button down event autorepeat is enabled for this + Set whether cursor press event autorepeat is enabled for this window. \param setting - - true to enable autorepeat of mouse button down events. - - false to disable autorepeat of mouse button down events. + - true to enable autorepeat of cursor press events. + - false to disable autorepeat of cursor press events. \return Nothing. */ - void setMouseAutoRepeatEnabled(bool setting); + void setCursorAutoRepeatEnabled(bool setting); /*! \brief Set the current auto-repeat delay setting for this window. \param delay - float value indicating the delay, in seconds, defore the first repeat - mouse button down event should be triggered when autorepeat is enabled. + float value indicating the delay, in seconds, before the first repeat + cursor press event should be triggered when autorepeat is enabled. \return Nothing. @@ -2011,9 +1933,8 @@ class CEGUIEXPORT Window : Set the current auto-repeat rate setting for this window. \param rate - float value indicating the rate, in seconds, at which repeat mouse - button down events should be generated after the initial delay has - expired. + float value indicating the rate, in seconds, at which repeat cursor press + events should be generated after the initial delay has expired. \return Nothing. @@ -2136,27 +2057,27 @@ class CEGUIEXPORT Window : /*! \brief Set whether this window will rise to the top of the z-order when clicked - with the left mouse button. + with the left cursor source. \note This is distinguished from the is/setZOrderingEnabled setting in that - if rise on click is disabled it only affects the users ability to affect - the z order of the Window by clicking the mouse; is still possible to - programatically alter the Window z-order by calling the moveToFront, + if rise on cursor activation is disabled it only affects the users ability to affect + the z order of the Window by activating the left cursor source; is still + possible to programmatic alter the Window z-order by calling the moveToFront, moveToBack, moveInFront and moveBehind member functions. Whereas if z ordering is disabled those functions are also precluded from affecting the Window z position. \param setting - true if the window should come to the top of other windows when the - left mouse button is pushed within its area. + left cursor source is activated within its area. - false if the window should not change z-order position when the left - mouse button is pushed within its area. + cursor source is activated within its area. \return Nothing. */ - void setRiseOnClickEnabled(bool setting) { d_riseOnClick = setting; } + void setRiseOnClickEnabled(bool setting) { d_riseOnPointerActivation = setting; } /*! \brief @@ -2177,7 +2098,7 @@ class CEGUIEXPORT Window : code is supposed to use skins is by defining a Falagard mapping (either in a scheme xml file or in code) and then create instances of that mapped type via WindowManager. See - WindowFactoryManager::addFalagardWindowMapping and \ref xml_scheme. + WindowFactoryManager::addFalagardWindowMapping and \ref xml_scheme. With that being said, it is possible for client code to use this function so long as you are aware of the implications of doing so: - Automatically created child windows (AutoWindows) will be deleted, and @@ -2282,43 +2203,61 @@ class CEGUIEXPORT Window : Nothing. */ virtual void update(float elapsed); - + /*! \brief Asks the widget to perform a clipboard copy to the provided clipboard - + \param clipboard Target clipboard class - + \return true if the copy was successful and allowed, false otherwise */ virtual bool performCopy(Clipboard& clipboard); - + /*! \brief Asks the widget to perform a clipboard cut to the provided clipboard - + \param clipboard Target clipboard class - + \return true if the cut was successful and allowed, false otherwise */ virtual bool performCut(Clipboard& clipboard); - + /*! \brief Asks the widget to perform a clipboard paste from the provided clipboard - + \param clipboard Source clipboard class - + \return true if the paste was successful and allowed, false otherwise */ virtual bool performPaste(Clipboard& clipboard); + /*! + \brief + Asks the widget to perform a undo operation + + \return + true if the undo was successful and allowed, false otherwise + */ + virtual bool performUndo(); + + /*! + \brief + Asks the widget to perform a redo operation + + \return + true if the redo was successful and allowed, false otherwise + */ + virtual bool performRedo(); + /*! \brief Writes an xml representation of this window object to \a out_stream. @@ -2352,15 +2291,15 @@ class CEGUIEXPORT Window : /*! \brief - Sets whether this window should ignore mouse events and pass them + Sets whether this window should ignore cursor events and pass them through to any windows behind it. In effect making the window - transparent to the mouse. + transparent to the cursor. \param setting - true if mouse pass through is enabled. - false if mouse pass through is not enabled. + true if cursor pass through is enabled. + false if cursor pass through is not enabled. */ - void setMousePassThroughEnabled(bool setting) {d_mousePassThroughEnabled = setting;} + void setCursorPassThroughEnabled(bool setting) {d_cursorPassThroughEnabled = setting;} /*! \brief @@ -2374,7 +2313,7 @@ class CEGUIEXPORT Window : code is supposed to use skins is by defining a Falagard mapping (either in a scheme xml file or in code) and then create instances of that mapped type via WindowManager. See - WindowFactoryManager::addFalagardWindowMapping and \ref xml_scheme. + WindowFactoryManager::addFalagardWindowMapping and \ref xml_scheme. */ void setWindowRenderer(const String& name); @@ -2532,8 +2471,8 @@ class CEGUIEXPORT Window : //! retrieves currently set margin const UBox& getMargin() const; - //! return Vector2 \a pos after being fully unprojected for this Window. - Vector2f getUnprojectedPosition(const Vector2f& pos) const; + //! return glm::vec2 \a pos after being fully unprojected for this Window. + glm::vec2 getUnprojectedPosition(const glm::vec2& pos) const; //! return the pointer to the BidiVisualMapping for this window, if any. const BidiVisualMapping* getBidiVisualMapping() const @@ -2593,7 +2532,7 @@ class CEGUIEXPORT Window : windows and widgets; updates should be disabled selectively and cautiously - if you are unsure of what you are doing, leave the mode set to WUM_ALWAYS. - + \param mode One of the WindowUpdateMode enumerated values indicating the mode to set for this Window. @@ -2612,7 +2551,7 @@ class CEGUIEXPORT Window : windows and widgets; updates should be disabled selectively and cautiously - if you are unsure of what you are doing, leave the mode set to WUM_ALWAYS. - + \return One of the WindowUpdateMode enumerated values indicating the current mode set for this Window. @@ -2621,27 +2560,19 @@ class CEGUIEXPORT Window : /*! \brief - Set whether mouse input that is not directly handled by this Window + Set whether cursor input that is not directly handled by this Window (including it's event subscribers) should be propagated back to the Window's parent. - - \param enabled - - true if unhandled mouse input should be propagated to the parent. - - false if unhandled mouse input should not be propagated. */ - void setMouseInputPropagationEnabled(const bool enabled); + void setCursorInputPropagationEnabled(const bool enabled); /*! \brief - Return whether mouse input that is not directly handled by this Window + Return whether cursor input that is not directly handled by this Window (including it's event subscribers) should be propagated back to the Window's parent. - - \return - - true if unhandled mouse input will be propagated to the parent. - - false if unhandled mouse input will not be propagated. */ - bool isMouseInputPropagationEnabled() const; + bool isCursorInputPropagationEnabled() const; /*! \brief @@ -2679,19 +2610,55 @@ class CEGUIEXPORT Window : /*! \brief - Return whether Window thinks mouse is currently within its area. + Return whether Window thinks cursor is currently within its area. \note - If the mouse cursor has moved or Window's area has changed since the + If the cursor has moved or Window's area has changed since the last time the GUIContext updated the window hit information, the value returned here may be inaccurate - this is not a bug, but is required to ensure correct handling of certain events. */ - bool isMouseContainedInArea() const; + bool isPointerContainedInArea() const; // overridden from Element const Sizef& getRootContainerSize() const; + /*! + \brief + Return whether this Window is focused or not. + + A window is focused when it is the active Window inside the current + GUIContext. + */ + bool isFocused() const; + + /*! + \brief + Makes this Window be focused. + + Focusing a Window means activating it and setting the focused flag. + This will also trigger the activated event. Focusing works only on + non-disabled widgets. + */ + void focus(); + + /*! + \brief + Unfocus this Window. + + This will trigger the deactivated event if this was an active window. + */ + void unfocus(); + + /*! + \brief + Return whether Window can be focused or not. + + A Window cannot be usually focused when it's disabled. Other widgets + can override this method based on their own behaviour. + */ + virtual bool canFocus(); + protected: // friend classes for construction / initialisation purposes (for now) friend class System; @@ -2722,7 +2689,7 @@ class CEGUIEXPORT Window : 'this'. */ virtual void onMoved(ElementEventArgs& e); - + virtual void onRotated(ElementEventArgs& e); /*! @@ -2862,7 +2829,7 @@ class CEGUIEXPORT Window : /*! \brief - Handler called when this window gains capture of mouse inputs. + Handler called when this window gains capture of cursor inputs. \param e WindowEventArgs object whose 'window' pointer field is set to the window @@ -2873,7 +2840,7 @@ class CEGUIEXPORT Window : /*! \brief - Handler called when this window loses capture of mouse inputs. + Handler called when this window loses capture of cursor inputs. \param e WindowEventArgs object whose 'window' pointer field is set to the window @@ -2993,162 +2960,110 @@ class CEGUIEXPORT Window : /*! \brief - Handler called when the mouse cursor has entered this window's area. + Handler called when the cursor has entered this window's area. \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. */ - virtual void onMouseEntersArea(MouseEventArgs& e); + virtual void onCursorEntersArea(CursorInputEventArgs& e); /*! \brief - Handler called when the mouse cursor has left this window's area. + Handler called when the cursor has left this window's area. \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. */ - virtual void onMouseLeavesArea(MouseEventArgs& e); + virtual void onCursorLeavesArea(CursorInputEventArgs& e); /*! \brief - Handler called when the mouse cursor has entered this window's area and + Handler called when the cursor has entered this window's area and is actually over some part of this windows surface and not, for instance over a child window - even though technically in those cases - the mouse is also within this Window's area, the handler will not be + the cursor is also within this Window's area, the handler will not be called. \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. \see - Window::onMouseEntersArea + Window::onCursorEntersArea */ - virtual void onMouseEnters(MouseEventArgs& e); + virtual void onCursorEnters(CursorInputEventArgs& e); /*! \brief - Handler called when the mouse cursor is no longer over this window's - surface area. This will be called when the mouse is not over a part - of this Window's actual surface - even though technically the mouse is - still within the Window's area, for example if the mouse moves over a + Handler called when the cursor is no longer over this window's + surface area. This will be called when the cursor is not over a part + of this Window's actual surface - even though technically the cursor is + still within the Window's area, for example if the cursor moves over a child window. \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. \see - Window::onMouseLeavesArea + Window::onCursorLeavesArea */ - virtual void onMouseLeaves(MouseEventArgs& e); + virtual void onCursorLeaves(CursorInputEventArgs& e); /*! \brief - Handler called when the mouse cursor has been moved within this window's - area. + Handler called when the cursor has been moved within this window's area. \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. */ - virtual void onMouseMove(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); /*! \brief - Handler called when the mouse wheel (z-axis) position changes within + Handler called when the cursor scroll value changes within this window's area. \param e - MouseEventArgs object. All fields are valid. - */ - virtual void onMouseWheel(MouseEventArgs& e); - - /*! - \brief - Handler called when a mouse button has been depressed within this - window's area. - - \param e - MouseEventArgs object. All fields are valid. - */ - virtual void onMouseButtonDown(MouseEventArgs& e); - - /*! - \brief - Handler called when a mouse button has been released within this - window's area. - - \param e - MouseEventArgs object. All fields are valid. - */ - virtual void onMouseButtonUp(MouseEventArgs& e); - - /*! - \brief - Handler called when a mouse button has been clicked (that is depressed - and then released, within a specified time) within this window's area. - - \param e - MouseEventArgs object. All fields are valid. - */ - virtual void onMouseClicked(MouseEventArgs& e); - - /*! - \brief - Handler called when a mouse button has been double-clicked within this - window's area. - - \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. */ - virtual void onMouseDoubleClicked(MouseEventArgs& e); + virtual void onScroll(CursorInputEventArgs& e); /*! \brief - Handler called when a mouse button has been triple-clicked within this - window's area. + Handler called when a cursor is held pressed within this window's area. \param e - MouseEventArgs object. All fields are valid. + CursorInputEventArgs object. All fields are valid. */ - virtual void onMouseTripleClicked(MouseEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); /*! \brief - Handler called when a key as been depressed while this window has input - focus. + Handler called when a cursor is activated within this window's area. \param e - KeyEventArgs object whose 'scancode' field is set to the Key::Scan value - representing the key that was pressed, and whose 'sysKeys' field - represents the combination of SystemKey that were active when the event - was generated. + CursorInputEventArgs object. All fields are valid. */ - virtual void onKeyDown(KeyEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); /*! \brief - Handler called when a key as been released while this window has input - focus. + Handler called when a character has been injected while this window + has input focus. \param e - KeyEventArgs object whose 'scancode' field is set to the Key::Scan value - representing the key that was released, and whose 'sysKeys' field - represents the combination of SystemKey that were active when the event - was generated. All other fields should be considered as 'junk'. + TextEventArgs object whose 'character' field is set to the Unicode code + point (encoded as utf32) for the character inputted. */ - virtual void onKeyUp(KeyEventArgs& e); + virtual void onCharacter(TextEventArgs& e); /*! \brief - Handler called when a character-key has been pressed while this window - has input focus. + Handler called when a semantic input event occurred \param e - KeyEventArgs object whose 'codepoint' field is set to the Unicode code - point (encoded as utf32) for the character typed, and whose 'sysKeys' - field represents the combination of SystemKey that were active when the - event was generated. All other fields should be considered as 'junk'. + The semantic input event */ - virtual void onCharacter(KeyEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); /*! \brief @@ -3275,6 +3190,12 @@ class CEGUIEXPORT Window : */ void queueGeometry(const RenderingContext& ctx); + /*! + \brief + Destroys the geometry buffers of this Window. + */ + void destroyGeometryBuffers(); + /*! \brief Update the rendering cache. @@ -3298,9 +3219,22 @@ class CEGUIEXPORT Window : /*! \brief - Fires off a repeated mouse button down event for this window. + Fires off a repeated cursor press event for this window. + Update position and clip region on this Windows geometry / rendering + surface. */ - void generateAutoRepeatEvent(MouseButton button); + void updateGeometryBuffersTranslationAndClipping(); + + /*! + \brief + Updates this Window's geometry buffers alpha value + */ + void updateGeometryBuffersAlpha(); + + /*! + \brief + */ + void generateAutoRepeatEvent(CursorInputSource source); /*! \brief @@ -3341,7 +3275,7 @@ class CEGUIEXPORT Window : //! \copydoc Element::setArea_impl virtual void setArea_impl(const UVector2& pos, const USize& size, bool topLeftSizing = false, bool fireEvents = true); - + /*! \brief Cleanup child windows @@ -3413,7 +3347,7 @@ class CEGUIEXPORT Window : Nothing. */ void removeWindowFromDrawList(const Window& wnd); - + /*! \brief Return whether the window is at the top of the Z-Order. This will @@ -3458,7 +3392,7 @@ class CEGUIEXPORT Window : virtual Rectf getInnerRectClipper_impl() const; //! Default implementation of function to return Window hit-test area. virtual Rectf getHitTestRect_impl() const; - + virtual int writePropertiesXML(XMLSerializer& xml_stream) const; virtual int writeChildWindowsXML(XMLSerializer& xml_stream) const; virtual bool writeAutoChildWindowXML(XMLSerializer& xml_stream) const; @@ -3472,11 +3406,11 @@ class CEGUIEXPORT Window : void markCachedWindowRectsInvalid(); void layoutLookNFeelChildWidgets(); - Window* getChildAtPosition(const Vector2f& position, - bool (Window::*hittestfunc)(const Vector2f&, bool) const, + Window* getChildAtPosition(const glm::vec2& position, + bool (Window::*hittestfunc)(const glm::vec2&, bool) const, bool allow_disabled = false) const; - bool isHitTargetWindow(const Vector2f& position, bool allow_disabled) const; + bool isHitTargetWindow(const glm::vec2& position, bool allow_disabled) const; /************************************************************************* Properties for Window base class @@ -3526,14 +3460,11 @@ class CEGUIEXPORT Window : Implementation Data *************************************************************************/ //! definition of type used for the list of child windows to be drawn - typedef std::vector ChildDrawList; + typedef std::vector ChildDrawList; //! definition of type used for the UserString dictionary. - typedef std::map UserStringMap; + typedef std::map UserStringMap; //! definition of type used to track properties banned from writing XML. - typedef std::set BannedXMLPropertySet; + typedef std::set BannedXMLPropertySet; //! type of Window (also the name of the WindowFactory that created us) const String d_type; @@ -3565,8 +3496,8 @@ class CEGUIEXPORT Window : String d_lookName; //! The WindowRenderer module that implements the Look'N'Feel specification WindowRenderer* d_windowRenderer; - //! Object which acts as a cache of geometry drawn by this Window. - GeometryBuffer* d_geometry; + //! List of geometry buffers that cache the geometry drawn by this Window. + std::vector d_geometryBuffers; //! RenderingSurface owned by this window (may be 0) RenderingSurface* d_surface; //! true if window geometry cache needs to be regenerated. @@ -3574,8 +3505,8 @@ class CEGUIEXPORT Window : //! holds setting for automatic creation of of surface (RenderingWindow) bool d_autoRenderingWindow; - //! Holds pointer to the Window objects current mouse cursor image. - const Image* d_mouseCursor; + //! Holds pointer to the Window objects current cursor image. + const Image* d_cursor; //! Alpha transparency setting for the Window float d_alpha; @@ -3622,23 +3553,21 @@ class CEGUIEXPORT Window : //! true if Window will be drawn on top of all other Windows bool d_alwaysOnTop; - //! whether window should rise in the z order when left clicked. - bool d_riseOnClick; + //! whether window should rise in the z order when left cursor source is activated. + bool d_riseOnPointerActivation; //! true if the Window responds to z-order change requests. bool d_zOrderingEnabled; - //! true if the Window wishes to hear about multi-click mouse events. - bool d_wantsMultiClicks; - //! whether (most) mouse events pass through this window - bool d_mousePassThroughEnabled; - //! whether pressed mouse button will auto-repeat the down event. + //! whether (most) cursor events pass through this window + bool d_cursorPassThroughEnabled; + //! whether pressed cursor will auto-repeat the down event. bool d_autoRepeat; //! seconds before first repeat event is fired float d_repeatDelay; //! seconds between further repeats after delay has expired. float d_repeatRate; - //! button we're tracking for auto-repeat purposes. - MouseButton d_repeatButton; + //! Cursor source we're tracking for auto-repeat purposes. + CursorInputSource d_repeatPointerSource; //! implements repeating - is true after delay has elapsed, bool d_repeating; //! implements repeating - tracks time elapsed. @@ -3675,14 +3604,22 @@ class CEGUIEXPORT Window : //! The mode to use for calling Window::update WindowUpdateMode d_updateMode; - //! specifies whether mouse inputs should be propagated to parent(s) - bool d_propagateMouseInputs; + //! specifies whether cursor inputs should be propagated to parent(s) + bool d_propagatePointerInputs; //! GUIContext. Set when this window is used as a root window. GUIContext* d_guiContext; - //! true when mouse is contained within this Window's area. - bool d_containsMouse; + //! true when cursor is contained within this Window's area. + bool d_containsPointer; + + //! The translation which was set for this window. + glm::vec3 d_translation; + //! true when this window is focused. + bool d_isFocused; + + //! The clipping region which was set for this window. + Rectf d_clippingRegion; private: /************************************************************************* @@ -3693,8 +3630,8 @@ class CEGUIEXPORT Window : //! Not intended for public use, only used as a "Font" property getter const Font* property_getFont() const; - //! Not intended for public use, only used as a "MouseCursor" property getter - const Image* property_getMouseCursor() const; + //! Not intended for public use, only used as a "Cursor" property getter + const Image* property_getCursor() const; //! connection for event listener for font render size changes. Event::ScopedConnection d_fontRenderSizeChangeConnection; diff --git a/cegui/include/CEGUI/WindowFactory.h b/cegui/include/CEGUI/WindowFactory.h index 143ee793b..ef621e371 100644 --- a/cegui/include/CEGUI/WindowFactory.h +++ b/cegui/include/CEGUI/WindowFactory.h @@ -59,11 +59,11 @@ T ## Factory() : WindowFactory( T::WidgetTypeName ) {}\ Window* createWindow(const String& name)\ {\ - return CEGUI_NEW_AO T(d_type, name);\ + return new T(d_type, name);\ }\ void destroyWindow(Window* window)\ {\ - CEGUI_DELETE_AO window;\ + delete window;\ }\ };\ T ## Factory& get ## T ## Factory(); @@ -112,8 +112,7 @@ namespace CEGUI CEGUI::WindowFactoryManager::addFactory >(); \endcode */ -class CEGUIEXPORT WindowFactory : - public AllocatedObject +class CEGUIEXPORT WindowFactory { public: /*! diff --git a/cegui/include/CEGUI/WindowFactoryManager.h b/cegui/include/CEGUI/WindowFactoryManager.h index 44c632ac8..1dc070344 100644 --- a/cegui/include/CEGUI/WindowFactoryManager.h +++ b/cegui/include/CEGUI/WindowFactoryManager.h @@ -59,8 +59,7 @@ namespace CEGUI with the window renderers and all. */ class CEGUIEXPORT WindowFactoryManager : - public Singleton, - public AllocatedObject + public Singleton { public: /*! @@ -119,8 +118,7 @@ class CEGUIEXPORT WindowFactoryManager : private: friend class WindowFactoryManager; - typedef std::vector TargetTypeStack; //!< Type used to implement stack of target type names. + typedef std::vector TargetTypeStack; //!< Type used to implement stack of target type names. TargetTypeStack d_targetStack; //!< Container holding the target types. }; @@ -457,15 +455,11 @@ class CEGUIEXPORT WindowFactoryManager : /************************************************************************* Implementation Data *************************************************************************/ - typedef std::map WindowFactoryRegistry; //!< Type used to implement registry of WindowFactory objects - typedef std::map TypeAliasRegistry; //!< Type used to implement registry of window type aliases. - typedef std::map FalagardMapRegistry; //!< Type used to implement registry of falagard window mappings. + typedef std::map WindowFactoryRegistry; //!< Type used to implement registry of WindowFactory objects + typedef std::map TypeAliasRegistry; //!< Type used to implement registry of window type aliases. + typedef std::map FalagardMapRegistry; //!< Type used to implement registry of falagard window mappings. //! Type used for list of WindowFacory objects that we created ourselves - typedef std::vector OwnedWindowFactoryList; + typedef std::vector OwnedWindowFactoryList; WindowFactoryRegistry d_factoryRegistry; //!< The container that forms the WindowFactory registry TypeAliasRegistry d_aliasRegistry; //!< The container that forms the window type alias registry. @@ -507,7 +501,7 @@ template void WindowFactoryManager::addFactory() { // create the factory object - WindowFactory* factory = CEGUI_NEW_AO T; + WindowFactory* factory = new T; // only do the actual add now if our singleton has already been created if (WindowFactoryManager::getSingletonPtr()) @@ -526,7 +520,7 @@ void WindowFactoryManager::addFactory() factory->getTypeName() + "' windows."); // delete the factory object - CEGUI_DELETE_AO factory; + delete factory; CEGUI_RETHROW; } } diff --git a/cegui/include/CEGUI/WindowManager.h b/cegui/include/CEGUI/WindowManager.h index e2977740d..a398ab8c0 100644 --- a/cegui/include/CEGUI/WindowManager.h +++ b/cegui/include/CEGUI/WindowManager.h @@ -58,8 +58,7 @@ namespace CEGUI used to access those Window objects by name. */ class CEGUIEXPORT WindowManager : public Singleton, - public EventSet, - public AllocatedObject + public EventSet { public: /************************************************************************* @@ -406,8 +405,7 @@ class CEGUIEXPORT WindowManager : public Singleton, /************************************************************************* Implementation Data *************************************************************************/ - typedef std::vector WindowVector; //!< Type to use for a collection of Window pointers. + typedef std::vector WindowVector; //!< Type to use for a collection of Window pointers. //! collection of created windows. WindowVector d_windowRegistry; diff --git a/cegui/include/CEGUI/WindowNavigator.h b/cegui/include/CEGUI/WindowNavigator.h new file mode 100644 index 000000000..6d478de71 --- /dev/null +++ b/cegui/include/CEGUI/WindowNavigator.h @@ -0,0 +1,136 @@ +/*********************************************************************** + created: 12/08/2013 + author: Timotei Dolean + + purpose: Implements the ability to navigate in the GUI +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIWindowNavigator_h_ +#define _CEGUIWindowNavigator_h_ + +#include +#include "CEGUI/String.h" +#include "CEGUI/SemanticInputEvent.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ + +/*! +\brief + Provides a strategy for navigating the GUI based on a specified mapping. + + For a brief tutorial on how to use the GUI navigation please refer + to the @ref gui_navigation_tutorial +*/ +class CEGUIEXPORT NavigationStrategy +{ +public: + virtual ~NavigationStrategy() {} + + /*! + \brief + Returns a window based on its neighbour and a certain payload + + \param neighbour + The neighbour window relative to which the new window is requested + + \param payload + A string payload value to help decide what window to return + */ + virtual Window* getWindow(Window* neighbour, const String& payload) = 0; +}; + +/*! +\brief + Provides a way of navigating the GUI by means of focusing windows + + For a brief tutorial on how to use the GUI navigation please refer + to the @ref gui_navigation_tutorial +*/ +class CEGUIEXPORT WindowNavigator +{ +public: + typedef std::map SemanticMappingsMap; + ~WindowNavigator() {} + + /*! + \brief + Creates a new navigator with the specified event <-> payload mapping and + the specified strategy + + \param mapping + A mapping from semantic input events to certain strategy-specific payloads + + \param strategy + The navigation strategy to be used + */ + WindowNavigator(SemanticMappingsMap mappings, NavigationStrategy* strategy); + + /*! + \brief + Handles the specified semantic input event and generate a navigation if + that is the case (a mapping matches) + + \param event + The semantic input event + */ + void handleSemanticEvent(const SemanticInputEvent& event); + + /*! + \brief + Sets a new current focused window + + \param window + The window to be the new focused one + */ + void setCurrentFocusedWindow(Window* window); + + /*! + \brief + Gets the current focused window + + \return + An instance of Window + */ + Window* getCurrentFocusedWindow(); + +private: + SemanticMappingsMap d_mappings; + NavigationStrategy* d_strategy; + + Window* d_currentFocusedWindow; +}; + +} + +#if defined (_MSC_VER) +# pragma warning(pop) +#endif + +#endif // end of guard _CEGUIWindowNavigator_h_ diff --git a/cegui/include/CEGUI/WindowRenderer.h b/cegui/include/CEGUI/WindowRenderer.h index fa879e28b..477f02ccf 100644 --- a/cegui/include/CEGUI/WindowRenderer.h +++ b/cegui/include/CEGUI/WindowRenderer.h @@ -47,8 +47,7 @@ namespace CEGUI \brief Base-class for the assignable WindowRenderer object */ -class CEGUIEXPORT WindowRenderer : - public AllocatedObject +class CEGUIEXPORT WindowRenderer { public: /************************************************************************* @@ -139,7 +138,7 @@ class CEGUIEXPORT WindowRenderer : Perform any updates needed because the given font's render size has changed. - /note + \note This base implementation deals with updates needed for various definitions in the assigned widget look. If you override, you should generally always call this base class implementation. @@ -218,8 +217,7 @@ class CEGUIEXPORT WindowRenderer : //! type used for entries in the PropertyList. typedef std::pair PropertyEntry; //! type to use for the property list. - typedef std::vector PropertyList; + typedef std::vector PropertyList; PropertyList d_properties; //!< The list of properties that this windowrenderer will be handling. // Window is friend so it can manipulate our 'd_window' member directly. diff --git a/cegui/include/CEGUI/WindowRendererManager.h b/cegui/include/CEGUI/WindowRendererManager.h index dd8ec93ac..49530a463 100644 --- a/cegui/include/CEGUI/WindowRendererManager.h +++ b/cegui/include/CEGUI/WindowRendererManager.h @@ -46,8 +46,7 @@ namespace CEGUI { class CEGUIEXPORT WindowRendererManager : - public Singleton, - public AllocatedObject + public Singleton { public: /************************************************************************* @@ -125,8 +124,7 @@ class CEGUIEXPORT WindowRendererManager : WR_Registry d_wrReg; //! Container type to hold WindowRenderFacory objects that we created. - typedef std::vector OwnedFactoryList; + typedef std::vector OwnedFactoryList; //! Container that tracks WindowFactory objects we created ourselves. static OwnedFactoryList d_ownedFactories; }; @@ -136,7 +134,7 @@ template void WindowRendererManager::addFactory() { // create the factory object - WindowRendererFactory* factory = CEGUI_NEW_AO T; + WindowRendererFactory* factory = new T; // only do the actual add now if our singleton has already been created if (WindowRendererManager::getSingletonPtr()) @@ -155,7 +153,7 @@ void WindowRendererManager::addFactory() "'" + factory->getName() + "' WindowRenderers."); // delete the factory object - CEGUI_DELETE_AO factory; + delete factory; CEGUI_RETHROW; } } diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/Button.h b/cegui/include/CEGUI/WindowRendererSets/Core/Button.h index b4fe69582..01e064e18 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/Button.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/Button.h @@ -40,10 +40,10 @@ namespace CEGUI This class requires LookNFeel to be assigned. The LookNFeel should provide the following: States (missing states will default to 'Normal'): - - Normal - Rendering for when the button is neither pushed or has the mouse hovering over it. - - Hover - Rendering for then the button has the mouse hovering over it. - - Pushed - Rendering for when the button is pushed and mouse is over it. - - PushedOff - Rendering for when the button is pushed and mouse is not over it. + - Normal - Rendering for when the button is neither pushed or has the cursor hovering over it. + - Hover - Rendering for then the button has the cursor hovering over it. + - Pushed - Rendering for when the button is pushed and cursor is over it. + - PushedOff - Rendering for when the button is pushed and cursor is not over it. - Disabled - Rendering for when the button is disabled. */ class COREWRSET_API FalagardButton : public WindowRenderer diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/Editbox.h b/cegui/include/CEGUI/WindowRendererSets/Core/Editbox.h index aaff04088..b84fa56d1 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/Editbox.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/Editbox.h @@ -48,8 +48,12 @@ namespace CEGUI States: - Enabled: Rendering for when the editbox is in enabled and is in read-write mode. + - EnabledFocused: Rendering for when the editbox is focused and is in + read-write mode. - ReadOnly: Rendering for when the editbox is in enabled and is in read-only mode. + - ReadOnlyFocused: Rendering for when the editbox is focused and is in + read-only mode. - Disabled: Rendering for when the editbox is disabled. - ActiveSelection: additional state rendered for text selection (the imagery in this section is rendered within the @@ -146,7 +150,7 @@ class COREWRSET_API FalagardEditbox : public EditboxWindowRenderer void render(); // overridden from EditboxWindowRenderer base class. - size_t getTextIndexFromPosition(const Vector2f& pt) const; + size_t getTextIndexFromPosition(const glm::vec2& pt) const; // overridden from WindowRenderer class void update(float elapsed); bool handleFontRenderSizeChange(const Font* const font); diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/ItemListbox.h b/cegui/include/CEGUI/WindowRendererSets/Core/ItemListbox.h deleted file mode 100644 index 80b9da491..000000000 --- a/cegui/include/CEGUI/WindowRendererSets/Core/ItemListbox.h +++ /dev/null @@ -1,88 +0,0 @@ -/************************************************************************ - created: Mon Mar 20 2006 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _FalItemListbox_h_ -#define _FalItemListbox_h_ - -#include "CEGUI/WindowRendererSets/Core/Module.h" -#include "CEGUI/widgets/ItemListBase.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ - /*! - \brief - ItemListbox class for the FalagardBase module. - - This class requires LookNFeel to be assigned. The LookNFeel should provide the following: - - States: - - Enabled - - Disabled - - Named Areas: - - ItemRenderArea - - ItemRenderAreaHScroll - - ItemRenderAreaVScroll - - ItemRenderAreaHVScroll - - - OR - - - ItemRenderingArea - - ItemRenderingAreaHScroll - - ItemRenderingAreaVScroll - - ItemRenderingAreaHVScroll - */ - class COREWRSET_API FalagardItemListbox : public ItemListBaseWindowRenderer - { - public: - static const String TypeName; //!< type name for this widget. - - /*! - \brief - Constructor - */ - FalagardItemListbox(const String& type); - - // overridden from ItemListBaseWindowRenderer base class. - void render(); - Rectf getItemRenderArea(void) const; - // overridden from WindowRenderer base class. - Rectf getUnclippedInnerRect() const; - - protected: - Rectf getItemRenderingArea(bool hscroll, bool vscroll) const; - - // overridden from WindowRenderer base class. - void onLookNFeelAssigned(); - void onLookNFeelUnassigned(); - - //! flag whether target window has looknfeel assigned yet. - bool d_widgetLookAssigned; - - }; - -} // End of CEGUI namespace section - -#endif // end of guard _FalItemListbox_h_ diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/ItemViewRenderer.h b/cegui/include/CEGUI/WindowRendererSets/Core/ItemViewRenderer.h new file mode 100644 index 000000000..ad5c670a2 --- /dev/null +++ b/cegui/include/CEGUI/WindowRendererSets/Core/ItemViewRenderer.h @@ -0,0 +1,59 @@ +/*********************************************************************** + created: Mon Jun 02 2014 + author: Timotei Dolean + purpose: Contains common rendering-related routines +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _FalItemViewRenderer_h_ +#define _FalItemViewRenderer_h_ + +#include "CEGUI/WindowRendererSets/Core/Module.h" +#include "CEGUI/views/ItemView.h" +#include "CEGUI/Rect.h" + +namespace CEGUI +{ + +/*! +\brief + Base class that contains common routines for view renderers. +*/ +class COREWRSET_API ItemViewRenderer +{ +public: + virtual ~ItemViewRenderer(); + +protected: + virtual Rectf getViewRenderArea(const ItemView* renderer) const; + Rectf getViewRenderArea(const ItemView* renderer, + bool hscroll, bool vscroll) const; + glm::vec2 getItemRenderStartPosition(ItemView* view, const Rectf& items_area) const; + void renderString(ItemView* view, RenderedString& rendered_string, + Rectf draw_rect, const Font* font, const Rectf* item_clipper, bool is_selected); + void resizeViewToContent(ItemView* view, bool fit_width, bool fit_height) const; +}; + +} + +#endif diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/ListView.h b/cegui/include/CEGUI/WindowRendererSets/Core/ListView.h new file mode 100644 index 000000000..675f50792 --- /dev/null +++ b/cegui/include/CEGUI/WindowRendererSets/Core/ListView.h @@ -0,0 +1,92 @@ +/*********************************************************************** + created: Mon May 26 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _FalListView_h_ +#define _FalListView_h_ + +#include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h" +#include "CEGUI/views/ListView.h" + +namespace CEGUI +{ + +/*! +\brief + ListView class for the FalagardBase module. + + This class requires LookNFeel to be assigned. + The LookNFeel should provide the following: + + States: + - Enabled + - Disabled + + Named Areas: + - ItemRenderingArea + - ItemRenderingAreaHScroll + - ItemRenderingAreaVScroll + - ItemRenderingAreaHVScroll + + OR + + - ItemRenderArea + - ItemRenderAreaHScroll + - ItemRenderAreaVScroll + - ItemRenderAreaHVScroll + + Child Widgets: + Scrollbar based widget with name suffix "__auto_vscrollbar__" + Scrollbar based widget with name suffix "__auto_hscrollbar__" +*/ +class COREWRSET_API FalagardListView : + public ItemViewWindowRenderer, + public ItemViewRenderer +{ +public: + //! Type name for this widget. + static const String TypeName; + + /*! + \brief + Constructor for the ListView Falagard class. + + \param type + The name of this renderer's factory. + */ + FalagardListView(const String& type); + + void render(); + + virtual Rectf getViewRenderArea(void) const; + virtual void resizeViewToContent(bool fit_width, bool fit_height) const; + +private: + void render(ListView* list_view); +}; + +} + +#endif diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/Listbox.h b/cegui/include/CEGUI/WindowRendererSets/Core/Listbox.h deleted file mode 100644 index 98b4955c0..000000000 --- a/cegui/include/CEGUI/WindowRendererSets/Core/Listbox.h +++ /dev/null @@ -1,100 +0,0 @@ -/*********************************************************************** - created: Mon Jul 4 2005 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _FalListbox_h_ -#define _FalListbox_h_ - -#include "CEGUI/WindowRendererSets/Core/Module.h" -#include "CEGUI/widgets/Listbox.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ - /*! - \brief - Listbox class for the FalagardBase module. - - This class requires LookNFeel to be assigned. The LookNFeel should provide the following: - - States: - - Enabled - - Disabled - - Named Areas: - - ItemRenderingArea - - ItemRenderingAreaHScroll - - ItemRenderingAreaVScroll - - ItemRenderingAreaHVScroll - - - OR - - - ItemRenderArea - - ItemRenderAreaHScroll - - ItemRenderAreaVScroll - - ItemRenderAreaHVScroll - - Child Widgets: - Scrollbar based widget with name suffix "__auto_vscrollbar__" - Scrollbar based widget with name suffix "__auto_hscrollbar__" - */ - class COREWRSET_API FalagardListbox : public ListboxWindowRenderer - { - public: - static const String TypeName; //!< type name for this widget. - - /*! - \brief - Constructor - */ - FalagardListbox(const String& type); - - /*! - \brief - Perform caching of the widget control frame and other 'static' areas. This - method should not render the actual items. Note that the items are typically - rendered to layer 3, other layers can be used for rendering imagery behind and - infront of the items. - - \return - Nothing. - */ - void cacheListboxBaseImagery(); - - // overriden from ListboxWindowRenderer - void render(); - - Rectf getListRenderArea(void) const; - - void resizeListToContent(bool fit_width, - bool fit_height) const; - - bool handleFontRenderSizeChange(const Font* const font); - - protected: - Rectf getItemRenderingArea(bool hscroll, bool vscroll) const; - }; -} // End of CEGUI namespace section - - -#endif // end of guard _FalListbox_h_ diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/MultiColumnList.h b/cegui/include/CEGUI/WindowRendererSets/Core/MultiColumnList.h index dd8e3f250..91013deee 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/MultiColumnList.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/MultiColumnList.h @@ -42,6 +42,7 @@ namespace CEGUI States: - Enabled + - EnabledFocused - Disabled Named Areas: diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/MultiLineEditbox.h b/cegui/include/CEGUI/WindowRendererSets/Core/MultiLineEditbox.h index d9518ae6b..db6bae79a 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/MultiLineEditbox.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/MultiLineEditbox.h @@ -45,9 +45,11 @@ namespace CEGUI This class requires LookNFeel to be assigned. The LookNFeel should provide the following: States: - - Enabled - Rendering for when the editbox is in enabled and is in read-write mode. - - ReadOnly - Rendering for when the editbox is in enabled and is in read-only mode. - - Disabled - Rendering for when the editbox is disabled. + - Enabled - Rendering for when the editbox is in enabled and is in read-write mode. + - EnabledFocused - Rendering for when the editbox is focused and is in read-write mode. + - ReadOnly - Rendering for when the editbox is in enabled and is in read-only mode. + - ReadOnlyFocused - Rendering for when the editbox is focused and is in read-only mode. + - Disabled - Rendering for when the editbox is disabled. NamedAreas: TextArea - area where text, selection, and caret imagery will appear. diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/Scrollbar.h b/cegui/include/CEGUI/WindowRendererSets/Core/Scrollbar.h index aafabbdef..4448b1323 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/Scrollbar.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/Scrollbar.h @@ -85,7 +85,7 @@ namespace CEGUI // overridden from Scrollbar base class. void updateThumb(void); float getValueFromThumb(void) const; - float getAdjustDirectionFromPoint(const Vector2f& pt) const; + float getAdjustDirectionFromPoint(const glm::vec2& pt) const; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/Slider.h b/cegui/include/CEGUI/WindowRendererSets/Core/Slider.h index 052498b5b..ce1731bf4 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/Slider.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/Slider.h @@ -46,6 +46,7 @@ namespace CEGUI States: - Enabled + - EnabledFocused - Disabled Named Areas: @@ -87,7 +88,7 @@ namespace CEGUI // overridden from Slider base class. void updateThumb(void); float getValueFromThumb(void) const; - float getAdjustDirectionFromPoint(const Vector2f& pt) const; + float getAdjustDirectionFromPoint(const glm::vec2& pt) const; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/StaticText.h b/cegui/include/CEGUI/WindowRendererSets/Core/StaticText.h index c4555ee7c..43367f395 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/StaticText.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/StaticText.h @@ -186,7 +186,7 @@ namespace CEGUI bool onTextChanged(const EventArgs& e); bool onSized(const EventArgs& e); bool onFontChanged(const EventArgs& e); - bool onMouseWheel(const EventArgs& e); + bool onScroll(const EventArgs& e); // event subscribers bool handleScrollbarChange(const EventArgs& e); diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/TabButton.h b/cegui/include/CEGUI/WindowRendererSets/Core/TabButton.h index ee66461b8..d0ec0989f 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/TabButton.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/TabButton.h @@ -39,8 +39,8 @@ namespace CEGUI This class requires LookNFeel to be assigned. The LookNFeel should provide the following: States (missing states will default to 'Normal'): - - Normal - Rendering for when the tab button is neither selected nor has the mouse hovering over it. - - Hover - Rendering for then the tab button has the mouse hovering over it. + - Normal - Rendering for when the tab button is neither selected nor has the cursor hovering over it. + - Hover - Rendering for then the tab button has the cursor hovering over it. - Selected - Rendering for when the tab button is the button for the selected tab. - Disabled - Rendering for when the tab button is disabled. */ diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/ToggleButton.h b/cegui/include/CEGUI/WindowRendererSets/Core/ToggleButton.h index 275c623ed..174e605fc 100644 --- a/cegui/include/CEGUI/WindowRendererSets/Core/ToggleButton.h +++ b/cegui/include/CEGUI/WindowRendererSets/Core/ToggleButton.h @@ -40,15 +40,17 @@ namespace CEGUI This class requires LookNFeel to be assigned. The LookNFeel should provide the following: States (missing states will default to 'Normal' or 'SelectedNormal' if selected) - - Normal - Rendering for when the togglebutton is neither pushed or has the mouse hovering over it. - - Hover - Rendering for then the togglebutton has the mouse hovering over it. - - Pushed - Rendering for when the togglebutton is not selected, is pushed and has the mouse over it. - - PushedOff - Rendering for when the togglebutton is not selected, is pushed and the mouse is not over it. + - Normal - Rendering for when the togglebutton is neither pushed or has the cursor hovering over it. + - Hover - Rendering for when the togglebutton has the cursor hovering over it. + - Focused - Rendering for when the togglebutton is focused. + - Pushed - Rendering for when the togglebutton is not selected, is pushed and has the cursor over it. + - PushedOff - Rendering for when the togglebutton is not selected, is pushed and the cursor is not over it. - Disabled - Rendering for when the togglebutton is not selected and is disabled. - - SelectedNormal - Rendering for when the togglebutton is selected and is neither pushed or has the mouse hovering over it. - - SelectedHover - Rendering for then the togglebutton is selected and has the mouse hovering over it. - - SelectedPushed - Rendering for when the togglebutton is selected, is pushed and has the mouse over it. - - SelectedPushedOff - Rendering for when the togglebutton is selected, is pushed and the mouse is not over it. + - SelectedNormal - Rendering for when the togglebutton is selected and is neither pushed or has the cursor hovering over it. + - SelectedHover - Rendering for then the togglebutton is selected and has the cursor hovering over it. + - SelectedFocused - Rendering for then the togglebutton is selected and it is focused. + - SelectedPushed - Rendering for when the togglebutton is selected, is pushed and has the cursor over it. + - SelectedPushedOff - Rendering for when the togglebutton is selected, is pushed and the cursor is not over it. - SelectedDisabled - Rendering for when the togglebutton is selected and is disabled. */ class COREWRSET_API FalagardToggleButton : public FalagardButton diff --git a/cegui/include/CEGUI/WindowRendererSets/Core/TreeView.h b/cegui/include/CEGUI/WindowRendererSets/Core/TreeView.h new file mode 100644 index 000000000..80ed8c870 --- /dev/null +++ b/cegui/include/CEGUI/WindowRendererSets/Core/TreeView.h @@ -0,0 +1,116 @@ +/*********************************************************************** + created: Fri Jun 06 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _FalTreeView_h_ +#define _FalTreeView_h_ + +#include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h" +#include "CEGUI/views/TreeView.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ + +/*! +\brief + TreeView class for the FalagardBase module. + + This class requires LookNFeel to be assigned. + The LookNFeel should provide the following: + + States: + - Enabled + - Disabled + + Named Areas: + - ItemRenderingArea + - ItemRenderingAreaHScroll + - ItemRenderingAreaVScroll + - ItemRenderingAreaHVScroll + + OR + + - ItemRenderArea + - ItemRenderAreaHScroll + - ItemRenderAreaVScroll + - ItemRenderAreaHVScroll + + Imagery sections: + - SubtreeExpander (shown when the subtree is collapsed) + - SubtreeCollapser (shown when the subtree is expanded) + + Child Widgets: + Scrollbar based widget with name suffix "__auto_vscrollbar__" + Scrollbar based widget with name suffix "__auto_hscrollbar__" +*/ +class COREWRSET_API FalagardTreeView : + public TreeViewWindowRenderer, + public ItemViewRenderer +{ +public: + //! Type name for this widget. + static const String TypeName; + /*! + \brief + Constructor for the TreeView Falagard class. + + \param type + The name of this renderer's factory. + */ + FalagardTreeView(const String& type); + + void render(); + + virtual Sizef getSubtreeExpanderSize(void) const; + virtual float getSubtreeExpanderXIndent(int depth) const; + virtual Rectf getViewRenderArea(void) const; + inline TreeView* getView() const; + virtual void resizeViewToContent(bool fit_width, bool fit_height) const; + +protected: + virtual void onLookNFeelAssigned(); + +private: + void renderTreeItem(TreeView* tree_view, const Rectf& items_area, + glm::vec2& item_pos, const TreeViewItemRenderingState* item_to_render, + size_t depth); + + const ImagerySection* d_subtreeExpanderImagery; + const ImagerySection* d_subtreeCollapserImagery; + Sizef d_subtreeExpanderImagerySize; +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/XMLAttributes.h b/cegui/include/CEGUI/XMLAttributes.h index dc4437122..d4b0c0d00 100644 --- a/cegui/include/CEGUI/XMLAttributes.h +++ b/cegui/include/CEGUI/XMLAttributes.h @@ -43,8 +43,7 @@ namespace CEGUI \brief Class representing a block of attributes associated with an XML element. */ - class CEGUIEXPORT XMLAttributes : - public AllocatedObject + class CEGUIEXPORT XMLAttributes { public: /*! diff --git a/cegui/include/CEGUI/XMLParser.h b/cegui/include/CEGUI/XMLParser.h index dd0c703eb..55eedf878 100644 --- a/cegui/include/CEGUI/XMLParser.h +++ b/cegui/include/CEGUI/XMLParser.h @@ -39,8 +39,7 @@ namespace CEGUI This is an abstract class that is used by CEGUI to interface with XML parser libraries. */ class CEGUIEXPORT XMLParser : - public PropertySet, - public AllocatedObject + public PropertySet { public: /*! @@ -94,10 +93,15 @@ namespace CEGUI String object holding the name of the XML schema file to use for validating the XML. Note that whether this is used or not is dependant upon the XMLParser in use. + \param allowXmlValidation + A boolean object used for disallowing xml validation for a single call, + defaulting to "true" to allow validation. + Only needed if xml validation should be disallowed once. + \return Nothing. */ - virtual void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName) = 0; + virtual void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool allowXmlValidation = true) = 0; /*! \brief @@ -117,10 +121,15 @@ namespace CEGUI String object holding the resource group identifier which will be passed to the ResourceProvider when loading the XML and schema files. + \param allowXmlValidation + A boolean object used for disallowing xml validation for a single call, + defaulting to "true" to allow validation. + Only needed if xml validation should be disallowed once. + \return Nothing. */ - virtual void parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup); + virtual void parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup, bool allowXmlValidation = true); /*! \brief @@ -132,14 +141,15 @@ namespace CEGUI \param source The XML source passed as a String - \param schemaName - String object holding the name of the XML schema file to use for validating the XML. - Note that whether this is used or not is dependant upon the XMLParser in use. + \param allowXmlValidation + A boolean object used for disallowing xml validation for a single call, + defaulting to "true" to allow validation. + Only needed if xml validation should be disallowed once. \return Nothing. */ - virtual void parseXMLString(XMLHandler& handler, const String& source, const String& schemaName); + virtual void parseXMLString(XMLHandler& handler, const String& source, const String& schemaName, bool allowXmlValidation = true); /*! \brief diff --git a/cegui/include/CEGUI/XMLParserModules/Expat/XMLParser.h b/cegui/include/CEGUI/XMLParserModules/Expat/XMLParser.h index 9d6fd4bd3..a9fbc105a 100644 --- a/cegui/include/CEGUI/XMLParserModules/Expat/XMLParser.h +++ b/cegui/include/CEGUI/XMLParserModules/Expat/XMLParser.h @@ -54,7 +54,7 @@ class CEGUIEXPATPARSER_API ExpatParser : public XMLParser ~ExpatParser(void); // Implementation of public abstract interface - void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName); + void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool /*allowXmlValidation*/); protected: // Implementation of protected abstract interface. diff --git a/cegui/include/CEGUI/XMLParserModules/Libxml2/XMLParser.h b/cegui/include/CEGUI/XMLParserModules/Libxml2/XMLParser.h index 174953336..802105f5f 100644 --- a/cegui/include/CEGUI/XMLParserModules/Libxml2/XMLParser.h +++ b/cegui/include/CEGUI/XMLParserModules/Libxml2/XMLParser.h @@ -53,7 +53,7 @@ class CEGUILIBXMLPARSER_API LibxmlParser : public XMLParser ~LibxmlParser(void); // implementation of abstract members of base class - void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName); + void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool /*allowXmlValidation*/); protected: // implementation of abstract members of base class diff --git a/cegui/include/CEGUI/XMLParserModules/RapidXML/XMLParser.h b/cegui/include/CEGUI/XMLParserModules/RapidXML/XMLParser.h index 19dc16fce..19a294cba 100644 --- a/cegui/include/CEGUI/XMLParserModules/RapidXML/XMLParser.h +++ b/cegui/include/CEGUI/XMLParserModules/RapidXML/XMLParser.h @@ -51,7 +51,7 @@ class CEGUIRAPIDXMLPARSER_API RapidXMLParser : public XMLParser // Implementation of public abstract interface void parseXML(XMLHandler& handler, const RawDataContainer& source, - const String& schemaName); + const String& schemaName, bool /*allowXmlValidation*/); protected: // Implementation of abstract interface. diff --git a/cegui/include/CEGUI/XMLParserModules/TinyXML/XMLParser.h b/cegui/include/CEGUI/XMLParserModules/TinyXML/XMLParser.h index d33f890fe..d70e3c15b 100644 --- a/cegui/include/CEGUI/XMLParserModules/TinyXML/XMLParser.h +++ b/cegui/include/CEGUI/XMLParserModules/TinyXML/XMLParser.h @@ -53,7 +53,7 @@ namespace CEGUI ~TinyXMLParser(void); // Implementation of public abstract interface - void parseXML(XMLHandler& handler, const RawDataContainer& filename, const String& schemaName); + void parseXML(XMLHandler& handler, const RawDataContainer& filename, const String& schemaName, bool /*allowXmlValidation*/); protected: // Implementation of abstract interface. diff --git a/cegui/include/CEGUI/XMLParserModules/Xerces/XMLParser.h b/cegui/include/CEGUI/XMLParserModules/Xerces/XMLParser.h index e7c356410..b30d81742 100644 --- a/cegui/include/CEGUI/XMLParserModules/Xerces/XMLParser.h +++ b/cegui/include/CEGUI/XMLParserModules/Xerces/XMLParser.h @@ -92,7 +92,7 @@ namespace CEGUI ~XercesParser(void); // Implementation of public abstract interface - void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName); + void parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool allowXmlValidation = true); // Internal methods /*! @@ -137,6 +137,32 @@ namespace CEGUI static const String& getSchemaDefaultResourceGroup() { return d_defaultSchemaResourceGroup; } + /*! + \brief + Sets whether xml validation is allowed or not. + If it's 'false' it will not allow any xml validation. + If it's 'true' the validation behaviour is dependending + on what is passed to parseXML. + + \param isEnabled + Boolean, either true or false. + + \return + Nothing. + */ + void setXmlValidationEnabled(const bool isEnabled) + { d_xmlValidationEnabled = isEnabled; } + + /*! + \brief + Returns whether xml validation is allowed or not. + + \return + 'true' if enabled otherwise 'false' + */ + bool isXmlValidationEnabled(void) const + { return d_xmlValidationEnabled; } + protected: static void initialiseSchema(XERCES_CPP_NAMESPACE::SAX2XMLReader* reader, const String& schemaName); static XERCES_CPP_NAMESPACE::SAX2XMLReader* createReader(XERCES_CPP_NAMESPACE::DefaultHandler& handler); @@ -148,6 +174,8 @@ namespace CEGUI //! holds the default resource group ID for loading schemas. static String d_defaultSchemaResourceGroup; + //! holds whether xml validation is allowed or not. + bool d_xmlValidationEnabled; //! Property for accessing the default schema resource group ID. static XercesParserProperties::SchemaDefaultResourceGroup s_schemaDefaultResourceGroupProperty; diff --git a/cegui/include/CEGUI/XMLSerializer.h b/cegui/include/CEGUI/XMLSerializer.h index 65041e97b..35d8e9963 100644 --- a/cegui/include/CEGUI/XMLSerializer.h +++ b/cegui/include/CEGUI/XMLSerializer.h @@ -82,8 +82,7 @@ namespace CEGUI } @endcode */ - class CEGUIEXPORT XMLSerializer : - public AllocatedObject + class CEGUIEXPORT XMLSerializer { public: /*! @@ -176,8 +175,7 @@ namespace CEGUI bool d_needClose; //!< Store whether the next operation need to close the tag or not bool d_lastIsText; //!< Store whether the last operation was a text node or not OutStream& d_stream; //!< A reference to the stream object use - std::vector d_tagStack; //!< Store the tag stack for correct closing of the tags. + std::vector d_tagStack; //!< Store the tag stack for correct closing of the tags. /*! \brief put padding in the stream before line data diff --git a/cegui/include/CEGUI/falagard/ComponentBase.h b/cegui/include/CEGUI/falagard/ComponentBase.h index 78b8b9295..485f9c481 100644 --- a/cegui/include/CEGUI/falagard/ComponentBase.h +++ b/cegui/include/CEGUI/falagard/ComponentBase.h @@ -34,8 +34,7 @@ namespace CEGUI { //! Common base class used for renderable components within an ImagerySection. -class CEGUIEXPORT FalagardComponentBase : - public AllocatedObject +class CEGUIEXPORT FalagardComponentBase { public: FalagardComponentBase(); diff --git a/cegui/include/CEGUI/falagard/Dimensions.h b/cegui/include/CEGUI/falagard/Dimensions.h index beb9a174a..8f0a73a56 100644 --- a/cegui/include/CEGUI/falagard/Dimensions.h +++ b/cegui/include/CEGUI/falagard/Dimensions.h @@ -37,8 +37,7 @@ namespace CEGUI { //! Abstract interface for a generic 'dimension' class. -class CEGUIEXPORT BaseDim : - public AllocatedObject +class CEGUIEXPORT BaseDim { public: BaseDim(); @@ -690,8 +689,7 @@ class CEGUIEXPORT PropertyDim : public BaseDim dimensional value, but also a record of what the dimension value is supposed to represent. (e.g. a co-ordinate on the x axis, or the height of something). */ -class CEGUIEXPORT Dimension : - public AllocatedObject +class CEGUIEXPORT Dimension { public: Dimension(); @@ -777,8 +775,7 @@ class CEGUIEXPORT Dimension : represent width and height depending upon what the assigned Dimension(s) represent. */ -class CEGUIEXPORT ComponentArea : - public AllocatedObject +class CEGUIEXPORT ComponentArea { public: ComponentArea(); @@ -853,7 +850,7 @@ class CEGUIEXPORT ComponentArea : area for this ComponentArea. \note - Calling this will replace any existing souce, such as a named area. + Calling this will replace any existing source, such as a named area. \param property String object holding the name of a Propery. The property should access @@ -871,7 +868,7 @@ class CEGUIEXPORT ComponentArea : const String& getNamedAreaSourceLook() const; //! Set the named area source of the ComponentArea. - void setNamedAreaSouce(const String& widget_look, const String& area_name); + void setNamedAreaSource(const String& widget_look, const String& area_name); /*! \brief diff --git a/cegui/include/CEGUI/falagard/EventAction.h b/cegui/include/CEGUI/falagard/EventAction.h index 47185f1d0..2ff894ef8 100644 --- a/cegui/include/CEGUI/falagard/EventAction.h +++ b/cegui/include/CEGUI/falagard/EventAction.h @@ -42,8 +42,7 @@ namespace CEGUI { class Window; -class CEGUIEXPORT EventAction : - public AllocatedObject +class CEGUIEXPORT EventAction { public: EventAction(const String& event_name, ChildEventAction action); diff --git a/cegui/include/CEGUI/falagard/EventLinkDefinition.h b/cegui/include/CEGUI/falagard/EventLinkDefinition.h index e1aed67ae..3ca03cea7 100644 --- a/cegui/include/CEGUI/falagard/EventLinkDefinition.h +++ b/cegui/include/CEGUI/falagard/EventLinkDefinition.h @@ -40,8 +40,7 @@ // Start of CEGUI namespace section namespace CEGUI { -class CEGUIEXPORT EventLinkDefinition : - public AllocatedObject +class CEGUIEXPORT EventLinkDefinition { public: EventLinkDefinition(const String& event_name); @@ -73,7 +72,7 @@ class CEGUIEXPORT EventLinkDefinition : typedef std::pair StringPair; //! type used for the collection of target events. - typedef std::vector LinkTargetCollection; + typedef std::vector LinkTargetCollection; //! collection of targets for this EventLinkDefinition. LinkTargetCollection d_targets; diff --git a/cegui/include/CEGUI/falagard/FrameComponent.h b/cegui/include/CEGUI/falagard/FrameComponent.h index cedf19b4d..6310aa01b 100644 --- a/cegui/include/CEGUI/falagard/FrameComponent.h +++ b/cegui/include/CEGUI/falagard/FrameComponent.h @@ -385,7 +385,7 @@ class CEGUIEXPORT FrameComponent : public FalagardComponentBase const CEGUI::ColourRect* modColours, const Rectf* clipper, bool clipToDisplay) const; - void renderImage(GeometryBuffer& buffer, const Image* image, + void renderImage(std::vector& geometry_buffers, const Image* image, VerticalFormatting vertFmt, HorizontalFormatting horzFmt, Rectf& destRect, const ColourRect& colours, diff --git a/cegui/include/CEGUI/falagard/ImagerySection.h b/cegui/include/CEGUI/falagard/ImagerySection.h index 5a2568b33..953cd1e6a 100644 --- a/cegui/include/CEGUI/falagard/ImagerySection.h +++ b/cegui/include/CEGUI/falagard/ImagerySection.h @@ -44,16 +44,15 @@ namespace CEGUI \brief Class that encapsulates a re-usable collection of imagery specifications. */ - class CEGUIEXPORT ImagerySection : - public AllocatedObject + class CEGUIEXPORT ImagerySection { public: //! Vector of ImageryComponent Pointers - typedef std::vector ImageryComponentPointerList; + typedef std::vector ImageryComponentPointerList; //! Vector of TextComponent Pointers - typedef std::vector TextComponentPointerList; + typedef std::vector TextComponentPointerList; //! Vector of FrameComponent Pointers - typedef std::vector FrameComponentPointerList; + typedef std::vector FrameComponentPointerList; /*! @@ -117,7 +116,7 @@ namespace CEGUI /*! \brief Removes an ImageryComponent from this ImagerySection. The supplied ImagerySection reference should be - retrieved via the getImageryComponentPointers function. The check to find out which ImagerySection to remove + retrieved via the getImageryComponents or getImageryComponentPointers function. The check to find out which ImagerySection to remove is done using memory address comparison (identity check). \param imageryComponent @@ -146,7 +145,7 @@ namespace CEGUI /*! \brief Removes an TextComponent from this ImagerySection. The supplied TextComponent reference should be - retrieved via the getTextComponentPointers function. The check to find out which TextComponent to remove + retrieved via the getTextComponents or getTextComponentPointers function. The check to find out which TextComponent to remove is done using memory address comparison (identity check). \param textComponent @@ -184,7 +183,7 @@ namespace CEGUI /*! \brief Removes an FrameComponent from this ImagerySection. The supplied FrameComponent reference should be - retrieved via the getFrameComponentPointers function. The check to find out which FrameComponent to remove + retrieved via the getFrameComponents or getFrameComponentPointers function. The check to find out which FrameComponent to remove is done using memory address comparison (identity check). \param frameComponent @@ -316,75 +315,56 @@ namespace CEGUI */ FrameComponentPointerList getFrameComponentPointers(); - protected: + typedef std::vector ImageryComponentList; + typedef std::vector TextComponentList; + typedef std::vector FrameComponentList; + /*! \brief - Helper method to initialise a ColourRect with appropriate values according to the way the - ImagerySection is set up. + Returns a const reference to the list of ImageryComponents that are currently added to this ImagerySection. - This will try and get values from multiple places: - - a property attached to \a wnd - - or the integral d_masterColours value. + \return + A const reference to the vector of ImageryComponents that are currently added to this ImagerySection */ - void initMasterColourRect(const Window& wnd, ColourRect& cr) const; - - private: - typedef std::vector ImageryList; - typedef std::vector TextList; - typedef std::vector FrameList; - - CEGUI::String d_name; //!< Holds the name of the ImagerySection. - CEGUI::ColourRect d_masterColours; //!< Naster colours for the the ImagerySection (combined with colours of each ImageryComponent). - FrameList d_frames; //!< Collection of FrameComponent objects to be drawn for this ImagerySection. - ImageryList d_images; //!< Collection of ImageryComponent objects to be drawn for this ImagerySection. - TextList d_texts; //!< Collection of TextComponent objects to be drawn for this ImagerySection. - String d_colourPropertyName; //!< name of property to fetch colours from. - - public: - //! \deprecated This iterator is deprecated because the function that uses the type is deprecated - typedef ConstVectorIterator ImageryComponentIterator; - //! \deprecated This iterator is deprecated because the function that uses the type is deprecated - typedef ConstVectorIterator TextComponentIterator; - //! \deprecated This iterator is deprecated because the function that uses the type is deprecated - typedef ConstVectorIterator FrameComponentIterator; + const ImageryComponentList& getImageryComponents() const; /*! \brief - Return a ImagerySection::ImageryComponentIterator object to iterate - over the ImageryComponent elements currently added to the - ImagerySection. + Returns a const reference to the list of ImageryComponents that are currently added to this ImagerySection. - \deprecated - This iterator is deprecated because it will be replaced by the function getImageryComponents - in the next version. + \return + A const reference to the vector of ImageryComponents that are currently added to this ImagerySection */ - ImageryComponentIterator getImageryComponentIterator() const; + const TextComponentList& getTextComponents() const; + /*! \brief - Return a ImagerySection::TextComponentIterator object to iterate - over the TextComponent elements currently added to the - ImagerySection. + Returns a const reference to the list of ImageryComponents that are currently added to this ImagerySection. - \deprecated - This iterator is deprecated because it will be replaced by the function getTextComponents - in the next version. + \return + A const reference to the vector of ImageryComponents that are currently added to this ImagerySection */ - TextComponentIterator getTextComponentIterator() const; + const FrameComponentList& getFrameComponents() const; + + protected: /*! \brief - Return a ImagerySection::FrameComponentIterator object to iterate - over the FrameComponent elements currently added to the - ImagerySection. + Helper method to initialise a ColourRect with appropriate values according to the way the + ImagerySection is set up. - \deprecated - This iterator is deprecated because it will be replaced by the function getFrameComponents - in the next version. + This will try and get values from multiple places: + - a property attached to \a wnd + - or the integral d_masterColours value. */ - FrameComponentIterator getFrameComponentIterator() const; + void initMasterColourRect(const Window& wnd, ColourRect& cr) const; + private: + CEGUI::String d_name; //!< Holds the name of the ImagerySection. + CEGUI::ColourRect d_masterColours; //!< Naster colours for the the ImagerySection (combined with colours of each ImageryComponent). + FrameComponentList d_frames; //!< Collection of FrameComponent objects to be drawn for this ImagerySection. + ImageryComponentList d_images; //!< Collection of ImageryComponent objects to be drawn for this ImagerySection. + TextComponentList d_texts; //!< Collection of TextComponent objects to be drawn for this ImagerySection. + String d_colourPropertyName; //!< name of property to fetch colours from. }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/falagard/LayerSpecification.h b/cegui/include/CEGUI/falagard/LayerSpecification.h index a8d96f44a..6efdc6150 100644 --- a/cegui/include/CEGUI/falagard/LayerSpecification.h +++ b/cegui/include/CEGUI/falagard/LayerSpecification.h @@ -42,13 +42,14 @@ namespace CEGUI \brief Class that encapsulates a single layer of imagery. */ - class CEGUIEXPORT LayerSpecification : - public AllocatedObject + class CEGUIEXPORT LayerSpecification { public: //! The container type for SectionSpecifications - typedef std::vector SectionSpecificationPointerList; + typedef std::vector SectionSpecificationList; + + //! The container type for pointers to SectionSpecifications + typedef std::vector SectionSpecificationPointerList; /*! @@ -141,6 +142,15 @@ namespace CEGUI */ void writeXMLToStream(XMLSerializer& xml_stream) const; + /*! + \brief + Returns a reference to the vector of SectionSpecifications that are currently added to this LayerSpecification. + + \return + A const reference to the vector SectionSpecifications that are currently added to this LayerSpecification + */ + const SectionSpecificationList& getSectionSpecifications() const; + /*! \brief Returns a vector of pointers to the SectionSpecifications that are currently added to this LayerSpecification. If a @@ -157,17 +167,10 @@ namespace CEGUI bool operator< (const LayerSpecification& otherLayerSpec) const; private: - //! \deprecated This type will be made public in the next version and be renamed to SectionSpecificationList. - typedef std::vector SectionList; - - SectionList d_sections; //!< Collection of SectionSpecification objects descibing the sections to be drawn for this layer. - uint d_layerPriority; //!< Priority of the layer. - public: - //! \deprecated This type will be removed in the next version and replaced by a const list in the getSectionSpecifications function. - typedef ConstVectorIterator SectionIterator; - //! \deprecated This function will be replaced by the getSectionSpecifications function in the next version. For editing getSectionSpecificationPointers can be used. - SectionIterator getSectionIterator() const; + //! Collection of SectionSpecification instances + SectionSpecificationList d_sections; + //! Priority of the layer + uint d_layerPriority; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/falagard/NamedArea.h b/cegui/include/CEGUI/falagard/NamedArea.h index 9d458d8ea..f6ff49e0a 100644 --- a/cegui/include/CEGUI/falagard/NamedArea.h +++ b/cegui/include/CEGUI/falagard/NamedArea.h @@ -37,8 +37,7 @@ namespace CEGUI NamedArea defines an area for a component which may later be obtained and referenced by a name unique to the WidgetLook holding the NamedArea. */ - class CEGUIEXPORT NamedArea : - public AllocatedObject + class CEGUIEXPORT NamedArea { public: NamedArea() {} diff --git a/cegui/include/CEGUI/falagard/NamedDefinitionCollator.h b/cegui/include/CEGUI/falagard/NamedDefinitionCollator.h index 1117b9b8d..2b64fcde0 100644 --- a/cegui/include/CEGUI/falagard/NamedDefinitionCollator.h +++ b/cegui/include/CEGUI/falagard/NamedDefinitionCollator.h @@ -80,7 +80,7 @@ class NamedDefinitionCollator protected: typedef std::pair Entry; - typedef std::vector ValueArray; + typedef std::vector ValueArray; struct pred { diff --git a/cegui/include/CEGUI/falagard/PropertyDefinition.h b/cegui/include/CEGUI/falagard/PropertyDefinition.h index 735854c4c..78365bdaf 100644 --- a/cegui/include/CEGUI/falagard/PropertyDefinition.h +++ b/cegui/include/CEGUI/falagard/PropertyDefinition.h @@ -63,7 +63,7 @@ class PropertyDefinition : public FalagardPropertyBase //------------------------------------------------------------------------// Property* clone() const { - return CEGUI_NEW_AO PropertyDefinition(*this); + return new PropertyDefinition(*this); } protected: diff --git a/cegui/include/CEGUI/falagard/PropertyInitialiser.h b/cegui/include/CEGUI/falagard/PropertyInitialiser.h index bd3c14835..18fb7bf80 100644 --- a/cegui/include/CEGUI/falagard/PropertyInitialiser.h +++ b/cegui/include/CEGUI/falagard/PropertyInitialiser.h @@ -37,8 +37,7 @@ namespace CEGUI \brief Class that holds information about a property and it's required initial value. */ - class CEGUIEXPORT PropertyInitialiser : - public AllocatedObject + class CEGUIEXPORT PropertyInitialiser { public: PropertyInitialiser() {}; diff --git a/cegui/include/CEGUI/falagard/PropertyLinkDefinition.h b/cegui/include/CEGUI/falagard/PropertyLinkDefinition.h index cfe833d31..646c9d992 100644 --- a/cegui/include/CEGUI/falagard/PropertyLinkDefinition.h +++ b/cegui/include/CEGUI/falagard/PropertyLinkDefinition.h @@ -39,9 +39,6 @@ namespace CEGUI { -//! \deprecated This will be removed in the next version as it has been replaced by Falagard_xmlHandler::ParentIdentifier -extern const String S_parentIdentifier; - /*! \brief Class representing a property that links to another property defined on @@ -112,7 +109,7 @@ class PropertyLinkDefinition : public FalagardPropertyBase //------------------------------------------------------------------------// Property* clone() const { - return CEGUI_NEW_AO PropertyLinkDefinition(*this); + return new PropertyLinkDefinition(*this); } protected: @@ -244,7 +241,7 @@ class PropertyLinkDefinition : public FalagardPropertyBase //------------------------------------------------------------------------// typedef std::pair StringPair; //! type used for the collection of targets. - typedef std::vector LinkTargetCollection; + typedef std::vector LinkTargetCollection; //! collection of targets for this PropertyLinkDefinition. LinkTargetCollection d_targets; diff --git a/cegui/include/CEGUI/falagard/SectionSpecification.h b/cegui/include/CEGUI/falagard/SectionSpecification.h index 7f68b8249..721431921 100644 --- a/cegui/include/CEGUI/falagard/SectionSpecification.h +++ b/cegui/include/CEGUI/falagard/SectionSpecification.h @@ -44,8 +44,7 @@ namespace CEGUI This class enables sections to be easily re-used, by different states and/or layers, by allowing sections to be specified by name rather than having mutiple copies of the same thing all over the place. */ - class CEGUIEXPORT SectionSpecification : - public AllocatedObject + class CEGUIEXPORT SectionSpecification { public: SectionSpecification(); diff --git a/cegui/include/CEGUI/falagard/StateImagery.h b/cegui/include/CEGUI/falagard/StateImagery.h index d40560e04..d699fcf85 100644 --- a/cegui/include/CEGUI/falagard/StateImagery.h +++ b/cegui/include/CEGUI/falagard/StateImagery.h @@ -43,13 +43,14 @@ namespace CEGUI \brief Class the encapsulates imagery for a given widget state. */ - class CEGUIEXPORT StateImagery : - public AllocatedObject + class CEGUIEXPORT StateImagery { public: + //! Container for LayerSpecifications. This container needs to be sorted for priority every time a member is changed, added or removed. + typedef std::vector LayerSpecificationList; + //! Container type for LayerSpecification pointers - typedef std::vector LayerSpecificationPointerList; + typedef std::vector LayerSpecificationPointerList; /*! \brief @@ -74,9 +75,6 @@ namespace CEGUI \param srcWindow Window to use when convering BaseDim values to pixels. - - \return - Nothing. */ void render(Window& srcWindow, const ColourRect* modcols = 0, const Rectf* clipper = 0) const; @@ -89,9 +87,6 @@ namespace CEGUI \param baseRect Rect to use when convering BaseDim values to pixels. - - \return - Nothing. */ void render(Window& srcWindow, const Rectf& baseRect, const ColourRect* modcols = 0, const Rectf* clipper = 0) const; @@ -101,25 +96,20 @@ namespace CEGUI \param layer LayerSpecification to be added to this state (will be copied) - - \return - Nothing. */ void addLayer(const LayerSpecification& layer); /*! \brief Sorts the LayerSpecifications after their priority. Whenever a LayerSpecification, which has been added - to this StateImagery, is changed, this sort function should be called. + to this StateImagery, is changed or an element is added to or removed from the list, this sort function + has to be called. */ void sort(); /*! \brief Removed all LayerSpecifications from this state. - - \return - Nothing. */ void clearLayers(); @@ -147,7 +137,7 @@ namespace CEGUI Clipping to the display effectively implies that the imagery should be rendered unclipped. - /return + \return - true if the imagery will be clipped to the display area. - false if the imagery will be clipped to the target window area. */ @@ -162,9 +152,6 @@ namespace CEGUI \param setting - true if the imagery should be clipped to the display area. - false if the imagery should be clipped to the target window area. - - \return - Nothing. */ void setClippedToDisplay(bool setting); @@ -174,13 +161,17 @@ namespace CEGUI \param xml_stream Stream where xml data should be output. - - - \return - Nothing. */ void writeXMLToStream(XMLSerializer& xml_stream) const; + /*! + \brief + Returns a const reference to the list of LayerSpecifications that are currently added to this StateImagery. + + \return + A const reference to the vector of LayerSpecifications that are currently added to this StateImagery + */ + const LayerSpecificationList& getLayerSpecifications() const; /*! \brief @@ -188,34 +179,19 @@ namespace CEGUI If a LayerSpecification is added or removed from this StateImagery, then the pointers in this vector are not valid anymore. The function should then be called again to retrieve valid pointers. - \note - Whenever a pointer from this list is changed in a way that the multiset needs to be resorted, the sort - function of this class must be called. + \note + Whenever a pointer from this list is changed in a way that the multiset needs to be resorted, the sort + function of this class must be called. - \return + \return A vector of pointers to the LayerSpecifications that are currently added to this StateImagery */ LayerSpecificationPointerList getLayerSpecificationPointers(); private: - /*! - \deprecated - This type is deprecated because it doesn't use CEGUI allocators and is private and needs to be replaced with a vector that gets - sorted whenever needed. std::multisets and sets make their elements constant which introduces issues when changing them. In the next - version a new public type "LayerSpecificationList" will replace this one. - */ - typedef std::multiset LayersList; - - CEGUI::String d_stateName; //!< Name of this state. - LayersList d_layers; //!< Collection of LayerSpecification objects to be drawn for this state. - bool d_clipToDisplay; //!< true if Imagery for this state should be clipped to the display instead of winodw (effectively, not clipped). - public: - //! \deprecated This type is deprecated and will be removed in the next version. A const reference to the Container type of getLayerSpecifications will replace this. - typedef ConstVectorIterator LayerIterator; - - //! \deprecated This function is deprecated. Instead the getLayerSpecifications will be used in the next version and getLayerSpecificationPointers can be used for editing. - LayerIterator getLayerIterator() const; - + CEGUI::String d_stateName; //!< Name of this state. + LayerSpecificationList d_layers; //!< Collection of LayerSpecification objects to be drawn for this state. + bool d_clipToDisplay; //!< true if Imagery for this state should be clipped to the display instead of winodw (effectively, not clipped). }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/falagard/WidgetComponent.h b/cegui/include/CEGUI/falagard/WidgetComponent.h index 88991d9e9..ea78efb5b 100644 --- a/cegui/include/CEGUI/falagard/WidgetComponent.h +++ b/cegui/include/CEGUI/falagard/WidgetComponent.h @@ -42,18 +42,13 @@ namespace CEGUI { /*! \brief - Class that encapsulates information regarding a sub-widget required for a widget. - - \todo - This is not finished in the slightest! There will be many changes here... + Class that encapsulates information regarding a child-widget that is used in a WidgetLookFeel. */ - class CEGUIEXPORT WidgetComponent : - public AllocatedObject + class CEGUIEXPORT WidgetComponent { public: WidgetComponent() {} - WidgetComponent(const String& type, - const String& look, + WidgetComponent(const String& targetType, const String& suffix, const String& renderer, bool autoWindow); @@ -75,11 +70,8 @@ namespace CEGUI const ComponentArea& getComponentArea() const; void setComponentArea(const ComponentArea& area); - const String& getBaseWidgetType() const; - void setBaseWidgetType(const String& type); - - const String& getWidgetLookName() const; - void setWidgetLookName(const String& look); + const String& getTargetType() const; + void setTargetType(const String& type); const String& getWidgetName() const; void setWidgetName(const String& name); @@ -138,10 +130,8 @@ namespace CEGUI static const VerticalAlignment VerticalAlignmentDefault; private: - typedef std::vector PropertiesList; - typedef std::vector EventActionList; + typedef std::vector PropertiesList; + typedef std::vector EventActionList; public: /************************************************************************* @@ -164,16 +154,14 @@ namespace CEGUI private: ComponentArea d_area; //!< Destination area for the widget (relative to it's parent). - String d_baseType; //!< Type of widget to be created. - String d_imageryName; //!< Name of a WidgetLookFeel to be used for the widget. - String d_name; //!< name to create this widget with. + String d_targetType; //!< The target type (e.g. falagard mapping or alias) mapping of the widget to be created. + String d_name; //!< Name to create this widget with. String d_rendererType; //!< Name of the window renderer type to assign to the widget. - bool d_autoWindow; //!< specifies whether to mark component as an auto-window. + bool d_autoWindow; //!< Specifies whether to mark component as an auto-window. VerticalAlignment d_vertAlign; //!< Vertical alignment to be used for this widget. HorizontalAlignment d_horzAlign; //!< Horizontal alignment to be used for this widget. PropertiesList d_properties; //!< Collection of PropertyInitialisers to be applied the the widget upon creation. - //! EventActions added to the WidgetComponent - EventActionList d_eventActions; + EventActionList d_eventActions; //!< EventActions added to the WidgetComponent }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/falagard/WidgetLookFeel.h b/cegui/include/CEGUI/falagard/WidgetLookFeel.h index 0288bbb8a..97f01f893 100644 --- a/cegui/include/CEGUI/falagard/WidgetLookFeel.h +++ b/cegui/include/CEGUI/falagard/WidgetLookFeel.h @@ -51,35 +51,138 @@ namespace CEGUI \brief Class that encapsulates Look N' Feel information for a widget. */ -class CEGUIEXPORT WidgetLookFeel : - public AllocatedObject +class CEGUIEXPORT WidgetLookFeel { public: - WidgetLookFeel(const String& name, const String& inherits); + WidgetLookFeel(const String& name, const String& inheritedLookName); WidgetLookFeel() {} WidgetLookFeel(const WidgetLookFeel& other); + WidgetLookFeel& operator=(const WidgetLookFeel& other); virtual ~WidgetLookFeel(); + /*! \brief Return a const reference to the StateImagery object for the specified state. + \param name + String object holding the name of the StateImagery to be returned. + \return StateImagery object for the requested state. + + \exception UnknownObjectException + Thrown if a StateImagery with the given name could not be found. */ - const StateImagery& getStateImagery(const CEGUI::String& state) const; + const StateImagery& getStateImagery(const CEGUI::String& stateName, bool includeInheritedLook = true) const; /*! \brief Return a const reference to the ImagerySection object with the specified name. + \param name + String object holding the name of the ImagerySection to be returned. + \return ImagerySection object with the specified name. + + \exception UnknownObjectException + Thrown if a ImagerySection with the given name could not be found. + */ + const ImagerySection& getImagerySection(const CEGUI::String& sectionName, bool includeInheritedLook = true) const; + + /*! + \brief + Return the NamedArea with the specified name. + + \param name + String object holding the name of the NamedArea to be returned. + + \return + The requested NamedArea object. + + \exception UnknownObjectException + Thrown if a NamedArea with the given name could not be found. + */ + const NamedArea& getNamedArea(const String& name, bool includeInheritedLook = true) const; + + /*! + \brief + Return the PropertyInitialiser with the specified name. + + \param name + String object holding the name of the PropertyInitialiser to be returned. + + \return + The requested PropertyInitialiser object. + + \exception UnknownObjectException + Thrown if a PropertyInitialiser with the given name could not be found. + */ + const PropertyInitialiser& getPropertyInitialiser(const String& name, bool includeInheritedLook = true) const; + + /*! + \brief + Return the PropertyDefinition with the specified name. + + \param name + String object holding the name of the PropertyDefinition to be returned. + + \return + The requested PropertyDefinitionBase object. + + \exception UnknownObjectException + Thrown if a PropertyDefinition with the given name could not be found. */ - const ImagerySection& getImagerySection(const CEGUI::String& section) const; + const PropertyDefinitionBase& getPropertyDefinition(const String& name, bool includeInheritedLook = true) const; + + /*! + \brief + Return the PropertyLinkDefinition with the specified name. + + \param name + String object holding the name of the PropertyLinkDefinition to be returned. + + \return + The requested PropertyDefinitionBase object. + + \exception UnknownObjectException + Thrown if a PropertyLinkDefinition with the given name could not be found. + */ + const PropertyDefinitionBase& getPropertyLinkDefinition(const String& name, bool includeInheritedLook = true) const; + + /*! + \brief + Return the WidgetComponent with the specified name. + + \param name + String object holding the name of the WidgetComponent to be returned. + + \return + The requested WidgetComponent object. + + \exception UnknownObjectException + Thrown if a WidgetComponent with the given name could not be found. + */ + const WidgetComponent& getWidgetComponent(const String& name, bool includeInheritedLook = true) const; + + /*! + \brief + Return the EventLinkDefinition with the specified name. + + \param name + String object holding the name of the EventLinkDefinition to be returned. + + \return + The requested EventLinkDefinition object. + + \exception UnknownObjectException + Thrown if a EventLinkDefinition with the given name could not be found. + */ + const EventLinkDefinition& getEventLinkDefinition(const String& name, bool includeInheritedLook = true) const; /*! \brief @@ -96,9 +199,6 @@ class CEGUIEXPORT WidgetLookFeel : \param section ImagerySection object to be added. - - \return - Nothing. */ void addImagerySection(const ImagerySection& section); @@ -111,9 +211,6 @@ class CEGUIEXPORT WidgetLookFeel : \param widget WidgetComponent object to be added. - - \return - Nothing. */ void addWidgetComponent(const WidgetComponent& widget); @@ -123,11 +220,8 @@ class CEGUIEXPORT WidgetLookFeel : \param section StateImagery object to be added. - - \return - Nothing. */ - void addStateSpecification(const StateImagery& state); + void addStateImagery(const StateImagery& state); /*! \brief @@ -135,48 +229,45 @@ class CEGUIEXPORT WidgetLookFeel : \param initialiser PropertyInitialiser object to be added. - - \return - Nothing. */ void addPropertyInitialiser(const PropertyInitialiser& initialiser); /*! \brief Clear all ImagerySections from the WidgetLookFeel. - - \return - Nothing. */ void clearImagerySections(); /*! \brief Clear all WidgetComponents from the WidgetLookFeel. - - \return - Nothing. */ void clearWidgetComponents(); /*! \brief Clear all StateImagery objects from the WidgetLookFeel. - - \return - Nothing. */ void clearStateSpecifications(); /*! \brief Clear all PropertyInitialiser objects from the WidgetLookFeel. - - \return - Nothing. */ void clearPropertyInitialisers(); + /*! + \brief + Clears the map of added PropertyDefinitions of this WidgetLookFeel and destroys the PropertyDefinitions. + */ + void clearPropertyDefinitions(); + + /*! + \brief + Clears the map of added PropertyLinkDefinitions of this WidgetLookFeel and destroys the PropertyLinkDefinitions. + */ + void clearPropertyLinkDefinitions(); + /*! \brief Initialise the given window using PropertyInitialsers and component @@ -184,9 +275,6 @@ class CEGUIEXPORT WidgetLookFeel : \param widget Window based object to be initialised. - - \return - Nothing. */ void initialiseWidget(Window& widget) const; @@ -197,135 +285,182 @@ class CEGUIEXPORT WidgetLookFeel : \param widget Window based object to be cleaned up. - - \return - Nothing. */ void cleanUpWidget(Window& widget) const; /*! \brief - Return whether imagery is defined for the given state. + Returns if a StateImagery with the given name is present in this look. - \param state - String object containing name of state to look for. + \param name + The name of the StateImagery to look for. - \return - - true if imagery exists for the specified state, - - false if no imagery exists for the specified state. + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - \deprecated This function is deprecated because it does not consider WidgetLook inheritance. It will be replaced by a - new isStateImageryPresent function in the next major version. + \return + - true, if the element with the given name is present, + - false, if no such element is present. */ - bool isStateImageryPresent(const String& state) const; + bool isStateImageryPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Adds a named area to the WidgetLookFeel. + Returns if a ImagerySection with the given name is present in this look. - \param area - NamedArea to be added. + \param name + The name of the ImagerySection to look for. + + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return - Nothing. + - true, if the element with the given name is present, + - false, if no such element is present. */ - void addNamedArea(const NamedArea& area); + bool isImagerySectionPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Clear all defined named areas from the WidgetLookFeel + Returns if a NamedArea with the given name is present in this look. + + \param name + The name of the NamedArea to look for. + + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return - Nothing. + - true, if the element with the given name is present, + - false, if no such element is present. */ - void clearNamedAreas(); + bool isNamedAreaPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Return the NamedArea with the specified name. + Returns if a WidgetComponent with the given name is present in this look. \param name - String object holding the name of the NamedArea to be returned. + The name of the WidgetComponent to look for. + + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return - The requested NamedArea object. + - true, if the element with the given name is present, + - false, if no such element is present. */ - const NamedArea& getNamedArea(const String& name) const; - - //! \deprecated This function is to be replaced by a new renameNamedArea function in the new version, which considers inheritance and accepts more appropriate parameters. - void renameNamedArea(const String& oldName, const String& newName); + bool isWidgetComponentPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - return whether a NamedArea object with the specified name exists for - this WidgetLookFeel. + Returns if a PropertyInitialiser with the given name is present in this look. \param name - String holding the name of the NamedArea to check for. + The name of the PropertyInitialiser to look for. - \return - - true if a named area with the requested name is defined for this - WidgetLookFeel. - - false if no such named area is defined for this WidgetLookFeel. + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - \deprecated This function is deprecated because it does not consider WidgetLook inheritance. It will be changed to isNamedAreaPresent() in the next major version. + \return + - true, if the element with the given name is present, + - false, if no such element is present. */ - bool isNamedAreaDefined(const String& name) const; + bool isPropertyInitialiserPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Layout the child widgets defined for this WidgetLookFeel which are - attached to the given window. + Returns if a PropertyDefinition with the given name is present in this look. - \param owner - Window object that has the child widgets that require laying out. + \param name + The name of the PropertyDefinition to look for. + + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return - Nothing. + - true, if the element with the given name is present, + - false, if no such element is present. */ - void layoutChildWidgets(const Window& owner) const; + bool isPropertyDefinitionPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Adds a property definition to the WidgetLookFeel. + Returns if a PropertyLinkDefinition with the given name is present in this look. - \param propdef - PropertyDefinition object to be added. + \param name + The name of the PropertyLinkDefinition to look for. + + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return - Nothing. + - true, if the element with the given name is present, + - false, if no such element is present. */ - void addPropertyDefinition(PropertyDefinitionBase* propdef); + bool isPropertyLinkDefinitionPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Adds a property link definition to the WidgetLookFeel. + Returns if a EventLinkDefinition with the given name is present in this look. - \param propdef - PropertyLinkDefinition object to be added. + \param name + The name of the EventLinkDefinition to look for. + + \param includeInheritedLook + If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return - Nothing. + - true, if the element with the given name is present, + - false, if no such element is present. */ - void addPropertyLinkDefinition(PropertyDefinitionBase* propdef); + bool isEventLinkDefinitionPresent(const String& name, bool includeInheritedLook = true) const; /*! \brief - Clear all defined property definitions from the WidgetLookFeel + Adds a named area to the WidgetLookFeel. - \return - Nothing. + \param area + NamedArea to be added. */ - void clearPropertyDefinitions(); + void addNamedArea(const NamedArea& area); + + /*! + \brief + Clear all defined named areas from the WidgetLookFeel + */ + void clearNamedAreas(); + + //! \deprecated This function is to be replaced by a new renameNamedArea function in the new version, which considers inheritance and accepts more appropriate parameters. + void renameNamedArea(const String& oldName, const String& newName); /*! \brief - Clear all defined property link definitions from the WidgetLookFeel + Layout the child widgets defined for this WidgetLookFeel which are + attached to the given window. - \return - Nothing. + \param owner + Window object that has the child widgets that require laying out. */ - void clearPropertyLinkDefinitions(); + void layoutChildWidgets(const Window& owner) const; + + /*! + \brief + Adds a PropertyDefinition to the WidgetLookFeel. The WidgetLookFeel takes over the ownership of the object. + + \param propdef + PropertyDefinition object to be added. + */ + void addPropertyDefinition(PropertyDefinitionBase* propertyDefiniton); + + /*! + \brief + Adds a PropertyLinkDefinition to the WidgetLookFeel. The WidgetLookFeel takes over the ownership of the object. + + \param propdef + PropertyLinkDefinition object to be added. + */ + void addPropertyLinkDefinition(PropertyDefinitionBase* propertyLinkDefiniton); /*! \brief @@ -350,9 +485,6 @@ class CEGUIEXPORT WidgetLookFeel : \param xml_stream Stream where xml data should be output. - - \return - Nothing. */ void writeXMLToStream(XMLSerializer& xml_stream) const; @@ -367,205 +499,29 @@ class CEGUIEXPORT WidgetLookFeel : */ const PropertyInitialiser* findPropertyInitialiser(const String& propertyName) const; - /*! - \brief - Takes the name for a WidgetComponent and returns a pointer to - it if it exists or a null pointer if it doesn't. - - \param name - The name of the Child component to look for. - - \deprecated - This function will be replaced by getWidgetComponent in the next version. - */ - const WidgetComponent* findWidgetComponent(const String& name) const; - - - /*! - \brief - Takes the name for a WidgetComponent and returns a pointer to - it if it exists or null pointer if it doesn't. - - \param name - The name of the WidgetComponent to look for. - - \param includeInheritedElements - If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - - \return - A pointer to the WidgetComponent. - - \deprecated - This function will be replaced by getWidgetComponent in the next version. - */ - WidgetComponent* retrieveWidgetComponentFromList(const String& name, bool includeInheritedElements = false); - - /*! - \brief - Takes the name for a Property (PropertyInitialiser) and returns a pointer to - it if it exists or 0 if it doesn't. - - \param name - The name of the Property (PropertyInitialiser) to look for. - - \param includeInheritedElements - If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - - \return - A pointer to the Property (PropertyInitialiser). - - \deprecated - This function will be replaced by getPropertyInitialiser in the next version. - */ - PropertyInitialiser* retrievePropertyInitialiserFromList(const String& name, bool includeInheritedElements = false); - - /*! - \brief - Takes the name for a PropertyDefinition and returns a pointer to - it if it exists or 0 if it doesn't. - - \param name - The name of the PropertyDefinition (PropertyDefinitionBase) to look for. - - \param includeInheritedElements - If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - - \return - A pointer to the PropertyDefinition (PropertyDefinitionBase). - - \deprecated - This function will be replaced by getPropertyDefinition in the next version. - */ - PropertyDefinitionBase* retrievePropertyDefinitionFromList(const String& name, bool includeInheritedElements = false); - - /*! - \brief - Takes the name for a PropertyLinkDefinition and returns a pointer to - it if it exists or 0 if it doesn't. - - \param name - The name of the PropertyLinkDefinition (PropertyDefinitionBase) to look for. - - \param includeInheritedElements - If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - - \return - A pointer to the PropertyLinkDefinition (PropertyDefinitionBase). - - \deprecated - This function will be replaced by getPropertyLinkDefinition in the next version. - */ - PropertyDefinitionBase* retrievePropertyLinkDefinitionFromList(const String& name, bool includeInheritedElements = false); - - /*! - \brief - Takes the name for a EventLinkDefinition and returns a pointer to - it if it exists or 0 if it doesn't. - - \param name - The name of the EventLinkDefinition to look for. - - \param includeInheritedElements - If set to true, this function will try to also include elements from the inherited WidgetLookFeel. - - \return - A pointer to the EventLinkDefinition. - - \deprecated - This function will be replaced by getEventLinkDefinition in the next version. - */ - EventLinkDefinition* retrieveEventLinkDefinitionFromList(const String& name, bool includeInheritedElements = false); - - - typedef std::set StringSet; + //! A typedef defining a set of String objects + typedef std::set StringSet; /** Typedefs for maps of Falagard elements this WidgetLookFeel owns. */ //! Map of Strings to StateImagery pointers - typedef std::map StateImageryPointerMap; + typedef std::map StateImageryPointerMap; //! Map of Strings to ImagerySection pointers - typedef std::map ImagerySectionPointerMap; + typedef std::map ImagerySectionPointerMap; //! Map of Strings to NamedArea pointers - typedef std::map NamedAreaPointerMap; + typedef std::map NamedAreaPointerMap; //! Map of Strings to WidgetComponent pointers - typedef std::map WidgetComponentPointerMap; + typedef std::map WidgetComponentPointerMap; //! Map of Strings to AnimationInstance pointers - typedef std::map AnimationInstancePointerMap; + typedef std::map AnimationInstancePointerMap; //! Map of Strings to EventLinkDefinition pointers - typedef std::map EventLinkDefinitionPointerMap; + typedef std::map EventLinkDefinitionPointerMap; /** Typedefs for maps of property related elements this WidgetLookFeel owns. */ //! Map of Strings to PropertyInitialiser pointers - typedef std::map PropertyInitialiserPointerMap; + typedef std::map PropertyInitialiserPointerMap; //! Map of Strings to PropertyDefinitionBase pointers - typedef std::map PropertyDefinitionBasePointerMap; - - + typedef std::map PropertyDefinitionBasePointerMap; - /** Typedefs for property related lists. */ - //! \deprecated This type is deprecated because it will be moved into the private section and changed into a map in the next version. - typedef std::vector PropertyList; - //! \deprecated This type is deprecated because it will be moved into the private section and changed into a map in the next version. - typedef std::vector PropertyDefinitionList; - //! \deprecated This type is deprecated because it will be moved into the private section and changed into a map in the next version. - typedef std::vector PropertyLinkDefinitionList; - - - - /** Obtains list of properties definitions. - * @access public - * @return CEGUI::WidgetLookFeel::PropertyDefinitionList List of properties - * definitions - */ - /*! - \deprecated - This function is deprecated because the return type is to be replaced by a map, a bool parameter for WLF-inheritance added. - The function will be replaced by getPropertyDefinitionMap in the next version. - */ - const PropertyDefinitionList& getPropertyDefinitions() const - { - return d_propertyDefinitions; - } - - /** Obtains list of properties link definitions. - * @access public - * @return CEGUI::WidgetLookFeel::PropertyLinkDefinitionList List of - * properties link definitions - */ - /*! - \deprecated - This function is deprecated because the return type is to be replaced by a map, a bool parameter for WLF-inheritance added. - The function will be replaced by getPropertyLinkDefinitionMap in the next version. - */ - const PropertyLinkDefinitionList& getPropertyLinkDefinitions() const - { - return d_propertyLinkDefinitions; - } - - /** Obtains list of properties. - * @access public - * @return CEGUI::WidgetLookFeel::PropertyList List of properties - */ - /*! - \deprecated - This function is deprecated because the return type is to be replaced by a map, a bool parameter for WLF-inheritance added. - The function will be replaced by getPropertyMap in the next version. - */ - const PropertyList& getProperties() const - { - return d_properties; - } //! perform any processing required due to the given font having changed. bool handleFontRenderSizeChange(Window& window, const Font* font) const; @@ -579,13 +535,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to StateImagery pointers. */ - StateImageryPointerMap getStateImageryMap(bool includeInheritedElements = false); + StateImageryPointerMap getStateImageryMap(bool includeInheritedLook = true); /*! \brief @@ -594,13 +550,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to ImagerySection pointers. */ - ImagerySectionPointerMap getImagerySectionMap(bool includeInheritedElements = false); + ImagerySectionPointerMap getImagerySectionMap(bool includeInheritedLook = true); /*! \brief @@ -609,13 +565,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to NamedArea pointers. */ - NamedAreaPointerMap getNamedAreaMap(bool includeInheritedElements = false); + NamedAreaPointerMap getNamedAreaMap(bool includeInheritedLook = true); /*! \brief @@ -624,13 +580,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to WidgetComponent pointers. */ - WidgetComponentPointerMap getWidgetComponentMap(bool includeInheritedElements = false); + WidgetComponentPointerMap getWidgetComponentMap(bool includeInheritedLook = true); /*! \brief @@ -639,13 +595,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to PropertyInitialiser pointers. */ - PropertyInitialiserPointerMap getPropertyInitialiserMap(bool includeInheritedElements = false); + PropertyInitialiserPointerMap getPropertyInitialiserMap(bool includeInheritedLook = true); /*! \brief @@ -654,13 +610,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to PropertyDefinition pointers. */ - PropertyDefinitionBasePointerMap getPropertyDefinitionMap(bool includeInheritedElements = false); + PropertyDefinitionBasePointerMap getPropertyDefinitionMap(bool includeInheritedLook = true); /*! \brief @@ -669,13 +625,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to PropertyLinkDefinition pointers. */ - PropertyDefinitionBasePointerMap getPropertyLinkDefinitionMap(bool includeInheritedElements = false); + PropertyDefinitionBasePointerMap getPropertyLinkDefinitionMap(bool includeInheritedLook = true); /*! \brief @@ -684,13 +640,13 @@ class CEGUIEXPORT WidgetLookFeel : removing elements), then the pointers in this map are not valid anymore. The function should then be called again to retrieve valid pointers. - \param includeInheritedElements + \param includeInheritedLook If set to true, this function will try to also include elements from the inherited WidgetLookFeel. \return A map of names to EventLinkDefinition pointers. */ - EventLinkDefinitionPointerMap getEventLinkDefinitionMap(bool includeInheritedElements = false); + EventLinkDefinitionPointerMap getEventLinkDefinitionMap(bool includeInheritedLook = true); /*! \brief @@ -701,205 +657,205 @@ class CEGUIEXPORT WidgetLookFeel : */ const CEGUI::String& getInheritedWidgetLookName() const; - StringSet getStateImageryNames(bool inherits = false) const; - //! \deprecated This function has been renamed to getStateImageryNames to conform the general way of naming functions, and will be replaced in the next version - StringSet getStateNames(bool inherits = false) const; - StringSet getImagerySectionNames(bool inherits = false) const; - //! \deprecated This function has been renamed to getImagerySectionNames to conform the general way of naming functions, and will be replaced in the next version - StringSet getImageryNames(bool inherits = false) const; - StringSet getNamedAreaNames(bool inherits = false) const; - StringSet getWidgetComponentNames(bool inherits = false) const; - //! \deprecated This function has been renamed to getWidgetComponentNames to conform the general way of naming functions, and will be replaced in the next version - StringSet getWidgetNames(bool inherits = false) const; - StringSet getPropertyInitialiserNames(bool inherits = false) const; - StringSet getPropertyDefinitionNames(bool inherits = false) const; - StringSet getPropertyLinkDefinitionNames(bool inherits = false) const; - StringSet getEventLinkDefinitionNames(bool inherits = false) const; - StringSet getAnimationNames(bool inherits = false) const; - -private: - /*! \brief - Returns a pointer to the inherited WidgetLookFeel. If this WidgetLookFeel does not inherit from another, the function returns 0. + Returns a String-Set of StateImagery names. + + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. \return - A pointer to the inherited WidgetLookFeel. + A StringSet containing the StateImagery names. */ - WidgetLookFeel* getInheritedWidgetLookFeel(); - - - typedef std::map StateList; - typedef std::map ImageryList; - typedef std::map NamedAreaList; - - //! \deprecated The type is deprecated, as it will be changed to a map in the next CEGUI version, in accordance with the existing StateImagery/ImagerySection/NamedArea container types - typedef std::vector WidgetList; + StringSet getStateImageryNames(bool includeInheritedLook = true) const; - typedef std::vector AnimationList; - //! The type is deprecated, as it will be changed to have the correct CEGUI allocator used starting in the next version - typedef std::multimap AnimationInstanceMap; - - //! \deprecated The type is deprecated, as it will be changed to a map in the next CEGUI version, in accordance with the existing StateImagery/ImagerySection/NamedArea container types - typedef std::vector EventLinkDefinitionList; - - //! Name of this WidgetLookFeel. - CEGUI::String d_lookName; - //! Name of a WidgetLookFeel inherited by this WidgetLookFeel. - CEGUI::String d_inheritedLookName; - //! Collection of ImagerySection objects. - ImageryList d_imagerySections; - //! Collection of WidgetComponent objects. - WidgetList d_childWidgets; - //! Collection of StateImagery objects. - StateList d_stateImagery; - //! Collection of PropertyInitialser objects. - PropertyList d_properties; - //! Collection of NamedArea objects. - NamedAreaList d_namedAreas; - //! Collection of PropertyDefinition objects. - mutable PropertyDefinitionList d_propertyDefinitions; - //! Collection of PropertyLinkDefinition objects. - mutable PropertyLinkDefinitionList d_propertyLinkDefinitions; - //! Collection of animation names associated with this WidgetLookFeel. - AnimationList d_animations; - //! map of windows and their associated animation instances - mutable AnimationInstanceMap d_animationInstances; - //! Collection of EventLinkDefinition objects. - EventLinkDefinitionList d_eventLinkDefinitions; + /*! + \brief + Returns a String-Set of ImagerySection names. - // these are container types used when composing final collections of - // objects that come via inheritence. - typedef NamedDefinitionCollator WidgetComponentCollator; - typedef NamedDefinitionCollator PropertyDefinitionCollator; - typedef NamedDefinitionCollator PropertyLinkDefinitionCollator; - typedef NamedDefinitionCollator PropertyInitialiserCollator; - typedef NamedDefinitionCollator EventLinkDefinitionCollator; - typedef std::set AnimationNameSet; + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. - // functions to populate containers with collections of objects that we - // gain through inheritence. - void appendChildWidgetComponents(WidgetComponentCollator& col, bool inherits = true) const; - void appendPropertyDefinitions(PropertyDefinitionCollator& col, bool inherits = true) const; - void appendPropertyLinkDefinitions(PropertyLinkDefinitionCollator& col, bool inherits = true) const; - void appendPropertyInitialisers(PropertyInitialiserCollator& col, bool inherits = true) const; - void appendEventLinkDefinitions(EventLinkDefinitionCollator& col, bool inherits = true) const; - void appendAnimationNames(AnimationNameSet& set, bool inherits = true) const; - - void swap(WidgetLookFeel& other); + \return + A StringSet containing the ImagerySection names. + */ + StringSet getImagerySectionNames(bool includeInheritedLook = true) const; -public: - /************************************************************************* - Iterator stuff - *************************************************************************/ + /*! + \brief + Returns a String-Set of NamedArea names. - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getStateImageryMap function instead to access the container. - typedef ConstMapIterator StateIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getImagerySectionMap function instead to access the container. - typedef ConstMapIterator ImageryIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getNamedAreaMap function instead to access the container. - typedef ConstMapIterator NamedAreaIterator; + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getWidgetComponentMap function instead to access the container. - typedef ConstVectorIterator WidgetComponentIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getPropertyDefinitionMap function instead to access the container. - typedef ConstVectorIterator PropertyDefinitionIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getPropertyLinkDefinitionMap function instead to access the container. - typedef ConstVectorIterator PropertyLinkDefinitionIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getPropertyInitialiserMap function instead to access the container. - typedef ConstVectorIterator PropertyInitialiserIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getEventLinkDefinitionMap function instead to access the container. - typedef ConstVectorIterator EventLinkDefinitionIterator; - //! \deprecated This typedef is deprecated because all iterator getter functions will be removed. Please use the getAnimationNames function instead to access the container. - typedef ConstVectorIterator AnimationNameIterator; + \return + A StringSet containing the NamedArea names. + */ + StringSet getNamedAreaNames(bool includeInheritedLook = true) const; /*! \brief - Returns an iterator for the StateImageries of this WidgetLookFeel. + Returns a String-Set of WidgetComponent (Child Widget) names. + + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getStateImageryMap function instead to access the container. + \return + A StringSet containing the WidgetComponent (Child Widget) names. */ - StateIterator getStateIterator(bool inherits = false) const; + StringSet getWidgetComponentNames(bool includeInheritedLook = true) const; + /*! \brief - Returns an iterator for the ImagerySections of this WidgetLookFeel. + Returns a String-Set of PropertyInitialiser (Property) names. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getImagerySectionMap function instead to access the container. + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. + + \return + A StringSet containing the PropertyInitialiser (Property) names. */ - ImageryIterator getImageryIterator(bool inherits = false) const; + StringSet getPropertyInitialiserNames(bool includeInheritedLook = true) const; /*! \brief - Returns an iterator for the NamedAreas of this WidgetLookFeel. + Returns a String-Set of PropertyDefinition names. + + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getNamedAreaMap function instead to access the container. + \return + A StringSet containing the PropertyDefinition names. */ - NamedAreaIterator getNamedAreaIterator(bool inherits = false) const; + StringSet getPropertyDefinitionNames(bool includeInheritedLook = true) const; /*! \brief - Returns an iterator for the WidgetComponents of this WidgetLookFeel. + Returns a String-Set of PropertyLinkDefinition names. + + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getWidgetComponentMap function instead to access the container. + \return + A StringSet containing the PropertyLinkDefinition names. */ - WidgetComponentIterator getWidgetComponentIterator(bool inherits = false) const; + StringSet getPropertyLinkDefinitionNames(bool includeInheritedLook = true) const; /*! \brief - Returns an iterator for the PropertyDefinitions of this WidgetLookFeel. + Returns a String-Set of EventLinkDefinition names. + + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getPropertyDefinitionMap function instead to access the container. + \return + A StringSet containing the EventLinkDefinition names. */ - PropertyDefinitionIterator getPropertyDefinitionIterator(bool inherits = false) const; + StringSet getEventLinkDefinitionNames(bool includeInheritedLook = true) const; /*! \brief - Returns an iterator for the PropertyLinkDefinitions of this WidgetLookFeel. + Returns a String-Set of Animation names. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getPropertyLinkDefinitionMap function instead to access the container. + \param includeInheritedLook + If true, this will also add the names from the inherited WidgetLook. + + \return + A StringSet containing the Animation names. */ - PropertyLinkDefinitionIterator getPropertyLinkDefinitionIterator(bool inherits = false) const; + StringSet getAnimationNames(bool includeInheritedLook = true) const; + +private: /*! \brief - Returns an iterator for the PropertyInitialisers of this WidgetLookFeel. + Returns a pointer to the inherited WidgetLookFeel. If this WidgetLookFeel does not inherit from another, the function returns 0. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getPropertyInitialiserMap function instead to access the container. + \return + A pointer to the inherited WidgetLookFeel. */ - PropertyInitialiserIterator getPropertyInitialiserIterator(bool inherits = false) const; + WidgetLookFeel* getInheritedWidgetLookFeel(); /*! \brief - Returns an iterator for the EventLinkDefinitions of this WidgetLookFeel. + Copies the PropertyDefinitions from another WidgetLookFeel. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getEventLinkDefinitionMap function instead to access the container. + \param widgetLook + WidgetLookFeel object to copy the PropertyDefinitions from. */ - EventLinkDefinitionIterator getEventLinkDefinitionIterator(bool inherits = false) const; + void copyPropertyDefinitionsFrom(const WidgetLookFeel& widgetLook); /*! \brief - Returns an iterator for the AnimationNames of this WidgetLookFeel. + Copies the PropertyLinkDefinitions from another WidgetLookFeel. - \deprecated - This function is deprecated because all iterator getter functions will be removed. Please use the getAnimationNames function instead to access the container. + \param widgetLook + WidgetLookFeel object to copy the PropertyLinkDefinitions from. */ - AnimationNameIterator getAnimationNameIterator(bool inherits = false) const; + void copyPropertyLinkDefinitionsFrom(const WidgetLookFeel& widgetLook); + + + //! Map types for the Falagard elements that this WidgetLookFeel can own. The keys are the names of the corresponding elements, as CEGUI::String. + typedef std::map StateImageryMap; + typedef std::map ImagerySectionMap; + typedef std::map NamedAreaMap; + + typedef std::map PropertyInitialiserMap; + typedef std::map PropertyDefinitionMap; + typedef std::map PropertyLinkDefinitionMap; + + typedef std::map WidgetComponentMap; + typedef std::map EventLinkDefinitionMap; + + //! List of animation names + typedef std::vector AnimationList; + //! Map of Windows to AnimationInstances + typedef std::multimap > AnimationInstanceMap; + + //! Name of this WidgetLookFeel. + CEGUI::String d_lookName; + //! Name of a WidgetLookFeel inherited by this WidgetLookFeel. + CEGUI::String d_inheritedLookName; + //! Map of ImagerySection objects. + ImagerySectionMap d_imagerySectionMap; + //! Map of WidgetComponent objects. + WidgetComponentMap d_widgetComponentMap; + //! Map of StateImagery objects. + StateImageryMap d_stateImageryMap; + //! Map of PropertyInitialser objects. + PropertyInitialiserMap d_propertyInitialiserMap; + //! Map of NamedArea objects. + NamedAreaMap d_namedAreaMap; + //! Map of PropertyDefinition objects. + mutable PropertyDefinitionMap d_propertyDefinitionMap; + //! Map of PropertyLinkDefinition objects. + mutable PropertyLinkDefinitionMap d_propertyLinkDefinitionMap; + //! List of animation names associated with this WidgetLookFeel. + AnimationList d_animations; + //! Map of windows and their associated animation instances + mutable AnimationInstanceMap d_animationInstances; + //! Collection of EventLinkDefinition objects. + EventLinkDefinitionMap d_eventLinkDefinitionMap; + + // these are container types used when composing final collections of + // objects that come via inheritence. + typedef NamedDefinitionCollator WidgetComponentCollator; + typedef NamedDefinitionCollator PropertyDefinitionCollator; + typedef NamedDefinitionCollator PropertyLinkDefinitionCollator; + typedef NamedDefinitionCollator PropertyInitialiserCollator; + typedef NamedDefinitionCollator EventLinkDefinitionCollator; + typedef std::set AnimationNameSet; + + // functions to populate containers with collections of objects that we + // gain through inheritence. + void appendChildWidgetComponents(WidgetComponentCollator& col, bool inherits = true) const; + void appendPropertyDefinitions(PropertyDefinitionCollator& col, bool inherits = true) const; + void appendPropertyLinkDefinitions(PropertyLinkDefinitionCollator& col, bool inherits = true) const; + void appendPropertyInitialisers(PropertyInitialiserCollator& col, bool inherits = true) const; + void appendEventLinkDefinitions(EventLinkDefinitionCollator& col, bool inherits = true) const; + void appendAnimationNames(AnimationNameSet& set, bool inherits = true) const; + + void swap(WidgetLookFeel& other); }; } diff --git a/cegui/include/CEGUI/falagard/WidgetLookManager.h b/cegui/include/CEGUI/falagard/WidgetLookManager.h index ec2cd1258..f85cb2366 100644 --- a/cegui/include/CEGUI/falagard/WidgetLookManager.h +++ b/cegui/include/CEGUI/falagard/WidgetLookManager.h @@ -47,8 +47,7 @@ namespace CEGUI Manager class that gives top-level access to widget data based "look and feel" specifications loaded into the system. */ class CEGUIEXPORT WidgetLookManager : - public Singleton, - public AllocatedObject + public Singleton { public: /*! @@ -84,10 +83,10 @@ namespace CEGUI /** Typedef for a set of WidgetLookFeel names. */ - typedef std::set WidgetLookNameSet; + typedef std::set WidgetLookNameSet; //! Typedef for a map of Strings to WidgetLookFeel objects - typedef std::map WidgetLookPointerMap; + typedef std::map WidgetLookPointerMap; /*! \brief @@ -111,12 +110,12 @@ namespace CEGUI \exception InvalidRequestException thrown if an invalid filename was provided. */ void parseLookNFeelSpecificationFromContainer(const RawDataContainer& source); - + /*! \see WidgetLookManager::parseLookNFeelSpecificationFromContainer */ void parseLookNFeelSpecificationFromFile(const String& filename, const String& resourceGroup = ""); - + /*! \see WidgetLookManager::parseLookNFeelSpecificationFromContainer */ @@ -211,7 +210,7 @@ namespace CEGUI String containing the WidgetLook parsed to XML. */ String getWidgetLookAsString(const String& widgetLookName) const; - + /*! \brief Writes a set WidgetLookFeels to a string. Note that XML file header and @@ -232,7 +231,7 @@ namespace CEGUI The \a prefix specifies a name prefix common to all widget looks to be written, you could specify this as "TaharezLook/" and then any defined widget look starting with that prefix, such - as "TaharezLook/Button" and "TaharezLook/Listbox" will be written to the stream. + as "TaharezLook/Button" and "TaharezLook/ListWidget" will be written to the stream. \param prefix String holding the widget look name prefix, which will be used when searching for the widget looks @@ -300,19 +299,11 @@ namespace CEGUI static String d_defaultResourceGroup; - //! Typedef for a map of Strings to WidgetLookFeel objects - // \deprecated Will use the correct allocator in the next version and will - // be renamed to "WidgetLookMap" + //! Typedef for a map of Strings to WidgetLookFeel instances typedef std::map WidgetLookList; //! List of WidgetLookFeels added to this Manager WidgetLookList d_widgetLooks; - - public: - //! \deprecated Use WidgetLookPointerMap instead, which provides direct access to the added elements. - typedef ConstMapIterator WidgetLookIterator; - //! \deprecated Use getWidgetLookPointerMap instead, which provides direct access to the added elements. In the next version getWidgetLookMap will be added to replace the const-ness. - WidgetLookIterator getWidgetLookIterator() const; }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/falagard/XMLHandler.h b/cegui/include/CEGUI/falagard/XMLHandler.h index 9723bcd6f..b5e58c573 100644 --- a/cegui/include/CEGUI/falagard/XMLHandler.h +++ b/cegui/include/CEGUI/falagard/XMLHandler.h @@ -604,8 +604,7 @@ namespace CEGUI NamedArea* d_namedArea; FrameComponent* d_framecomponent; - std::vector d_dimStack; + std::vector d_dimStack; PropertyDefinitionBase* d_propertyLink; EventLinkDefinition* d_eventLink; diff --git a/cegui/include/CEGUI/svg/SVGBasicShape.h b/cegui/include/CEGUI/svg/SVGBasicShape.h new file mode 100644 index 000000000..22e7549d5 --- /dev/null +++ b/cegui/include/CEGUI/svg/SVGBasicShape.h @@ -0,0 +1,282 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVGBasicShape_h_ +#define _SVGBasicShape_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/Vector.h" + +#include "CEGUI/svg/SVGPaintStyle.h" +#include "CEGUI/svg/SVGImage.h" + +#include "glm/glm.hpp" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ +class GeometryBuffer; + +/*! +\brief + Defines a class that acts as interface for several classes that store the data of SVG BasicShapes. +*/ +class CEGUIEXPORT SVGBasicShape +{ +public: + SVGBasicShape() {} + SVGBasicShape(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation); + + virtual ~SVGBasicShape(); + + /*! + \brief + Renders the shape into a new geometry buffer and adds it to the list. + \param geometry_buffers + The GeometryBuffer list to which the new geometry of this Image will be added to. + \param render_settings + The ImageRenderSettings that contain render settings for new GeometryBuffers. + */ + virtual void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const = 0; + + + //! The BasicShape's style, which describes the filling and stroke of the graphical element. + SVGPaintStyle d_paintStyle; + //! The matrix transformation to apply to the element. + glm::mat3x3 d_transformation; +}; + + +/*! +\brief + Defines a class for storing the data of the SVG 'rect' element based on how it is defined in the SVG standard. + + The 'rect' element defines a rectangle which is axis-aligned with the current user coordinate system. + Rounded rectangles can be achieved by setting appropriate values for attributes 'rx' and 'ry'. + http://www.w3.org/TR/SVGTiny12/shapes.html#RectElement +*/ +class CEGUIEXPORT SVGRect : public SVGBasicShape +{ +public: + SVGRect() + {} + + SVGRect(const SVGPaintStyle& paint_style, const glm::mat3x3& transformation, + const float x, const float y, + const float width, const float height, + const float rx = 0.0f, const float ry = 0.0f); + + //! Implementation of SVGBasicShape interface + void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const; + + //! The x-axis coordinate of the side of the rectangle which has the smaller x-axis coordinate value in the current user coordinate system + float d_x; + //! The y-axis coordinate of the side of the rectangle which has the smaller y-axis coordinate value in the current user coordinate system. + float d_y; + //! The width of the rectangle. A negative value is unsupported. A value of zero disables rendering of the element. + float d_width; + //! The height of the rectangle. A negative value is unsupported. A value of zero disables rendering of the element. + float d_height; + //! For rounded rectangles, the x-axis radius of the ellipse used to round off the corners of the rectangle. A negative value is unsupported. + float d_rx; + //! For rounded rectangles, the y-axis radius of the ellipse used to round off the corners of the rectangle. A negative value is unsupported. + float d_ry; +}; + + +/*! +\brief + Defines a class for storing the data of the SVG 'circle' element based on how it is defined in the SVG standard. + + The 'circle' element defines a circle based on a center point and a radius. + http://www.w3.org/TR/SVGTiny12/shapes.html#CircleElement +*/ +class CEGUIEXPORT SVGCircle : public SVGBasicShape +{ +public: + SVGCircle() + {} + + SVGCircle(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const float cx, + const float cy, + const float r); + + //! Implementation of SVGBasicShape interface + void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const; + + //! The x-axis coordinate of the center of the circle. + float d_cx; + //! The y-axis coordinate of the center of the circle. + float d_cy; + //! The radius of the circle. A negative value is unsupported. Default = 0. + float d_r; +}; + + +/*! +\brief + Defines a class for storing the data of the SVG 'ellipse' element based on how it is defined in the SVG standard. + + The 'ellipse' element defines an ellipse which is axis-aligned with the current user coordinate system based on a center point and two radii. + http://www.w3.org/TR/SVGTiny12/shapes.html#EllipseElement +*/ +class CEGUIEXPORT SVGEllipse : public SVGBasicShape +{ +public: + SVGEllipse() + {} + + SVGEllipse(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const float cx, + const float cy, + const float rx, + const float ry); + + //! Implementation of SVGBasicShape interface + void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const; + + //! The x-axis coordinate of the center of the ellipse. + float d_cx; + //! The y-axis coordinate of the center of the ellipse. + float d_cy; + //! The x-axis radius of the ellipse. A negative value is unsupported. Default = 0. + float d_rx; + //! The y-axis radius of the ellipse. A negative value is unsupported. Default = 0. + float d_ry; +}; + + +/*! +\brief + Defines a class for storing the data of the SVG 'line' element based on how it is defined in the SVG standard. + + The 'line' element defines a line segment that starts at one point and ends at another. + http://www.w3.org/TR/SVGTiny12/shapes.html#LineElement +*/ +class CEGUIEXPORT SVGLine : public SVGBasicShape +{ +public: + //! Constructors + SVGLine(const SVGPaintStyle& paint_style, const glm::mat3x3& transformation, + const float x1, const float y1, + const float x2, const float y2); + + SVGLine(const SVGPaintStyle& paint_style, const glm::mat3x3& transformation, + const glm::vec2& line_start, const glm::vec2& line_end); + + SVGLine() + {} + + //! Implementation of SVGBasicShape interface + void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const; + + //! The x-axis coordinate of the start of the line + float d_x1; + //! The y-axis coordinate of the start of the line + float d_y1; + //! The x-axis coordinate of the end of the line + float d_x2; + //! The y-axis coordinate of the end of the line + float d_y2; +}; + +/*! +\brief + Defines a class for storing the data of the SVG 'polyline' element based on how it is defined in the SVG standard. + + The 'polyline' element defines a set of connected straight line segments. + Typically, 'polyline' elements define open shapes. + http://www.w3.org/TR/SVGTiny12/shapes.html#PolylineElement +*/ +class CEGUIEXPORT SVGPolyline : public SVGBasicShape +{ +public: + //! Constructor + SVGPolyline(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const std::vector& points); + + SVGPolyline() + {} + + //! Implementation of SVGBasicShape interface + void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const; + + //! The points defining the line + std::vector d_points; +}; + + +/*! +\brief + Defines a class for storing the data of the SVG 'polygon' element based on how it is defined in the SVG standard. + + The 'polygon' element defines a closed shape consisting of a set of connected straight line segments. + http://www.w3.org/TR/SVGTiny12/shapes.html#PolygonElement +*/ +class CEGUIEXPORT SVGPolygon : public SVGBasicShape +{ +public: + //! Constructor + SVGPolygon(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const std::vector& points); + + SVGPolygon() + {} + + //! Implementation of SVGBasicShape interface + void render(std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const; + + //! The points defining the line + std::vector d_points; +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif + diff --git a/cegui/include/CEGUI/svg/SVGData.h b/cegui/include/CEGUI/svg/SVGData.h new file mode 100644 index 000000000..767795349 --- /dev/null +++ b/cegui/include/CEGUI/svg/SVGData.h @@ -0,0 +1,363 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVGData_h_ +#define _SVGData_h_ + +#include "CEGUI/ChainedXMLHandler.h" +#include "CEGUI/Base.h" +#include "CEGUI/String.h" +#include "CEGUI/svg/SVGPaintStyle.h" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + + +namespace CEGUI +{ +class SVGBasicShape; + +/*! +\brief + Defines a class for the SVG data. + + The SVGData class stores data of a vector graphics image based on the SVG Tiny 1.2 + file standard. The SVGData is utilised by the SVGImage class. + + The data for this class can be either be created by parsing it from an SVG file + or be added manually by a user to draw custom geometry. +*/ +class CEGUIEXPORT SVGData : + public ChainedXMLHandler +{ +public: + //! Enumerator describing the available unit types in the SVG standard for the length type + enum SVGUnit + { + SLU_UNDEFINED, + SLU_IN, + SLU_CM, + SLU_MM, + SLU_PT, + SLU_PC, + SLU_PX, + SLU_PERCENT, + + SLU_COUNT + }; + + struct SVGLength + { + SVGLength() : + d_value(0.f), + d_unit(SLU_UNDEFINED) + {} + + float d_value; + SVGUnit d_unit; + }; + + SVGData(const String& name); + + SVGData(const String& name, + const String& filename, + const String& resourceGroup); + + ~SVGData(); + + + /*! + \brief + Returns the name given to the SVGData when it was created. + + \return + Reference to a String object that holds the name of the SVGData. + */ + const String& getName() const; + + /*! + \brief + Loads and parses the specified SVG file into this SVGData object. + + \param file_name + The filename of the SVG file that is to be loaded. + + \param resource_group + Resource group identifier to be passed to the resource provider when + loading the image file. + + \return + Nothing. + */ + void loadFromFile(const String& file_name, + const String& resource_group); + + /*! + \brief + Adds a SVGBasicShape to the list of shapes of this class. This class takes ownership + of the passed object and will free the memory itself. + \param svg_shape + The SVGBasicShape that will be added. + */ + void addShape(SVGBasicShape* svg_shape); + + /*! + \brief + Deletes all shapes in the list and clears the list. + */ + void destroyShapes(); + + /*! + \brief + Returns the list of shapes of this class. + \return + The list of shapes of this class. + */ + const std::vector& getShapes() const; + + /*! + \brief + Returns the SVGData's width in pixels. + \return + The SVGData's width in pixels. + */ + float getWidth() const; + + /*! + \brief + Sets the SVGData's width in pixels. + \param width + The width in pixels. + */ + void setWidth(float width); + + /*! + \brief + Returns the SVGData's height in pixels. + \return + The SVGData's height in pixels. + */ + float getHeight() const; + + /*! + \brief + Sets the SVGData's height in pixels. + \param width + The height in pixels. + */ + void setHeight(float height); + +protected: + // implement chained xml handler abstract interface + void elementStartLocal(const String& element, + const XMLAttributes& attributes); + void elementEndLocal(const String& element); + + /*! + \brief + Function that handles the opening SVG element. + + \note + This function processes the SVG document fragment which contains + the SVG graphics elements, container elements, etc. ... + + */ + void elementSVGStart(const XMLAttributes& attributes); + + /*! + \brief + Function that handles opening SVG 'rect' elements. + + \note + This function processes the SVG 'rect' element. + */ + void elementSVGRect(const XMLAttributes& attributes); + + /*! + \brief + Function that handles opening SVG 'circle' elements. + + \note + This function processes the SVG 'circle' element. + */ + void elementSVGCircle(const XMLAttributes& attributes); + + /*! + \brief + Function that handles opening SVG 'ellipse' elements. + + \note + This function processes the SVG 'ellipse' element. + */ + void elementSVGEllipse(const XMLAttributes& attributes); + + /*! + \brief + Function that handles opening SVG 'line' elements. + + \note + This function processes the SVG 'line' element. + */ + void elementSVGLine(const XMLAttributes& attributes); + + /*! + \brief + Function that handles opening SVG 'polyline' elements. + + \note + This function processes the SVG 'polyline' element. + */ + void elementSVGPolyline(const XMLAttributes& attributes); + + /*! + \brief + Function that handles opening SVG 'polygon' elements. + + \note + This function processes the SVG 'polygon' element. + */ + void elementSVGPolygon(const XMLAttributes& attributes); + + //! Name of this SVGData objects + CEGUI::String d_name; + /*! + \brief + The SVGData's width in pixels. + + This is the value representing the intrinsic width of the 'SVG document fragment'. It is used in CEGUI + to determine the clipping area of the SVG image and to scale the image elements in case the Image is + rendered with horizontal stretching. + */ + float d_width; + /*! + \brief + The SVGData's height in pixels. + + This is the value representing the intrinsic height of the 'SVG document fragment'. It is used in CEGUI + to determine the clipping area of the SVG image and to scale the image elements in case the Image is + rendered with vertical stretching. + */ + float d_height; + + //! The basic shapes that were added to the SVGData + std::vector d_svgBasicShapes; + +private: + /*! + \brief + Function that parses the paint style (fill and stroke parameters) from an SVG graphics element. + \param attributes + The XML attributes from which the values will be parsed. + */ + static SVGPaintStyle parsePaintStyle(const XMLAttributes& attributes); + + //! Parses the String value of a 'fill' property + static void parsePaintStyleFill(const String& fillString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'fill-rule' property + static void parsePaintStyleFillRule(const String& fillRuleString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'fill-opacity' property + static void parsePaintStyleFillOpacity(const String& fillOpacityString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke' property + static void parsePaintStyleStroke(const String& strokeString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-width' property + static void parsePaintStyleStrokeWidth(const String& strokeWidthString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-linecap' property + static void parsePaintStyleStrokeLinecap(const String& strokeLinecapString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-linejoin' property + static void parsePaintStyleStrokeLinejoin(const String& strokeLinejoinString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-miterlimit' property + static void parsePaintStyleMiterlimitString(const String& strokeMiterLimitString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-dasharray' property + static void parsePaintStyleStrokeDashArray(const String& strokeDashArrayString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-dashoffset' property + static void parsePaintStyleStrokeDashOffset(const String& strokeDashOffsetString, SVGPaintStyle& paint_style); + + //! Parses the String value of a 'stroke-opacity' property + static void parsePaintStyleStrokeOpacity(const String& strokeOpacityString, SVGPaintStyle& paint_style); + + /*! + \brief + Function that parses a String into an SVG length object and returns it. + + \param length_string + The String containing the characters that should be parsed into an SVG length. + + \return + The SVGLength object. + + \exception SVGParsingException thrown if there was some problem parsing the String. + */ + static SVGData::SVGLength parseLengthDataType(const String& length_string); + + //! Parses the String value of a 'points' property + static void parsePointsString(const String &pointsString, std::vector& points); + + /*! + \brief + Function that parses a 'transform' attribute and creates a mat3x3 from it. + \param attributes + The XML attributes from which the values will be parsed. + */ + static glm::mat3x3 parseTransform(const XMLAttributes& attributes); + + /*! + \brief + Function that parses the an SVG list of lengths from a String. + \param list_of_lengths_string + The String containing the list of lengths. + */ + static std::vector parseListOfLengths(const String& list_of_lengths_string); + + /*! + \brief + Function that parses an SVG paint colour and returns the CEGUI Colour created from it. + \param colour_string + The colour String value from which the colour values will be parsed; + */ + static glm::vec3 parseColour(const CEGUI::String& colour_string); +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif + diff --git a/cegui/include/CEGUI/svg/SVGDataManager.h b/cegui/include/CEGUI/svg/SVGDataManager.h new file mode 100644 index 000000000..f6fb70050 --- /dev/null +++ b/cegui/include/CEGUI/svg/SVGDataManager.h @@ -0,0 +1,177 @@ +/*********************************************************************** + created: 1st August 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVGDataManager_h_ +#define _SVGDataManager_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/Singleton.h" +#include "CEGUI/String.h" +#include "CEGUI/IteratorBase.h" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + + +namespace CEGUI +{ +class SVGData; + +class CEGUIEXPORT SVGDataManager : + public Singleton +{ +public: + SVGDataManager(); + ~SVGDataManager(); + + /*! + \brief + Creates an instance of SVGData class registered using the name \a name. + + \param name + String object describing the name that the newly created instance will + be created with. This name must be unique within the system. + + \exception UnknownObjectException + thrown if no Image subclass has been registered using identifier \a type. + + \exception AlreadyExistsException + thrown if an Image instance named \a name already exists. + */ + SVGData& create(const String& name); + + /*! + \brief + Creates an instance of SVGData class registered using the name \a name. + + \param name + String object describing the name that the newly created instance will + be created with. This name must be unique within the system. + + \param filename + String object that specifies the path and filename of the image file to + use when creating the texture. + + \param resourceGroup + String object that specifies the resource group identifier to be passed + to the resource provider when loading the texture file \a filename. + + \exception UnknownObjectException + thrown if no Image subclass has been registered using identifier \a type. + + \exception AlreadyExistsException + thrown if an Image instance named \a name already exists. + */ + SVGData& create(const String& name, + const String& filename, + const String& resourceGroup); + + /*! + \brief + Destroys the SVGData object. + + \param svgData + The object to destroy + */ + void destroy(SVGData& svgData); + + /*! + \brief + Destroys the SVGData object registered using the name \a name. + + \param name + The String holding the name of the SVGData object to be destroyed. + */ + void destroy(const String& name); + + /*! + \brief + Destroys all of the SVGData objects created with this manager. + */ + void destroyAll(); + + /*! + \brief + Returns a SVGData object that was previously created by calling a + create function of this class. + + \param name + String holding the name of the SVGData object to be returned. + + \exceptions + - UnknownObjectException - thrown if no SVGData object named \a name + exists within the system. + */ + SVGData& getSVGData(const String& name) const; + + + /*! + \brief + Return whether an SVGData object with the given name exists. + + \param name + String holding the name of the SVGData object to be checked. + */ + bool isSVGDataDefined(const String& name) const; + + + //! container type used to hold the SVGData objects. + typedef std::map SVGDataMap; + + //! ConstBaseIterator type definition. + typedef SVGDataMap::iterator SVGDataIterator; + + static SVGDataManager& getSingleton(); + static SVGDataManager* getSingletonPtr(); + +protected: + /*! + \brief + Logs the creation of the SVGData object. + + \param svgData + The SVGData object that was created. + */ + void logSVGDataCreation(SVGData* svgData); + + //! container holding the SVGData objects. + SVGDataMap d_svgDataMap; +}; + + + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif + diff --git a/cegui/include/CEGUI/svg/SVGImage.h b/cegui/include/CEGUI/svg/SVGImage.h new file mode 100644 index 000000000..587c29200 --- /dev/null +++ b/cegui/include/CEGUI/svg/SVGImage.h @@ -0,0 +1,132 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVGImage_h_ +#define _SVGImage_h_ + +#include "CEGUI/Image.h" + +#include "glm/glm.hpp" + +namespace CEGUI +{ +class SVGData; + +/*! +\brief + Defines the SVGImage class, which describes a vector graphics image that can be + rendered by CEGUI. + +*/ +class CEGUIEXPORT SVGImage : public Image +{ +public: + /*! + \brief + A struct that contains the render settings for the SVGImage class. + */ + struct SVGImageRenderSettings : public ImageRenderSettings + { + //! Constructor + SVGImageRenderSettings(const ImageRenderSettings& img_render_settings, + const glm::vec2& scale_factor, + bool anti_aliasing) : + ImageRenderSettings(img_render_settings), + d_scaleFactor(scale_factor), + d_antiAliasing(anti_aliasing) + { + } + + //! The scaling factor of the geometry + glm::vec2 d_scaleFactor; + //! Create anti-aliasing geometry using alpha-blending for all shapes + bool d_antiAliasing; + }; + + SVGImage(const String& name); + SVGImage(const String& name, SVGData& svg_data); + SVGImage(const XMLAttributes& attributes); + + // Implement CEGUI::Image interface + void render(std::vector& image_geometry_buffers, + const ImageRenderSettings& render_settings) const; + + /*! + \brief + Sets the SVGData object of this SVGImage. + + \param texture + The pointer to the SVGData object to be used by this SVGImage. Can be 0. + */ + void setSVGData(SVGData* svg_Data); + + /*! + \brief + Returns the pointer to the SVGData object of this SVGImage. + + \return + The pointer to the SVGData object of this SVGImage. Can be 0. + */ + SVGData* getSVGData(); + + /*! + \brief + Returns if the rendered geometry of this Image will be extended with geometry + that creates an alpha-blended transition to defeat aliasing artefacts. + */ + bool getUsesGeometryAntialiasing() const; + + /*! + \brief + Sets if the rendered geometry will be extended with geometry that creates + an alpha-blended transition to defeat aliasing artefacts. + \param use_geometry_antialiasing + The setting for geometry anti-aliasing that wille be applied to this Image. + */ + void setUseGeometryAntialiasing(bool use_geometry_antialiasing); + +protected: + /*! + \brief + Reference to the SVGData used as basis for drawing. The SVGData can be shared + between SVGImages. Changing the SVGData object will result in changes between all + SVGImages. + */ + SVGData* d_svgData; + + + /*! + \brief + Determines if the rendered geometry will be extended with geometry that creates + an alpha-blended transition to defeat aliasing artefacts + */ + bool d_useGeometryAntialiasing; +}; + +} + +#endif + diff --git a/cegui/include/CEGUI/svg/SVGPaintStyle.h b/cegui/include/CEGUI/svg/SVGPaintStyle.h new file mode 100644 index 000000000..7b95c47c8 --- /dev/null +++ b/cegui/include/CEGUI/svg/SVGPaintStyle.h @@ -0,0 +1,194 @@ +/*********************************************************************** + created: 1st August 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVGShapeStyle_h_ +#define _SVGShapeStyle_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/Colour.h" +#include "CEGUI/GeometryBuffer.h" +#include "glm/glm.hpp" + +#include + +#if defined(_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ + +/*! +\brief + Defines the 'paint' type based on how it is used in SVG. Main purpose is for defining how + 'fill' and 'stroke' are to be drawn. +*/ +class CEGUIEXPORT SVGPaint +{ +public: + SVGPaint(); + + //! Defines if the paint is to be drawn at all. + bool d_none; + //! Defines the colour of the paint. + glm::vec3 d_colour; +}; + +/*! +\brief + Defines the SVGShapeStyle class, which describes the overall shape style of an SVG shape. +*/ +class CEGUIEXPORT SVGPaintStyle +{ +public: + /*! + \brief + Specifies the shape which shall be used at the end of open subpaths when they are stroked. + */ + enum SVGLinecap + { + //! A simple linear cap through the endpoint. + SLC_BUTT, + //! A rounded cap with the endpoint as center. + SLC_ROUND, + //! A simple linear cap that is offset from the endpoint by the stroke width. + SLC_SQUARE, + + SLC_COUNT + }; + + /*! + \brief + Specifies the shape which shall be used at the corners of shapes when they are stroked. + */ + enum SVGLinejoin + { + /*! + \brief + Makes two lines join at the intersection points of their outlines. This can be influenced + by the value set for stroke-miterlimit. In the case the miter is exceedingly long a bevel + linejoin will then be used for that corner. + */ + SLJ_MITER, + //! A rounded linejoin. + SLJ_ROUND, + //! A linejoin with two corners. + SLJ_BEVEL, + + SLJ_COUNT + }; + + + SVGPaintStyle(); + + //! The 'fill' property defines how the interior of a graphical element must be painted. + SVGPaint d_fill; + + /*! + \brief + The 'fill-rule' property indicates the algorithm which must be used to determine what parts + of the canvas are included inside the shape. + */ + PolygonFillRule d_fillRule; + + /*! + \brief + The opacity setting that will be applied to the fill. Values must be inside range 0.0 + (fully transparent) to 1.0 (fully opaque). Default is 1.0. + */ + float d_fillOpacity; + + //! The 'stroke' property defines how the stroke of a graphical element must be painted. + SVGPaint d_stroke; + + /*! + \brief + The width of the stroke which shall be used on the current object. + No stroke shall be painted for a zero value. A negative value is unsupported and must be + treated as if the stroke had not been specified. Default is 1.0. + */ + float d_strokeWidth; + + /*! + \brief + Specifies the shape which shall be used at the end of open subpaths when they are stroked. + */ + SVGLinecap d_strokeLinecap; + + /*! + \brief + Specifies the shape which shall be used at the corners of shapes when they are stroked. + */ + SVGLinejoin d_strokeLinejoin; + + /*! + \brief + When two line segments meet at a sharp angle and miter joins have been specified for 'stroke-linejoin', + it is possible for the miter to extend far beyond the thickness of the line stroking the path. The + 'stroke-miterlimit' imposes a limit on the ratio of the miter length to the 'stroke-width'. When the + limit is exceeded, the join must be converted from a miter to a bevel. + The limit on the ratio of the miter length to the 'stroke-width'. The value of must be a + number greater than or equal to 1. Any other value shall be treated as unsupported and processed as if + the property had not been specified. + */ + float d_strokeMiterlimit; + + /*! + \brief + Indicates if dashing shall be used. If stroked and dash array is set to none, the line must be drawn solid. + */ + bool d_strokeDashArrayNone; + + /*! + \brief + Specifies the pattern of dashes and gaps that shall be used to stroke paths. + */ + std::vector d_strokeDashArray; + + /*! + \brief + Specifies the distance into the dash pattern that must be used to start the dash. + */ + float d_strokeDashOffset; + + /*! + \brief + The opacity setting that will be applied to the stroke. Values must be inside range 0.0 + (fully transparent) to 1.0 (fully opaque). Default is 1.0. + */ + float d_strokeOpacity; +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif + diff --git a/cegui/include/CEGUI/svg/SVGTesselator.h b/cegui/include/CEGUI/svg/SVGTesselator.h new file mode 100644 index 000000000..fd6379e7c --- /dev/null +++ b/cegui/include/CEGUI/svg/SVGTesselator.h @@ -0,0 +1,600 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVGTesselator_h_ +#define _SVGTesselator_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/Vertex.h" +#include "CEGUI/svg/SVGImage.h" +#include "CEGUI/svg/SVGPaintStyle.h" + +#include "glm/glm.hpp" + +#include + +namespace CEGUI +{ +class GeometryBuffer; +class SVGRect; +class SVGCircle; +class SVGEllipse; +class SVGLine; +class SVGPolyline; +class SVGPolygon; +class SVGPaintStyle; +/*! +\brief + Defines a static class that provides helper functions for the tesselation of + SVGBasicShapes. +*/ +class CEGUIEXPORT SVGTesselator +{ +public: + + //! Object containing the data needed for rendering segments + class StrokeSegmentData + { + public: + StrokeSegmentData(GeometryBuffer& geometry_buffer, const float stroke_half_width, const SVGPaintStyle& paint_style, const float max_scale); + + /*! + \brief + Sets the pointers to the line points of this segment + */ + void setPoints(const glm::vec2& prev_point, + const glm::vec2& cur_point, + const glm::vec2& next_point); + + //! Half of the width of the stroke + const float d_strokeHalfWidth; + //! The geometry buffer we will draw into + GeometryBuffer& d_geometryBuffer; + //! The paint style + const SVGPaintStyle& d_paintStyle; + + //! Last left stroke point, lying in anti-clockwise direction away from the stroke direction. + glm::vec2 d_lastPointLeft; + //! Last right stroke point, lying in clockwise direction away from the stroke direction. + glm::vec2 d_lastPointRight; + //! Last left stroke fade point, lying in anti-clockwise direction away from the stroke direction. + glm::vec2 d_lastFadePointLeft; + //! Last right stroke fade point, lying in clockwise direction away from the stroke direction. + glm::vec2 d_lastFadePointRight; + + //! Current left stroke point, lying in anti-clockwise direction away from the stroke direction. + glm::vec2 d_currentPointLeft; + //! Current right stroke point, lying in clockwise direction away from the stroke direction. + glm::vec2 d_currentPointRight; + //! Current left stroke fade point, lying in anti-clockwise direction away from the stroke direction. + glm::vec2 d_currentFadePointLeft; + //! Current right stroke fade point, lying in clockwise direction away from the stroke direction. + glm::vec2 d_currentFadePointRight; + + //! Last left stroke point, lying in anti-clockwise direction away from the stroke direction. + glm::vec2 d_subsequentPointLeft; + //! Last right stroke point, lying in clockwise direction away from the stroke direction. + glm::vec2 d_subsequentPointRight; + //! Last left stroke fade point, lying in anti-clockwise direction away from the stroke direction. + glm::vec2 d_subsequentFadePointLeft; + //! Last right stroke fade point, lying in clockwise direction away from the stroke direction. + glm::vec2 d_subsequentFadePointRight; + + //! The vertex we will modify with positions and append to the GeometryBuffer + ColouredVertex d_strokeVertex; + //! The vertex we will modify with positions and append to the GeometryBuffer + ColouredVertex d_strokeFadeVertex; + + //! The maximum of the scalings (either vert or horz). We need this to determine the degree of tesselation + // of curved elements of the stroke + float d_maxScale; + + //! Anti-aliasing offsets, the first element represents the offset of the solid stroke, the second is for the + // offset of the alpha-fade + glm::vec2 d_antiAliasingOffsets; + + //! Pointer to the previous line point of this segment + const glm::vec2* d_prevPoint; + //! Pointer to the current line point of this segment + const glm::vec2* d_curPoint; + //! Pointer to the subsequent line point of this segment + const glm::vec2* d_nextPoint; + }; + + /*! + \brief + Tesselates an SVGRect and adds the created geometry to the GeometryBuffer + list. + + \param rect + The SVGRect object that contains the data. + \param geometry_buffers + The GeometryBuffer list to which the created geometry will be added. + \param render_settings + The ImageRenderSettings for the geometry that will be created. + */ + static void tesselateRect(const SVGRect* rect, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings); + /*! + \brief + Tesselates an SVGCircle and adds the created geometry to the GeometryBuffer + list. + + \param rect + The SVGCircle object that contains the data. + \param geometry_buffers + The GeometryBuffer list to which the created geometry will be added. + \param render_settings + The ImageRenderSettings for the geometry that will be created. + */ + static void tesselateCircle(const SVGCircle* circle, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings); + + /*! + \brief + Tesselates an SVGEllipse and adds the created geometry to the GeometryBuffer + list. + + \param rect + The SVGEllipse object that contains the data. + \param geometry_buffers + The GeometryBuffer list to which the created geometry will be added. + \param render_settings + The ImageRenderSettings for the geometry that will be created. + */ + static void tesselateEllipse(const SVGEllipse* ellipse, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings); + + /*! + \brief + Tesselates an SVGLine and adds the created geometry to the GeometryBuffer + list. + + \param line + The SVGLine object that contains the data. + \param geometry_buffers + The GeometryBuffer list to which the created geometry will be added. + \param render_settings + The ImageRenderSettings for the geometry that will be created. + */ + static void tesselateLine(const SVGLine* line, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings); + + /*! + \brief + Tesselates an SVGPolyline and adds the created geometry to the GeometryBuffer + list. + + \param polyline + The SVGPolyline object that contains the data. + \param geometry_buffers + The GeometryBuffer list to which the created geometry will be added. + \param render_settings + The ImageRenderSettings for the geometry that will be created. + */ + static void tesselatePolyline(const SVGPolyline* polyline, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings); + + /*! + \brief + Tesselates an SVGPolygon and adds the created geometry to the GeometryBuffer + list. + + \param polyline + The SVGPolygon object that contains the data. + \param geometry_buffers + The GeometryBuffer list to which the created geometry will be added. + \param render_settings + The ImageRenderSettings for the geometry that will be created. + */ + static void tesselatePolygon(const SVGPolygon* polyline, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings); + +private: + /*! + \brief + Enumeration that defines how two lines are or are not intersecting with each other. + */ + enum LineIntersectResult + { + LIR_PARALLEL, + LIR_COINCIDENT, + LIR_NOT_INTERSECTING, + LIR_INTERESECTING, + + LIR_COUNT + }; + + //! Constructor. + SVGTesselator(); + + //! Destructor. + ~SVGTesselator(); + + //! Helper function for creating a fill based on a list of polygon points + static void createFill(const std::vector& points, + GeometryBuffer& geometry_buffer, + const SVGPaintStyle& paint_style, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors); + + //! Helper function for creating a stroke based on a list of subsequent points forming the stroke + static void createStroke(const std::vector& points, + GeometryBuffer& geometry_buffer, + const SVGPaintStyle& paint_style, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const bool is_shape_closed); + + //! Stroke helper function that determines vertices of a stroke segment and adds them to the geometry buffer + static void createStrokeLinejoin(StrokeSegmentData& stroke_data, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const bool draw = true); + + //! Stroke helper function that determines and adds the anti-aliased geometry of a bevel- or rounded-linejoin + static void createStrokeLinejoinBevelOrRoundAA(StrokeSegmentData &stroke_data, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const glm::vec2& cur_point, + const glm::vec2& second_bevel_point, + const glm::vec2& segment_end_left, + const glm::vec2& segment_end_right, + const glm::vec2& prev_to_cur, + const glm::vec2& cur_to_next, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const SVGPaintStyle::SVGLinejoin linejoin, + const bool polygon_is_clockwise, + const bool draw); + + //! Stroke helper function that determines and adds the geometry of a bevel- or rounded-linejoin + static void createStrokeLinejoinBevelOrRound(StrokeSegmentData &stroke_data, + const glm::vec2& cur_point, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const glm::vec2& segment_end_left, + const glm::vec2& segment_end_right, + const glm::vec2& second_bevel_point, + const SVGPaintStyle::SVGLinejoin linejoin, + const bool polygon_is_clockwise, + const bool draw); + + //! Checks if the vector is left (meaning that the angle is smaller in clockwise direction) of the other vector + static bool isVectorLeftOfOtherVector(const glm::vec2& vector, + const glm::vec2& vector_other); + + //! Checks if the stroke miter is exceeding the maximum set for it, and if this is the case switches the linejoin to bevel + static void handleStrokeMiterExceedance(const StrokeSegmentData& stroke_data, + const glm::vec2& cur_point, + const glm::vec2& inner_intersection, + SVGPaintStyle::SVGLinejoin& linejoin); + + //! Calculates the anti-aliased miter-linejoin points and sets the points necessary to form the connection + static void calculateAAMiterAndSetConnectionPoints(StrokeSegmentData& stroke_data, + const glm::vec2& segment_end_left_orig, + const glm::vec2& segment_end_right_orig, + const bool polygon_is_clockwise, + const glm::vec2& prev_to_cur, + const glm::vec2& cur_to_next, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const glm::vec2& scale_factors); + + //! Calculates the scaled vector based on two direction vectors and their perpendicular vectors + static glm::vec2 calculateScaledCombinedVector(const glm::vec2& scale_factors, + const glm::vec2& prev_to_cur, + const glm::vec2& cur_to_next, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const bool polygon_is_clockwise); + + //! Returns the inverse of the factor by which the length of the given unit factor would be increased, when it gets scaled by the given scale factors along the x- and y-axis. + static float calculateLengthScale(const glm::vec2 &direction, const glm::vec2& scale_factors); + + //! Stroke draw helper function that adds geometry to connect linejoins and linecaps with each other. Creates a connection consisting of 1 quad. + static void createStrokeSegmentConnection(StrokeSegmentData &stroke_data); + + //! Stroke draw helper function that adds geometry to connect anti-aliased linejoins and linecaps with each other. Creates a connection consisting of 3 quads. + static void createStrokeSegmentConnectionAA(StrokeSegmentData &stroke_data); + + //! Add the stroke linecap AA geometry + static void addStrokeLinecapAAGeometryVertices(StrokeSegmentData &stroke_data, const glm::vec2& linecap_left, const glm::vec2& linecap_right, + const glm::vec2& linecap_fade_left, const glm::vec2& linecap_fade_right); + + //! Stroke draw helper function that adds the linecap depending on linecap type and beginning/end + static void createStrokeLinecap(StrokeSegmentData& stroke_data, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const bool is_start); + + //! Helper function to set the stroke-data's last point values + static void setStrokeDataLastPoints(StrokeSegmentData &stroke_data, const glm::vec2& last_point_left, const glm::vec2& last_point_right); + + //! Helper function to set the stroke-data's last anti-aliased point values + static void setStrokeDataLastPointsAA(StrokeSegmentData &stroke_data, const glm::vec2& last_point_left, + const glm::vec2& last_point_right, const glm::vec2& last_point_left_fade, + const glm::vec2& last_point_right_fade); + + //! Helper function to set the stroke-data's current point values + static void setStrokeDataCurrentPoints(StrokeSegmentData &stroke_data, const glm::vec2& current_point_left, const glm::vec2& current_point_right); + + //! Helper function to set the stroke-data's current anti-aliased point values + static void setStrokeDataCurrentPointsAA(StrokeSegmentData &stroke_data, const glm::vec2& current_point_left, + const glm::vec2& current_point_right, const glm::vec2& current_point_left_fade, + const glm::vec2& current_point_right_fade); + + //! Helper function to set the stroke-data's subsequent point values + static void setStrokeDataSubsequentPoints(StrokeSegmentData &stroke_data, const glm::vec2& subsequent_point_left, const glm::vec2& subsequent_point_right); + + //! Helper function to set the stroke-data's subsequent anti-aliased point values + static void setStrokeDataSubsequentPointsAA(StrokeSegmentData &stroke_data, const glm::vec2& subsequent_point_left, + const glm::vec2& subsequent_point_right, const glm::vec2& subsequent_point_left_fade, + const glm::vec2& subsequent_point_right_fade); + + //! Helper function that sets the subsequentPoints as the new lastPoints + static void setStrokeDataSubsequentPointsAsLastPoints(StrokeSegmentData &stroke_data); + + //! Helper function that sets the anti-aliased subsequentPoints as the new lastPoints + static void setStrokeDataSubsequentPointsAsLastPointsAA(StrokeSegmentData &stroke_data); + + //! Helper function that sets the lastPoints as the new currentPoints + static void setStrokeDataLastPointsAsCurrentPoints(StrokeSegmentData &stroke_data); + + //! Helper function that sets the lastPoints as the new currentPoints + static void setStrokeDataLastPointsAsCurrentPointsAA(StrokeSegmentData &stroke_data); + + //! Stroke helper function that determines if the polygon encompassed by the points is clockwise + static bool isPolygonClockwise(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3); + + //! Helper function that creates and sets the parameters for a coloured geometry buffer + static void setupGeometryBuffers(GeometryBuffer*& fill_geometry_buffer, + GeometryBuffer*& stroke_geometry_buffer, + std::vector& geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::mat3x3& svg_transformation, + const bool is_fill_needing_stencil); + + //! Helper function for setting an SVG GeometryBuffer's render settings and transformation matrix + static void setupGeometryBufferSettings(CEGUI::GeometryBuffer* geometry_buffer, + const SVGImage::SVGImageRenderSettings &render_settings, + const glm::mat4& cegui_transformation_matrix); + + //! Turns a matrix as defined by SVG into a matrix that can be used internally by the CEGUI Renderers + static glm::mat4 createRenderableMatrixFromSVGMatrix(glm::mat3 svg_matrix); + + //! Helper function for getting the fill Colour from an SVGPaintStyle + static glm::vec4 getFillColour(const SVGPaintStyle& paint_style); + + //! Helper function for getting the stroke Colour from an SVGPaintStyle + static glm::vec4 getStrokeColour(const SVGPaintStyle& paint_style); + + //! Create the circle's fill + static void createCircleFill(const std::vector& circle_points, + float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors); + + //! Calculate the tesselation parameters necessary to calculate the circle points + static void calculateCircleTesselationParameters(const float radius, + const float max_scale, + float& num_segments, + float& cos_value, + float& sin_value); + + //! Calculate the circle points + static void createCirclePoints(const float radius, + const float num_segments, + const float cos_value, + const float sin_value, + std::vector& circle_points); + + //! Create the circle's stroke + static void createCircleStroke(const std::vector& circle_points, + float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors); + + //! Helper function for creating a triangle strip with filling + static void createTriangleStripFillGeometry(const std::vector& points, + GeometryBuffer& geometry_buffer, + const SVGPaintStyle& paint_style); + + //! Helper function for creating an arc's stroke + static void createArcStrokeGeometry(std::vector& points, + GeometryBuffer& geometry_buffer, + ColouredVertex& stroke_vertex); + + //! Helper function for calculating and creating an anti-aliased stroke for an arc + static void createArcStrokeAAGeometry(const std::vector& points, + const glm::vec2& arc_center_point, + const glm::vec2& arc_draw_origin_point, + StrokeSegmentData& stroke_data, + const glm::vec2& scale_factors, + const bool polygon_is_clockwise, + glm::vec2& linecap_left_AA, + glm::vec2& linecap_right_AA, + glm::vec2& linecap_left_fade, + glm::vec2& linecap_right_fade); + + //! Creates the basic ellipse points + static void createEllipsePoints(const float radiusX, + const float radiusY, + const float max_scale, + std::vector& ellipse_points); + + //! Create the ellipse's fill + static void createEllipseFill(const std::vector& ellipse_points, + const float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors); + + //! Create the circle or ellipse's anti-aliased fill points + static void createCircleOrEllipseFillPointsAA(const std::vector &points, + const glm::vec2 &anti_aliasing_offsets, + const glm::vec2 &scale_factors, + std::vector &modified_points, + std::vector &fade_points); + //! Create the ellipse's stroke + static void createEllipseStroke(const std::vector& ellipse_points, + const float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors); + + //! Create circle or ellipse stroke points + static void createCircleOrEllipseStrokePoints(const std::vector& points, + StrokeSegmentData& stroke_data, + std::vector& outer_points, + std::vector& inner_points); + + //! Create anti-aliased circle or ellipse stroke points + static void createCircleOrEllipseStrokePointsAA(const std::vector& points, + StrokeSegmentData& stroke_data, + const glm::vec2& scale_factors, + std::vector& outer_points, + std::vector& outer_points_fade, + std::vector& inner_points, + std::vector& inner_points_fade); + + //! Scales the points of an ellipse (originally circle points) so that they match the scaling + static void scaleEllipsePoints(std::vector& circle_points, + const bool isRadiusXBigger, + const float radiusRatio); + + //! Helper function for adding an anti-aliasing quad of a stroke to the GeometryBuffer + static void addStrokeQuadAA(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& fade_point1, + const glm::vec2& fade_point2, + GeometryBuffer& geometry_buffer, + ColouredVertex& stroke_vertex, + ColouredVertex& stroke_fade_vertex); + + //! Helper function for appending a circle fill triangle to a GeometryBuffer + static void addTriangleGeometry(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3, + GeometryBuffer &geometry_buffer, + ColouredVertex &vertex); + + //! Creates the stroke geometry of an arbitrary stroke based on the outer and inner points + static void createStrokeGeometry(const std::vector& outer_circle_points, + const std::vector& inner_circle_points, + StrokeSegmentData &stroke_data, + const bool is_surface_closed); + + //! Creates the stroke geometry of an arbitrary anti-aliased stroke, based on the outer and inner points of it + static void createStrokeGeometryAA(const std::vector& outer_points, + const std::vector& outer_points_fade, + const std::vector& inner_points, + const std::vector& inner_points_fade, + StrokeSegmentData &stroke_data, + const bool is_surface_closed); + + //! Creates the anti-aliasing fade fill geometry for an arbitrary anti-aliased fill, based on normal points and fade points + static void createFillGeometryAAFadeOnly(const std::vector& points, + const std::vector& points_fade, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const bool is_surface_closed); + + //! Calculates the parameters necessary to calculate the arc points + static void calculateArcTesselationParameters(const float radius, + const float arc_angle, + const float max_scale, + float& num_segments, + float& tangential_factor, + float& radial_factor); + + //! Calculates the points of an arc. + static void createArcPoints(const glm::vec2& center_point, + const glm::vec2& start_point, + const glm::vec2& end_point, + const float num_segments, + const float tangential_factor, + const float radial_factor, + std::vector& arc_points); + + //! Function to determine the geometry offsets needed in anti-aliasing, depending on the width + static void determineAntiAliasingOffsets(float width, glm::vec2& antialiasing_offsets); + + //! Helper function to determine the scale factors in x and y-direction based on the transformation matrix and the image scale + static glm::vec2 determineScaleFactors(const glm::mat3& transformation, const SVGImage::SVGImageRenderSettings& render_settings); + + //! Intersects two lines and returns the result. Also the intersection point will be given if there is an intersection.. + static LineIntersectResult intersectLines(const glm::vec2& line1_start, const glm::vec2& line1_end, + const glm::vec2& line2_start, const glm::vec2& line2_end, + glm::vec2& intersection); + + //! Create the rectangles fill + static void createRectangleFill(const SVGPaintStyle& paint_style, std::vector& rectangle_points, GeometryBuffer& geometry_buffer); + + + //! Helper function to get the min and max x and y coordinates of a list of points + static void calculateMinMax(const std::vector& points, glm::vec2& min, glm::vec2& max); + + //! Helper function to append a fill-quad based on its 4 corner points to the Geometrybuffer + static void addFillQuad(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3, + const glm::vec2& point4, + GeometryBuffer& geometry_buffer, + ColouredVertex& fill_vertex); + + //! Helper function to append a stroke-quad based on its 4 corner points to the Geometrybuffer + static void addStrokeQuad(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3, + const glm::vec2& point4, + GeometryBuffer& geometry_buffer, + ColouredVertex& stroke_vertex); + + //! Helper function to append a triangle fan, which is based on a list of points, to the Geometrybuffer + static void addTriangleFanGeometry(const std::vector &points, + GeometryBuffer& geometry_buffer, + ColouredVertex& coloured_vertex); +}; + +} + +#endif + diff --git a/cegui/include/CEGUI/MemoryOgreAllocator.h b/cegui/include/CEGUI/views/All.h similarity index 71% rename from cegui/include/CEGUI/MemoryOgreAllocator.h rename to cegui/include/CEGUI/views/All.h index 1d112410a..da768a109 100644 --- a/cegui/include/CEGUI/MemoryOgreAllocator.h +++ b/cegui/include/CEGUI/views/All.h @@ -1,11 +1,9 @@ /*********************************************************************** - created: 18/10/2010 - author: Martin Preisler - - purpose: Implements an allocator that delegates to Ogre + created: Mon May 26 2014 + author: Timotei Dolean *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -26,20 +24,13 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIMemoryOgreAllocator_h_ -#define _CEGUIMemoryOgreAllocator_h_ - -#include - -namespace CEGUI -{ - -// I deliberately kept the interface exactly the same, -// so this will do just fine... - -CEGUI_SET_DEFAULT_ALLOCATOR(::Ogre::GeneralAllocPolicy) -CEGUI_SET_ALLOCATOR(System, ::Ogre::GeneralAllocPolicy) +#ifndef _CEGUIAllViews_h_ +#define _CEGUIAllViews_h_ -} +#include "./ItemModel.h" +#include "./ItemView.h" +#include "./ListView.h" +#include "./StandardItemModel.h" +#include "./TreeView.h" -#endif // end of guard _CEGUIMemoryOgreAllocator_h_ +#endif diff --git a/cegui/include/CEGUI/views/GenericItemModel.h b/cegui/include/CEGUI/views/GenericItemModel.h new file mode 100644 index 000000000..843e0ddbb --- /dev/null +++ b/cegui/include/CEGUI/views/GenericItemModel.h @@ -0,0 +1,560 @@ +/*********************************************************************** + created: Sat Aug 09 2014 + author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIAbstractItemModel_h_ +#define _CEGUIAbstractItemModel_h_ + +#include "CEGUI/views/ItemModel.h" +#include "CEGUI/Exceptions.h" +#include + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ +/*! +\brief + Base class for the items used by GenericItemModel. The item has a list + of children attached to it, thus being able to represent a tree hierarchy. + + It's important to understand that this is a simple class that only holds + structured data. Direct changes to this item won't be propagated to the + ItemModel it's part of, unless one links them manually. In order to modify + this item and update the ItemModel (and consequently the view) you need to + call ItemModel implementation's functions (e.g.: + GenericItemModel::removeItem(const GenericItem*)). +*/ +class CEGUIEXPORT GenericItem +{ +public: + GenericItem(); + explicit GenericItem(const String& text); + GenericItem(const String& text, const String& icon); + virtual ~GenericItem(); + + String getText() const { return d_text; } + void setText(const String& val) { d_text = val; } + + String getIcon() const { return d_icon; } + void setIcon(const String& icon) { d_icon = icon; } + + GenericItem* getParent() const { return d_parent; } + void setParent(GenericItem* item) { d_parent = item; } + + std::vector& getChildren() { return d_children; } + + /*! + \brief + Adds a child item to the item. + + \remark + This method does not notify anyone of the child that was just + added. If you want the notifications, you can use one of the following + methods: + - GenericItemModel::addItemAtPosition(GenericItem*, size_t) + - GenericItemModel::addItemAtPosition(GenericItem*, const ModelIndex&, size_t) + - GenericItemModel::insertItem(GenericItem*, const GenericItem*) + + */ + virtual void addItem(GenericItem* child); + + virtual bool operator== (const GenericItem& other) const; + virtual bool operator!= (const GenericItem& other) const; + virtual bool operator< (const GenericItem& other) const; + +protected: + String d_text; + String d_icon; + + std::vector d_children; + GenericItem* d_parent; +}; + +/*! +\brief + An abstract implementation of the ItemModel that works with + a tree structure using items of class that inherits from GenericItem. + + Users of this class can either create a template instantiation of this + implementation, or inherit it and augment with custom operations or + overwrite certain methods to provide more functionality (e.g.: getData). + + One such example is the following, where we instantiate a model for our + own MyItem type: + \code{.cpp} + class MyItem : public GenericItem + { + }; + + typedef GenericItemModel MyItemModel; + \endcode + +\remark + Items added to the model are taken over and managed by the model, which + means they are deleted by it. delete is used for that, so + new should be used for already created objects that are added. + +\tparam TGenericItem + The type of the item this model operates on. The type \b needs to inherit + directly or indirectly from GenericItem. +*/ +template +class GenericItemModel : public ItemModel +{ +public: + /*! + \brief + Creates a new model instance using the specified \a root item, which + must not be NULL - otherwise an InvalidRequestException is thrown. + + The \a root will be taken ownership of, and cleaned when the model is + destructed (using delete). + + An example of initializing such GenericItemModel implementation is the + following: + \code{.cpp} + class MyItemModel : public GenericItemModel + { + MyItemModel() : GenericItemModel(new MyItem) + { + } + }; + \endcode + + Alternatively, if you want to create a root upon declaring the model, you + can let the caller provide it, in which case our \b MyItemModel constructor + will receive the root TGenericItem instance. + */ + explicit GenericItemModel(TGenericItem* root); + virtual ~GenericItemModel(); + + /*! + \brief + Adds a new item in the model with the specified text, taking ownership + of it. + + If this method is used, the TGenericItem type should have a string + constructor in order to successfully compile. This method is equivalent + with: + \code{.cpp} + GenericItem* item = new GenericItem("MyText"); + model->addItem(item); + \endcode + */ + virtual void addItem(String text); + //! Adds the item as child of the root and takes ownership of it. + virtual void addItem(GenericItem* item); + //! Adds the item as child of the root at the specified position. + virtual void addItemAtPosition(GenericItem* item, size_t pos); + /*! + \brief + Adds the item as child of the specified parent, at the specified position. + + After the addition, the \a parent's node will contain \a item as child + at the \a position. + */ + virtual void addItemAtPosition(GenericItem* item, const ModelIndex& parent, + size_t position); + + /*! + \brief + Inserts the specified \a item before the specified \a position item. + If \a position is NULL the new item will be added at the beginning of + the root's children list. + + This method allows for arbitrary level (nestedness/depth) insertions. + Another function which can be used instead of this, is + addItemAtPosition(GenericItem*, const ModelIndex&, size_t). + */ + virtual void insertItem(GenericItem* item, const GenericItem* position); + + virtual void removeItem(const GenericItem* item); + virtual void removeItem(const ModelIndex& index); + + /*! + \brief + Clears the items of this ItemModel, deleting them, using delete + on each, optionally notifying any listeners of the removal of the items. + + \param notify + If true, it will raise the EventChildrenWillBeRemoved and + EventChildrenRemoved events for each deleted item. + */ + virtual void clear(bool notify = true); + + /*! + \brief + Gets the underlying TGenericItem represented by the given \a index or + NULL if the index does not represent a valid item. + + This method is the inverse of to getIndexForItem(const GenericItem*). + */ + virtual TGenericItem* getItemForIndex(const ModelIndex& index) const; + + /*! + \brief + Creates a ModelIndex that represents the specified index. + + This method is the inverse of getItemForIndex(const ModelIndex&). + */ + virtual ModelIndex getIndexForItem(const GenericItem* item) const; + + //! Gets the ordinal id (index) of the specified item in parent's children list. + virtual int getChildId(const GenericItem* item) const; + + /*! + \brief + This represents the conceptual root of this model. This root will be + ignored in normal operations. It's merely used in order to provide + an access point to the items tree. + */ + TGenericItem& getRoot() { return static_cast(*d_root); } + + virtual bool isValidIndex(const ModelIndex& model_index) const; + virtual ModelIndex makeIndex(size_t child, const ModelIndex& parent_index); + virtual bool areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const; + virtual int compareIndices(const ModelIndex& index1, const ModelIndex& index2) const; + virtual ModelIndex getParentIndex(const ModelIndex& model_index) const; + virtual int getChildId(const ModelIndex& model_index) const; + virtual ModelIndex getRootIndex() const; + virtual size_t getChildCount(const ModelIndex& model_index) const; + virtual String getData(const ModelIndex& model_index, ItemDataRole role = IDR_Text); + +protected: + //! Deletes all children of the specified item, optionally invoking the + //! EventChildren(WillBe)Removed event + void deleteChildren(GenericItem* item, bool notify); + + //! Makes a valid index if \a id is withing \a vector's bounds. + template + ModelIndex makeValidIndex(size_t id, std::vector& vector); + + GenericItem* d_root; +}; + +//----------------------------------------------------------------------------// +// Implementation of the GenericItemModel +//----------------------------------------------------------------------------// +template +GenericItemModel::GenericItemModel(TGenericItem* root) : +d_root(root) +{ + if (root == 0) + CEGUI_THROW(InvalidRequestException("Root cannot be null")); +} + +//----------------------------------------------------------------------------// +template +template +ModelIndex GenericItemModel::makeValidIndex(size_t id, + std::vector& vector) +{ + if (id >= 0 && id < vector.size()) + return ModelIndex(vector.at(id)); + + return ModelIndex(); +} + +template +GenericItemModel::~GenericItemModel() +{ + clear(false); + + delete d_root; +} + +//----------------------------------------------------------------------------// +template +bool GenericItemModel::isValidIndex(const ModelIndex& model_index) const +{ + return model_index.d_modelData != 0; +} + +//----------------------------------------------------------------------------// +template +ModelIndex GenericItemModel::makeIndex(size_t child, + const ModelIndex& parent_index) +{ + if (parent_index.d_modelData == 0) + return ModelIndex(); + + GenericItem* item = static_cast(parent_index.d_modelData); + return makeValidIndex(child, item->getChildren()); +} + +//----------------------------------------------------------------------------// +template +bool GenericItemModel::areIndicesEqual(const ModelIndex& index1, + const ModelIndex& index2) const +{ + return compareIndices(index1, index2) == 0; +} + +//----------------------------------------------------------------------------// +template +int GenericItemModel::compareIndices(const ModelIndex& index1, + const ModelIndex& index2) const +{ + if (!isValidIndex(index1) || !isValidIndex(index2) || + index1.d_modelData == index2.d_modelData) + return 0; + + if (*getItemForIndex(index1) < *getItemForIndex(index2)) + return -1; + + return *getItemForIndex(index1) == *getItemForIndex(index2) ? 0 : 1; +} + +//----------------------------------------------------------------------------// +template +ModelIndex GenericItemModel::getParentIndex(const ModelIndex& model_index) const +{ + if (model_index.d_modelData == d_root) + return ModelIndex(); + + GenericItem* item = static_cast(model_index.d_modelData); + if (item->getParent() == 0) + return getRootIndex(); + + return ModelIndex(item->getParent()); +} + +//----------------------------------------------------------------------------// +template +int GenericItemModel::getChildId(const ModelIndex& model_index) const +{ + return getChildId(getItemForIndex(model_index)); +} + +//----------------------------------------------------------------------------// +template +int GenericItemModel::getChildId(const GenericItem* item) const +{ + if (item == 0 || item->getParent() == 0) + return -1; + + GenericItem* parent_item = item->getParent(); + + std::vector::iterator itor = std::find( + parent_item->getChildren().begin(), parent_item->getChildren().end(), item); + + if (itor == parent_item->getChildren().end()) + return -1; + + return std::distance(parent_item->getChildren().begin(), itor); +} + +//----------------------------------------------------------------------------// +template +ModelIndex GenericItemModel::getRootIndex() const +{ + return ModelIndex(d_root); +} + +//----------------------------------------------------------------------------// +template +size_t GenericItemModel::getChildCount(const ModelIndex& model_index) const +{ + if (model_index.d_modelData == 0) + return d_root->getChildren().size(); + + return static_cast(model_index.d_modelData)->getChildren().size(); +} + +//----------------------------------------------------------------------------// +template +String GenericItemModel::getData(const ModelIndex& model_index, + ItemDataRole role /*= IDR_Text*/) +{ + if (!isValidIndex(model_index)) + return ""; + + GenericItem* item = static_cast(model_index.d_modelData); + if (role == IDR_Text) return item->getText(); + if (role == IDR_Icon) return item->getIcon(); + if (role == IDR_Tooltip) return "Tooltip for " + item->getText(); + + return ""; +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::addItem(String text) +{ + addItem(new TGenericItem(text)); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::addItem(GenericItem* item) +{ + if (item == 0) + CEGUI_THROW(InvalidRequestException("Cannot add a NULL item to the model!")); + + addItemAtPosition(item, + d_root->getChildren().empty() ? 0 : d_root->getChildren().size()); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::addItemAtPosition(GenericItem* item, size_t pos) +{ + addItemAtPosition(item, getRootIndex(), pos); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::addItemAtPosition(GenericItem* new_item, + const ModelIndex& parent_index, size_t position) +{ + notifyChildrenWillBeAdded(parent_index, position, 1); + + GenericItem* parent = static_cast(parent_index.d_modelData); + if (position > parent->getChildren().size()) + CEGUI_THROW(InvalidRequestException("The specified position is out of range.")); + + new_item->setParent(parent); + parent->getChildren().insert(parent->getChildren().begin() + position, new_item); + + notifyChildrenAdded(parent_index, position, 1); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::insertItem(GenericItem* item, + const GenericItem* position) +{ + int child_id = position == 0 ? -1 : getChildId(position); + + ModelIndex parent_index = getRootIndex(); + if (position != 0) + parent_index = getParentIndex(getIndexForItem(position)); + + addItemAtPosition(item, parent_index, + child_id <= 0 ? 0 : static_cast(child_id)); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::removeItem(const ModelIndex& index) +{ + removeItem(getItemForIndex(index)); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::removeItem(const GenericItem* item) +{ + GenericItem* parent_item = item->getParent(); + + std::vector::iterator itor = std::find( + parent_item->getChildren().begin(), parent_item->getChildren().end(), + item); + + if (itor != parent_item->getChildren().end()) + { + size_t child_id = std::distance(parent_item->getChildren().begin(), itor); + + notifyChildrenWillBeRemoved(ModelIndex(parent_item), child_id, 1); + + deleteChildren(*itor, true); + delete *itor; + parent_item->getChildren().erase(itor); + + notifyChildrenRemoved(ModelIndex(parent_item), child_id, 1); + } +} + +//----------------------------------------------------------------------------// +template +TGenericItem* GenericItemModel::getItemForIndex( + const ModelIndex& index) const +{ + if (index.d_modelData == 0) + return 0; + + return static_cast(index.d_modelData); +} + +//----------------------------------------------------------------------------// +template +void GenericItemModel::clear(bool notify /*= true */) +{ + deleteChildren(d_root, notify); +} + +//----------------------------------------------------------------------------// +template +ModelIndex GenericItemModel::getIndexForItem( + const GenericItem* item) const +{ + // TODO: this is annoying. We should be able to just hand out the ModelIndex + // Right now we can't, since we're in a const method, operating on a const item + // In hindsight, the index we hand out will be modifiable so maybe we need + // to change the const-ness of the item parameter. + GenericItem* parent = item->getParent(); + int child_id = getChildId(item); + return ModelIndex(child_id != -1 ? parent->getChildren().at(child_id) : 0); +} + +//----------------------------------------------------------------------------// +template +void CEGUI::GenericItemModel::deleteChildren(GenericItem* item, + bool notify) +{ + if (item == 0) + CEGUI_THROW(InvalidRequestException("Cannot delete children of a NULL item!")); + + size_t items_count = item->getChildren().size(); + std::vector::iterator itor = item->getChildren().begin(); + + if (notify) + { + notifyChildrenWillBeRemoved(ModelIndex(item), 0, items_count); + } + + while (itor != item->getChildren().end()) + { + deleteChildren(*itor, notify); + delete *itor; + itor = item->getChildren().erase(itor); + } + + if (notify) + { + notifyChildrenRemoved(ModelIndex(item), 0, items_count); + } +} +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/views/ItemModel.h b/cegui/include/CEGUI/views/ItemModel.h new file mode 100644 index 000000000..bf4fad34c --- /dev/null +++ b/cegui/include/CEGUI/views/ItemModel.h @@ -0,0 +1,398 @@ +/*********************************************************************** + created: Tue May 20 2014 + author: Timotei Dolean + + purpose: Provides ModelIndex and ItemModel which are the basis of the + Model-View architecture. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIItemModel_h_ +#define _CEGUIItemModel_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/EventArgs.h" +#include "CEGUI/EventSet.h" +#include "CEGUI/ForwardRefs.h" +#include "CEGUI/String.h" + +namespace CEGUI +{ + +/*! +\brief + ModelIndex is CEGUI's way of representing user data in the views. It uses + a \b void* pointer to store a reference to arbitrary, user-owned data. + + Even though the naming might suggest a particular order, it doesn't have any. + For comparing two indices ItemModel::compareIndices(const ModelIndex&, const ModelIndex&) + should be used. + + The index should not be stored because the pointed data might be deleted in + the meantime. The only entity that should interpret the contents of this + class is the ItemModel (and its descendants). All decisions (e.g.: comparisons, + data providing) based on an index need to go through the ItemModel. + + All operations with the view are done using the ModelIndex. For example, if you want + to select something you need to give it the ModelIndex of that item's. What that means + is that the view doesn't know about the actual model items. +*/ +class CEGUIEXPORT ModelIndex +{ +public: + /*! + \brief + Constructs an index with the specified model data. + + \param model_data + Optional model data associated with this index. + */ + explicit ModelIndex(void* model_data = 0); + + /*! + \brief + Pointer to model-specific data. + + \remark + DO NOT USE/INTERPRET in view. This is just a simple way for the model + to be able to manage its data and logic. + */ + void* d_modelData; + + CEGUIEXPORT friend std::ostream& operator<< (std::ostream& os, const ModelIndex& arg); +}; + +/*! +\brief + Enumeration that specifies which type of data is required from the ItemModel + in order for the view to render it. + + Users can use the IDR_User member as a starting base for custom roles. Anything + below is reserved for CEGUI usage. +*/ +enum ItemDataRole +{ + IDR_Text, + //! The string returned for the icon must be an image name that can + //! retrieved from ImageManager + IDR_Icon, + IDR_Tooltip, + + //! This marks the beginning of the user-defined item data roles + IDR_User = 0x1000 +}; + +/* +TODO: The count thing is very ugly and counter-intuitive to the whole design. + We should either: + * Fire an event per index + * Store the actual indices in a vector. +*/ + +/*! +\brief + Arguments class for events that happened with regard to the specified ItemModel + on the specified indices. +*/ +class CEGUIEXPORT ModelEventArgs : public EventArgs +{ +public: + ModelEventArgs(ItemModel* item_model, ModelIndex parent_index, size_t start_id, size_t count = 1); + + //! The source ItemModel that triggered the event. + ItemModel* d_itemModel; + + //! The parent ModelIndex the event happened under. + ModelIndex d_parentIndex; + + //! The starting id the event happened on. + size_t d_startId; + + //! The number of items after the start index that have been affected by the event. + size_t d_count; +}; + +/*! +\brief + Abstract class defining the interface between the view and the user data. + This is used by views to query data that is to be shown. + + A view will require a custom implementation of this provider. CEGUI provides + a basic implementation in form of GenericItemModel. + + This model provides events to notify listeners (usually the view it is + attached to) of different events that will happen or happened. It is the + implementer's job to properly raise the events with the proper arguments so + that the view can correctly process those and render the view. For convenience, + there are the notifyChildren* method which raise the specified events + with the proper event arguments. +*/ +class CEGUIEXPORT ItemModel : public EventSet +{ +public: + virtual ~ItemModel(); + + //! Name of the event triggered \b before children will be added + static const String EventChildrenWillBeAdded; + //! Name of the event triggered \b after new children were added + static const String EventChildrenAdded; + + //! Name of the event triggered \b before existing children will be removed + static const String EventChildrenWillBeRemoved; + //! Name of the event triggered \b after existing children were removed + static const String EventChildrenRemoved; + + //! Name of the event triggered \b before existing children's data will be changed + static const String EventChildrenDataWillChange; + //! Name of the event triggered \b after existing children's data was changed + static const String EventChildrenDataChanged; + + /*! + \brief + Returns true if the specified ModelIndex is valid, false otherwise. + + Usually, an index is valid if at least it does not contain a reference + to a NULL object. Extra logic can be added to check that the referenced + object is actually part of the model. + */ + virtual bool isValidIndex(const ModelIndex& model_index) const = 0; + + /*! + \brief + Creates a new ModelIndex that points to the specified child of the + specified parent index. + + To create an index for a nested item, you need to chain the index creation. + Given a model for the following tree: +
+        A
+        |
+        |--B
+        |  |--C
+        |
+        |--D
+        
+ + We can compute the indices for the nodes in the following way: + \code{.cpp} + ModelIndex a = makeIndex(0, getRootIndex()); + ModelIndex b = makeIndex(0, a); + ModelIndex c = makeIndex(0, b); + ModelIndex d = makeIndex(1, a); + \endcode + + \param child + The ordinal child id (index), which is a number between 0 and + getChildrenCount(parent_index). This will specify which children in the + parent's index list of children should be referenced. + */ + virtual ModelIndex makeIndex(size_t child, const ModelIndex& parent_index) = 0; + + /*! + \brief + Compares semantically two indices and returns true if they are equal, + false otherwise. + */ + virtual bool areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const; + + /*! + \brief + Compares semantically the contents of the specified two indices and returns: + - 0 if they are equal. + - -1 if first index is less than the second index. + - 1 if the first index is bigger than the second index. + + This function is used by the view when it needs to sort the items. + */ + virtual int compareIndices(const ModelIndex& index1, const ModelIndex& index2) const = 0; + + /*! + \brief + Returns the ModelIndex which is parent for the specified ModelIndex. + + \return + The returned index should be equal to getRootIndex() for direct children + of the root index. If this is called on the root index, it returns + an invalid (empty/default) ModelIndex. + */ + virtual ModelIndex getParentIndex(const ModelIndex& model_index) const = 0; + + /*! + \brief + Returns the ordinal id (index) of the child represented by the given + index, in its parent's list or -1 if no such child exists. + */ + virtual int getChildId(const ModelIndex& model_index) const = 0; + + /*! + \brief + Returns the root ModelIndex of this model. + + \remark + This index is not used for any rendering, but only to provide the initial + access to the items. For example, in the case of a list this might contain + all the items in the list. + */ + virtual ModelIndex getRootIndex() const = 0; + + /*! + \brief + Returns the number of direct children of the specified ModelIndex. + */ + virtual size_t getChildCount(const ModelIndex& model_index) const = 0; + + /*! + \brief + Returns the string representation of the specified ModelIndex based on + the specified role. + It is up to the view to interpret the string based on the role requested. + + \remark + For example, in the case of an image decoration, the name of the image + could be returned, and the view would use ImageManager to retrieve the + specific Image instance by the name and render that. + + An example implementation for the IDR_Icon role could be: + \code{.cpp} + Image* img; // get the image from somewhere + + String getData(const ModelIndex& model_index, ItemDataRole role) + { + if (role == IDR_Icon) return img->getName(); + } + \endcode + */ + virtual String getData(const ModelIndex& model_index, ItemDataRole role = IDR_Text) = 0; + + /*! + \brief + Notifies any listeners of the EventChildrenWillBeAdded event that new children + will be added to this model. + + \param parent_index + The parent index under which children will be added. + + \param start_id + The id of the child starting from which children will be added. + + \param count + The number of children that will be added. + + \remark + If this method is overridden, it *needs* to call this base method or invoke + manually the EventChildrenWillBeAdded event. + */ + virtual void notifyChildrenWillBeAdded(ModelIndex parent_index, + size_t start_id, size_t count); + + /*! + \brief + Notifies any listeners of the EventChildrenAdded event that new children + have been added to this model. + + \param parent_index + The parent index under which children have been added. + + \param start_id + The id of the child starting from which children have been added. + + \param count + The number of children that have been added. + + \remark + If this method is overridden, it *needs* to call this base method or invoke + manually the EventChildrenAdded event. + */ + virtual void notifyChildrenAdded(ModelIndex parent_index, + size_t start_id, size_t count); + + /*! + \brief + Notifies any listeners of the EventChildrenWillBeRemoved event that existing + children will be removed from this model. + + \param parent_index + The parent index under which children will be removed. + + \param start_id + The id of the child starting from which children will be removed. + + \param count + The number of children that will be removed. + + \remark + If this method is overridden, it *needs* to call this base method or invoke + manually the EventChildrenWillBeRemoved event. + */ + virtual void notifyChildrenWillBeRemoved(ModelIndex parent_index, + size_t start_id, size_t count); + + /*! + \brief + Notifies any listeners of the EventChildrenRemoved event that existing + children have been removed from this model. + + \param parent_index + The parent index under which children have been removed. + + \param start_id + The id of the child starting from which children have been removed. + + \param count + The number of children that have been removed. + + \remark + If this method is overridden, it *needs* to call this base method or invoke + manually the EventChildrenRemoved event. + */ + virtual void notifyChildrenRemoved(ModelIndex parent_index, + size_t start_id, size_t count); + + /*! + \brief + Notifies any listeners of the EventChildDataWillChange event that existing + children's data will change. + + \remark + If this method is overridden, it *needs* to call this base method or invoke + manually the EventChildDataWillChange event. + */ + virtual void notifyChildrenDataWillChange(ModelIndex parent_index, + size_t start_id, size_t count); + + /*! + \brief + Notifies any listeners of the EventChildDataChanged event that existing + children's data has been updated. + + \remark + If this method is overridden, it *needs* to call this base method or invoke + manually the EventChildDataChanged event. + */ + virtual void notifyChildrenDataChanged(ModelIndex parent_index, + size_t start_id, size_t count); +}; + +} + +#endif diff --git a/cegui/include/CEGUI/views/ItemView.h b/cegui/include/CEGUI/views/ItemView.h new file mode 100644 index 000000000..3cf589460 --- /dev/null +++ b/cegui/include/CEGUI/views/ItemView.h @@ -0,0 +1,443 @@ +/*********************************************************************** + created: Sat May 24 2014 + author: Timotei Dolean + + purpose: Interface of the base class for all item model-based views. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CEGUIItemView_h_ +#define _CEGUIItemView_h_ + +#include "CEGUI/Base.h" +#include "CEGUI/Colour.h" +#include "CEGUI/ColourRect.h" +#include "CEGUI/InputEvent.h" +#include "CEGUI/Rect.h" +#include "CEGUI/Window.h" +#include "CEGUI/views/ItemModel.h" +#include "CEGUI/widgets/Scrollbar.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ +class ItemView; + +/*! +\brief + This renderer interface provides data for the views to aid in the rendering + process. +*/ +class CEGUIEXPORT ItemViewWindowRenderer : public WindowRenderer +{ +public: + ItemViewWindowRenderer(const String& name); + + /*! + \brief + Returns a Rectf object describing, in unclipped pixels, the window + relative area that is to be used for rendering the view. + */ + virtual Rectf getViewRenderArea(void) const = 0; + + /*! + \brief + Resize the view such that its content can be displayed without needing + scrollbars if there is enough space, otherwise make the view as + large as possible (without moving it). + */ + virtual void resizeViewToContent(bool fit_width, bool fit_height) const = 0; + + virtual ItemView* getView() const; +}; + +/*! +\brief + This enumeration controls the \b display mode of the scrollbar, that is, + it's visibility. This does not affect the scrollbar behaviour. For example, + even if the scrollbar is SDM_Hidden, one can still scroll it if the size + allows it (content is bigger than the view). +*/ +enum ScrollbarDisplayMode +{ + //! The scrollbar will be shown always, even if the content is smaller than + //! the view. + SDM_Shown, + //! The scrollbar will be hidden, even if the content is bigger than the + //! view and scrolling is possible. + SDM_Hidden, + //! The scrollbar will be shown only if the underlining view's size is too + //! small to contain its items. + SDM_WhenNeeded +}; + +enum ViewSortMode +{ + //! Items are not sorted, but shown in the same order as they are provided by the model. + VSM_None, + VSM_Ascending, + VSM_Descending +}; + +template<> +class CEGUIEXPORT PropertyHelper +{ +public: + typedef ScrollbarDisplayMode return_type; + typedef return_type safe_method_return_type; + typedef ScrollbarDisplayMode pass_type; + typedef String string_return_type; + + static const String& getDataTypeName(); + + static return_type fromString(const String& str); + static string_return_type toString(pass_type val); +}; + +template<> +class CEGUIEXPORT PropertyHelper +{ +public: + typedef ViewSortMode return_type; + typedef return_type safe_method_return_type; + typedef ViewSortMode pass_type; + typedef String string_return_type; + + static const String& getDataTypeName(); + + static return_type fromString(const String& str); + static string_return_type toString(pass_type val); +}; + +/*! +\brief + Stores the selection state of a ModelIndex. This is used to regenerate + the new proper selection index when the model changes in any way (e.g.: + new item, removed item). +*/ +struct CEGUIEXPORT ModelIndexSelectionState +{ + ModelIndex d_parentIndex; + size_t d_childId; + + ModelIndex d_selectedIndex; +}; +typedef std::vector SelectionStatesVector; + +class CEGUIEXPORT ItemViewEventArgs : public WindowEventArgs +{ +public: + ItemViewEventArgs(ItemView* wnd, ModelIndex index = ModelIndex()); + + //! The index affected by the event. + ModelIndex d_index; +}; + +/*! +\brief + Abstract base class for all view classes that use an ItemModel to provide + the data to be rendered. In order for a view to properly display data, + the setModel(ItemModel*) function should be called with an instance of the + model. + + This class is mean to be inherited by a specific view before being used. +*/ +class CEGUIEXPORT ItemView : public Window +{ +public: + ItemView(const String& type, const String& name); + + virtual ~ItemView(); + + static const Colour DefaultTextColour; + static const Colour DefaultSelectionColour; + //! Widget name for the vertical scrollbar component. + static const String VertScrollbarName; + //! Widget name for the horizontal scrollbar component. + static const String HorzScrollbarName; + + static const String EventVertScrollbarDisplayModeChanged; + static const String EventHorzScrollbarDisplayModeChanged; + static const String EventSelectionChanged; + static const String EventMultiselectModeChanged; + static const String EventSortModeChanged; + //! Triggered when items are added, removed or when the view's item are cleared. + static const String EventViewContentsChanged; + + //! Sets the ItemModel to be used inside this view. + virtual void setModel(ItemModel* item_model); + + //! Returns the current ItemModel of this view. + virtual ItemModel* getModel() const; + + /*! + \brief + Instructs this ItemView to prepare its rendering state for rendering. + This is usually done by updating the rendering state if it got dirty + in the meantime. + */ + virtual void prepareForRender(); + + //! Gets the colour used for rendering the text. + const ColourRect& getTextColourRect() const; + //! Sets the colour used for rendering the text. + void setTextColourRect(const ColourRect& colour_rect); + void setTextColour(Colour colour); + + //! Gets the colour used for highlighting the selection. + const ColourRect& getSelectionColourRect() const; + //! Sets the colour used for highlighting the selection. + void setSelectionColourRect(const ColourRect& colour_rect); + + bool isDirty() const; + //! Specifies whether this view requires processing before being able to render it. + void setIsDirty(bool value); + + /*! + \brief + Invalidates this view by marking the rendering state as dirty. That means + that the next call to prepareForRender() will have to reconstruct it's + rendering state. + + This also calls the base Window::invalidate. + */ + virtual void invalidateView(bool recursive); + + /*! + \brief + Gets the current state of the indices used for selection. + + \remark + This vector's iterator might get invalidated in the case when items are + removed from the underlying ItemModel while iterating over this vector. + + In the following example you can see a way of removing the selecting items: + \code + while(!view->getIndexSelectionStates().empty()) + { + ModelIndexSelectionState& state = view->getIndexSelectionStates().back(); + view->getIndexSelectionStates().pop_back(); + // remove item from model + } + \endcode + */ + const std::vector& getIndexSelectionStates() const; + + /*! + \brief + Returns the ModelIndex of the item at the specified position. + + \param position + The position is expected to be in screen coordinates - it will be converted + to window coordinates internally. + + \return + The ModelIndex for the position or a default-constructed ModelIndex + if nothing was found at that position or if the position is outside + the view's rendering area. + */ + virtual ModelIndex indexAt(const glm::vec2& position) = 0; + + /*! + \brief + Sets the item specified by the \a index as the currently selected one. + + \return + True if the index has been successfully selected, false otherwise. + */ + virtual bool setSelectedIndex(const ModelIndex& index); + virtual bool setIndexSelectionState(const ModelIndex& index, bool selected); + + virtual bool isIndexSelected(const ModelIndex& index) const; + + /*! + \brief + Ensures that the item specified by the \a index is visible by setting + the proper the vertical and horizontal scrollbars' position. + */ + virtual void ensureIndexIsVisible(const ModelIndex& index); + + //! Clears all selected indices. + void clearSelections(); + + void setSelectionBrushImage(const Image* image); + /*! + \brief + Sets the image represented by the specified \name as the selection brush. + + This call is the same as: + \code{.cpp} + Image* img = ImageManager::getSingleton().getImage(name); + view->setSelectionBrushImage(img); + \endcode + */ + void setSelectionBrushImage(const String& name); + const Image* getSelectionBrushImage(void) const; + + /*! + \brief + Returns a pointer to the vertical Scrollbar component widget for this view. + + \exception UnknownObjectException + Thrown if the vertical Scrollbar component does not exist. + */ + Scrollbar* getVertScrollbar() const; + + void setVertScrollbarDisplayMode(ScrollbarDisplayMode mode); + ScrollbarDisplayMode getVertScrollbarDisplayMode() const; + + /*! + \brief + Returns a pointer to the horizontal Scrollbar component widget for this view. + + \exception UnknownObjectException + Thrown if the horizontal Scrollbar component does not exist. + */ + Scrollbar* getHorzScrollbar() const; + + void setHorzScrollbarDisplayMode(ScrollbarDisplayMode mode); + ScrollbarDisplayMode getHorzScrollbarDisplayMode() const; + + /*! + \brief + Specifies whether the view will vertically auto-resize to match the + content's height or not. This happens when the parent size is changed, + items are added or removed. + */ + void setAutoResizeHeightEnabled(bool enabled); + bool isAutoResizeHeightEnabled() const; + + /*! + \brief + Specifies whether the view will horizontally auto-resize to match the + content's height or not. This happens when the parent size is changed, + items are added or removed. + */ + void setAutoResizeWidthEnabled(bool enabled); + bool isAutoResizeWidthEnabled() const; + + //! Specifies whether this view should show tooltips for its items or not. + bool isItemTooltipsEnabled() const; + void setItemTooltipsEnabled(bool enabled); + + //! Specifies whether one can select multiple items in the view or not. + bool isMultiSelectEnabled() const; + void setMultiSelectEnabled(bool enabled); + + ViewSortMode getSortMode() const; + //! Setting a new sorting mode will trigger the instant sorting of this view. + void setSortMode(ViewSortMode sort_mode); + + //! Returns the width of the rendered contents. + float getRenderedMaxWidth() const; + //! Returns the height of the rendered contents. + float getRenderedTotalHeight() const; + +protected: + ItemModel* d_itemModel; + ColourRect d_textColourRect; + ColourRect d_selectionColourRect; + bool d_isDirty; + bool d_needsFullRender; + std::vector d_indexSelectionStates; + ModelIndex d_lastSelectedIndex; + const Image* d_selectionBrush; + ScrollbarDisplayMode d_vertScrollbarDisplayMode; + ScrollbarDisplayMode d_horzScrollbarDisplayMode; + bool d_isItemTooltipsEnabled; + bool d_isMultiSelectEnabled; + ViewSortMode d_sortMode; + bool d_isAutoResizeHeightEnabled; + bool d_isAutoResizeWidthEnabled; + + //TODO: move this into the renderer instead? + float d_renderedMaxWidth; + float d_renderedTotalHeight; + + void addItemViewProperties(); + virtual void updateScrollbars(); + void updateScrollbar(Scrollbar* scrollbar, float available_area, + float rendered_area, ScrollbarDisplayMode display_mode); + virtual ItemViewWindowRenderer* getViewRenderer(); + void updateScrollbarDisplayMode(ScrollbarDisplayMode& target_mode, + ScrollbarDisplayMode new_mode, String change_event); + + virtual void initialiseComponents(void); + + virtual bool onChildrenWillBeAdded(const EventArgs& args); + virtual bool onChildrenAdded(const EventArgs& args); + virtual bool onChildrenWillBeRemoved(const EventArgs& args); + virtual bool onChildrenRemoved(const EventArgs& args); + virtual bool onChildrenDataWillChange(const EventArgs& args); + virtual bool onChildrenDataChanged(const EventArgs& args); + + virtual bool onScrollPositionChanged(const EventArgs& args); + virtual void onSelectionChanged(ItemViewEventArgs& args); + virtual void onMultiselectModeChanged(WindowEventArgs& args); + virtual void onSortModeChanged(WindowEventArgs& args); + virtual void onViewContentsChanged(WindowEventArgs& args); + + virtual void onScroll(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); + virtual void onParentSized(ElementEventArgs& e); + + Event::Connection d_eventChildrenWillBeAddedConnection; + Event::Connection d_eventChildrenAddedConnection; + Event::Connection d_eventChildrenWillBeRemovedConnection; + Event::Connection d_eventChildrenRemovedConnection; + Event::Connection d_eventChildrenDataWillChangeConnection; + Event::Connection d_eventChildrenDataChangedConnection; + void connectToModelEvents(ItemModel* d_itemModel); + void disconnectModelEvents(); + + void handleOnScroll(Scrollbar* scrollbar, float scroll); + void setupTooltip(glm::vec2 position); + int getSelectedIndexPosition(const ModelIndex& index) const; + virtual bool handleSelection(const glm::vec2& position, bool should_select, + bool is_cumulative, bool is_range); + virtual bool handleSelection(const ModelIndex& index, bool should_select, + bool is_cumulative, bool is_range); + + virtual void resortView() = 0; + void handleSelectionNavigation(SemanticEventArgs& e); + + //! Returns the Rectf that contains the specified \a index. + virtual Rectf getIndexRect(const ModelIndex& index) = 0; + + void updateAutoResizeFlag(bool& flag, bool enabled); + void resizeToContent(); +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/views/ListView.h b/cegui/include/CEGUI/views/ListView.h new file mode 100644 index 000000000..5754146b9 --- /dev/null +++ b/cegui/include/CEGUI/views/ListView.h @@ -0,0 +1,122 @@ +/*********************************************************************** + created: Sat May 24 2014 + author: Timotei Dolean + + purpose: Interface for a view that displays a list of model items. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIListView_h_ +#define _CEGUIListView_h_ + +#include "CEGUI/ForwardRefs.h" +#include "CEGUI/views/ItemView.h" +#include + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ + +/*! +\brief + This internal struct represents the rendering state of an item that is part + of the ListView. This is recomputed each time the ListView is invalidated. + + This struct is meant to be used as a caching mechanism so that the ItemModel + is not queries each time rendering is done. That means, the users of ListView + shouldn't use this struct for interacting with the list, but rather use the + attached ItemModel. +*/ +struct CEGUIEXPORT ListViewItemRenderingState +{ + RenderedString d_string; + //! The name of the image that represents the icon + String d_icon; + Sizef d_size; + bool d_isSelected; + ModelIndex d_index; + String d_text; + ListView* d_attachedListView; + + ListViewItemRenderingState(ListView* list_view); + bool operator< (const ListViewItemRenderingState& other) const; + bool operator> (const ListViewItemRenderingState& other) const; +}; + +/*! +\brief + View that displays items in a listed fashion. + + ItemModel%s that use a tree structure can be still rendered by this view, + but only the children that are direct children of the ItemModel::getRootIndex() + are taken into considerations. That is, you cannot use a list to render + arbitrary list of children, unless a specific ItemModel implementation that + provides that is specified. +*/ +class CEGUIEXPORT ListView : public ItemView +{ +public: + //! Window factory name + static const String WidgetTypeName; + //! Namespace for global events + static const String EventNamespace; + + ListView(const String& type, const String& name); + virtual ~ListView(); + + const std::vector& getItems() const; + + virtual void prepareForRender(); + + virtual ModelIndex indexAt(const glm::vec2& position); + +protected: + virtual bool onChildrenAdded(const EventArgs& args); + virtual bool onChildrenRemoved(const EventArgs& args); + +private: + std::vector d_items; + std::vector d_sortedItems; + + void resortListView(); + virtual void resortView(); + + //! Updates the rendering state for the specified \a item using the specified + //! \a index as the data source. + void updateItem(ListViewItemRenderingState& item, ModelIndex index, + float& max_width, float& total_height); + + virtual Rectf getIndexRect(const ModelIndex& index); +}; + +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/views/StandardItemModel.h b/cegui/include/CEGUI/views/StandardItemModel.h new file mode 100644 index 000000000..fd64ec431 --- /dev/null +++ b/cegui/include/CEGUI/views/StandardItemModel.h @@ -0,0 +1,81 @@ +/*********************************************************************** + created: Wed May 23 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUIStandardItemModel_h_ +#define _CEGUIStandardItemModel_h_ + +#include "CEGUI/views/ItemModel.h" +#include "CEGUI/views/GenericItemModel.h" +#include + +namespace CEGUI +{ + +/*! +\brief + This is an implementation of GenericItem that has an additional id. +*/ +class CEGUIEXPORT StandardItem : public GenericItem +{ +public: + StandardItem(); + explicit StandardItem(const String& text, uint id = 0); + StandardItem(const String& text, const String& icon, uint id = 0); + + //! Id of this item + uint getId() const { return d_id; } + void setId(uint val) { d_id = val; } + +protected: + uint d_id; +}; + +/*! +\brief + This is an example model that inherits the default GenericItemModel + functionality over a specified model type (StandardItem). + + Besides that we added a new function that updates a given item's text. +*/ +class CEGUIEXPORT StandardItemModel : public GenericItemModel +{ +public: + StandardItemModel(); + + /*! + \brief + Updates the specified \a item's text with the new one. + + This function will notify the listeners that the specified \a item's + text has been changed, via the EventChildrenDataWillChange and + EventChildrenDataChanged events. + */ + void updateItemText(StandardItem* item, const String& new_text); +}; + +} + +#endif diff --git a/cegui/include/CEGUI/views/TreeView.h b/cegui/include/CEGUI/views/TreeView.h new file mode 100644 index 000000000..1b00560e0 --- /dev/null +++ b/cegui/include/CEGUI/views/TreeView.h @@ -0,0 +1,227 @@ +/*********************************************************************** + created: Fri Jun 06 2014 + author: Timotei Dolean + + purpose: Interface for a view that displays a tree of model items. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUITreeView_h_ +#define _CEGUITreeView_h_ + +#include "CEGUI/EventArgs.h" +#include "CEGUI/InputEvent.h" +#include "CEGUI/ForwardRefs.h" +#include "CEGUI/views/ItemView.h" +#include + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4251) +#endif + +namespace CEGUI +{ + +/*! +\brief + This renderer provides extra TreeView-specific rendering information. +*/ +class CEGUIEXPORT TreeViewWindowRenderer : public ItemViewWindowRenderer +{ +public: + TreeViewWindowRenderer(const String& type); + + /*! + \brief + Returns a Size object describing, in unclipped pixels, the size of the + expander that opens (expands) or closes a subtree. This includes + any potential padding around it. + */ + virtual Sizef getSubtreeExpanderSize() const = 0; + + /*! + \brief + Returns the horizontal (X-axis) indentation size for the subtree expander. + The indent specifies the X-coordinate where the expander is positioned. + + \param depth + The depth of the item for which to compute the actual indentation. + Depth 0 is the depth for the root's children items. + */ + virtual float getSubtreeExpanderXIndent(int depth) const = 0; +}; + +/*! +\brief + This struct represents the internal rendering state of the TreeView. It should + not be used to manipulate the TreeView or its items unless a TreeView's + method requires it. This struct is exposed only because it's cheaper to use + this for specific operations rather than compute it based of a ModelIndex + each request. + + Access to the root state is done via TreeView::getRootItemState(). +*/ +class CEGUIEXPORT TreeViewItemRenderingState +{ +public: + //! These children are rendered via the renderer. If sorting is enabled, + //! this vector will be sorted. + std::vector d_renderedChildren; + + //! This represents the total children count this item has, even if not rendered yet. + //! This is the case when this node has not been opened/expanded yet. + size_t d_totalChildCount; + + String d_text; + //! The name of the image that represents the icon + String d_icon; + RenderedString d_string; + Sizef d_size; + bool d_isSelected; + ModelIndex d_parentIndex; + size_t d_childId; + bool d_subtreeIsExpanded; + int d_nestedLevel; + + TreeView* d_attachedTreeView; + + TreeViewItemRenderingState(TreeView* attached_tree_view); + bool operator< (const TreeViewItemRenderingState& other) const; + bool operator> (const TreeViewItemRenderingState& other) const; + +protected: + //! Holds the unsorted children on which all tree operations are done. + std::vector d_children; + + void sortChildren(); + + friend class TreeView; +}; + +/*! +\brief + View that displays items in a tree fashion. A list-only ItemModel can be + provided as well as the ItemModel of this view. +*/ +class CEGUIEXPORT TreeView : public ItemView +{ +public: + //! Window factory name + static const String WidgetTypeName; + //! Namespace for global events + static const String EventNamespace; + static const String EventSubtreeExpanded; + static const String EventSubtreeCollapsed; + + TreeView(const String& type, const String& name); + virtual ~TreeView(); + + const TreeViewItemRenderingState& getRootItemState() const; + + virtual void prepareForRender(); + + virtual ModelIndex indexAt(const glm::vec2& position); + + float getSubtreeExpanderMargin() const; + //! Allows setting extra margin around the subtree expander component. + void setSubtreeExpanderMargin(float value); + + TreeViewItemRenderingState* getTreeViewItemForIndex(const ModelIndex& index); + + /*! + \brief + Triggers the \b recursive expansion of all subtrees in the TreeView. + This will raise the EventSubtreeExpanded event for all non-expanded + subtrees. + + This function invokes the expandSubtreeRecursive(TreeViewItemRenderingState) + recursively on each item. + */ + void expandAllSubtrees(); + void expandSubtreeRecursive(TreeViewItemRenderingState& item); + + /*! + \brief + Toggles the expanded/collapsed state of the specified tree item. + This will raise the EventSubtreeExpanded or EventSubtreeCollapsed + events based on the current item's state. + */ + void toggleSubtree(TreeViewItemRenderingState& item); + +protected: + virtual TreeViewWindowRenderer* getViewRenderer(); + virtual bool handleSelection(const glm::vec2& position, bool should_select, + bool is_cumulative, bool is_range); + virtual bool handleSelection(const ModelIndex& index, bool should_select, + bool is_cumulative, bool is_range); + + virtual bool onChildrenRemoved(const EventArgs& args); + virtual bool onChildrenAdded(const EventArgs& args); + + virtual void onSubtreeExpanded(ItemViewEventArgs& args); + virtual void onSubtreeCollapsed(ItemViewEventArgs& args); + +private: + typedef void (TreeView::*TreeViewItemAction)( + TreeViewItemRenderingState& item, bool toggles_expander); + typedef std::vector ItemStateVector; + + TreeViewItemRenderingState d_rootItemState; + TreeViewItemRenderingState computeRenderingStateForIndex( + const ModelIndex& parent_index, size_t child_id, size_t nested_level, + float& rendered_max_width, float& rendered_total_height); + + float d_subtreeExpanderMargin; + + void addTreeViewProperties(); + + void computeRenderedChildrenForItem(TreeViewItemRenderingState &item, + const ModelIndex& index, float& rendered_max_width, float& rendered_total_height); + + void updateRenderingStateForItem(TreeViewItemRenderingState& item, + float& rendered_max_width, float& rendered_total_height); + + void fillRenderingState(TreeViewItemRenderingState& state, const ModelIndex& index, float& rendered_max_width, float& rendered_total_height); + + ModelIndex indexAtWithAction(const glm::vec2& position, TreeViewItemAction action); + ModelIndex indexAtRecursive(TreeViewItemRenderingState& item, float& cur_height, + const glm::vec2& window_position, bool& handled, TreeViewItemAction action); + + void clearItemRenderedChildren(TreeViewItemRenderingState& item, float& renderedTotalHeight); + void handleSelectionAction(TreeViewItemRenderingState& item, bool toggles_expander); + + void noopAction(TreeViewItemRenderingState& item, bool toggles_expander) {} + + virtual void resortView(); + + virtual Rectf getIndexRect(const ModelIndex& index); +}; + +}; + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif diff --git a/cegui/include/CEGUI/widgets/All.h b/cegui/include/CEGUI/widgets/All.h index 56b69c5a7..aa39e84d2 100644 --- a/cegui/include/CEGUI/widgets/All.h +++ b/cegui/include/CEGUI/widgets/All.h @@ -24,10 +24,9 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIAll_h_ -#define _CEGUIAll_h_ +#ifndef _CEGUIAllWidgets_h_ +#define _CEGUIAllWidgets_h_ -#include "./ClippedContainer.h" #include "./Combobox.h" #include "./ComboDropList.h" #include "./DefaultWindow.h" @@ -38,12 +37,10 @@ #include "./GroupBox.h" #include "./HorizontalLayoutContainer.h" #include "./ItemEntry.h" -#include "./ItemListbox.h" -#include "./LayoutCell.h" -#include "./Listbox.h" #include "./ListboxItem.h" #include "./ListboxTextItem.h" #include "./ListHeader.h" +#include "./ListWidget.h" #include "./Menubar.h" #include "./MenuItem.h" #include "./MultiColumnList.h" @@ -63,8 +60,7 @@ #include "./Titlebar.h" #include "./ToggleButton.h" #include "./Tooltip.h" -#include "./Tree.h" -#include "./TreeItem.h" +#include "./TreeWidget.h" #include "./VerticalLayoutContainer.h" -#endif // End of guard _CEGUIAll_h_ +#endif // End of guard _CEGUIAllWidgets_h_ diff --git a/cegui/include/CEGUI/widgets/ButtonBase.h b/cegui/include/CEGUI/widgets/ButtonBase.h index 5d6c16d6e..71d5dd9b9 100644 --- a/cegui/include/CEGUI/widgets/ButtonBase.h +++ b/cegui/include/CEGUI/widgets/ButtonBase.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 13/4/2004 author: Paul D Turner - + purpose: Interface to base class for ButtonBase widget *************************************************************************/ /*************************************************************************** @@ -57,9 +57,10 @@ class CEGUIEXPORT ButtonBase : public Window \brief return true if user is hovering over this widget (or it's pushed and user is not over it for highlight) - \return - true if the user is hovering or if the button is pushed and the mouse is not over the button. Otherwise return false. - */ + \return + true if the user is hovering or if the button is pushed and the pointer is + not over the button. Otherwise return false. + */ bool isHovering(void) const {return d_hovering;} @@ -98,29 +99,30 @@ class CEGUIEXPORT ButtonBase : public Window /************************************************************************* Overridden event handlers *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); - virtual void onCaptureLost(WindowEventArgs& e); - virtual void onMouseLeaves(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorLeaves(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); + virtual void onCaptureLost(WindowEventArgs& e); /************************************************************************* Implementation Functions *************************************************************************/ - /*! - \brief - Update the internal state of the widget with the mouse at the given position. + /*! + \brief + Update the internal state of the widget with the cursor at the given position. - \param mouse_pos - Point object describing, in screen pixel co-ordinates, the location of the mouse cursor. + \param cursor_pos + Point object describing, in screen pixel co-ordinates, the location of + the cursor. - \return - Nothing - */ - void updateInternalState(const Vector2f& mouse_pos); + \return + Nothing + */ + void updateInternalState(const glm::vec2& cursor_pos); - bool calculateCurrentHoverState(const Vector2f& mouse_pos); + bool calculateCurrentHoverState(const glm::vec2& cursor_pos); /************************************************************************* Implementation Data diff --git a/cegui/include/CEGUI/widgets/ClippedContainer.h b/cegui/include/CEGUI/widgets/ClippedContainer.h deleted file mode 100644 index 54c583129..000000000 --- a/cegui/include/CEGUI/widgets/ClippedContainer.h +++ /dev/null @@ -1,133 +0,0 @@ -/*********************************************************************** - created: Sun Jun 11 2006 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIClippedContainer_h_ -#define _CEGUIClippedContainer_h_ - -#include "../Window.h" -#include "../WindowFactory.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -/*! -\brief - Helper container window that has configurable clipping. - Used by the ItemListbox widget. - -\deprecated - This class is deprecated and is scheduled for removal. The function this - class used to provide was broken when the inner-rect (aka client area) - support got fixed. The good news is that fixing inner-rect support - effectively negated the need for this class anyway - clipping areas can - now be established in the looknfeel and extracted via the WindowRenderer. -*/ -class CEGUIEXPORT ClippedContainer : public Window -{ -public: - /************************************************************************* - Constants - *************************************************************************/ - static const String WidgetTypeName; //!< Type name for ClippedContainer. - static const String EventNamespace; //!< Namespace for global events - - /************************************************************************* - Object construction and destruction - *************************************************************************/ - /*! - \brief - Constructor for ClippedContainer objects. - */ - ClippedContainer(const String& type, const String& name); - - /*! - \brief - Destructor for ClippedContainer objects. - */ - ~ClippedContainer(void); - - /************************************************************************* - Public interface methods - *************************************************************************/ - /*! - \brief - Return the current clipping rectangle. - - \return - Rect object describing the clipping area in pixel that will be applied during rendering. - */ - const Rectf& getClipArea(void) const; - - /*! - \brief - Returns the reference window used for converting the clipper rect to screen space. - */ - Window* getClipperWindow(void) const; - - /*! - \brief - Set the custom clipper area in pixels. - */ - void setClipArea(const Rectf& r); - - /*! - \brief - Set the clipper reference window. - - \param w - The window to be used a base for converting the custom clipper rect to - screen space. NULL if the clipper rect is relative to the screen. - */ - void setClipperWindow(Window* w); - -protected: - /************************************************************************* - Overridden from Window. - *************************************************************************/ - virtual Rectf getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const; - virtual void drawSelf(const RenderingContext&) {} - - /************************************************************************* - Data fields - *************************************************************************/ - //! the pixel rect to be used for clipping relative to either a window or the screen. - Rectf d_clipArea; - //! the base window which the clipping rect is relative to. - Window* d_clipperWindow; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIClippedContainer_h_ diff --git a/cegui/include/CEGUI/widgets/ComboDropList.h b/cegui/include/CEGUI/widgets/ComboDropList.h index a78c666e9..f5345364b 100644 --- a/cegui/include/CEGUI/widgets/ComboDropList.h +++ b/cegui/include/CEGUI/widgets/ComboDropList.h @@ -29,23 +29,22 @@ #ifndef _CEGUIComboDropList_h_ #define _CEGUIComboDropList_h_ -#include "./Listbox.h" - +#include "CEGUI/widgets/ListWidget.h" #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif - // Start of CEGUI namespace section namespace CEGUI { /*! \brief - Base class for the combo box drop down list. This is a specialisation of the Listbox class. + Base class for the combo box drop down list. + This is a specialisation of the ListWidget class. */ -class CEGUIEXPORT ComboDropList : public Listbox +class CEGUIEXPORT ComboDropList : public ListWidget { public: static const String EventNamespace; //!< Namespace for global events @@ -56,7 +55,7 @@ class CEGUIEXPORT ComboDropList : public Listbox Constants *************************************************************************/ // Event names - /** Event fired when the user confirms the selection by clicking the mouse. + /** Event fired when the user confirms the selection by activation (of the cursor). * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the ComboDropList whose selection has been * confirmed by the user. @@ -82,9 +81,9 @@ class CEGUIEXPORT ComboDropList : public Listbox Set whether the drop-list is 'armed' for selection. \note - This setting is not exclusively under client control; the ComboDropList will auto-arm in - response to certain left mouse button events. This is also dependant upon the autoArm - setting of the ComboDropList. + This setting is not exclusively under client control; the ComboDropList will auto-arm in + response to certain cursor left source events. This is also dependent upon the autoArm + setting of the ComboDropList. \param setting - true to arm the box; items will be highlighted and the next left button up event @@ -115,9 +114,9 @@ class CEGUIEXPORT ComboDropList : public Listbox \brief Set the mode of operation for the ComboDropList. - \param setting - - true if the ComboDropList auto-arms when the mouse enters the box. - - false if the user must click to arm the box. + \param setting + - true if the ComboDropList auto-arms when the cursor enters the box. + - false if the user must activate to arm the box. \return Nothing. @@ -129,9 +128,9 @@ class CEGUIEXPORT ComboDropList : public Listbox \brief returns the mode of operation for the drop-list - \return - - true if the ComboDropList auto-arms when the mouse enters the box. - - false if the user must click to arm the box. + \return + - true if the ComboDropList auto-arms when the cursor enters the box. + - false if the user must click to arm the box. */ bool isAutoArmEnabled(void) const { return d_autoArm; } @@ -169,20 +168,19 @@ class CEGUIEXPORT ComboDropList : public Listbox /************************************************************************* Overridden Event handling *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); - virtual void onActivated(ActivationEventArgs& e); - virtual void onListContentsChanged(WindowEventArgs& e); - virtual void onSelectionChanged(WindowEventArgs& e); + virtual void onViewContentsChanged(WindowEventArgs& e); + virtual void onSelectionChanged(ItemViewEventArgs& e); /************************************************************************* Implementation Data *************************************************************************/ - bool d_autoArm; //!< true if the box auto-arms when the mouse enters it. + bool d_autoArm; //!< true if the box auto-arms when the cursor enters it. bool d_armed; //!< true when item selection has been armed. - ListboxItem* d_lastClickSelected; //!< Item last accepted by user. + StandardItem* d_lastItemSelected; //!< Item last accepted by user. }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/widgets/Combobox.h b/cegui/include/CEGUI/widgets/Combobox.h index c7038058d..31bcfc9bc 100644 --- a/cegui/include/CEGUI/widgets/Combobox.h +++ b/cegui/include/CEGUI/widgets/Combobox.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 13/4/2004 author: Paul D Turner - + purpose: Interface to base class for Combobox widget *************************************************************************/ /*************************************************************************** @@ -32,6 +32,8 @@ #include "CEGUI/Base.h" #include "CEGUI/Window.h" #include "CEGUI/RegexMatcher.h" +#include "CEGUI/views/ItemView.h" +#include "CEGUI/views/StandardItemModel.h" #if defined(_MSC_VER) # pragma warning(push) @@ -118,7 +120,7 @@ class CEGUIEXPORT Combobox : public Window */ static const String EventTextAccepted; - // event names from list box + // event names from list widget /** Event fired when the contents of the list is changed. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the Combobox whose list content has @@ -185,7 +187,7 @@ class CEGUIEXPORT Combobox : public Window static const String ButtonName; //!< Widget suffix for the button component. // override from Window class - bool isHit(const Vector2f& position, + bool isHit(const glm::vec2& position, const bool allow_disabled = false) const; /*! @@ -193,10 +195,12 @@ class CEGUIEXPORT Combobox : public Window returns the mode of operation for the combo box. \return - - true if the user can show the list and select an item with a single mouse click. - - false if the user must click to show the list and then click again to select an item. + - true if the user can show the list and select an item with a single + cursor activation. + - false if the user must activate the cursor to show the list and then + activate the cursor again to select an item. */ - bool getSingleClickEnabled(void) const; + bool getSingleCursorActivationEnabled(void) const; /*! @@ -260,7 +264,7 @@ class CEGUIEXPORT Combobox : public Window return true if the Editbox has input focus. \return - true if the Editbox has keyboard input focus, false if the Editbox does not have keyboard input focus. + true if the Editbox has input focus, false if the Editbox does not have input focus. */ bool hasInputFocus(void) const; @@ -338,7 +342,7 @@ class CEGUIEXPORT Combobox : public Window */ size_t getSelectionEndIndex(void) const; - + /*! \brief return the length of the current selection (in code points / characters). @@ -368,23 +372,23 @@ class CEGUIEXPORT Combobox : public Window *************************************************************************/ /*! \brief - Return number of items attached to the list box + Return number of items attached to the list widget. \return - the number of items currently attached to this list box. + the number of items currently attached to this list widget. */ size_t getItemCount(void) const; - + /*! \brief Return a pointer to the currently selected item. \return - Pointer to a ListboxItem based object that is the selected item in the list. will return NULL if - no item is selected. + Pointer to a StandardItem based object that is the selected item in the list. + Will return NULL if no item is selected. */ - ListboxItem* getSelectedItem(void) const; + StandardItem* getSelectedItem(void) const; /*! @@ -395,26 +399,24 @@ class CEGUIEXPORT Combobox : public Window Zero based index of the item to be returned. \return - Pointer to the ListboxItem at index position \a index in the list box. + Pointer to the StandardItem at index position \a index in the list widget. \exception InvalidRequestException thrown if \a index is out of range. */ - ListboxItem* getListboxItemFromIndex(size_t index) const; + StandardItem* getItemFromIndex(size_t index) const; /*! \brief - Return the index of ListboxItem \a item + Return the index of StandardItem \a item \param item - Pointer to a ListboxItem whos zero based index is to be returned. + Pointer to a StandardItem who's zero based index is to be returned. \return - Zero based index indicating the position of ListboxItem \a item in the list box. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. + Zero based index indicating the position of StandardItem \a item in the list widget. */ - size_t getItemIndex(const ListboxItem* item) const; + size_t getItemIndex(const StandardItem* item) const; /*! @@ -450,26 +452,26 @@ class CEGUIEXPORT Combobox : public Window String object containing the text to be searched for. \param start_item - ListboxItem where the search is to begin, the search will not include \a item. If \a item is - NULL, the search will begin from the first item in the list. + StandardItem where the search is to begin, the search will not + include \a item. If \a item is NULL, the search will begin from the + first item in the list. \return - Pointer to the first ListboxItem in the list after \a item that has text matching \a text. If - no item matches the criteria NULL is returned. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. + Pointer to the first StandardItem in the list after \a item that has + text matching \a text. If no item matches the criteria NULL is returned. */ - ListboxItem* findItemWithText(const String& text, const ListboxItem* start_item); + StandardItem* findItemWithText(const String& text, const StandardItem* start_item); /*! \brief - Return whether the specified ListboxItem is in the List + Return whether the specified StandardItem is in the List \return - true if ListboxItem \a item is in the list, false if ListboxItem \a item is not in the list. + true if StandardItem \a item is in the list, false ifStandardItem + \a item is not in the list. */ - bool isListboxItemInList(const ListboxItem* item) const; + bool isItemInList(const StandardItem* item) const; /*! @@ -535,13 +537,15 @@ class CEGUIEXPORT Combobox : public Window Set the mode of operation for the combo box. \param setting - - true if the user should be able to show the list and select an item with a single mouse click. - - false if the user must click to show the list and then click again to select an item. + - true if the user should be able to show the list and select an item + with a single cursor activation. + - false if the user must activate the cursor to show the list and then + activate the cursor again to select an item. \return Nothing. */ - void setSingleClickEnabled(bool setting); + void setSingleCursorActivationEnabled(bool setting); //! Select item in list matching editbox text, clear selection if none match void selectListItemWithEditboxText(); @@ -693,50 +697,43 @@ class CEGUIEXPORT Combobox : public Window /*! \brief - Add the given ListboxItem to the list. + Add the given StandardItem to the list. \param item - Pointer to the ListboxItem to be added to the list. Note that it is the passed object that is added to the - list, a copy is not made. If this parameter is NULL, nothing happens. - - \return - Nothing. + Pointer to the StandardItem to be added to the list. Note that it is + the passed object that is added to the list, a copy is not made. + If this parameter is NULL, nothing happens. */ - void addItem(ListboxItem* item); + void addItem(StandardItem* item); /*! \brief - Insert an item into the list box after a specified item already in the list. + Insert an item into the list after a specified item already in the list. Note that if the list is sorted, the item may not end up in the requested position. \param item - Pointer to the ListboxItem to be inserted. Note that it is the passed object that is added to the - list, a copy is not made. If this parameter is NULL, nothing happens. + Pointer to the StandardItem to be inserted. Note that it is the passed + object that is added to the list, a copy is not made. + If this parameter is NULL, nothing happens. \param position - Pointer to a ListboxItem that \a item is to be inserted after. If this parameter is NULL, the item is - inserted at the start of the list. - - \return - Nothing. + Pointer to a StandardItem that \a item is to be inserted after. If this + parameter is NULL, the item is inserted at the start of the list. */ - void insertItem(ListboxItem* item, const ListboxItem* position); + void insertItem(StandardItem* item, const StandardItem* position); /*! \brief - Removes the given item from the list box. + Removes the given item from the list widget. \param item - Pointer to the ListboxItem that is to be removed. If \a item is not attached to this list box then nothing - will happen. - - \return - Nothing. + Pointer to the StandardItem that is to be removed. + If \a item is not attached to this list widget then nothing will happen. */ - void removeItem(const ListboxItem* item); + void removeItem(const StandardItem* item); /*! @@ -761,7 +758,6 @@ class CEGUIEXPORT Combobox : public Window */ void setSortingEnabled(bool setting); - /*! \brief Set whether the vertical scroll bar should always be shown. @@ -789,62 +785,44 @@ class CEGUIEXPORT Combobox : public Window */ void setShowHorzScrollbar(bool setting); + /*! + \brief + Set the select state of an attached StandardItem. - /*! - \brief - Set the select state of an attached ListboxItem. - - This is the recommended way of selecting and deselecting items attached to a list box as it respects the - multi-select mode setting. It is possible to modify the setting on ListboxItems directly, but that approach - does not respect the settings of the list box. - - \param item - The ListboxItem to be affected. This item must be attached to the list box. - - \param state - true to select the item, false to de-select the item. + \param item + The StandardItem to be affected. - \return - Nothing. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. - */ - void setItemSelectState(ListboxItem* item, bool state); + \param state + true to select the item, false to de-select the item. + */ + void setItemSelectState(StandardItem* item, bool state); /*! \brief - Set the select state of an attached ListboxItem. - - This is the recommended way of selecting and deselecting items attached to a list box as it respects the - multi-select mode setting. It is possible to modify the setting on ListboxItems directly, but that approach - does not respect the settings of the list box. + Set the select state of an attached StandardItem. \param item_index - The zero based index of the ListboxItem to be affected. This must be a valid index (0 <= index < getItemCount()) + The zero based index of the StandardItem to be affected. + This must be a valid index (0 <= index < getItemCount()) \param state true to select the item, false to de-select the item. - \return - Nothing. - - \exception InvalidRequestException thrown if \a item_index is out of range for the list box + \exception InvalidRequestException thrown if \a item_index is out of range for the list widget */ void setItemSelectState(size_t item_index, bool state); /*! \brief - Causes the list box to update it's internal state after changes have been made to one or more - attached ListboxItem objects. + Causes the list widget to update it's internal state after changes have + been made to one or more attached StandardItem objects. - Client code must call this whenever it has made any changes to ListboxItem objects already attached to the - list box. If you are just adding items, or removed items to update them prior to re-adding them, there is - no need to call this method. - - \return - Nothing. + Client code must call this whenever it has made any changes to + StandardItem objects already attached to the list widget. If you are + just adding items, or removed items to update them prior to re-adding + them, there is no need to call this method. */ void handleUpdatedListItemData(void); @@ -891,18 +869,18 @@ class CEGUIEXPORT Combobox : public Window bool droplist_HiddenHandler(const EventArgs& e); - /*! - \brief - Mouse button down handler attached to edit box - */ - bool editbox_MouseDownHandler(const EventArgs& e); + /*! + \brief + Pointer press & hold handler attached to edit box + */ + bool editbox_PointerPressHoldHandler(const EventArgs& e); /*! \brief Update the Combobox text to reflect programmatically made changes to selected list item. */ - void itemSelectChangeTextUpdate(const ListboxItem* const item, + void itemSelectChangeTextUpdate(const StandardItem* const item, bool new_state, bool old_state); /************************************************************************* @@ -917,13 +895,13 @@ class CEGUIEXPORT Combobox : public Window bool editbox_EditboxFullEventHandler(const EventArgs& e); bool editbox_TextAcceptedEventHandler(const EventArgs& e); bool editbox_TextChangedEventHandler(const EventArgs& e); - bool listbox_ListContentsChangedHandler(const EventArgs& e); - bool listbox_ListSelectionChangedHandler(const EventArgs& e); - bool listbox_SortModeChangedHandler(const EventArgs& e); - bool listbox_VertScrollModeChangedHandler(const EventArgs& e); - bool listbox_HorzScrollModeChangedHandler(const EventArgs& e); + bool listwidget_ListContentsChangedHandler(const EventArgs& e); + bool listwidget_ListSelectionChangedHandler(const EventArgs& e); + bool listwidget_SortModeChangedHandler(const EventArgs& e); + bool listwidget_VertScrollModeChangedHandler(const EventArgs& e); + bool listwidget_HorzScrollModeChangedHandler(const EventArgs& e); + - /************************************************************************* New Events for Combobox *************************************************************************/ diff --git a/cegui/include/CEGUI/widgets/DefaultWindow.h b/cegui/include/CEGUI/widgets/DefaultWindow.h index 2473ba7e5..6f66a2921 100644 --- a/cegui/include/CEGUI/widgets/DefaultWindow.h +++ b/cegui/include/CEGUI/widgets/DefaultWindow.h @@ -73,22 +73,22 @@ class CEGUIEXPORT DefaultWindow : public Window */ virtual ~DefaultWindow(void) {} + bool canFocus(); protected: - //! helper to update mouse input handled state - void updateMouseEventHandled(MouseEventArgs& e) const; + //! helper to update cursor input handled state + void updatePointerEventHandled(CursorInputEventArgs& e) const; // overridden functions from Window base class bool moveToFront_impl(bool wasClicked); - // override the mouse event handlers - void onMouseMove(MouseEventArgs& e); - void onMouseWheel(MouseEventArgs& e); - void onMouseButtonDown(MouseEventArgs& e); - void onMouseButtonUp(MouseEventArgs& e); - void onMouseClicked(MouseEventArgs& e); - void onMouseDoubleClicked(MouseEventArgs& e); - void onMouseTripleClicked(MouseEventArgs& e); + // override the cursor event handlers + void onCursorMove(CursorInputEventArgs& e); + void onScroll(CursorInputEventArgs& e); + void onCursorPressHold(CursorInputEventArgs& e); + void onCursorActivate(CursorInputEventArgs& e); + + void onSemanticInputEvent(SemanticEventArgs& e); }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/widgets/DragContainer.h b/cegui/include/CEGUI/widgets/DragContainer.h index 2b819639c..a0949fc3f 100644 --- a/cegui/include/CEGUI/widgets/DragContainer.h +++ b/cegui/include/CEGUI/widgets/DragContainer.h @@ -80,12 +80,12 @@ namespace CEGUI * value has been changed. */ static const String EventDragAlphaChanged; - /** Event fired when the mouse cursor to used when dragging is changed. + /** Event fired when the cursor used when dragging is changed. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the DragContainer whose dragging - * mouse cursor image has been changed. + * cursor image has been changed. */ - static const String EventDragMouseCursorChanged; + static const String EventDragCursorChanged; /** Event fired when the drag pixel threshold is changed. * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the DragContainer whose dragging pixel @@ -147,7 +147,7 @@ namespace CEGUI \return - true if the DragContainer is being dragged. - - false if te DragContainer is not being dragged. + - false if the DragContainer is not being dragged. */ bool isBeingDragged(void) const; @@ -155,10 +155,10 @@ namespace CEGUI \brief Return the current drag threshold in pixels. - The drag threshold is the number of pixels that the mouse must be - moved with the left button held down in order to commence a drag + The drag threshold is the number of pixels that the cursor must be + moved with the left source held pressed in order to commence a drag operation. - + \return float value indicating the current drag threshold value. */ @@ -168,8 +168,8 @@ namespace CEGUI \brief Set the current drag threshold in pixels. - The drag threshold is the number of pixels that the mouse must be - moved with the left button held down in order to commence a drag + The drag threshold is the number of pixels that the cursor must be + moved with the left source held pressed in order to commence a drag operation. \param pixels @@ -209,47 +209,47 @@ namespace CEGUI /*! \brief - Return the Image currently set to be used for the mouse cursor when a - drag operation is in progress. + Return the Image currently set to be used for the cursor + when a drag operation is in progress. \return - Image object currently set to be used as the mouse cursor when dragging. + Image object currently set to be used as the cursor when dragging. */ - const Image* getDragCursorImage(void) const; + const Image* getDragIndicatorImage(void) const; /*! \brief - Set the Image to be used for the mouse cursor when a drag operation is - in progress. + Set the Image to be used for the cursor when a drag + operation is in progress. - This method may be used during a drag operation to update the current mouse + This method may be used during a drag operation to update the current cursor image. \param image - Image object to be used as the mouse cursor while dragging. + Image object to be used as the cursor while dragging. \return Nothing. */ - void setDragCursorImage(const Image* image); + void setDragIndicatorImage(const Image* image); /*! \brief - Set the Image to be used for the mouse cursor when a drag operation is - in progress. + Set the Image to be used for the cursor when a drag + operation is in progress. - This method may be used during a drag operation to update the current mouse + This method may be used during a drag operation to update the current cursor image. \param name - Image to be used as the mouse cursor when dragging. + Image to be used as the cursor when dragging. \return Nothing. \exception UnknownObjectException thrown if Image \name is unknown. */ - void setDragCursorImage(const String& name); + void setDragIndicatorImage(const String& name); /*! \brief @@ -287,14 +287,14 @@ namespace CEGUI /*! \brief Immediately pick up the DragContainer and optionally set the sticky - mode in order to allow this to happen. Any current interaction - (i.e. mouse capture) will be interrupted. + mode in order to allow this to happen. Any current interaction + (i.e. cursor capture) will be interrupted. \param force_sticky - true to automatically enable the sticky mode in order to facilitate picking up the DragContainer. - false to ignore the pick up request if the sticky mode is not - alraedy enabled (default). + already enabled (default). \return - true if the DragContainer was successfully picked up. @@ -304,7 +304,7 @@ namespace CEGUI /*! \brief - Set the fixed mouse cursor dragging offset to be used for this + Set the fixed cursor dragging offset to be used for this DragContainer. \param offset @@ -319,7 +319,7 @@ namespace CEGUI /*! \brief - Return the fixed mouse cursor dragging offset to be used for this + Return the fixed cursor dragging offset to be used for this DragContainer. \return @@ -361,21 +361,21 @@ namespace CEGUI protected: /************************************************************************* - Protected Implementation Methods + Protected Implementation Methods *************************************************************************/ /*! \brief Return whether the required minimum movement threshold before initiating dragging has been exceeded. - \param local_mouse - Mouse position as a pixel offset from the top-left corner of this window. + \param local_cursor + Cursor position as a pixel offset from the top-left corner of this window. \return - true if the threshold has been exceeded and dragging should be initiated. - false if the threshold has not been exceeded. - */ - bool isDraggingThresholdExceeded(const Vector2f& local_mouse); + */ + bool isDraggingThresholdExceeded(const glm::vec2& local_cursor); /*! \brief @@ -387,22 +387,22 @@ namespace CEGUI void initialiseDragging(void); /*! - \brief - Update state for window dragging. + \brief + Update state for window dragging. - \param local_mouse - Mouse position as a pixel offset from the top-left corner of this window. + \param local_cursor + Cursor position as a pixel offset from the top-left corner of this window. \return Nothing. */ - void doDragging(const Vector2f& local_mouse); + void doDragging(const glm::vec2& local_cursor); /*! \brief - Method to update mouse cursor image + Method to update cursor image */ - void updateActiveMouseCursor(void) const; + void updateActiveCursor(void) const; /************************************************************************* Overrides of methods in Window @@ -411,9 +411,9 @@ namespace CEGUI /************************************************************************* Overrides for Event handler methods *************************************************************************/ - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); - virtual void onMouseMove(MouseEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); virtual void onAlphaChanged(WindowEventArgs& e); virtual void onClippingChanged(WindowEventArgs& e);/*Window::drawSelf(z);*/ @@ -480,13 +480,13 @@ namespace CEGUI /*! \brief - Method called when the mouse cursor to use when dragging is changed. + Method called when the cursor to use when dragging is changed. \param e WindowEventArgs object. \return Nothing. */ - virtual void onDragMouseCursorChanged(WindowEventArgs& e); + virtual void onDragCursorChanged(WindowEventArgs& e); /*! \brief @@ -519,24 +519,24 @@ namespace CEGUI Data *************************************************************************/ bool d_draggingEnabled; //!< True when dragging is enabled. - bool d_leftMouseDown; //!< True when left mouse button is down. + bool d_leftPointerHeld; //!< True when left cursor source is held. bool d_dragging; //!< true when being dragged. UVector2 d_dragPoint; //!< point we are being dragged at. UVector2 d_startPosition; //!< position prior to dragging. - float d_dragThreshold; //!< Pixels mouse must move before dragging commences. + float d_dragThreshold; //!< Pixels cursor must move before dragging commences. float d_dragAlpha; //!< Alpha value to set when dragging. float d_storedAlpha; //!< Alpha value to re-set when dragging ends. bool d_storedClipState; //!< Parent clip state to re-set. Window* d_dropTarget; //!< Target window for possible drop operation. - const Image* d_dragCursorImage; //!< Image to use for mouse cursor when dragging. + const Image* d_dragIndicatorImage; //!< Image to use for cursor when dragging. bool d_dropflag; //!< True when we're being dropped //! true when we're in 'sticky' mode. bool d_stickyMode; //! true after been picked-up / dragged via sticky mode bool d_pickedUp; - //! true if fixed mouse offset is used for dragging position. + //! true if fixed cursor offset is used for dragging position. bool d_usingFixedDragOffset; - //! current fixed mouse offset value. + //! current fixed cursor offset value. UVector2 d_fixedDragOffset; private: @@ -546,7 +546,7 @@ namespace CEGUI /*! \brief Adds properties specific to the DragContainer base class. - + \return Nothing. */ diff --git a/cegui/include/CEGUI/widgets/Editbox.h b/cegui/include/CEGUI/widgets/Editbox.h index e8c25c714..4d4136541 100644 --- a/cegui/include/CEGUI/widgets/Editbox.h +++ b/cegui/include/CEGUI/widgets/Editbox.h @@ -41,6 +41,8 @@ // Start of CEGUI namespace section namespace CEGUI { +class UndoHandler; + //! Base class for the EditboxWindowRenderer class class CEGUIEXPORT EditboxWindowRenderer : public WindowRenderer { @@ -60,7 +62,7 @@ class CEGUIEXPORT EditboxWindowRenderer : public WindowRenderer Code point index into the text that is rendered closest to screen position \a pt. */ - virtual size_t getTextIndexFromPosition(const Vector2f& pt) const = 0; + virtual size_t getTextIndexFromPosition(const glm::vec2& pt) const = 0; }; //----------------------------------------------------------------------------// @@ -151,8 +153,8 @@ class CEGUIEXPORT Editbox : public Window return true if the Editbox has input focus. \return - - true if the Editbox has keyboard input focus. - - false if the Editbox does not have keyboard input focus. + - true if the Editbox has input focus. + - false if the Editbox does not have input focus. */ bool hasInputFocus(void) const; @@ -454,16 +456,22 @@ class CEGUIEXPORT Editbox : public Window //! \copydoc Window::performCut virtual bool performCut(Clipboard& clipboard); - + //! \copydoc Window::performPaste virtual bool performPaste(Clipboard& clipboard); - + //! Constructor for Editbox class. Editbox(const String& type, const String& name); //! Destructor for Editbox class. virtual ~Editbox(void); + //! \copydoc Window::performUndo + virtual bool performUndo(); + + //! \copydoc Window::performRedo + virtual bool performRedo(); + protected: /*! \brief @@ -477,7 +485,7 @@ class CEGUIEXPORT Editbox : public Window Code point index into the text that is rendered closest to screen position \a pt. */ - size_t getTextIndexFromPosition(const Vector2f& pt) const; + size_t getTextIndexFromPosition(const glm::vec2& pt) const; //! Clear the currently defined selection (just the region, not the text). void clearSelection(void); @@ -515,23 +523,23 @@ class CEGUIEXPORT Editbox : public Window //! Processing for Delete key void handleDelete(void); - //! Processing to move caret one character left - void handleCharLeft(uint sysKeys); + //! Processing to move caret one character left (and optionally select it) + void handleCharLeft(bool select); - //! Processing to move caret one word left - void handleWordLeft(uint sysKeys); + //! Processing to move caret one word left (and optionally select it) + void handleWordLeft(bool select); - //! Processing to move caret one character right - void handleCharRight(uint sysKeys); + //! Processing to move caret one character right (and optionally select it) + void handleCharRight(bool select); - //! Processing to move caret one word right - void handleWordRight(uint sysKeys); + //! Processing to move caret one word right (and optionally select it) + void handleWordRight(bool select); - //! Processing to move caret to the start of the text. - void handleHome(uint sysKeys); + //! Processing to move caret to the start of the text. (and optionally select it) + void handleHome(bool select); - //! Processing to move caret to the end of the text - void handleEnd(uint sysKeys); + //! Processing to move caret to the end of the text (and optionally select it) + void handleEnd(bool select); //! validate window renderer virtual bool validateWindowRenderer(const WindowRenderer* renderer) const; @@ -602,16 +610,15 @@ class CEGUIEXPORT Editbox : public Window virtual void onTextAcceptedEvent(WindowEventArgs& e); // Overridden event handlers - void onMouseButtonDown(MouseEventArgs& e); - void onMouseButtonUp(MouseEventArgs& e); - void onMouseDoubleClicked(MouseEventArgs& e); - void onMouseTripleClicked(MouseEventArgs& e); - void onMouseMove(MouseEventArgs& e); + void onCursorPressHold(CursorInputEventArgs& e); + void onCursorActivate(CursorInputEventArgs& e); + void onCursorMove(CursorInputEventArgs& e); void onCaptureLost(WindowEventArgs& e); - void onCharacter(KeyEventArgs& e); - void onKeyDown(KeyEventArgs& e); + void onCharacter(TextEventArgs& e); void onTextChanged(WindowEventArgs& e); + void onSemanticInputEvent(SemanticEventArgs& e); + //! True if the editbox is in read-only mode bool d_readOnly; //! True if the editbox text should be rendered masked. @@ -640,6 +647,8 @@ class CEGUIEXPORT Editbox : public Window MatchState d_validatorMatchState; //! Previous match state change response bool d_previousValidityChangeResponse; + //! Undo handler + UndoHandler *d_undoHandler; private: diff --git a/cegui/include/CEGUI/widgets/FrameWindow.h b/cegui/include/CEGUI/widgets/FrameWindow.h index 812be5a96..624c75c43 100644 --- a/cegui/include/CEGUI/widgets/FrameWindow.h +++ b/cegui/include/CEGUI/widgets/FrameWindow.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 13/4/2004 author: Paul D Turner - + purpose: Interface to base class for FrameWindow *************************************************************************/ /*************************************************************************** @@ -52,7 +52,7 @@ class CEGUIEXPORT FrameWindow : public Window static const String WidgetTypeName; //!< Window factory name /************************************************************************* - Constants + Constants *************************************************************************/ // additional event names for this window /** Event fired when the rollup (shade) state of the window is changed. @@ -90,10 +90,11 @@ class CEGUIEXPORT FrameWindow : public Window static const String CloseButtonName; //!< Widget name for the close button component. - /*! - \brief - Enumeration that defines the set of possible locations for the mouse on a frame windows sizing border. - */ + /*! + \brief + Enumeration that defines the set of possible locations for the cursor + on a frame windows sizing border. + */ enum SizingLocation { SizingNone, //!< Position is not a sizing location. SizingTopLeft, //!< Position will size from the top-left. @@ -117,8 +118,8 @@ class CEGUIEXPORT FrameWindow : public Window Nothing */ virtual void initialiseComponents(void); - - + + /*! \brief Return whether this window is sizable. Note that this requires that the window have an enabled frame and that sizing itself is enabled @@ -145,7 +146,7 @@ class CEGUIEXPORT FrameWindow : public Window \return true if the window has a title bar and it is enabled, false if the window has no title bar or if the title bar is disabled. - */ + */ bool isTitleBarEnabled(void) const; @@ -291,12 +292,12 @@ class CEGUIEXPORT FrameWindow : public Window This is intended for internal system use - it is the method by which the title bar moves the frame window. \param offset - Vector2 object containing the offsets to apply (offsets are in screen pixels). + vec2 object containing the offsets to apply (offsets are in screen pixels). \return Nothing. */ - void offsetPixelPosition(const Vector2f& offset); + void offsetPixelPosition(const glm::vec2& offset); /*! @@ -324,47 +325,47 @@ class CEGUIEXPORT FrameWindow : public Window /*! \brief - Return a pointer to the currently set Image to be used for the north-south - sizing mouse cursor. + Return a cursor to the currently set Image to be used for the north-south + sizing cursor. \return Pointer to an Image object, or 0 for none. */ - const Image* getNSSizingCursorImage() const; + const Image* getNSSizingIndicatorImage() const; /*! \brief - Return a pointer to the currently set Image to be used for the east-west - sizing mouse cursor. + Return a cursor to the currently set Image to be used for the east-west + sizing cursor. \return Pointer to an Image object, or 0 for none. */ - const Image* getEWSizingCursorImage() const; + const Image* getEWSizingIndicatorImage() const; /*! \brief - Return a pointer to the currently set Image to be used for the northwest-southeast - sizing mouse cursor. + Return a cursor to the currently set Image to be used for the northwest-southeast + sizing cursor. \return Pointer to an Image object, or 0 for none. */ - const Image* getNWSESizingCursorImage() const; + const Image* getNWSESizingIndicatorImage() const; /*! \brief - Return a pointer to the currently set Image to be used for the northeast-southwest - sizing mouse cursor. + Return a cursor to the currently set Image to be used for the northeast-southwest + sizing cursor. \return Pointer to an Image object, or 0 for none. */ - const Image* getNESWSizingCursorImage() const; + const Image* getNESWSizingIndicatorImage() const; /*! \brief - Set the Image to be used for the north-south sizing mouse cursor. + Set the Image to be used for the north-south sizing cursor. \param image Pointer to an Image object, or 0 for none. @@ -372,11 +373,11 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. */ - void setNSSizingCursorImage(const Image* image); + void setNSSizingIndicatorImage(const Image* image); /*! \brief - Set the Image to be used for the east-west sizing mouse cursor. + Set the Image to be used for the east-west sizing cursor. \param image Pointer to an Image object, or 0 for none. @@ -384,11 +385,11 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. */ - void setEWSizingCursorImage(const Image* image); + void setEWSizingIndicatorImage(const Image* image); /*! \brief - Set the Image to be used for the northwest-southeast sizing mouse cursor. + Set the Image to be used for the northwest-southeast sizing cursor. \param image Pointer to an Image object, or 0 for none. @@ -396,11 +397,11 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. */ - void setNWSESizingCursorImage(const Image* image); + void setNWSESizingIndicatorImage(const Image* image); /*! \brief - Set the Image to be used for the northeast-southwest sizing mouse cursor. + Set the Image to be used for the northeast-southwest sizing cursor. \param image Pointer to an Image object, or 0 for none. @@ -408,11 +409,11 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. */ - void setNESWSizingCursorImage(const Image* image); + void setNESWSizingIndicatorImage(const Image* image); /*! \brief - Set the image to be used for the north-south sizing mouse cursor. + Set the image to be used for the north-south sizing cursor. \param name String holding the name of the Image to be used. @@ -420,13 +421,13 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. - \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities. + \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existent entities. */ - void setNSSizingCursorImage(const String& name); + void setNSSizingIndicatorImage(const String& name); /*! \brief - Set the image to be used for the east-west sizing mouse cursor. + Set the image to be used for the east-west sizing cursor. \param name String holding the name of the Image to be used. @@ -434,13 +435,13 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. - \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities. + \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existent entities. */ - void setEWSizingCursorImage(const String& name); + void setEWSizingIndicatorImage(const String& name); /*! \brief - Set the image to be used for the northwest-southeast sizing mouse cursor. + Set the image to be used for the northwest-southeast sizing cursor. \param name String holding the name of the Image to be used. @@ -448,13 +449,13 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. - \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities. + \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existent entities. */ - void setNWSESizingCursorImage(const String& name); + void setNWSESizingIndicatorImage(const String& name); /*! \brief - Set the image to be used for the northeast-southwest sizing mouse cursor. + Set the image to be used for the northeast-southwest sizing cursor. \param name String holding the name of the Image to be used. @@ -462,13 +463,12 @@ class CEGUIEXPORT FrameWindow : public Window \return Nothing. - \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existant entities. + \exception UnknownObjectException thrown if either \a imageset or \a image refer to non-existent entities. */ - void setNESWSizingCursorImage(const String& name); + void setNESWSizingIndicatorImage(const String& name); // overridden from Window class - bool isHit(const Vector2f& position, const bool /*allow_disabled*/) const - { return Window::isHit(position) && !d_rolledup; } + bool isHit(const glm::vec2& position, const bool allow_disabled) const; /*! \brief @@ -562,15 +562,15 @@ class CEGUIEXPORT FrameWindow : public Window the sizing border. \param pt - Point object describing, in pixels, the window relative offset to check. + vec2 object describing, in pixels, the window relative offset to check. \return One of the SizingLocation enumerated values that describe which part of the sizing border that \a pt corresponded to, if any. */ - SizingLocation getSizingBorderAtPoint(const Vector2f& pt) const; + SizingLocation getSizingBorderAtPoint(const glm::vec2& pt) const; + - /*! \brief return true if given SizingLocation is on left edge. @@ -630,11 +630,11 @@ class CEGUIEXPORT FrameWindow : public Window bool closeClickHandler(const EventArgs& e); - /*! - \brief - Set the appropriate mouse cursor for the given window-relative pixel point. - */ - void setCursorForPoint(const Vector2f& pt) const; + /*! + \brief + Set the appropriate cursor for the given window-relative pixel point. + */ + void setIndicatorForPoint(const glm::vec2& pt) const; /*! @@ -669,9 +669,9 @@ class CEGUIEXPORT FrameWindow : public Window /************************************************************************* Overridden event handlers *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); virtual void onTextChanged(WindowEventArgs& e); virtual void onActivated(ActivationEventArgs& e); @@ -692,7 +692,7 @@ class CEGUIEXPORT FrameWindow : public Window bool d_sizingEnabled; //!< true if sizing is enabled for this window. bool d_beingSized; //!< true if window is being sized. float d_borderSize; //!< thickness of the sizing border around this window - Vector2f d_dragPoint; //!< point window is being dragged at. + glm::vec2 d_dragPoint; //!< point window is being dragged at. // images for cursor when on sizing border const Image* d_nsSizingCursor; //!< North/South sizing cursor image. diff --git a/cegui/include/CEGUI/widgets/GroupBox.h b/cegui/include/CEGUI/widgets/GroupBox.h index 62992ef17..f13888842 100644 --- a/cegui/include/CEGUI/widgets/GroupBox.h +++ b/cegui/include/CEGUI/widgets/GroupBox.h @@ -31,7 +31,6 @@ #include "../Base.h" #include "../WindowFactory.h" -#include "./ClippedContainer.h" #include #if defined(_MSC_VER) diff --git a/cegui/include/CEGUI/widgets/ItemEntry.h b/cegui/include/CEGUI/widgets/ItemEntry.h index 681437e13..d71036680 100644 --- a/cegui/include/CEGUI/widgets/ItemEntry.h +++ b/cegui/include/CEGUI/widgets/ItemEntry.h @@ -211,10 +211,7 @@ class CEGUIEXPORT ItemEntry : public Window */ virtual void onSelectionChanged(WindowEventArgs& e); - /************************************************************************* - Overridden Event Handlers - *************************************************************************/ - virtual void onMouseClicked(MouseEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); /************************************************************************* Implementation Data diff --git a/cegui/include/CEGUI/widgets/ItemListBase.h b/cegui/include/CEGUI/widgets/ItemListBase.h index 4f88b3eee..597144672 100644 --- a/cegui/include/CEGUI/widgets/ItemListBase.h +++ b/cegui/include/CEGUI/widgets/ItemListBase.h @@ -374,10 +374,16 @@ class CEGUIEXPORT ItemListBase : public Window /*! \brief - Notify this ItemListBase that the given item was just clicked. + Notify this ItemListBase that the given item was just activated. Internal function - NOT to be used from client code. + + \param cumulativeSelection + True if this entry should cumulate to the previous selection + + \param rangeSelection + True if this entry should do a range selection */ - virtual void notifyItemClicked(ItemEntry*) {} + virtual void notifyItemActivated(ItemEntry*, bool cumulativeSelection, bool rangeSelection) {} /*! \brief @@ -555,8 +561,7 @@ class CEGUIEXPORT ItemListBase : public Window /************************************************************************* Implementation Data *************************************************************************/ - typedef std::vector ItemEntryList; + typedef std::vector ItemEntryList; ItemEntryList d_listItems; //!< list of items in the list. //!< True if this ItemListBase widget should automatically resize to fit its content. False if not. diff --git a/cegui/include/CEGUI/widgets/ItemListbox.h b/cegui/include/CEGUI/widgets/ItemListbox.h deleted file mode 100644 index b5349cc07..000000000 --- a/cegui/include/CEGUI/widgets/ItemListbox.h +++ /dev/null @@ -1,280 +0,0 @@ -/************************************************************************ - created: Tue Sep 27 2005 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIItemListbox_h_ -#define _CEGUIItemListbox_h_ - -#include "./ScrolledItemListBase.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// begin CEGUI namespace -namespace CEGUI -{ - -/*! -\brief - ItemListbox window class -*/ -class CEGUIEXPORT ItemListbox : public ScrolledItemListBase -{ -public: - static const String EventNamespace; //!< Namespace for global events - static const String WidgetTypeName; //!< Window factory name - - /************************************************************************ - Constants - *************************************************************************/ - /** Event fired when the list selection changes. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the ItemListbox whose current selection - * has been changed. - */ - static const String EventSelectionChanged; - /** Event fired when the multiselect mode of the list box is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the ItemListbox whose multiselect mode - * has been changed. - */ - static const String EventMultiSelectModeChanged; - - /************************************************************************ - Accessors - *************************************************************************/ - /*! - \brief - Returns the number of selected items in this ItemListbox. - */ - size_t getSelectedCount(void) const; - - /*! - \brief - Returns a pointer to the last selected item. - - \return - A pointer to the last selected item, 0 is none. - */ - ItemEntry* getLastSelectedItem(void) const {return d_lastSelected;} - - /*! - \brief - Returns a pointer to the first selected item - - \param start_index - The index where the search should begin. If omitted the search will - begin with the first item. - - \return - A pointer to the first selected item in the listbox. - If no item is selected the return value is 0. - If \a start_index is out of bounds the return value is 0. - - \note - If multiselect is disabled then this does the equivalent of calling - getLastSelectedItem. - If multiselect is enabled it will search the array starting at \a start_index - */ - ItemEntry* getFirstSelectedItem(size_t start_index=0) const; - - /*! - \brief - Returns a pointer to the next seleced item relative to a previous call to - getFirstSelectedItem or getNextSelectedItem. - - \return - A pointer to the next seleced item. If there are no further selected items - the return value is 0. - If multiselect is disabled the return value is 0. - - \note - This member function will take on from where the last call to - getFirstSelectedItem or getNextSelectedItem returned. So be sure to start with a - call to getFirstSelectedItem. - - This member function should be preferred over getNextSelectedItemAfter as it will - perform better, especially on large lists. - */ - ItemEntry* getNextSelectedItem(void) const; - - /*! - \brief - Returns a pointer to the next selected item after the item 'start_item' given. - - \note - This member function will search the array from the beginning and will be slow - for large lists, it will not advance the internal counter used by - getFirstSelectedItem and getNextSelectedItem either. - */ - ItemEntry* getNextSelectedItemAfter(const ItemEntry* start_item) const; - - /*! - \brief - Returns 'true' if multiple selections are allowed. 'false' if not. - */ - bool isMultiSelectEnabled(void) const {return d_multiSelect;} - - /*! - \brief - Returns 'true' if the item at the given index is selectable and currently selected. - */ - bool isItemSelected(size_t index) const; - - /************************************************************************ - Manipulators - *************************************************************************/ - /*! - \brief - Set whether or not multiple selections should be allowed. - */ - void setMultiSelectEnabled(bool state); - - /*! - \brief - Clears all selections. - */ - void clearAllSelections(void); - - /*! - \brief - Select a range of items. - - \param a - Start item. (inclusive) - - \param z - End item. (inclusive) - */ - void selectRange(size_t a, size_t z); - - /*! - \brief - Select all items. - Does nothing if multiselect is disabled. - */ - void selectAllItems(void); - - /************************************************************************ - Object Construction and Destruction - *************************************************************************/ - /*! - \brief - Constructor for the ItemListbox base class constructor. - */ - ItemListbox(const String& type, const String& name); - - /*! - \brief - Destructor for the ItemListbox base class. - */ - virtual ~ItemListbox(void) {} - - /************************************************************************ - Implementation functions - ************************************************************************/ - /*! - \brief - Setup size and position for the item widgets attached to this ItemListbox - */ - virtual void layoutItemWidgets(); - - /*! - \brief - Returns the Size in unclipped pixels of the content attached to this ItemListbox. - */ - virtual Sizef getContentSize() const; - - /*! - \brief - Notify this ItemListbox that the given ListItem was just clicked. - Internal function - not to be used from client code. - */ - virtual void notifyItemClicked(ItemEntry* li); - - /*! - \brief - Notify this ItemListbox that the given ListItem just changed selection state. - Internal function - not to be used from client code. - */ - virtual void notifyItemSelectState(ItemEntry* li, bool state); - -protected: - /************************************************************************ - Protected implementation functions - ************************************************************************/ - /*! - \brief - Returns a pointer to the first selected item starting the search - from \a start_index - - \param start_index - The index where the search should begin (inclusive) - - \return - A pointer to the first selected item in the listbox found - If no item is selected the return value is 0 - If \a start_index is out of bounds the return value is 0 - - \note - This function advances the internal counter and is made for - getFirstSelectedItem and getNextSelectedItem - */ - ItemEntry* findSelectedItem(size_t start_index) const; - - // overridden from ItemListBase - bool handle_PaneChildRemoved(const EventArgs& e); - - /************************************************************************ - New event handlers - ************************************************************************/ - virtual void onSelectionChanged(WindowEventArgs& e); - virtual void onMultiSelectModeChanged(WindowEventArgs& e); - - /************************************************************************ - Overridden event handlers - ************************************************************************/ - virtual void onKeyDown(KeyEventArgs& e); - - /************************************************************************ - Implementation data - ************************************************************************/ - bool d_multiSelect; //! Controls whether multiple items can be selected simultaneously - ItemEntry* d_lastSelected; //! The last item that was selected - mutable size_t d_nextSelectionIndex; //! The index of the last item that was returned with the getFirst/NextSelection members - -private: - void addItemListboxProperties(void); -}; - -} // end CEGUI namespace - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIItemListbox_h_ diff --git a/cegui/include/CEGUI/widgets/LayoutCell.h b/cegui/include/CEGUI/widgets/LayoutCell.h deleted file mode 100644 index 14a0ff8ef..000000000 --- a/cegui/include/CEGUI/widgets/LayoutCell.h +++ /dev/null @@ -1,155 +0,0 @@ -/*********************************************************************** - created: 22/2/2011 - author: Martin Preisler - - purpose: Defines base (and default) layout cell class -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUILayoutCell_h_ -#define _CEGUILayoutCell_h_ - -#include "../Window.h" - -#include - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ - -/*! -\brief - Represents a cell in a layout container - -\par - Layout cell's role is to encapsulate widgets inside a layout container. - It also contains a "Margin" property to set contained widget's margin on - all 4 edges. - - Unless you want to set the margin, you should never encounter this class. - Everything is encapsulated automatically when adding widgets into layout - containers. You will however see instances of this class inside XML layout - files. -*/ -class CEGUIEXPORT LayoutCell : public Window -{ -public: - /************************************************************************* - Event name constants - *************************************************************************/ - //! Namespace for events - static const String EventNamespace; - //! Window factory name - static const String WidgetTypeName; - - /*! - \brief - Constructor for LayoutCell class - - \param type - String object holding Window type (usually provided by WindowFactory). - - \param name - String object holding unique name for the Window. - */ - LayoutCell(const String& type, const String& name); - - /*! - \brief - Destructor - */ - virtual ~LayoutCell(void); - - virtual const CachedRectf& getClientChildContentArea() const; - - virtual void notifyScreenAreaChanged(bool recursive); - -protected: - /// @copydoc Window::getUnclippedInnerRect_impl - virtual Rectf getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const; - - Rectf getClientChildContentArea_impl(bool skipAllPixelAlignment) const; - - /// @copydoc Window::addChild_impl - virtual void addChild_impl(Element* element); - /// @copydoc Window::removeChild_impl - virtual void removeChild_impl(Element* element); - - /************************************************************************* - Event trigger methods - *************************************************************************/ - /*! - \brief - Handler called when child window gets sized - - \param e - WindowEventArgs object whose 'window' pointer field is set to the - window that triggered the event. For this event the trigger window is - the one that was sized. - */ - virtual bool handleChildSized(const EventArgs& e); - - /*! - \brief - Handler called when child window gets added - - \param e - WindowEventArgs object whose 'window' pointer field is set to the - window that triggered the event. For this event the trigger window is - the one that was added. - */ - virtual bool handleChildAdded(const EventArgs& e); - - /*! - \brief - Handler called when child window gets removed - - \param e - WindowEventArgs object whose 'window' pointer field is set to the - window that triggered the event. For this event the trigger window is - the one that was removed. - */ - virtual bool handleChildRemoved(const EventArgs& e); - - /************************************************************************* - Implementation Data - *************************************************************************/ - typedef std::multimap ConnectionTracker; - //! Tracks event connections we make. - ConnectionTracker d_eventConnections; - - CachedRectf d_clientChildContentArea; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUILayoutCell_h_ diff --git a/cegui/include/CEGUI/widgets/LayoutContainer.h b/cegui/include/CEGUI/widgets/LayoutContainer.h index 888055a2a..593349031 100644 --- a/cegui/include/CEGUI/widgets/LayoutContainer.h +++ b/cegui/include/CEGUI/widgets/LayoutContainer.h @@ -109,14 +109,14 @@ class CEGUIEXPORT LayoutContainer : public Window virtual void notifyScreenAreaChanged(bool recursive); + size_t getIdxOfChild(Window* wnd) const; + protected: /// @copydoc Window::getUnclippedInnerRect_impl virtual Rectf getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const; Rectf getClientChildContentArea_impl(bool skipAllPixelAlignment) const; - size_t getIdxOfChild(Window* wnd) const; - /// @copydoc Window::addChild_impl virtual void addChild_impl(Element* element); /// @copydoc Window::removeChild_impl diff --git a/cegui/include/CEGUI/widgets/ListHeader.h b/cegui/include/CEGUI/widgets/ListHeader.h index 8e180c7da..65ace2162 100644 --- a/cegui/include/CEGUI/widgets/ListHeader.h +++ b/cegui/include/CEGUI/widgets/ListHeader.h @@ -940,8 +940,7 @@ class CEGUIEXPORT ListHeader : public Window /************************************************************************* Implementation Data *************************************************************************/ - typedef std::vector SegmentList; + typedef std::vector SegmentList; SegmentList d_segments; //!< Attached segment windows in header order. ListHeaderSegment* d_sortSegment; //!< Pointer to the segment that is currently set as the sork-key, bool d_sizingEnabled; //!< true if segments can be sized by the user. diff --git a/cegui/include/CEGUI/widgets/ListHeaderSegment.h b/cegui/include/CEGUI/widgets/ListHeaderSegment.h index 2c465ad2b..80e0d2753 100644 --- a/cegui/include/CEGUI/widgets/ListHeaderSegment.h +++ b/cegui/include/CEGUI/widgets/ListHeaderSegment.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 15/6/2004 author: Paul D Turner - + purpose: Interface to list header segment class. *************************************************************************/ /*************************************************************************** @@ -92,12 +92,12 @@ class CEGUIEXPORT ListHeaderSegment : public Window * be dragged. */ static const String EventSegmentDragStart; - /** Event fired when segment dragging has stopped (via mouse release). - * Hanlders are passed a const WindowEventArgs reference with + /** Event fired when segment dragging has stopped (via cursor release). + * Handlers are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the ListHeaderSegment that is no longer * being dragged. */ - static const String EventSegmentDragStop; + static const String EventSegmentDragStop; /** Event fired when the segment drag position has changed. * Hanlders are passed a const WindowEventArgs reference with * WindowEventArgs::window set to the ListHeaderSegment whose position has @@ -118,8 +118,8 @@ class CEGUIEXPORT ListHeaderSegment : public Window static const String EventClickableSettingChanged; // Defaults - static const float DefaultSizingArea; //!< Default size of the sizing area. - static const float SegmentMoveThreshold; //!< Amount the mouse must be dragged before drag-moving is initiated. + static const float DefaultSizingArea; //!< Default size of the sizing area. + static const float SegmentMoveThreshold; //!< Amount the cursor must be dragged before drag-moving is initiated. /************************************************************************* @@ -182,7 +182,7 @@ class CEGUIEXPORT ListHeaderSegment : public Window \return Point object describing the drag move offset position. */ - const Vector2f& getDragMoveOffset(void) const {return d_dragPosition;} + const glm::vec2& getDragMoveOffset(void) const {return d_dragPosition;} /*! @@ -325,26 +325,26 @@ class CEGUIEXPORT ListHeaderSegment : public Window \brief Update state for drag sizing. - \param local_mouse - Mouse position as a pixel offset from the top-left corner of this window. + \param local_cursor + Cursor position as a pixel offset from the top-left corner of this window. \return Nothing. */ - void doDragSizing(const Vector2f& local_mouse); + void doDragSizing(const glm::vec2& local_cursor); /*! \brief Update state for drag moving. - \param local_mouse - Mouse position as a pixel offset from the top-left corner of this window. + \param local_cursor + Cursor position as a pixel offset from the top-left corner of this window. \return Nothing. */ - void doDragMoving(const Vector2f& local_mouse); + void doDragMoving(const glm::vec2& local_cursor); /*! @@ -373,14 +373,14 @@ class CEGUIEXPORT ListHeaderSegment : public Window Return whether the required minimum movement threshold before initiating drag-moving has been exceeded. - \param local_mouse - Mouse position as a pixel offset from the top-left corner of this window. + \param local_cursor + Cursor position as a pixel offset from the top-left corner of this window. \return true if the threshold has been exceeded and drag-moving should be initiated, or false if the threshold has not been exceeded. - */ - bool isDragMoveThresholdExceeded(const Vector2f& local_mouse); + */ + bool isDragMoveThresholdExceeded(const glm::vec2& local_cursor); /************************************************************************* New Event Handlers @@ -429,7 +429,7 @@ class CEGUIEXPORT ListHeaderSegment : public Window /*! \brief - Handler called when the user stops dragging the segment (releases mouse button) + Handler called when the user stops dragging the segment (releases cursor source) */ virtual void onSegmentDragStop(WindowEventArgs& e); @@ -458,34 +458,34 @@ class CEGUIEXPORT ListHeaderSegment : public Window /************************************************************************* Overridden Event Handlers *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); - virtual void onMouseDoubleClicked(MouseEventArgs& e); - virtual void onMouseLeaves(MouseEventArgs& e); - virtual void onCaptureLost(WindowEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); + virtual void onCursorLeaves(CursorInputEventArgs& e); + virtual void onCaptureLost(WindowEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); /************************************************************************* Implementation Data *************************************************************************/ - const Image* d_sizingMouseCursor; //!< Image to use for mouse when sizing (typically set by derived class). - const Image* d_movingMouseCursor; //!< Image to use for mouse when moving (typically set by derived class). + const Image* d_sizingCursor; //!< Image to use for cursor when sizing (typically set by derived class). + const Image* d_movingCursor; //!< Image to use for cursor when moving (typically set by derived class). - float d_splitterSize; //!< pixel width of the sizing area. - bool d_splitterHover; //!< True if the mouse is over the splitter + float d_splitterSize; //!< pixel width of the sizing area. + bool d_splitterHover; //!< True if the cursor is over the splitter bool d_dragSizing; //!< true when we are being sized. - Vector2f d_dragPoint; //!< point we are being dragged at when sizing or moving. + glm::vec2 d_dragPoint; //!< point we are being dragged at when sizing or moving. SortDirection d_sortDir; //!< Direction for sorting (used for deciding what icon to display). - bool d_segmentHover; //!< true when the mouse is within the segment area (and not in sizing area). - bool d_segmentPushed; //!< true when the left mouse button has been pressed within the confines of the segment. + bool d_segmentHover; //!< true when the cursor is within the segment area (and not in sizing area). + bool d_segmentPushed; //!< true when the left cursor source has been activated within the confines of the segment. bool d_sizingEnabled; //!< true when sizing is enabled for this segment. bool d_movingEnabled; //!< True when drag-moving is enabled for this segment; bool d_dragMoving; //!< true when segment is being drag moved. - Vector2f d_dragPosition; //!< position of dragged segment. + glm::vec2 d_dragPosition; //!< position of dragged segment. bool d_allowClicks; //!< true if the segment can be clicked. private: diff --git a/cegui/include/CEGUI/widgets/ListWidget.h b/cegui/include/CEGUI/widgets/ListWidget.h new file mode 100644 index 000000000..6e7d9537d --- /dev/null +++ b/cegui/include/CEGUI/widgets/ListWidget.h @@ -0,0 +1,118 @@ +/*********************************************************************** + created: Sat Jul 19 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CEGUIListWidget_h_ +#define _CEGUIListWidget_h_ + +#include "CEGUI/views/ListView.h" +#include "CEGUI/views/StandardItemModel.h" + +namespace CEGUI +{ + +/*! +\brief + This is a convenience widget as an alternative to the new list view, for + simple scenarios that don't require a custom ItemModel implementation. + + Basically, what this class does, is to use a StandardItemModel as the source + ItemModel, and provide some quick-access methods directly to the items, + instead of going through the ModelIndex. Most of the ListView functions + have the item-typed variants/overloads here. It also provides size_t-based + index overloads, since this is a list with only one level of nestedness. + + This a direct alternative for the old ListBox or ItemListbox widgets. +*/ +class CEGUIEXPORT ListWidget : public ListView +{ +public: + //! Window factory name + static const String WidgetTypeName; + //! Namespace for global events + static const String EventNamespace; + + ListWidget(const String& type, const String& name); + virtual ~ListWidget(); + + void setIndexSelectionState(size_t item_index, bool state); + void setIndexSelectionState(StandardItem* item, bool state); + + /*! + \brief + Gets the ordinal first item. If the ListWidget has multi selection enabled + and multiple items are selected, the first one will be returned. + */ + StandardItem* getFirstSelectedItem(); + + /*! + \brief + Returns the next selected item after the specified \a start_item + + \param start_item + The item to start the search after. If this is NULL the search will + begin at the beginning of the list. + */ + StandardItem* getNextSelectedItem(const StandardItem* start_item); + StandardItem* getItemAtIndex(size_t index); + + /*! + \brief + Returns a StandardItem that has the specified \a text, the searching + procedure starting from \a start_item + + \param start_item + If \a start_item is NULL, the search will start from the first item + of the list. + */ + StandardItem* findItemWithText(const String& text, const StandardItem* start_item); + + bool isItemInList(const StandardItem* item); + bool isItemSelected(const StandardItem* item); + bool isIndexSelected(size_t index); + + size_t getItemCount() const; + size_t getSelectedItemsCount() const; + + virtual StandardItemModel* getModel(); + + void addItem(const String& text); + void addItem(StandardItem* item); + void insertItem(StandardItem* item, const StandardItem* position); + + void removeItem(const StandardItem* item); + //! Clears the items in this list and deletes all associated items. + void clearList(); + + virtual void ensureIndexIsVisible(const StandardItem* item); + +protected: + virtual void initialiseComponents(); + + StandardItemModel d_itemModel; +}; + +} +#endif diff --git a/cegui/include/CEGUI/widgets/Listbox.h b/cegui/include/CEGUI/widgets/Listbox.h deleted file mode 100644 index bf8aad1c2..000000000 --- a/cegui/include/CEGUI/widgets/Listbox.h +++ /dev/null @@ -1,791 +0,0 @@ -/*********************************************************************** - created: 13/4/2004 - author: Paul D Turner - - purpose: Interface to base class for Listbox widget -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIListbox_h_ -#define _CEGUIListbox_h_ - -#include "../Base.h" -#include "../Window.h" -#include - - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - - -// Start of CEGUI namespace section -namespace CEGUI -{ - -/*! -\brief - Base class for Listbox window renderer. -*/ -class CEGUIEXPORT ListboxWindowRenderer : public WindowRenderer -{ -public: - /*! - \brief - Constructor - */ - ListboxWindowRenderer(const String& name); - - /*! - \brief - Return a Rect object describing, in un-clipped pixels, the window - relative area that is to be used for rendering list items. - */ - virtual Rectf getListRenderArea(void) const = 0; - - /*! - * Resize the Listbox the renderer is attached to such that it's - * content can be displayed without needing scrollbars if there is - * enough space, otherwise make the Listbox as large as possible - * (without moving it). - */ - virtual void resizeListToContent(bool fit_width, - bool fit_height) const = 0; -}; - -/*! -\brief - Base class for standard Listbox widget. -*/ -class CEGUIEXPORT Listbox : public Window -{ -public: - static const String EventNamespace; //!< Namespace for global events - static const String WidgetTypeName; //!< Window factory name - - /************************************************************************* - Constants - *************************************************************************/ - // event names - /** Event fired when the contents of the list is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Listbox whose content is changed. - */ - static const String EventListContentsChanged; - /** Event fired when there is a change to the currently selected item(s) - * within the list. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Litbox that has had a change in the - * selected items. - */ - static const String EventSelectionChanged; - /** Event fired when the sort mode setting changes for the Listbox. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Listbox whose sort mode has been - * changed. - */ - static const String EventSortModeChanged; - /** Event fired when the multi-select mode setting changes for the Listbox. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Listbox whose multi-select mode has - * been changed. - */ - static const String EventMultiselectModeChanged; - /** Event fired when the mode setting that forces the display of the - * vertical scroll bar for the Listbox is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Listbox whose vertical - * scrollbar mode has been changed. - */ - static const String EventVertScrollbarModeChanged; - /** Event fired when the mode setting that forces the display of the - * horizontal scroll bar for the Listbox is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Listbox whose horizontal - * scrollbar mode has been changed. - */ - static const String EventHorzScrollbarModeChanged; - - /************************************************************************* - Child Widget name constants - *************************************************************************/ - static const String VertScrollbarName; //!< Widget name for the vertical scrollbar component. - static const String HorzScrollbarName; //!< Widget name for the horizontal scrollbar component. - - /************************************************************************* - Accessor Methods - *************************************************************************/ - /*! - \brief - Return number of items attached to the list box - - \return - the number of items currently attached to this list box. - */ - size_t getItemCount(void) const {return d_listItems.size();} - - - /*! - \brief - Return the number of selected items in the list box. - - \return - Total number of attached items that are in the selected state. - */ - size_t getSelectedCount(void) const; - - - /*! - \brief - Return a pointer to the first selected item. - - \return - Pointer to a ListboxItem based object that is the first selected item in the list. will return NULL if - no item is selected. - */ - ListboxItem* getFirstSelectedItem(void) const; - - - /*! - \brief - Return a pointer to the next selected item after item \a start_item - - \param start_item - Pointer to the ListboxItem where the search for the next selected item is to begin. If this - parameter is NULL, the search will begin with the first item in the list box. - - \return - Pointer to a ListboxItem based object that is the next selected item in the list after - the item specified by \a start_item. Will return NULL if no further items were selected. - - \exception InvalidRequestException thrown if \a start_item is not attached to this list box. - */ - ListboxItem* getNextSelected(const ListboxItem* start_item) const; - - - /*! - \brief - Return the item at index position \a index. - - \param index - Zero based index of the item to be returned. - - \return - Pointer to the ListboxItem at index position \a index in the list box. - - \exception InvalidRequestException thrown if \a index is out of range. - */ - ListboxItem* getListboxItemFromIndex(size_t index) const; - - - /*! - \brief - Return the index of ListboxItem \a item - - \param item - Pointer to a ListboxItem whos zero based index is to be returned. - - \return - Zero based index indicating the position of ListboxItem \a item in the list box. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. - */ - size_t getItemIndex(const ListboxItem* item) const; - - - /*! - \brief - return whether list sorting is enabled - - \return - true if the list is sorted, false if the list is not sorted - */ - bool isSortEnabled(void) const {return d_sorted;} - - /*! - \brief - return whether multi-select is enabled - - \return - true if multi-select is enabled, false if multi-select is not enabled. - */ - bool isMultiselectEnabled(void) const {return d_multiselect;} - - bool isItemTooltipsEnabled(void) const {return d_itemTooltips;} - - /*! - \brief - return whether the string at index position \a index is selected - - \param index - Zero based index of the item to be examined. - - \return - true if the item at \a index is selected, false if the item at \a index is not selected. - - \exception InvalidRequestException thrown if \a index is out of range. - */ - bool isItemSelected(size_t index) const; - - - /*! - \brief - Search the list for an item with the specified text - - \param text - String object containing the text to be searched for. - - \param start_item - ListboxItem where the search is to begin, the search will not include \a item. If \a item is - NULL, the search will begin from the first item in the list. - - \return - Pointer to the first ListboxItem in the list after \a item that has text matching \a text. If - no item matches the criteria NULL is returned. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. - */ - ListboxItem* findItemWithText(const String& text, const ListboxItem* start_item); - - - /*! - \brief - Return whether the specified ListboxItem is in the List - - \return - true if ListboxItem \a item is in the list, false if ListboxItem \a item is not in the list. - */ - bool isListboxItemInList(const ListboxItem* item) const; - - - /*! - \brief - Return whether the vertical scroll bar is always shown. - - \return - - true if the scroll bar will always be shown even if it is not required. - - false if the scroll bar will only be shown when it is required. - */ - bool isVertScrollbarAlwaysShown(void) const; - - - /*! - \brief - Return whether the horizontal scroll bar is always shown. - - \return - - true if the scroll bar will always be shown even if it is not required. - - false if the scroll bar will only be shown when it is required. - */ - bool isHorzScrollbarAlwaysShown(void) const; - - - /************************************************************************* - Manipulator Methods - *************************************************************************/ - /*! - \brief - Initialise the Window based object ready for use. - - \note - This must be called for every window created. Normally this is handled automatically by the WindowFactory for each Window type. - - \return - Nothing - */ - virtual void initialiseComponents(void); - - - /*! - \brief - Remove all items from the list. - - Note that this will cause 'AutoDelete' items to be deleted. - */ - void resetList(void); - - - /*! - \brief - Add the given ListboxItem to the list. - - \param item - Pointer to the ListboxItem to be added to the list. Note that it is the passed object that is added to the - list, a copy is not made. If this parameter is NULL, nothing happens. - - \return - Nothing. - */ - void addItem(ListboxItem* item); - - - /*! - \brief - Insert an item into the list box before a specified item already in the - list. - - Note that if the list is sorted, the item may not end up in the - requested position. - - \param item - Pointer to the ListboxItem to be inserted. Note that it is the passed - object that is added to the list, a copy is not made. If this parameter - is NULL, nothing happens. - - \param position - Pointer to a ListboxItem that \a item is to be inserted before. If this - parameter is NULL, the item is inserted at the start of the list. - - \return - Nothing. - - \exception InvalidRequestException thrown if no ListboxItem \a position is - attached to this list box. - */ - void insertItem(ListboxItem* item, const ListboxItem* position); - - - /*! - \brief - Removes the given item from the list box. If the item is has the auto delete state set, the item will be deleted. - - \param item - Pointer to the ListboxItem that is to be removed. If \a item is not attached to this list box then nothing - will happen. - - \return - Nothing. - */ - void removeItem(const ListboxItem* item); - - - /*! - \brief - Clear the selected state for all items. - - \return - Nothing. - */ - void clearAllSelections(void); - - - /*! - \brief - Set whether the list should be sorted. - - \param setting - true if the list should be sorted, false if the list should not be sorted. - - \return - Nothing. - */ - void setSortingEnabled(bool setting); - - - /*! - \brief - Set whether the list should allow multiple selections or just a single selection - - \param setting - true if the widget should allow multiple items to be selected, false if the widget should only allow - a single selection. - - \return - Nothing. - */ - void setMultiselectEnabled(bool setting); - - - /*! - \brief - Set whether the vertical scroll bar should always be shown. - - \param setting - true if the vertical scroll bar should be shown even when it is not required. false if the vertical - scroll bar should only be shown when it is required. - - \return - Nothing. - */ - void setShowVertScrollbar(bool setting); - - - /*! - \brief - Set whether the horizontal scroll bar should always be shown. - - \param setting - true if the horizontal scroll bar should be shown even when it is not required. false if the horizontal - scroll bar should only be shown when it is required. - - \return - Nothing. - */ - void setShowHorzScrollbar(bool setting); - - void setItemTooltipsEnabled(bool setting); - /*! - \brief - Set the select state of an attached ListboxItem. - - This is the recommended way of selecting and deselecting items attached to a list box as it respects the - multi-select mode setting. It is possible to modify the setting on ListboxItems directly, but that approach - does not respect the settings of the list box. - - \param item - The ListboxItem to be affected. This item must be attached to the list box. - - \param state - true to select the item, false to de-select the item. - - \return - Nothing. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. - */ - void setItemSelectState(ListboxItem* item, bool state); - - - /*! - \brief - Set the select state of an attached ListboxItem. - - This is the recommended way of selecting and deselecting items attached to a list box as it respects the - multi-select mode setting. It is possible to modify the setting on ListboxItems directly, but that approach - does not respect the settings of the list box. - - \param item_index - The zero based index of the ListboxItem to be affected. This must be a valid index (0 <= index < getItemCount()) - - \param state - true to select the item, false to de-select the item. - - \return - Nothing. - - \exception InvalidRequestException thrown if \a item_index is out of range for the list box - */ - void setItemSelectState(size_t item_index, bool state); - - - /*! - \brief - Causes the list box to update it's internal state after changes have been made to one or more - attached ListboxItem objects. - - Client code must call this whenever it has made any changes to ListboxItem objects already attached to the - list box. If you are just adding items, or removed items to update them prior to re-adding them, there is - no need to call this method. - - \return - Nothing. - */ - void handleUpdatedItemData(void); - - - /*! - \brief - Ensure the item at the specified index is visible within the list box. - - \param item_index - Zero based index of the item to be made visible in the list box. If this value is out of range, the - list is always scrolled to the bottom. - - \return - Nothing. - */ - void ensureItemIsVisible(size_t item_index); - - - /*! - \brief - Ensure the item at the specified index is visible within the list box. - - \param item - Pointer to the ListboxItem to be made visible in the list box. - - \return - Nothing. - - \exception InvalidRequestException thrown if \a item is not attached to this list box. - */ - void ensureItemIsVisible(const ListboxItem* item); - - - /*! - \brief - Return a Rect object describing, in un-clipped pixels, the window relative area - that is to be used for rendering list items. - - \return - Rect object describing the area of the Window to be used for rendering - list box items. - */ - virtual Rectf getListRenderArea(void) const; - - - /*! - \brief - Return a pointer to the vertical scrollbar component widget for this - Listbox. - - \return - Pointer to a Scrollbar object. - - \exception UnknownObjectException - Thrown if the vertical Scrollbar component does not exist. - */ - Scrollbar* getVertScrollbar() const; - - /*! - \brief - Return a pointer to the horizontal scrollbar component widget for this - Listbox. - - \return - Pointer to a Scrollbar object. - - \exception UnknownObjectException - Thrown if the horizontal Scrollbar component does not exist. - */ - Scrollbar* getHorzScrollbar() const; - - - /*! - \brief - Return the sum of all item heights - */ - float getTotalItemsHeight(void) const; - - - /*! - \brief - Return the width of the widest item - */ - float getWidestItemWidth(void) const; - - - /*! - \brief - Return a pointer to the ListboxItem attached to this Listbox at the - given screen pixel co-ordinate. - - \return - Pointer to the ListboxItem attached to this Listbox that is at screen - position \a pt, or 0 if no ListboxItem attached to this Listbox is at - that position. - */ - ListboxItem* getItemAtPoint(const Vector2f& pt) const; - - - /************************************************************************* - Construction and Destruction - *************************************************************************/ - /*! - \brief - Constructor for Listbox base class. - */ - Listbox(const String& type, const String& name); - - - /*! - \brief - Destructor for Listbox base class. - */ - virtual ~Listbox(void); - - -protected: - /************************************************************************* - Abstract Implementation Functions (must be provided by derived class) - *************************************************************************/ - /*! - \brief - Return a Rect object describing, in un-clipped pixels, the window relative area - that is to be used for rendering list items. - - \return - Rect object describing the area of the Window to be used for rendering - list box items. - */ - //virtual Rect getListRenderArea_impl(void) const = 0; - - - /************************************************************************* - Implementation Functions - *************************************************************************/ - /*! - \brief - display required integrated scroll bars according to current state of the list box and update their values. - */ - void configureScrollbars(void); - - /*! - \brief - select all strings between positions \a start and \a end. (inclusive) - including \a end. - */ - void selectRange(size_t start, size_t end); - - - /*! - \brief - Clear the selected state for all items (implementation) - - \return - true if some selections were cleared, false nothing was changed. - */ - bool clearAllSelections_impl(void); - - - /*! - \brief - Remove all items from the list. - - \note - Note that this will cause 'AutoDelete' items to be deleted. - - \return - - true if the list contents were changed. - - false if the list contents were not changed (list already empty). - */ - bool resetList_impl(void); - - /*! - \brief - Internal handler that is triggered when the user interacts with the scrollbars. - */ - bool handle_scrollChange(const EventArgs& args); - - - // validate window renderer - virtual bool validateWindowRenderer(const WindowRenderer* renderer) const; - - /*! - \brief - Causes the internal list to be (re)sorted. - */ - void resortList(); - - /************************************************************************* - New event handlers - *************************************************************************/ - /*! - \brief - Handler called internally when the list contents are changed - */ - virtual void onListContentsChanged(WindowEventArgs& e); - - - /*! - \brief - Handler called internally when the currently selected item or items changes. - */ - virtual void onSelectionChanged(WindowEventArgs& e); - - - /*! - \brief - Handler called internally when the sort mode setting changes. - */ - virtual void onSortModeChanged(WindowEventArgs& e); - - - /*! - \brief - Handler called internally when the multi-select mode setting changes. - */ - virtual void onMultiselectModeChanged(WindowEventArgs& e); - - - /*! - \brief - Handler called internally when the forced display of the vertical scroll bar setting changes. - */ - virtual void onVertScrollbarModeChanged(WindowEventArgs& e); - - - /*! - \brief - Handler called internally when the forced display of the horizontal scroll bar setting changes. - */ - virtual void onHorzScrollbarModeChanged(WindowEventArgs& e); - - - /************************************************************************* - Overridden Event handlers - *************************************************************************/ - virtual void onSized(ElementEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); - virtual void onMouseMove(MouseEventArgs& e); - - - /************************************************************************* - Implementation Data - *************************************************************************/ - typedef std::vector LBItemList; - bool d_sorted; //!< true if list is sorted - bool d_multiselect; //!< true if multi-select is enabled - bool d_forceVertScroll; //!< true if vertical scrollbar should always be displayed - bool d_forceHorzScroll; //!< true if horizontal scrollbar should always be displayed - bool d_itemTooltips; //!< true if each item should have an individual tooltip - LBItemList d_listItems; //!< list of items in the list box. - ListboxItem* d_lastSelected; //!< holds pointer to the last selected item (used in range selections) - - friend class ListboxWindowRenderer; - -private: - - /************************************************************************* - Private methods - *************************************************************************/ - void addListboxProperties(void); -}; - - -/*! -\brief - Helper function used in sorting to compare two list box item text strings - via the ListboxItem pointers and return if \a a is less than \a b. -*/ -bool lbi_less(const ListboxItem* a, const ListboxItem* b); - - -/*! -\brief - Helper function used in sorting to compare two list box item text strings - via the ListboxItem pointers and return if \a a is greater than \a b. -*/ -bool lbi_greater(const ListboxItem* a, const ListboxItem* b); - -} // End of CEGUI namespace section - - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIListbox_h_ diff --git a/cegui/include/CEGUI/widgets/ListboxItem.h b/cegui/include/CEGUI/widgets/ListboxItem.h index 9fd4e1449..f332bf9aa 100644 --- a/cegui/include/CEGUI/widgets/ListboxItem.h +++ b/cegui/include/CEGUI/widgets/ListboxItem.h @@ -48,8 +48,7 @@ namespace CEGUI \brief Base class for list box items */ -class CEGUIEXPORT ListboxItem : - public AllocatedObject +class CEGUIEXPORT ListboxItem { public: /************************************************************************* @@ -371,7 +370,7 @@ class CEGUIEXPORT ListboxItem : Perform any updates needed because the given font's render size has changed. - /note + \note The base implementation just returns false. \param font @@ -412,7 +411,7 @@ class CEGUIEXPORT ListboxItem : \return Nothing. */ - virtual void draw(GeometryBuffer& buffer, const Rectf& targetRect, + virtual void draw(std::vector& geometry_buffers, const Rectf& targetRect, float alpha, const Rectf* clipper) const = 0; /************************************************************************* @@ -436,14 +435,6 @@ class CEGUIEXPORT ListboxItem : /************************************************************************* Implementation methods *************************************************************************/ - /*! - \brief - Return a ColourRect object describing the colours in \a cols after having their alpha - component modulated by the value \a alpha. - */ - ColourRect getModulateAlphaColourRect(const ColourRect& cols, float alpha) const; - - /*! \brief Return a colour value describing the colour specified by \a col after having its alpha diff --git a/cegui/include/CEGUI/widgets/ListboxTextItem.h b/cegui/include/CEGUI/widgets/ListboxTextItem.h index 2fd23d427..386fdff67 100644 --- a/cegui/include/CEGUI/widgets/ListboxTextItem.h +++ b/cegui/include/CEGUI/widgets/ListboxTextItem.h @@ -190,7 +190,7 @@ class CEGUIEXPORT ListboxTextItem : public ListboxItem Required implementations of pure virtuals from the base class. *************************************************************************/ Sizef getPixelSize(void) const; - void draw(GeometryBuffer& buffer, const Rectf& targetRect, float alpha, const Rectf* clipper) const; + void draw(std::vector& geometry_buffers, const Rectf& targetRect, float alpha, const Rectf* clipper) const; protected: void parseTextString() const; diff --git a/cegui/include/CEGUI/widgets/MenuItem.h b/cegui/include/CEGUI/widgets/MenuItem.h index 949d43f94..97a87ba5d 100644 --- a/cegui/include/CEGUI/widgets/MenuItem.h +++ b/cegui/include/CEGUI/widgets/MenuItem.h @@ -68,10 +68,12 @@ class CEGUIEXPORT MenuItem : public ItemEntry *************************************************************************/ /*! \brief - return true if user is hovering over this widget (or it's pushed and user is not over it for highlight) + return true if user is hovering over this widget (or it's pushed and + user is not over it for highlight) \return - true if the user is hovering or if the button is pushed and the mouse is not over the button. Otherwise return false. + true if the user is hovering or if the button is pushed and the cursor + is not over the button. Otherwise return false. */ bool isHovering(void) const { @@ -112,7 +114,8 @@ class CEGUIEXPORT MenuItem : public ItemEntry /*! \brief - Returns true if the menu item popup is closed or opened automatically if hovering with the mouse. + Returns true if the menu item popup is closed or opened automatically + if hovering with the cursor. */ bool hasAutoPopup(void) const { @@ -257,11 +260,11 @@ class CEGUIEXPORT MenuItem : public ItemEntry /************************************************************************* Overridden event handlers *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); - virtual void onMouseLeaves(MouseEventArgs& e); + virtual void onCursorLeaves(CursorInputEventArgs& e); virtual void onTextChanged(WindowEventArgs& e); virtual void updateSelf(float elapsed); @@ -271,20 +274,20 @@ class CEGUIEXPORT MenuItem : public ItemEntry *************************************************************************/ /*! \brief - Update the internal state of the widget with the mouse at the given position. + Update the internal state of the widget with the cursor at the given position. - \param mouse_pos - Point object describing, in screen pixel co-ordinates, the location of the mouse cursor. + \param cursor_pos + Point object describing, in screen pixel co-ordinates, the location of the cursor. \return Nothing */ - void updateInternalState(const Vector2f& mouse_pos); + void updateInternalState(const glm::vec2& cursor_pos); /*! \brief - Recursive function that closes all popups down the hierarcy starting with this one. + Recursive function that closes all popups down the hierarchy starting with this one. \return Nothing. @@ -312,7 +315,7 @@ class CEGUIEXPORT MenuItem : public ItemEntry bool d_opened; //!< true when the menu item's popup menu is in its opened state. bool d_popupClosing; //!< true when the d_popupTimerTimeElapsed timer is running to close the popup (another menu item of our container is hovered) bool d_popupOpening; //!< true when the d_popupTimerTimeElapsed timer is running to open the popup (the menu item is hovered) - float d_autoPopupTimeout; //!< the time in seconds, to wait before opening / closing the popup if the mouse is over the item / over another item in our container + float d_autoPopupTimeout; //!< the time in seconds, to wait before opening / closing the popup if the cursor is over the item / over another item in our container float d_autoPopupTimeElapsed; //!< the current time, which is already elapsed if the timer is running (d_popupClosing or d_popupOpening is true) PopupMenu* d_popup; //!< PopupMenu that this item displays when activated. diff --git a/cegui/include/CEGUI/widgets/MultiColumnList.h b/cegui/include/CEGUI/widgets/MultiColumnList.h index a32a48da0..dbf23f3d3 100644 --- a/cegui/include/CEGUI/widgets/MultiColumnList.h +++ b/cegui/include/CEGUI/widgets/MultiColumnList.h @@ -1512,7 +1512,7 @@ class CEGUIEXPORT MultiColumnList : public Window ListboxItem that is under window pixel co-ordinate \a pt, or NULL if no item is under that position. */ - ListboxItem* getItemAtPoint(const Vector2f& pt) const; + ListboxItem* getItemAtPoint(const glm::vec2& pt) const; /*! @@ -1652,15 +1652,14 @@ class CEGUIEXPORT MultiColumnList : public Window */ virtual void onListColumnMoved(WindowEventArgs& e); - /************************************************************************* Overridden Event handlers *************************************************************************/ virtual void onFontChanged(WindowEventArgs& e); virtual void onSized(ElementEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); - + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onScroll(CursorInputEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); /************************************************************************* Handlers for subscribed events @@ -1681,8 +1680,7 @@ class CEGUIEXPORT MultiColumnList : public Window */ struct ListRow { - typedef std::vector RowItems; + typedef std::vector RowItems; RowItems d_items; uint d_sortColumn; uint d_rowID; @@ -1723,8 +1721,7 @@ class CEGUIEXPORT MultiColumnList : public Window uint d_columnCount; //!< keeps track of the number of columns. // storage of items in the list box. - typedef std::vector ListItemGrid; + typedef std::vector ListItemGrid; ListItemGrid d_grid; //!< Holds the list box data. //! whether header size will be considered when auto-sizing columns. @@ -1738,6 +1735,7 @@ class CEGUIEXPORT MultiColumnList : public Window Private methods *************************************************************************/ void addMultiColumnListProperties(void); + void handleSelection(const glm::vec2& position, bool cumulative, bool range); }; diff --git a/cegui/include/CEGUI/widgets/MultiLineEditbox.h b/cegui/include/CEGUI/widgets/MultiLineEditbox.h index ef79a69c7..e8b87d509 100644 --- a/cegui/include/CEGUI/widgets/MultiLineEditbox.h +++ b/cegui/include/CEGUI/widgets/MultiLineEditbox.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 30/6/2004 author: Paul D Turner - + purpose: Interface to the Multi-lien edit box base class. *************************************************************************/ /*************************************************************************** @@ -34,6 +34,7 @@ #include "../Font.h" #include +#include #if defined(_MSC_VER) # pragma warning(push) @@ -44,6 +45,9 @@ // Start of CEGUI namespace section namespace CEGUI { +// forward declaration +class UndoHandler; + /*! \brief Base class for multi-line edit box window renderer objects. @@ -159,8 +163,7 @@ class CEGUIEXPORT MultiLineEditbox : public Window size_t d_length; //!< Code point length of this line. float d_extent; //!< Rendered extent of this line. }; - typedef std::vector LineList; //!< Type for collection of LineInfos. + typedef std::vector LineList; //!< Type for collection of LineInfos. /************************************************************************* Accessor Functions @@ -170,8 +173,8 @@ class CEGUIEXPORT MultiLineEditbox : public Window return true if the edit box has input focus. \return - - true if the edit box has keyboard input focus. - - false if the edit box does not have keyboard input focus. + - true if the edit box has input focus. + - false if the edit box does not have input focus. */ bool hasInputFocus(void) const; @@ -218,7 +221,7 @@ class CEGUIEXPORT MultiLineEditbox : public Window */ size_t getSelectionEndIndex(void) const; - + /*! \brief return the length of the current selection (in code points / characters). @@ -367,7 +370,7 @@ class CEGUIEXPORT MultiLineEditbox : public Window Nothing. */ void setSelection(size_t start_pos, size_t end_pos); - + /*! \brief @@ -443,13 +446,13 @@ class CEGUIEXPORT MultiLineEditbox : public Window // selection brush image property support void setSelectionBrushImage(const Image* image); const Image* getSelectionBrushImage() const; - + //! \copydoc Window::performCopy virtual bool performCopy(Clipboard& clipboard); - + //! \copydoc Window::performCut virtual bool performCut(Clipboard& clipboard); - + //! \copydoc Window::performPaste virtual bool performPaste(Clipboard& clipboard); @@ -457,12 +460,18 @@ class CEGUIEXPORT MultiLineEditbox : public Window \brief Format the text into lines as dictated by the formatting options. - \param update_scrollbars + \param update_scrollbars - true if scrollbar configuration should be performed. - false if scrollbar configuration should not be performed. */ void formatText(const bool update_scrollbars); + //! \copydoc Window::performUndo + virtual bool performUndo(); + + //! \copydoc Window::performRedo + virtual bool performRedo(); + /************************************************************************* Construction and Destruction *************************************************************************/ @@ -498,13 +507,6 @@ class CEGUIEXPORT MultiLineEditbox : public Window /************************************************************************* Implementation Methods *************************************************************************/ - /*! - \brief - Format the text into lines as needed by the current formatting options. - \deprecated - This is deprecated in favour of the version taking a boolean. - */ - void formatText(void); /*! \brief @@ -512,7 +514,7 @@ class CEGUIEXPORT MultiLineEditbox : public Window \note Any single whitespace character is one token, any group of other characters is a token. - + \return The code point length of the token. */ @@ -536,7 +538,7 @@ class CEGUIEXPORT MultiLineEditbox : public Window \return Code point index into the text that is rendered closest to screen position \a pt. */ - size_t getTextIndexFromPosition(const Vector2f& pt) const; + size_t getTextIndexFromPosition(const glm::vec2& pt) const; /*! @@ -570,95 +572,131 @@ class CEGUIEXPORT MultiLineEditbox : public Window void handleDelete(void); - /*! - \brief - Processing to move caret one character left - */ - void handleCharLeft(uint sysKeys); + /*! + \brief + Processing to move caret one character left + \param select + when true, the left character will be also selected + */ + void handleCharLeft(bool select); - /*! - \brief - Processing to move caret one word left - */ - void handleWordLeft(uint sysKeys); + /*! + \brief + Processing to move caret one word left - /*! - \brief - Processing to move caret one character right - */ - void handleCharRight(uint sysKeys); + \param select + when true, the left word will be also selected + */ + void handleWordLeft(bool select); - /*! - \brief - Processing to move caret one word right - */ - void handleWordRight(uint sysKeys); + /*! + \brief + Processing to move caret one character right + \param select + when true, the right character will be also selected + */ + void handleCharRight(bool select); - /*! - \brief - Processing to move caret to the start of the text. - */ - void handleDocHome(uint sysKeys); + /*! + \brief + Processing to move caret one word right - /*! - \brief - Processing to move caret to the end of the text - */ - void handleDocEnd(uint sysKeys); + \param select + when true, the right word will be also selected + */ + void handleWordRight(bool select); - /*! - \brief - Processing to move caret to the start of the current line. - */ - void handleLineHome(uint sysKeys); + /*! + \brief + Processing to move caret to the start of the text. + \param select + when true, the text until the beginning of the document will be also selected + */ + void handleDocHome(bool select); - /*! - \brief - Processing to move caret to the end of the current line - */ - void handleLineEnd(uint sysKeys); + /*! + \brief + Processing to move caret to the end of the text + + \param select + when true, the text until the end of the document will be also selected + */ + void handleDocEnd(bool select); - /*! - \brief - Processing to move caret up a line. - */ - void handleLineUp(uint sysKeys); + /*! + \brief + Processing to move caret to the start of the current line. - /*! - \brief - Processing to move caret down a line. - */ - void handleLineDown(uint sysKeys); + \param select + when true, the text until the start of the line be also selected + */ + void handleLineHome(bool select); + + + /*! + \brief + Processing to move caret to the end of the current line + + \param select + when true, the text until the end of the line will be also selected + */ + void handleLineEnd(bool select); + + + /*! + \brief + Processing to move caret up a line. + + \param select + when true, a line up will be also selected + */ + void handleLineUp(bool select); + + + /*! + \brief + Processing to move caret down a line. + + \param select + when true, a line down will be also selected + */ + void handleLineDown(bool select); /*! \brief Processing to insert a new line / paragraph. */ - void handleNewLine(uint sysKeys); + void handleNewLine(); /*! \brief Processing to move caret one page up + + \param select + when true, a page up will be also selected */ - void handlePageUp(uint sysKeys); + void handlePageUp(bool select); /*! \brief Processing to move caret one page down + + \param select + when true, a page down will be also selected */ - void handlePageDown(uint sysKeys); + void handlePageDown(bool select); /*! \brief @@ -734,19 +772,17 @@ class CEGUIEXPORT MultiLineEditbox : public Window /************************************************************************* Overridden event handlers *************************************************************************/ - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); - virtual void onMouseDoubleClicked(MouseEventArgs& e); - virtual void onMouseTripleClicked(MouseEventArgs& e); - virtual void onMouseMove(MouseEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); - virtual void onCharacter(KeyEventArgs& e); - virtual void onKeyDown(KeyEventArgs& e); + virtual void onCharacter(TextEventArgs& e); virtual void onTextChanged(WindowEventArgs& e); virtual void onSized(ElementEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); + virtual void onScroll(CursorInputEventArgs& e); virtual void onFontChanged(WindowEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); /************************************************************************* Implementation data @@ -760,9 +796,11 @@ class CEGUIEXPORT MultiLineEditbox : public Window size_t d_dragAnchorIdx; //!< Selection index for drag selection anchor point. static String d_lineBreakChars; //!< Holds what we consider to be line break characters. - bool d_wordWrap; //!< true when formatting uses word-wrapping. - LineList d_lines; //!< Holds the lines for the current formatting. - float d_widestExtent; //!< Holds the extent of the widest line as calculated in the last formatting pass. + bool d_wordWrap; //!< true when formatting uses word-wrapping. + LineList d_lines; //!< Holds the lines for the current formatting. + float d_lastRenderWidth; //!< Holds last render area width + float d_widestExtent; //!< Holds the extent of the widest line as calculated in the last formatting pass. + UndoHandler* d_undoHandler; //!< Undo handler class // component widget settings bool d_forceVertScroll; //!< true if vertical scrollbar should always be displayed @@ -777,6 +815,8 @@ class CEGUIEXPORT MultiLineEditbox : public Window Private methods *************************************************************************/ void addMultiLineEditboxProperties(void); + + void handleSelectAllText(SemanticEventArgs& e); }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/widgets/PopupMenu.h b/cegui/include/CEGUI/widgets/PopupMenu.h index cc42222d4..68b7dc07e 100644 --- a/cegui/include/CEGUI/widgets/PopupMenu.h +++ b/cegui/include/CEGUI/widgets/PopupMenu.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 27/3/2005 author: Tomas Lindquist Olsen (based on code by Paul D Turner) - + purpose: Interface to base class for PopupMenu widget *************************************************************************/ /*************************************************************************** @@ -170,7 +170,7 @@ class CEGUIEXPORT PopupMenu : public MenuBase /*! \brief - Setup size and position for the item widgets attached to this Listbox + Setup size and position for the item widgets attached to this Window \return Nothing. @@ -194,8 +194,8 @@ class CEGUIEXPORT PopupMenu : public MenuBase virtual void onDestructionStarted(WindowEventArgs& e); virtual void onShown(WindowEventArgs& e); virtual void onHidden(WindowEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); /************************************************************************* diff --git a/cegui/include/CEGUI/widgets/PushButton.h b/cegui/include/CEGUI/widgets/PushButton.h index 705a3bd6b..7346beb75 100644 --- a/cegui/include/CEGUI/widgets/PushButton.h +++ b/cegui/include/CEGUI/widgets/PushButton.h @@ -91,7 +91,8 @@ class CEGUIEXPORT PushButton : public ButtonBase /************************************************************************* Overridden Event Handlers *************************************************************************/ - virtual void onMouseButtonUp(MouseEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); }; } // End of CEGUI namespace section diff --git a/cegui/include/CEGUI/widgets/ScrollablePane.h b/cegui/include/CEGUI/widgets/ScrollablePane.h index 78e249f6a..dab588849 100644 --- a/cegui/include/CEGUI/widgets/ScrollablePane.h +++ b/cegui/include/CEGUI/widgets/ScrollablePane.h @@ -564,7 +564,7 @@ class CEGUIEXPORT ScrollablePane : public Window void removeChild_impl(Element* element); void onSized(ElementEventArgs& e); - void onMouseWheel(MouseEventArgs& e); + void onScroll(CursorInputEventArgs& e); //! \copydoc Window::getChildByNamePath_impl NamedElement* getChildByNamePath_impl(const String& name_path) const; diff --git a/cegui/include/CEGUI/widgets/Scrollbar.h b/cegui/include/CEGUI/widgets/Scrollbar.h index a3bb1e48d..3d236de8c 100644 --- a/cegui/include/CEGUI/widgets/Scrollbar.h +++ b/cegui/include/CEGUI/widgets/Scrollbar.h @@ -75,7 +75,7 @@ class CEGUIEXPORT ScrollbarWindowRenderer : public WindowRenderer - 0 to indicate scroll bar position should not be changed. - +1 to indicate scroll bar position should be moved to a higher value. */ - virtual float getAdjustDirectionFromPoint(const Vector2f& pt) const = 0; + virtual float getAdjustDirectionFromPoint(const glm::vec2& pt) const = 0; }; /*! @@ -493,7 +493,7 @@ class CEGUIEXPORT Scrollbar : public Window - 0 to indicate scroll bar position should not be changed. - +1 to indicate scroll bar position should be moved to a higher value. */ - float getAdjustDirectionFromPoint(const Vector2f& pt) const; + float getAdjustDirectionFromPoint(const glm::vec2& pt) const; /** implementation func that updates scroll position value, returns true if * value was changed. NB: Fires no events and does no other updates. @@ -538,8 +538,8 @@ class CEGUIEXPORT Scrollbar : public Window virtual void onScrollConfigChanged(WindowEventArgs& e); // Overridden event handlers - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onScroll(CursorInputEventArgs& e); // base class overrides void banPropertiesForAutoWindow(); diff --git a/cegui/include/CEGUI/widgets/ScrolledItemListBase.h b/cegui/include/CEGUI/widgets/ScrolledItemListBase.h deleted file mode 100644 index e1429546a..000000000 --- a/cegui/include/CEGUI/widgets/ScrolledItemListBase.h +++ /dev/null @@ -1,203 +0,0 @@ -/************************************************************************ - created: Sat Oct 29 2005 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUIScrolledItemListBase_h_ -#define _CEGUIScrolledItemListBase_h_ - -#include "./ItemListBase.h" -#include "./Scrollbar.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif -// begin CEGUI namespace -namespace CEGUI -{ - -/*! -\brief - ScrolledItemListBase window class -*/ -class CEGUIEXPORT ScrolledItemListBase : public ItemListBase -{ -public: - static const String EventNamespace; //!< Namespace for global events - - /************************************************************************ - Constants - *************************************************************************/ - static const String VertScrollbarName; //!< Name for vertical scrollbar component - static const String HorzScrollbarName; //!< Name for horizontal scrollbar component - static const String ContentPaneName; //!< Name for the content pane component - - /** Event fired when the vertical scroll bar mode changes. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the ScrolledItemListBase whose vertical - * scroll bar mode has been changed. - */ - static const String EventVertScrollbarModeChanged; - /** Event fired when the horizontal scroll bar mode change. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the ScrolledItemListBase whose horizontal - * scroll bar mode has been changed. - */ - static const String EventHorzScrollbarModeChanged; - - /************************************************************************ - Accessors - *************************************************************************/ - /*! - \brief - Returns whether the vertical scrollbar is being forced visible. Despite content size. - */ - bool isVertScrollbarAlwaysShown(void) const {return d_forceVScroll;} - - /*! - \brief - Returns whether the horizontal scrollbar is being forced visible. Despite content size. - */ - bool isHorzScrollbarAlwaysShown(void) const {return d_forceHScroll;} - - /*! - \brief - Get the vertical scrollbar component attached to this window. - */ - Scrollbar* getVertScrollbar() const; - - /*! - \brief - Get the horizontal scrollbar component attached to this window. - */ - Scrollbar* getHorzScrollbar() const; - - /************************************************************************ - Manipulators - *************************************************************************/ - /*! - \brief - Sets whether the vertical scrollbar should be forced visible. Despite content size. - */ - void setShowVertScrollbar(bool mode); - - /*! - \brief - Sets whether the horizontal scrollbar should be forced visible. Despite content size. - */ - void setShowHorzScrollbar(bool mode); - - /*! - \brief - Scroll the vertical list position if needed to ensure that the ItemEntry - \a item is, if possible, fully visible witin the ScrolledItemListBase - viewable area. - - \param item - const reference to an ItemEntry attached to this ScrolledItemListBase - that should be made visible in the view area. - - \return - Nothing. - */ - void ensureItemIsVisibleVert(const ItemEntry& item); - - /*! - \brief - Scroll the horizontal list position if needed to ensure that the - ItemEntry \a item is, if possible, fully visible witin the - ScrolledItemListBase viewable area. - - \param item - const reference to an ItemEntry attached to this ScrolledItemListBase - that should be made visible in the view area. - - \return - Nothing. - */ - void ensureItemIsVisibleHorz(const ItemEntry& item); - - /************************************************************************ - Object Construction and Destruction - *************************************************************************/ - /*! - \brief - Constructor for the ScrolledItemListBase base class constructor - */ - ScrolledItemListBase(const String& type, const String& name); - - /*! - \brief - Destructor for the ScrolledItemListBase base class. - */ - virtual ~ScrolledItemListBase(void); - - // overridden from ItemListBase - virtual void initialiseComponents(void); - -protected: - /************************************************************************ - Implementation functions - ************************************************************************/ - /*! - \brief - Configure scrollbars - */ - void configureScrollbars(const Sizef& doc_size); - - /************************************************************************ - New event handlers - ************************************************************************/ - virtual void onVertScrollbarModeChanged(WindowEventArgs& e); - virtual void onHorzScrollbarModeChanged(WindowEventArgs& e); - - /************************************************************************ - Overridden event handlers - ************************************************************************/ - virtual void onMouseWheel(MouseEventArgs& e); - - /************************************************************************ - Event subscribers - ************************************************************************/ - bool handle_VScroll(const EventArgs& e); - bool handle_HScroll(const EventArgs& e); - - /************************************************************************ - Implementation data - ************************************************************************/ - bool d_forceVScroll; - bool d_forceHScroll; - -private: - void addScrolledItemListBaseProperties(void); -}; - -} // end CEGUI namespace - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUIScrolledItemListBase_h_ diff --git a/cegui/include/CEGUI/widgets/Slider.h b/cegui/include/CEGUI/widgets/Slider.h index e5bb4cb75..cf4d85d1b 100644 --- a/cegui/include/CEGUI/widgets/Slider.h +++ b/cegui/include/CEGUI/widgets/Slider.h @@ -84,7 +84,7 @@ class CEGUIEXPORT SliderWindowRenderer : public WindowRenderer - 0 to indicate slider should not be moved. - +1 to indicate slider should be moved to a higher setting. */ - virtual float getAdjustDirectionFromPoint(const Vector2f& pt) const = 0; + virtual float getAdjustDirectionFromPoint(const glm::vec2& pt) const = 0; }; @@ -284,7 +284,7 @@ class CEGUIEXPORT Slider : public Window - 0 to indicate slider should not be moved. - +1 to indicate slider should be moved to a higher setting. */ - virtual float getAdjustDirectionFromPoint(const Vector2f& pt) const; + virtual float getAdjustDirectionFromPoint(const glm::vec2& pt) const; /*! @@ -370,8 +370,8 @@ class CEGUIEXPORT Slider : public Window /************************************************************************* Overridden event handlers *************************************************************************/ - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onScroll(CursorInputEventArgs& e); /************************************************************************* diff --git a/cegui/include/CEGUI/widgets/TabButton.h b/cegui/include/CEGUI/widgets/TabButton.h index 7c167466f..6d87e59d2 100644 --- a/cegui/include/CEGUI/widgets/TabButton.h +++ b/cegui/include/CEGUI/widgets/TabButton.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 8/8/2004 author: Steve Streeting - + purpose: Interface to base class for TabButton widget *************************************************************************/ /*************************************************************************** @@ -56,14 +56,14 @@ class CEGUIEXPORT TabButton : public ButtonBase * WindowEventArgs::window set to the TabButton that was clicked. */ static const String EventClicked; - /** Event fired when use user attempts to drag the button with middle mouse - * button. - * Handlers are passed a const MouseEventArgs reference with all fields + /** Event fired when use user attempts to drag the button with middle cursor + * source. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ static const String EventDragged; - /** Event fired when the scroll wheel is used on top of the button. - * Handlers are passed a const MouseEventArgs reference with all fields + /** Event fired when a scroll action is executed on top of the button. + * Handlers are passed a const CursorInputEventArgs reference with all fields * valid. */ static const String EventScrolled; @@ -130,10 +130,10 @@ class CEGUIEXPORT TabButton : public ButtonBase /************************************************************************* Overridden Event Handlers *************************************************************************/ - virtual void onMouseButtonUp(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); - virtual void onMouseMove(MouseEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onScroll(CursorInputEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); }; diff --git a/cegui/include/CEGUI/widgets/TabControl.h b/cegui/include/CEGUI/widgets/TabControl.h index 8cc468392..5d00ea2ca 100644 --- a/cegui/include/CEGUI/widgets/TabControl.h +++ b/cegui/include/CEGUI/widgets/TabControl.h @@ -324,7 +324,7 @@ class CEGUIEXPORT TabControl : public Window /*! \brief - Destructor for Listbox base class. + Destructor for TabControl base class. */ virtual ~TabControl(void); @@ -456,8 +456,7 @@ class CEGUIEXPORT TabControl : public Window *************************************************************************/ UDim d_tabHeight; //!< The height of the tabs in pixels UDim d_tabPadding; //!< The padding of the tabs relative to parent - typedef std::vector TabButtonVector; + typedef std::vector TabButtonVector; TabButtonVector d_tabButtonVector; //!< Sorting for tabs float d_firstTabOffset; //!< The offset in pixels of the first tab TabPanePosition d_tabPanePos; //!< The position of the tab pane @@ -494,7 +493,7 @@ class CEGUIEXPORT TabControl : public Window void addChild_impl(Element* element); void removeChild_impl(Element* element); - + //! \copydoc Window::getChildByNamePath_impl virtual NamedElement* getChildByNamePath_impl(const String& name_path) const; diff --git a/cegui/include/CEGUI/widgets/Thumb.h b/cegui/include/CEGUI/widgets/Thumb.h index 784b1de59..ad1d9f45b 100644 --- a/cegui/include/CEGUI/widgets/Thumb.h +++ b/cegui/include/CEGUI/widgets/Thumb.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 25/4/2004 author: Paul D Turner - + purpose: Interface for a 'Thumb' widget. Intended to be used as part of other widgets such as scrollers and sliders. *************************************************************************/ @@ -48,7 +48,7 @@ namespace CEGUI /*! \brief Base class for Thumb widget. - + The thumb widget is used to compose other widgets (like sliders and scroll bars). You would not normally need to use this widget directly unless you are making a new widget of some type. */ @@ -83,7 +83,7 @@ class CEGUIEXPORT Thumb : public PushButton /************************************************************************* Accessor Functions - *************************************************************************/ + *************************************************************************/ /*! \brief return whether hot-tracking is enabled or not. @@ -176,7 +176,7 @@ class CEGUIEXPORT Thumb : public PushButton nothing. */ void setHorzFree(bool setting) {d_horzFree = setting;} - + /*! \brief @@ -278,7 +278,7 @@ class CEGUIEXPORT Thumb : public PushButton /*! \brief - Handler triggered when the user begins to drag the thumb. + Handler triggered when the user begins to drag the thumb. */ virtual void onThumbTrackStarted(WindowEventArgs& e); @@ -294,8 +294,8 @@ class CEGUIEXPORT Thumb : public PushButton /************************************************************************* Overridden event handling routines *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); @@ -313,7 +313,7 @@ class CEGUIEXPORT Thumb : public PushButton // internal state bool d_beingDragged; //!< true if thumb is being dragged - Vector2f d_dragPoint; //!< point where we are being dragged at. + glm::vec2 d_dragPoint; //!< point where we are being dragged at. private: diff --git a/cegui/include/CEGUI/widgets/Titlebar.h b/cegui/include/CEGUI/widgets/Titlebar.h index 64716c6c6..07d954254 100644 --- a/cegui/include/CEGUI/widgets/Titlebar.h +++ b/cegui/include/CEGUI/widgets/Titlebar.h @@ -1,7 +1,7 @@ /*********************************************************************** created: 25/4/2004 author: Paul D Turner - + purpose: Interface for a Titlebar Widget *************************************************************************/ /*************************************************************************** @@ -85,7 +85,7 @@ class CEGUIEXPORT Titlebar : public Window \brief Gets the point at which the title bar widget is/was being dragged */ - const Vector2f& getDragPoint() const; + const glm::vec2& getDragPoint() const; /************************************************************************* Construction / Destruction @@ -108,12 +108,12 @@ class CEGUIEXPORT Titlebar : public Window /************************************************************************* Overridden event handler functions *************************************************************************/ - virtual void onMouseMove(MouseEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseButtonUp(MouseEventArgs& e); - virtual void onMouseDoubleClicked(MouseEventArgs& e); + virtual void onCursorMove(CursorInputEventArgs& e); + virtual void onCursorPressHold(CursorInputEventArgs& e); + virtual void onCursorActivate(CursorInputEventArgs& e); virtual void onCaptureLost(WindowEventArgs& e); virtual void onFontChanged(WindowEventArgs &e); + virtual void onSemanticInputEvent(SemanticEventArgs& e); /************************************************************************* @@ -122,7 +122,7 @@ class CEGUIEXPORT Titlebar : public Window /*! \brief Event handler called when the 'draggable' state for the title bar is changed. - + Note that this is for 'internal' use at the moment and as such does not add or fire a public Event that can be subscribed to. */ @@ -132,7 +132,7 @@ class CEGUIEXPORT Titlebar : public Window Implementation Data *************************************************************************/ bool d_dragging; //!< set to true when the window is being dragged. - Vector2f d_dragPoint; //!< Point at which we are being dragged. + glm::vec2 d_dragPoint; //!< Point at which we are being dragged. bool d_dragEnabled; //!< true when dragging for the widget is enabled. Rectf d_oldCursorArea; //!< Used to backup cursor restraint area. diff --git a/cegui/include/CEGUI/widgets/ToggleButton.h b/cegui/include/CEGUI/widgets/ToggleButton.h index e40d21d86..5d29d3ef5 100644 --- a/cegui/include/CEGUI/widgets/ToggleButton.h +++ b/cegui/include/CEGUI/widgets/ToggleButton.h @@ -65,7 +65,8 @@ class CEGUIEXPORT ToggleButton : public ButtonBase virtual void onSelectStateChange(WindowEventArgs& e); // base class overriddes - void onMouseButtonUp(MouseEventArgs& e); + void onCursorActivate(CursorInputEventArgs& e); + void onSemanticInputEvent(SemanticEventArgs& e); bool d_selected; }; diff --git a/cegui/include/CEGUI/widgets/Tooltip.h b/cegui/include/CEGUI/widgets/Tooltip.h index 3512dff46..9932dfdb3 100644 --- a/cegui/include/CEGUI/widgets/Tooltip.h +++ b/cegui/include/CEGUI/widgets/Tooltip.h @@ -64,10 +64,10 @@ namespace CEGUI /*! \brief Base class for Tooltip widgets. - - The Tooltip class shows a simple pop-up window around the mouse position + + The Tooltip class shows a simple pop-up window around the cursor position with some text information. The tool-tip fades in when the user hovers - with the mouse over a window which has tool-tip text set, and then fades + with the cursor over a window which has tool-tip text set, and then fades out after some pre-set time. \note @@ -171,8 +171,8 @@ namespace CEGUI /*! \brief - Return the number of seconds the mouse should hover stationary over the target window before - the tooltip gets activated. + Return the number of seconds the cursor should hover stationary + over the target window before the tooltip gets activated. \return float value representing a number of seconds. @@ -182,7 +182,7 @@ namespace CEGUI /*! \brief Set the number of seconds the tooltip should be displayed for before it automatically - de-activates itself. 0 indicates that the tooltip should never timesout and auto-deactivate. + de-activates itself. 0 indicates that the tooltip should never timeout and auto-deactivate. \param seconds float value representing a number of seconds. @@ -194,8 +194,8 @@ namespace CEGUI /*! \brief - Set the number of seconds the mouse should hover stationary over the target window before - the tooltip gets activated. + Set the number of seconds the cursor should hover stationary over + the target window before the tooltip gets activated. \param seconds float value representing a number of seconds. @@ -208,7 +208,7 @@ namespace CEGUI /*! \brief Return the number of seconds the tooltip should be displayed for before it automatically - de-activates itself. 0 indicates that the tooltip never timesout and auto-deactivates. + de-activates itself. 0 indicates that the tooltip never timeout and auto-deactivates. \return float value representing a number of seconds. @@ -322,7 +322,7 @@ namespace CEGUI ************************************************************************/ void updateSelf(float elapsed); void onHidden(WindowEventArgs& e); - void onMouseEnters(MouseEventArgs& e); + void onCursorEnters(CursorInputEventArgs& e); void onTextChanged(WindowEventArgs& e); /************************************************************************ @@ -331,7 +331,7 @@ namespace CEGUI bool d_active; //!< true if the tooltip is active float d_elapsed; //!< Used to track state change timings const Window* d_target; //!< Current target Window for this Tooltip. - float d_hoverTime; //!< tool-tip hover time (seconds mouse must stay stationary before tip shows). + float d_hoverTime; //!< tool-tip hover time (seconds cursor must stay stationary before tip shows). float d_displayTime; //!< tool-tip display time (seconds that tip is showsn for). float d_fadeTime; //!< tool-tip fade time (seconds it takes for tip to fade in and/or out). //! are in positionSelf function? (to avoid infinite recursion issues) diff --git a/cegui/include/CEGUI/widgets/Tree.h b/cegui/include/CEGUI/widgets/Tree.h deleted file mode 100644 index 7c91550f6..000000000 --- a/cegui/include/CEGUI/widgets/Tree.h +++ /dev/null @@ -1,877 +0,0 @@ -/*********************************************************************** - created: 5-13-07 - author: Jonathan Welch (Based on Code by David Durant) - *************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUITree_h_ -#define _CEGUITree_h_ - -#include "../Base.h" -#include "../Window.h" -#include "../WindowManager.h" -#include "./TreeItem.h" -#include "./Scrollbar.h" -#include - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -/*! - \brief - EventArgs based class that is used for objects passed to input event - handlers concerning Tree events. - */ -class CEGUIEXPORT TreeEventArgs : public WindowEventArgs -{ -public: - TreeEventArgs(Window* wnd) : WindowEventArgs(wnd) - { treeItem = 0; } - - TreeItem *treeItem; -}; - - -/*! - \brief - Base class for standard Tree widget. - - \deprecated - The CEGUI::Tree, CEGUI::TreeItem and any other associated classes are - deprecated and thier use should be minimised - preferably eliminated - - where possible. It is extremely unfortunate that this widget was ever added - to CEGUI since its design and implementation are poor and do not meet - established standards for the CEGUI project. - \par - While no alternative currently exists, a superior, replacement tree widget - will be provided prior to the final removal of the current implementation. - */ -class CEGUIEXPORT Tree : public Window -{ - friend class TreeItem; - - typedef std::vector LBItemList; - -public: - //! Namespace for global events - static const String EventNamespace; - static const String WidgetTypeName; - - /************************************************************************* - Constants - *************************************************************************/ - // event names - /** Event fired when the content of the tree is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Tree whose content has changed. - */ - static const String EventListContentsChanged; - /** Event fired when there is a change to the currently selected item(s). - * Handlers are passed a const TreeEventArgs reference with - * WindowEventArgs::window set to the Tree whose item selection has changed, - * and TreeEventArgs::treeItem is set to the (last) item to be selected, or - * 0 if none. - */ - static const String EventSelectionChanged; - /** Event fired when the sort mode setting for the Tree is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Tree whose sort mode has been - * changed. - */ - static const String EventSortModeChanged; - /** Event fired when the multi-select mode setting for the Tree changes. - * Handlers are passed a const TreeEventArgs reference with - * WindowEventArgs::window set to the Tree whose setting has changed. - * TreeEventArgs::treeItem is always set to 0. - */ - static const String EventMultiselectModeChanged; - /** Event fired when the mode setting that forces the display of the - * vertical scroll bar for the tree is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Tree whose vertical scrollbar mode has - * been changed. - */ - static const String EventVertScrollbarModeChanged; - /** Event fired when the mode setting that forces the display of the - * horizontal scroll bar for the tree is changed. - * Handlers are passed a const WindowEventArgs reference with - * WindowEventArgs::window set to the Tree whose horizontal scrollbar mode - * has been changed. - */ - static const String EventHorzScrollbarModeChanged; - /** Event fired when a branch of the tree is opened by the user. - * Handlers are passed a const TreeEventArgs reference with - * WindowEventArgs::window set to the Tree containing the branch that has - * been opened and TreeEventArgs::treeItem set to the TreeItem at the head - * of the opened branch. - */ - static const String EventBranchOpened; - /** Event fired when a branch of the tree is closed by the user. - * Handlers are passed a const TreeEventArgs reference with - * WindowEventArgs::window set to the Tree containing the branch that has - * been closed and TreeEventArgs::treeItem set to the TreeItem at the head - * of the closed branch. - */ - static const String EventBranchClosed; - - //Render the actual tree - void doTreeRender() - { populateGeometryBuffer(); } - - //UpdateScrollbars - void doScrollbars() - { configureScrollbars(); } - - /************************************************************************* - Accessor Methods - *************************************************************************/ - /*! - \brief - Return number of items attached to the tree - - \return - the number of items currently attached to this tree. - */ - size_t getItemCount(void) const - { return d_listItems.size(); } - - /*! - \brief - Return the number of selected items in the tree. - - \return - Total number of attached items that are in the selected state. - */ - size_t getSelectedCount(void) const; - - /*! - \brief - Return a pointer to the first selected item. - - \return - Pointer to a TreeItem based object that is the first selected item in - the tree. will return 0 if no item is selected. - */ - TreeItem* getFirstSelectedItem(void) const; - - /*! - \brief - Return a pointer to the first selected item. - - \return - Pointer to a TreeItem based object that is the last item selected by the - user, not necessarily the last selected in the tree. Will return 0 if - no item is selected. - */ - TreeItem* getLastSelectedItem(void) const - { return d_lastSelected; } - - /*! - \brief - Return a pointer to the next selected item after item \a start_item - - \param start_item - Pointer to the TreeItem where the search for the next selected item is - to begin. If this parameter is 0, the search will begin with the first - item in the tree. - - \return - Pointer to a TreeItem based object that is the next selected item in - the tree after the item specified by \a start_item. Will return 0 if - no further items were selected. - - \exception InvalidRequestException thrown if \a start_item is not attached - to this tree. - */ - TreeItem* getNextSelected(const TreeItem* start_item) const; - - TreeItem* getNextSelectedItemFromList(const LBItemList &itemList, - const TreeItem* start_item, - bool& foundStartItem) const; - - /*! - \brief - return whether tree sorting is enabled - - \return - - true if the tree is sorted - - false if the tree is not sorted - */ - bool isSortEnabled(void) const - { return d_sorted; } - - void setItemRenderArea(Rectf& r) - { d_itemArea = r; } - - Scrollbar* getVertScrollbar() - { return d_vertScrollbar; } - - Scrollbar* getHorzScrollbar() - { return d_horzScrollbar; } - - /*! - \brief - return whether multi-select is enabled - - \return - true if multi-select is enabled, false if multi-select is not enabled. - */ - bool isMultiselectEnabled(void) const - { return d_multiselect; } - - bool isItemTooltipsEnabled(void) const - { return d_itemTooltips; } - - /*! - \brief - Search the tree for an item with the specified text - - \param text - String object containing the text to be searched for. - - \param start_item - TreeItem where the search is to begin, the search will not include \a - item. If \a item is 0, the search will begin from the first item in - the tree. - - \return - Pointer to the first TreeItem in the tree after \a item that has text - matching \a text. If no item matches the criteria, 0 is returned. - - \exception InvalidRequestException thrown if \a item is not attached to - this tree. - */ - TreeItem* findFirstItemWithText(const String& text); - - TreeItem* findNextItemWithText(const String& text, - const TreeItem* start_item); - - TreeItem* findItemWithTextFromList(const LBItemList &itemList, - const String& text, - const TreeItem* start_item, - bool foundStartItem); - - /*! - \brief - Search the tree for an item with the specified text - - \param text - String object containing the text to be searched for. - - \param start_item - TreeItem where the search is to begin, the search will not include - \a item. If \a item is 0, the search will begin from the first item in - the tree. - - \return - Pointer to the first TreeItem in the tree after \a item that has text - matching \a text. If no item matches the criteria 0 is returned. - - \exception InvalidRequestException thrown if \a item is not attached to - this tree. - */ - TreeItem* findFirstItemWithID(uint searchID); - TreeItem* findNextItemWithID(uint searchID, const TreeItem* start_item); - TreeItem* findItemWithIDFromList(const LBItemList &itemList, uint searchID, - const TreeItem* start_item, - bool foundStartItem); - - /*! - \brief - Return whether the specified TreeItem is in the tree - - \return - - true if TreeItem \a item is in the tree - - false if TreeItem \a item is not in the tree. - */ - bool isTreeItemInList(const TreeItem* item) const; - - /*! - \brief - Return whether the vertical scroll bar is always shown. - - \return - - true if the scroll bar will always be shown even if it is not required. - - false if the scroll bar will only be shown when it is required. - */ - bool isVertScrollbarAlwaysShown(void) const; - - /*! - \brief - Return whether the horizontal scroll bar is always shown. - - \return - - true if the scroll bar will always be shown even if it is not required. - - false if the scroll bar will only be shown when it is required. - */ - bool isHorzScrollbarAlwaysShown(void) const; - - /************************************************************************* - Manipulator Methods - *************************************************************************/ - /*! - \brief - Initialise the Window based object ready for use. - - \note - This must be called for every window created. Normally this is handled - automatically by the WindowFactory for each Window type. - - \return - Nothing - */ - virtual void initialise(void); - - /*! - \brief - Remove all items from the tree. - - Note that this will cause 'AutoDelete' items to be deleted. - */ - void resetList(void); - - /*! - \brief - Add the given TreeItem to the tree. - - \param item - Pointer to the TreeItem to be added to the tree. Note that it is the - passed object that is added to the tree, a copy is not made. If this - parameter is NULL, nothing happens. - - \return - Nothing. - */ - void addItem(TreeItem* item); - - /*! - \brief - Insert an item into the tree after a specified item already in the - tree. - - Note that if the tree is sorted, the item may not end up in the - requested position. - - \param item - Pointer to the TreeItem to be inserted. Note that it is the passed - object that is added to the tree, a copy is not made. If this - parameter is 0, nothing happens. - - \param position - Pointer to a TreeItem that \a item is to be inserted after. If this - parameter is 0, the item is inserted at the start of the tree. - - \return - Nothing. - - \exception InvalidRequestException thrown if no TreeItem \a position is - attached to this tree. - */ - void insertItem(TreeItem* item, const TreeItem* position); - - /*! - \brief - Removes the given item from the tree. If the item is has the auto - delete state set, the item will be deleted. - - \param item - Pointer to the TreeItem that is to be removed. If \a item is not - attached to this tree then nothing will happen. - - \return - Nothing. - */ - void removeItem(const TreeItem* item); - - /*! - \brief - Clear the selected state for all items. - - \return - Nothing. - */ - void clearAllSelections(void); - bool clearAllSelectionsFromList(const LBItemList &itemList); - - /*! - \brief - Set whether the tree should be sorted. - - \param setting - - true if the tree should be sorted - - false if the tree should not be sorted. - - \return - Nothing. - */ - void setSortingEnabled(bool setting); - - /*! - \brief - Set whether the tree should allow multiple selections or just a single - selection. - - \param setting - - true if the widget should allow multiple items to be selected - - false if the widget should only allow a single selection. - - \return - Nothing. - */ - void setMultiselectEnabled(bool setting); - - /*! - \brief - Set whether the vertical scroll bar should always be shown. - - \param setting - - true if the vertical scroll bar should be shown even when it is not - required. - - false if the vertical scroll bar should only be shown when it is - required. - - \return - Nothing. - */ - void setShowVertScrollbar(bool setting); - - /*! - \brief - Set whether the horizontal scroll bar should always be shown. - - \param setting - - true if the horizontal scroll bar should be shown even when it is not - required. - - false if the horizontal scroll bar should only be shown when it is - required. - - \return - Nothing. - */ - void setShowHorzScrollbar(bool setting); - - void setItemTooltipsEnabled(bool setting); - - /*! - \brief - Set the select state of an attached TreeItem. - - This is the recommended way of selecting and deselecting items attached - to a tree as it respects the multi-select mode setting. It is - possible to modify the setting on TreeItems directly, but that approach - does not respect the settings of the tree. - - \param item - The TreeItem to be affected. - This item must be attached to the tree. - - \param state - - true to select the item. - - false to de-select the item. - - \return - Nothing. - - \exception InvalidRequestException thrown if \a item is not attached to - this tree. - */ - void setItemSelectState(TreeItem* item, bool state); - - /*! - \brief - Set the select state of an attached TreeItem. - - This is the recommended way of selecting and deselecting items attached - to a tree as it respects the multi-select mode setting. It is - possible to modify the setting on TreeItems directly, but that approach - does not respect the settings of the tree. - - \param item_index - The zero based index of the TreeItem to be affected. - This must be a valid index (0 <= index < getItemCount()) - - \param state - - true to select the item. - - false to de-select the item. - - \return - Nothing. - - \exception InvalidRequestException thrown if \a item_index is out of range - for the tree - */ - void setItemSelectState(size_t item_index, bool state); - - /*! - \brief - Set the LookNFeel that shoule be used for this window. - - \param look - String object holding the name of the look to be assigned to the window. - - \return - Nothing. - - \exception UnknownObjectException - thrown if the look'n'feel specified by \a look does not exist. - - \note - Once a look'n'feel has been assigned it is locked - as in cannot be - changed. - */ - virtual void setLookNFeel(const String& look); - - /*! - \brief - Causes the tree to update it's internal state after changes have - been made to one or more attached TreeItem objects. - - Client code must call this whenever it has made any changes to TreeItem - objects already attached to the tree. If you are just adding items, - or removed items to update them prior to re-adding them, there is no - need to call this method. - - \return - Nothing. - */ - void handleUpdatedItemData(void); - - /*! - \brief - Ensure the item at the specified index is visible within the tree. - - \param item - Pointer to the TreeItem to be made visible in the tree. - - \return - Nothing. - - \exception InvalidRequestException thrown if \a item is not attached to - this tree. - */ - void ensureItemIsVisible(const TreeItem* item); - - - /************************************************************************* - Construction and Destruction - *************************************************************************/ - /*! - \brief - Constructor for Tree base class. - */ - Tree(const String& type, const String& name); - - /*! - \brief - Destructor for Tree base class. - */ - virtual ~Tree(void); - -protected: - /************************************************************************* - Abstract Implementation Functions (must be provided by derived class) - *************************************************************************/ - /*! - \brief - Return a Rect object describing, in un-clipped pixels, the window - relative area that is to be used for rendering tree items. - - \return - Rect object describing the area of the Window to be used for rendering - tree items. - */ - virtual Rectf getTreeRenderArea(void) const - { return d_itemArea; } - - /*! - \brief - create and return a pointer to a Scrollbar widget for use as vertical - scroll bar. - - \param name - String holding the name to be given to the created widget component. - - \return - Pointer to a Scrollbar to be used for scrolling the tree vertically. - */ - virtual Scrollbar* createVertScrollbar(const String& name) const - { return static_cast(getChild(name)); } - - /*! - \brief - create and return a pointer to a Scrollbar widget for use as horizontal - scroll bar. - - \param name - String holding the name to be given to the created widget component. - - \return - Pointer to a Scrollbar to be used for scrolling the tree horizontally. - */ - virtual Scrollbar* createHorzScrollbar(const String& name) const - { return static_cast(getChild(name)); } - - /*! - \brief - Perform caching of the widget control frame and other 'static' areas. - This method should not render the actual items. Note that the items - are typically rendered to layer 3, other layers can be used for - rendering imagery behind and infront of the items. - - \return - Nothing. - */ - virtual void cacheTreeBaseImagery() - {} - - /************************************************************************* - Implementation Functions - *************************************************************************/ - /*! - \brief - Checks if a tree item is visible (searches sub-items) - */ - bool containsOpenItemRecursive(const LBItemList& itemList, TreeItem* item); - - /*! - \brief - Add tree specific events - */ - void addTreeEvents(void); - - - /*! - \brief - display required integrated scroll bars according to current state of - the tree and update their values. - */ - void configureScrollbars(void); - - /*! - \brief - select all strings between positions \a start and \a end. (inclusive) - including \a end. - */ - void selectRange(size_t start, size_t end); - - /*! - \brief - Return the sum of all item heights - */ - float getTotalItemsHeight(void) const; - void getTotalItemsInListHeight(const LBItemList &itemList, - float *heightSum) const; - - /*! - \brief - Return the width of the widest item - */ - float getWidestItemWidth(void) const; - void getWidestItemWidthInList(const LBItemList &itemList, int itemDepth, - float *widest) const; - - /*! - \brief - Clear the selected state for all items (implementation) - - \return - - true if treeItem was found in the search. - - false if it was not. - */ - bool getHeightToItemInList(const LBItemList &itemList, - const TreeItem *treeItem, - int itemDepth, - float *height) const; - - /*! - \brief - Clear the selected state for all items (implementation) - - \return - - true if some selections were cleared - - false nothing was changed. - */ - bool clearAllSelections_impl(void); - - /*! - \brief - Return the TreeItem under the given window local pixel co-ordinate. - - \return - TreeItem that is under window pixel co-ordinate \a pt, or 0 if no - item is under that position. - */ - TreeItem* getItemAtPoint(const Vector2f& pt) const; - TreeItem* getItemFromListAtPoint(const LBItemList &itemList, float *bottomY, - const Vector2f& pt) const; - - /*! - \brief - Remove all items from the tree. - - \note - Note that this will cause 'AutoDelete' items to be deleted. - - \return - - true if the tree contents were changed. - - false if the tree contents were not changed (tree already empty). - */ - bool resetList_impl(void); - - /*! - \brief - Internal handler that is triggered when the user interacts with the - scrollbars. - */ - bool handle_scrollChange(const EventArgs& args); - - // overridden from Window base class. - virtual void populateGeometryBuffer(); - bool handleFontRenderSizeChange(const EventArgs& args); - - void drawItemList(LBItemList& itemList, Rectf& itemsArea, float widest, - Vector2f& itemPos, GeometryBuffer& geometry, float alpha); - - /************************************************************************* - New event handlers - *************************************************************************/ - /*! - \brief - Handler called internally when the tree contents are changed - */ - virtual void onListContentsChanged(WindowEventArgs& e); - - /*! - \brief - Handler called internally when the currently selected item or items - changes. - */ - virtual void onSelectionChanged(TreeEventArgs& e); - - /*! - \brief - Handler called internally when the sort mode setting changes. - */ - virtual void onSortModeChanged(WindowEventArgs& e); - - /*! - \brief - Handler called internally when the multi-select mode setting changes. - */ - virtual void onMultiselectModeChanged(WindowEventArgs& e); - - /*! - \brief - Handler called internally when the forced display of the vertical scroll - bar setting changes. - */ - virtual void onVertScrollbarModeChanged(WindowEventArgs& e); - - /*! - \brief - Handler called internally when the forced display of the horizontal - scroll bar setting changes. - */ - virtual void onHorzScrollbarModeChanged(WindowEventArgs& e); - - /*! - \brief - Handler called internally when the user opens a branch of the tree. - */ - virtual void onBranchOpened(TreeEventArgs& e); - - /*! - \brief - Handler called internally when the user closes a branch of the tree. - */ - virtual void onBranchClosed(TreeEventArgs& e); - - /************************************************************************* - Overridden Event handlers - *************************************************************************/ - virtual void onSized(ElementEventArgs& e); - virtual void onMouseButtonDown(MouseEventArgs& e); - virtual void onMouseWheel(MouseEventArgs& e); - virtual void onMouseMove(MouseEventArgs& e); - - /************************************************************************* - Implementation Data - *************************************************************************/ - //! true if tree is sorted - bool d_sorted; - //! true if multi-select is enabled - bool d_multiselect; - //! true if vertical scrollbar should always be displayed - bool d_forceVertScroll; - //! true if horizontal scrollbar should always be displayed - bool d_forceHorzScroll; - //! true if each item should have an individual tooltip - bool d_itemTooltips; - //! vertical scroll-bar widget - Scrollbar* d_vertScrollbar; - //! horizontal scroll-bar widget - Scrollbar* d_horzScrollbar; - //! list of items in the tree. - LBItemList d_listItems; - //! holds pointer to the last selected item (used in range selections) - TreeItem* d_lastSelected; - const ImagerySection* d_openButtonImagery; - const ImagerySection* d_closeButtonImagery; - -private: - /************************************************************************* - Private methods - *************************************************************************/ - void addTreeProperties(void); - Rectf d_itemArea; -}; - -/*! - \brief - Helper function used in sorting to compare two tree item text strings - via the TreeItem pointers and return if \a a is less than \a b. - */ -bool lbi_less(const TreeItem* a, const TreeItem* b); - - -/*! - \brief - Helper function used in sorting to compare two tree item text strings - via the TreeItem pointers and return if \a a is greater than \a b. - */ -bool lbi_greater(const TreeItem* a, const TreeItem* b); - -} // End of CEGUI namespace section - - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUITree_h_ diff --git a/cegui/include/CEGUI/widgets/TreeItem.h b/cegui/include/CEGUI/widgets/TreeItem.h deleted file mode 100644 index 602430624..000000000 --- a/cegui/include/CEGUI/widgets/TreeItem.h +++ /dev/null @@ -1,698 +0,0 @@ -/*********************************************************************** - created: 5-13-07 - author: Jonathan Welch (Based on Code by David Durant) - *************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGUITreeItem_h_ -#define _CEGUITreeItem_h_ - -#include "../Base.h" -#include "../String.h" -#include "../ColourRect.h" -#include "../BasicRenderedStringParser.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4251) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -/*! - \brief - Base class for tree items - - \deprecated - The CEGUI::Tree, CEGUI::TreeItem and any other associated classes are - deprecated and thier use should be minimised - preferably eliminated - - where possible. It is extremely unfortunate that this widget was ever added - to CEGUI since its design and implementation are poor and do not meet - established standards for the CEGUI project. - \par - While no alternative currently exists, a superior, replacement tree widget - will be provided prior to the final removal of the current implementation. - */ -class CEGUIEXPORT TreeItem : public - AllocatedObject -{ -public: - typedef std::vector LBItemList; - - /************************************************************************* - Constants - *************************************************************************/ - //! Default text colour. - static const Colour DefaultTextColour; - //! Default selection brush colour. - static const Colour DefaultSelectionColour; - - /************************************************************************* - Construction and Destruction - *************************************************************************/ - /*! - \brief - base class constructor - */ - TreeItem(const String& text, uint item_id = 0, void* item_data = 0, - bool disabled = false, bool auto_delete = true); - - /*! - \brief - base class destructor - */ - virtual ~TreeItem(void); - - /************************************************************************* - Accessors - *************************************************************************/ - /*! - \brief - Return a pointer to the font being used by this TreeItem - - This method will try a number of places to find a font to be used. If - no font can be found, NULL is returned. - - \return - Font to be used for rendering this item - */ - const Font* getFont(void) const; - - /*! - \brief - Return the current colours used for text rendering. - - \return - ColourRect object describing the currently set colours - */ - ColourRect getTextColours(void) const - { return d_textCols; } - - /************************************************************************* - Manipulator methods - *************************************************************************/ - /*! - \brief - Set the font to be used by this TreeItem - - \param font - Font to be used for rendering this item - - \return - Nothing - */ - void setFont(const Font* font); - - /*! - \brief - Set the font to be used by this TreeItem - - \param font_name - String object containing the name of the Font to be used for rendering - this item - - \return - Nothing - */ - void setFont(const String& font_name); - - /*! - \brief - Set the colours used for text rendering. - - \param cols - ColourRect object describing the colours to be used. - - \return - Nothing. - */ - void setTextColours(const ColourRect& cols) - { d_textCols = cols; d_renderedStringValid = false; } - - /*! - \brief - Set the colours used for text rendering. - - \param top_left_colour - Colour (as ARGB value) to be applied to the top-left corner of each text - glyph rendered. - - \param top_right_colour - Colour (as ARGB value) to be applied to the top-right corner of each - text glyph rendered. - - \param bottom_left_colour - Colour (as ARGB value) to be applied to the bottom-left corner of each - text glyph rendered. - - \param bottom_right_colour - Colour (as ARGB value) to be applied to the bottom-right corner of each - text glyph rendered. - - \return - Nothing. - */ - void setTextColours(Colour top_left_colour, Colour top_right_colour, - Colour bottom_left_colour, Colour bottom_right_colour); - - /*! - \brief - Set the colours used for text rendering. - - \param col - colour value to be used when rendering. - - \return - Nothing. - */ - void setTextColours(Colour col) - { setTextColours(col, col, col, col); } - - /*! - \brief - return the text string set for this tree item. - - Note that even if the item does not render text, the text string can - still be useful, since it is used for sorting tree items. - - \return - String object containing the current text for the tree item. - */ - const String& getText() const {return d_textLogical;} - - //! return text string with \e visual ordering of glyphs. - const String& getTextVisual() const; - - /*! - \brief - Return the text string currently set to be used as the tooltip text for - this item. - - \return - String object containing the current tooltip text as sued by this item. - */ - const String& getTooltipText(void) const - { return d_tooltipText; } - - /*! - \brief - Return the current ID assigned to this tree item. - - Note that the system does not make use of this value, client code can - assign any meaning it wishes to the ID. - - \return - ID code currently assigned to this tree item - */ - uint getID(void) const - { return d_itemID; } - - /*! - \brief - Return the pointer to any client assigned user data attached to this - tree item. - - Note that the system does not make use of this data, client code can - assign any meaning it wishes to the attached data. - - \return - Pointer to the currently assigned user data. - */ - void* getUserData(void) const - { return d_itemData; } - - /*! - \brief - return whether this item is selected. - - \return - - true if the item is selected. - - false if the item is not selected. - */ - bool isSelected(void) const - { return d_selected; } - - /*! - \brief - return whether this item is disabled. - - \return - - true if the item is disabled. - - false if the item is enabled. - */ - bool isDisabled(void) const - { return d_disabled; } - - /*! - \brief - return whether this item will be automatically deleted when it is - removed from the tree or when the the tree it is attached to is - destroyed. - - \return - - true if the item object will be deleted by the system when it is - removed from the tree, or when the tree it is attached to is - destroyed. - - false if client code must destroy the item after it is removed from - the tree. - */ - bool isAutoDeleted(void) const - { return d_autoDelete; } - - /*! - \brief - Get the owner window for this TreeItem. - - The owner of a TreeItem is typically set by the tree widget when an - item is added or inserted. - - \return - Ponter to the window that is considered the owner of this TreeItem. - */ - const Window* getOwnerWindow(void) - { return d_owner; } - - /*! - \brief - Return the current colours used for selection highlighting. - - \return - ColourRect object describing the currently set colours. - */ - ColourRect getSelectionColours(void) const - { return d_selectCols; } - - - /*! - \brief - Return the current selection highlighting brush. - - \return - Pointer to the Image object currently used for selection highlighting. - */ - const Image* getSelectionBrushImage(void) const - { return d_selectBrush; } - - - /************************************************************************* - Manipulators - *************************************************************************/ - /*! - \brief - set the text string for this tree item. - - Note that even if the item does not render text, the text string can - still be useful, since it is used for sorting tree items. - - \param text - String object containing the text to set for the tree item. - - \return - Nothing. - */ - void setText(const String& text); - - /*! - \brief - Set the tooltip text to be used for this item. - - \param text - String object holding the text to be used in the tooltip displayed for - this item. - - \return - Nothing. - */ - void setTooltipText(const String& text) - { d_tooltipText = text; } - - /*! - \brief - Set the ID assigned to this tree item. - - Note that the system does not make use of this value, client code can - assign any meaning it wishes to the ID. - - \param item_id - ID code to be assigned to this tree item - - \return - Nothing. - */ - void setID(uint item_id) - { d_itemID = item_id; } - - /*! - \brief - Set the client assigned user data attached to this lis box item. - - Note that the system does not make use of this data, client code can - assign any meaning it wishes to the attached data. - - \param item_data - Pointer to the user data to attach to this tree item. - - \return - Nothing. - */ - void setUserData(void* item_data) - { d_itemData = item_data; } - - /*! - \brief - Set the selected state for the item. - - \param setting - - true if the item is selected. - - false if the item is not selected. - - \return - Nothing. - */ - void setSelected(bool setting) - { d_selected = setting; } - - /*! - \brief - Set the disabled state for the item. - - \param setting - - true if the item should be disabled. - - false if the item should be enabled. - - \return - Nothing. - */ - void setDisabled(bool setting) - { d_disabled = setting; } - - /*! - \brief - Set whether this item will be automatically deleted when it is removed - from the tree, or when the tree it is attached to is destroyed. - - \param setting - - true if the item object should be deleted by the system when the it - is removed from the tree, or when the tree it is attached to is - destroyed. - - false if client code will destroy the item after it is removed from - the tree. - - \return - Nothing. - */ - void setAutoDeleted(bool setting) - { d_autoDelete = setting; } - - /*! - \brief - Set the owner window for this TreeItem. This is called by the tree - widget when an item is added or inserted. - - \param owner - Ponter to the window that should be considered the owner of this - TreeItem. - - \return - Nothing - */ - void setOwnerWindow(const Window* owner) - { d_owner = owner; } - - /*! - \brief - Set the colours used for selection highlighting. - - \param cols - ColourRect object describing the colours to be used. - - \return - Nothing. - */ - void setSelectionColours(const ColourRect& cols) - { d_selectCols = cols; } - - - /*! - \brief - Set the colours used for selection highlighting. - - \param top_left_colour - Colour (as ARGB value) to be applied to the top-left corner of the - selection area. - - \param top_right_colour - Colour (as ARGB value) to be applied to the top-right corner of the - selection area. - - \param bottom_left_colour - Colour (as ARGB value) to be applied to the bottom-left corner of the - selection area. - - \param bottom_right_colour - Colour (as ARGB value) to be applied to the bottom-right corner of the - selection area. - - \return - Nothing. - */ - void setSelectionColours(Colour top_left_colour, - Colour top_right_colour, - Colour bottom_left_colour, - Colour bottom_right_colour); - - /*! - \brief - Set the colours used for selection highlighting. - - \param col - colour value to be used when rendering. - - \return - Nothing. - */ - void setSelectionColours(Colour col) - { setSelectionColours(col, col, col, col); } - - - /*! - \brief - Set the selection highlighting brush image. - - \param image - Pointer to the Image object to be used for selection highlighting. - - \return - Nothing. - */ - void setSelectionBrushImage(const Image* image) - { d_selectBrush = image; } - - - /*! - \brief - Set the selection highlighting brush image. - - \param name - Name of the image to be used. - - \return - Nothing. - */ - void setSelectionBrushImage(const String& name); - - /*! - \brief - Tell the treeItem where its button is located. - Calculated and set in Tree.cpp. - - \param buttonOffset - Location of the button in screenspace. - */ - void setButtonLocation(Rectf& buttonOffset) - { d_buttonLocation = buttonOffset; } - - Rectf& getButtonLocation(void) - { return d_buttonLocation; } - - bool getIsOpen(void) - { return d_isOpen; } - - void toggleIsOpen(void) - { d_isOpen = !d_isOpen; } - - TreeItem *getTreeItemFromIndex(size_t itemIndex); - - size_t getItemCount(void) const - { return d_listItems.size(); } - - LBItemList &getItemList(void) - { return d_listItems; } - - void addItem(TreeItem* item); - void removeItem(const TreeItem* item); - - void setIcon(const Image &theIcon) - { d_iconImage = &theIcon; } - - /************************************************************************* - Abstract portion of interface - *************************************************************************/ - /*! - \brief - Return the rendered pixel size of this tree item. - - \return - Size object describing the size of the tree item in pixels. - */ - virtual Sizef getPixelSize(void) const; - - /*! - \brief - Draw the tree item in its current state - - \param position - Vector2 object describing the upper-left corner of area that should be - rendered in to for the draw operation. - - \param alpha - Alpha value to be used when rendering the item (between 0.0f and 1.0f). - - \param clipper - Rect object describing the clipping rectangle for the draw operation. - - \return - Nothing. - */ - virtual void draw(GeometryBuffer& buffer, const Rectf& targetRect, - float alpha, const Rectf* clipper) const; - - /*! - \brief - Perform any updates needed because the given font's render size has - changed. - - \param font - Pointer to the Font whose render size has changed. - - \return - - true if some action was taken. - - false if no action was taken (i.e font is not used here). - */ - virtual bool handleFontRenderSizeChange(const Font* const font); - - /************************************************************************* - Operators - *************************************************************************/ - /*! - \brief - Less-than operator, compares item texts. - */ - virtual bool operator<(const TreeItem& rhs) const - { return getText() < rhs.getText(); } - - /*! - \brief - Greater-than operator, compares item texts. - */ - virtual bool operator>(const TreeItem& rhs) const - { return getText() > rhs.getText(); } - -protected: - /************************************************************************* - Implementation methods - *************************************************************************/ - /*! - \brief - Return a ColourRect object describing the colours in \a cols after - having their alpha component modulated by the value \a alpha. - */ - ColourRect getModulateAlphaColourRect(const ColourRect& cols, - float alpha) const; - - /*! - \brief - Return a colour value describing the colour specified by \a col after - having its alpha component modulated by the value \a alpha. - */ - Colour calculateModulatedAlphaColour(Colour col, float alpha) const; - - //! parse the text visual string into a RenderString representation. - void parseTextString() const; - - /************************************************************************* - Implementation Data - *************************************************************************/ - //! Text for this tree item. If not rendered, still used for sorting. - String d_textLogical; //!< text rendered by this component. - //! pointer to bidirection support object - BidiVisualMapping* d_bidiVisualMapping; - //! whether bidi visual mapping has been updated since last text change. - mutable bool d_bidiDataValid; - //! Text for the individual tooltip of this item. - String d_tooltipText; - //! ID code assigned by client code. - uint d_itemID; - //! Pointer to some client code data. - void* d_itemData; - //! true if item is selected. false if item is not selected. - bool d_selected; - //! true if item is disabled. false if item is not disabled. - bool d_disabled; - //! true if the system will destroy this item, false if client code will. - bool d_autoDelete; - //! Location of the 'expand' button for the item. - Rectf d_buttonLocation; - //! Pointer to the window that owns this item. - const Window* d_owner; - //! Colours used for selection highlighting. - ColourRect d_selectCols; - //! Image used for rendering selection. - const Image* d_selectBrush; - //! Colours used for rendering the text. - ColourRect d_textCols; - //! Font used for rendering text. - const Font* d_font; - //! Image for the icon to be displayed with this TreeItem. - const Image* d_iconImage; - //! list of items in this item's tree branch. - LBItemList d_listItems; - //! true if the this item's tree branch is opened. - bool d_isOpen; - //! Parser used to produce a final RenderedString from the standard String. - static BasicRenderedStringParser d_stringParser; - //! RenderedString drawn by this item. - mutable RenderedString d_renderedString; - //! boolean used to track when item state changes (and needs re-parse) - mutable bool d_renderedStringValid; -}; - -} // End of CEGUI namespace section - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - -#endif // end of guard _CEGUITreeItem_h_ diff --git a/cegui/include/CEGUI/widgets/TreeWidget.h b/cegui/include/CEGUI/widgets/TreeWidget.h new file mode 100644 index 000000000..ddedc76d5 --- /dev/null +++ b/cegui/include/CEGUI/widgets/TreeWidget.h @@ -0,0 +1,63 @@ +/*********************************************************************** + created: Wed Aug 07 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CEGUITreeWidget_h_ +#define _CEGUITreeWidget_h_ + +#include "CEGUI/views/TreeView.h" +#include "CEGUI/views/StandardItemModel.h" + +namespace CEGUI +{ + +/*! +\brief + This is a convenience widget as an alternative to the new tree view, for + simple scenarios that don't require a custom ItemModel implementation. + + This is a direct alternative to the old Tree widget. +*/ +class CEGUIEXPORT TreeWidget : public TreeView +{ +public: + //! Window factory name + static const String WidgetTypeName; + //! Namespace for global events + static const String EventNamespace; + + TreeWidget(const String& type, const String& name); + virtual ~TreeWidget(); + + virtual StandardItemModel* getModel(); + + void addItem(StandardItem* item); +protected: + virtual void initialiseComponents(); + StandardItemModel d_itemModel; +}; + +} +#endif diff --git a/cegui/src/Affector.cpp b/cegui/src/Affector.cpp index 1003a1634..70c394a2a 100644 --- a/cegui/src/Affector.cpp +++ b/cegui/src/Affector.cpp @@ -132,7 +132,7 @@ KeyFrame* Affector::createKeyFrame(float position) "already is a KeyFrame on that position.")); } - KeyFrame* ret = CEGUI_NEW_AO KeyFrame(this, position); + KeyFrame* ret = new KeyFrame(this, position); d_keyFrames.insert(std::make_pair(position, ret)); return ret; @@ -163,7 +163,7 @@ void Affector::destroyKeyFrame(KeyFrame* keyframe) } d_keyFrames.erase(it); - CEGUI_DELETE_AO keyframe; + delete keyframe; } //----------------------------------------------------------------------------// diff --git a/cegui/src/AndroidUtils.cpp b/cegui/src/AndroidUtils.cpp new file mode 100644 index 000000000..93d30be69 --- /dev/null +++ b/cegui/src/AndroidUtils.cpp @@ -0,0 +1,47 @@ +/*********************************************************************** + created: 25/09/2014 + author: David Reepmeyer + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/AndroidUtils.h" + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +android_app* AndroidUtils::app = 0; + +//----------------------------------------------------------------------------// +android_app* AndroidUtils::getAndroidApp() { + return app; +} + +//----------------------------------------------------------------------------// +void AndroidUtils::setAndroidApp(android_app* androidapp) { + app = androidapp; +} + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section diff --git a/cegui/src/Animation.cpp b/cegui/src/Animation.cpp index 7bdddd085..7d7d1f87c 100644 --- a/cegui/src/Animation.cpp +++ b/cegui/src/Animation.cpp @@ -107,7 +107,7 @@ Affector* Animation::createAffector(void) { // no checking needed! - Affector* ret = CEGUI_NEW_AO Affector(this); + Affector* ret = new Affector(this); d_affectors.push_back(ret); return ret; @@ -136,7 +136,7 @@ void Animation::destroyAffector(Affector* affector) } d_affectors.erase(it); - CEGUI_DELETE_AO affector; + delete affector; } //----------------------------------------------------------------------------// diff --git a/cegui/src/AnimationManager.cpp b/cegui/src/AnimationManager.cpp index 1514b1c3d..64b7342bd 100644 --- a/cegui/src/AnimationManager.cpp +++ b/cegui/src/AnimationManager.cpp @@ -35,6 +35,7 @@ #include "CEGUI/System.h" #include "CEGUI/XMLParser.h" #include "CEGUI/Animation_xmlHandler.h" +#include "CEGUI/Quaternion.h" // Start of CEGUI namespace section namespace CEGUI @@ -64,23 +65,23 @@ AnimationManager::AnimationManager(void) # define addBasicInterpolator(i) { Interpolator* in = i; addInterpolator(in); d_basicInterpolators.push_back(in); } // create and add basic interpolators shipped with CEGUI - addBasicInterpolator(CEGUI_NEW_AO TplDiscreteRelativeInterpolator("String")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("float")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("int")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("uint")); - addBasicInterpolator(CEGUI_NEW_AO TplDiscreteInterpolator("bool")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("Sizef")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("Vector2f")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("Vector3f")); - addBasicInterpolator(CEGUI_NEW_AO QuaternionSlerpInterpolator()); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("Rectf")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("Colour")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("ColourRect")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("UDim")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("UVector2")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("URect")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("UBox")); - addBasicInterpolator(CEGUI_NEW_AO TplLinearInterpolator("USize")); + addBasicInterpolator(new TplDiscreteRelativeInterpolator("String")); + addBasicInterpolator(new TplLinearInterpolator("float")); + addBasicInterpolator(new TplLinearInterpolator("int")); + addBasicInterpolator(new TplLinearInterpolator("uint")); + addBasicInterpolator(new TplDiscreteInterpolator("bool")); + addBasicInterpolator(new TplLinearInterpolator("Sizef")); + addBasicInterpolator(new TplLinearInterpolator("vec2")); + addBasicInterpolator(new TplLinearInterpolator("vec3")); + addBasicInterpolator(new QuaternionSlerpInterpolator()); + addBasicInterpolator(new TplLinearInterpolator("Rectf")); + addBasicInterpolator(new TplLinearInterpolator("Colour")); + addBasicInterpolator(new TplLinearInterpolator("ColourRect")); + addBasicInterpolator(new TplLinearInterpolator("UDim")); + addBasicInterpolator(new TplLinearInterpolator("UVector2")); + addBasicInterpolator(new TplLinearInterpolator("URect")); + addBasicInterpolator(new TplLinearInterpolator("UBox")); + addBasicInterpolator(new TplLinearInterpolator("USize")); } @@ -100,7 +101,7 @@ AnimationManager::~AnimationManager() for (BasicInterpolatorList::const_iterator it = d_basicInterpolators.begin(); it != d_basicInterpolators.end(); ++it) { - CEGUI_DELETE_AO *it; + delete *it; } d_basicInterpolators.clear(); @@ -163,7 +164,7 @@ Animation* AnimationManager::createAnimation(const String& name) String finalName(name.empty() ? generateUniqueAnimationName() : name); - Animation* ret = CEGUI_NEW_AO Animation(finalName); + Animation* ret = new Animation(finalName); d_animations.insert(std::make_pair(finalName, ret)); return ret; @@ -190,7 +191,7 @@ void AnimationManager::destroyAnimation(const String& name) destroyAllInstancesOfAnimation(animation); d_animations.erase(it); - CEGUI_DELETE_AO animation; + delete animation; } //----------------------------------------------------------------------------// @@ -204,7 +205,7 @@ void AnimationManager::destroyAllAnimations() for (AnimationMap::const_iterator it = d_animations.begin(); it != d_animations.end(); ++it) { - CEGUI_DELETE_AO it->second; + delete it->second; } d_animations.clear(); @@ -259,7 +260,7 @@ AnimationInstance* AnimationManager::instantiateAnimation(Animation* animation) "animation, please provide a valid pointer.")); } - AnimationInstance* ret = CEGUI_NEW_AO AnimationInstance(animation); + AnimationInstance* ret = new AnimationInstance(animation); d_animationInstances.insert(std::make_pair(animation, ret)); return ret; @@ -282,7 +283,7 @@ void AnimationManager::destroyAnimationInstance(AnimationInstance* instance) if (it->second == instance) { d_animationInstances.erase(it); - CEGUI_DELETE_AO instance; + delete instance; return; } } @@ -301,7 +302,7 @@ void AnimationManager::destroyAllInstancesOfAnimation(Animation* animation) AnimationInstanceMap::iterator toErase = it; ++it; - CEGUI_DELETE_AO toErase->second; + delete toErase->second; d_animationInstances.erase(toErase); } } @@ -312,7 +313,7 @@ void AnimationManager::destroyAllAnimationInstances() for (AnimationInstanceMap::const_iterator it = d_animationInstances.begin(); it != d_animationInstances.end(); ++it) { - CEGUI_DELETE_AO it->second; + delete it->second; } d_animationInstances.clear(); diff --git a/cegui/src/Animation_xmlHandler.cpp b/cegui/src/Animation_xmlHandler.cpp index ed865939d..e29b61d28 100644 --- a/cegui/src/Animation_xmlHandler.cpp +++ b/cegui/src/Animation_xmlHandler.cpp @@ -103,7 +103,7 @@ void Animation_xmlHandler::elementStartLocal(const String& element, } else if (element == AnimationDefinitionHandler::ElementName) { - d_chainedHandler = CEGUI_NEW_AO AnimationDefinitionHandler(attributes, ""); + d_chainedHandler = new AnimationDefinitionHandler(attributes, ""); } else Logger::getSingleton().logEvent("Animation_xmlHandler::elementStart: " @@ -169,9 +169,9 @@ void AnimationDefinitionHandler::elementStartLocal( const XMLAttributes& attributes) { if (element == AnimationAffectorHandler::ElementName) - d_chainedHandler = CEGUI_NEW_AO AnimationAffectorHandler(attributes, *d_anim); + d_chainedHandler = new AnimationAffectorHandler(attributes, *d_anim); else if (element == AnimationSubscriptionHandler::ElementName) - d_chainedHandler = CEGUI_NEW_AO AnimationSubscriptionHandler(attributes, *d_anim); + d_chainedHandler = new AnimationSubscriptionHandler(attributes, *d_anim); else Logger::getSingleton().logEvent( "AnimationDefinitionHandler::elementStart: " @@ -232,7 +232,7 @@ void AnimationAffectorHandler::elementStartLocal( const XMLAttributes& attributes) { if (element == AnimationKeyFrameHandler::ElementName) - d_chainedHandler = CEGUI_NEW_AO AnimationKeyFrameHandler(attributes, *d_affector); + d_chainedHandler = new AnimationKeyFrameHandler(attributes, *d_affector); else Logger::getSingleton().logEvent( "AnimationAffectorHandler::elementStart: " diff --git a/cegui/src/BasicImage.cpp b/cegui/src/BasicImage.cpp deleted file mode 100644 index 79691fb19..000000000 --- a/cegui/src/BasicImage.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/*********************************************************************** - created: Wed Feb 16 2011 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/BasicImage.h" -#include "CEGUI/GeometryBuffer.h" -#include "CEGUI/Texture.h" -#include "CEGUI/Vertex.h" -#include "CEGUI/ColourRect.h" -#include "CEGUI/XMLAttributes.h" -#include "CEGUI/System.h" // this being here is a bit nasty IMO -#include "CEGUI/CoordConverter.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -const String ImageTypeAttribute( "type" ); -const String ImageNameAttribute( "name" ); -const String ImageTextureAttribute( "texture" ); -const String ImageXPosAttribute( "xPos" ); -const String ImageYPosAttribute( "yPos" ); -const String ImageWidthAttribute( "width" ); -const String ImageHeightAttribute( "height" ); -const String ImageXOffsetAttribute( "xOffset" ); -const String ImageYOffsetAttribute( "yOffset" ); -const String ImageAutoScaledAttribute( "autoScaled" ); -const String ImageNativeHorzResAttribute( "nativeHorzRes" ); -const String ImageNativeVertResAttribute( "nativeVertRes" ); - -//----------------------------------------------------------------------------// -BasicImage::BasicImage(const String& name) : - d_name(name), - d_texture(0), - d_pixelSize(0, 0), - d_area(0.0f, 0.0f, 0.0f, 0.0f), - d_pixelOffset(0.0f, 0.0f), - d_autoScaled(ASM_Disabled), - d_nativeResolution(640, 480), - d_scaledSize(0, 0), - d_scaledOffset(0, 0) -{ -} - -//----------------------------------------------------------------------------// -BasicImage::BasicImage(const XMLAttributes& attributes) : - d_name(attributes.getValueAsString(ImageNameAttribute)), - d_texture(&System::getSingleton().getRenderer()->getTexture( - attributes.getValueAsString(ImageTextureAttribute))), - d_pixelSize(static_cast(attributes.getValueAsInteger(ImageWidthAttribute, 0)), - static_cast(attributes.getValueAsInteger(ImageHeightAttribute, 0))), - d_area(Vector2f(static_cast(attributes.getValueAsInteger(ImageXPosAttribute, 0)), - static_cast(attributes.getValueAsInteger(ImageYPosAttribute, 0))), - d_pixelSize), - d_pixelOffset(Vector2f( - static_cast(attributes.getValueAsInteger(ImageXOffsetAttribute, 0)), - static_cast(attributes.getValueAsInteger(ImageYOffsetAttribute, 0)))), - d_nativeResolution(Sizef( - static_cast(attributes.getValueAsInteger(ImageNativeHorzResAttribute, 640)), - static_cast(attributes.getValueAsInteger(ImageNativeVertResAttribute, 480)))) -{ - d_autoScaled = PropertyHelper::fromString(attributes.getValueAsString(ImageAutoScaledAttribute)); - - // force initialisation of the autoscaling fields. - updateScaledSizeAndOffset( - System::getSingleton().getRenderer()->getDisplaySize()); -} - -//----------------------------------------------------------------------------// -BasicImage::BasicImage(const String& name, Texture* texture, - const Rectf& pixel_area, const Vector2f& pixel_offset, - const AutoScaledMode autoscaled, const Sizef& native_res) : - d_name(name), - d_texture(texture), - d_pixelSize(pixel_area.getSize()), - d_area(pixel_area), - d_pixelOffset(pixel_offset), - d_autoScaled(autoscaled), - d_nativeResolution(native_res) - -{ - // force initialisation of the autoscaling fields. - updateScaledSizeAndOffset( - System::getSingleton().getRenderer()->getDisplaySize()); -} - -//----------------------------------------------------------------------------// -void BasicImage::setTexture(Texture* texture) -{ - d_texture = texture; -} - -//----------------------------------------------------------------------------// -void BasicImage::setArea(const Rectf& pixel_area) -{ - d_area = pixel_area; - d_pixelSize = pixel_area.getSize(); - - if (d_autoScaled != ASM_Disabled) - updateScaledSize( - System::getSingleton().getRenderer()->getDisplaySize()); - else - d_scaledSize = d_pixelSize; -} - -//----------------------------------------------------------------------------// -void BasicImage::setOffset(const Vector2f& pixel_offset) -{ - d_pixelOffset = pixel_offset; - - if (d_autoScaled != ASM_Disabled) - updateScaledOffset( - System::getSingleton().getRenderer()->getDisplaySize()); - else - d_scaledOffset = d_pixelOffset; -} - -//----------------------------------------------------------------------------// -void BasicImage::setAutoScaled(const AutoScaledMode autoscaled) -{ - d_autoScaled = autoscaled; - - if (d_autoScaled != ASM_Disabled) - { - updateScaledSizeAndOffset( - System::getSingleton().getRenderer()->getDisplaySize()); - } - else - { - d_scaledSize = d_pixelSize; - d_scaledOffset = d_pixelOffset; - } -} - -//----------------------------------------------------------------------------// -void BasicImage::setNativeResolution(const Sizef& native_res) -{ - d_nativeResolution = native_res; - - if (d_autoScaled != ASM_Disabled) - updateScaledSizeAndOffset( - System::getSingleton().getRenderer()->getDisplaySize()); -} - -//----------------------------------------------------------------------------// -const String& BasicImage::getName() const -{ - return d_name; -} - -//----------------------------------------------------------------------------// -const Sizef& BasicImage::getRenderedSize() const -{ - return d_scaledSize; -} - -//----------------------------------------------------------------------------// -const Vector2f& BasicImage::getRenderedOffset() const -{ - return d_scaledOffset; -} - -//----------------------------------------------------------------------------// -void BasicImage::render(GeometryBuffer& buffer, const Rectf& dest_area, - const Rectf* clip_area, const ColourRect& colours) const -{ - const QuadSplitMode quad_split_mode(TopLeftToBottomRight); - - Rectf dest(dest_area); - // apply rendering offset to the destination Rect - dest.offset(d_scaledOffset); - - // get the rect area that we will actually draw to (i.e. perform clipping) - Rectf final_rect(clip_area ? dest.getIntersection(*clip_area) : dest ); - - // check if rect was totally clipped - if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0)) - return; - - // Obtain correct scale values from the texture - const Vector2f& scale = d_texture->getTexelScaling(); - const Vector2f tex_per_pix(d_area.getWidth() / dest.getWidth(), d_area.getHeight() / dest.getHeight()); - - // calculate final, clipped, texture co-ordinates - const Rectf tex_rect((d_area.d_min + ((final_rect.d_min - dest.d_min) * tex_per_pix)) * scale, - (d_area.d_max + ((final_rect.d_max - dest.d_max) * tex_per_pix)) * scale); - - // URGENT FIXME: Shouldn't this be in the hands of the user? - final_rect.d_min.d_x = CoordConverter::alignToPixels(final_rect.d_min.d_x); - final_rect.d_min.d_y = CoordConverter::alignToPixels(final_rect.d_min.d_y); - final_rect.d_max.d_x = CoordConverter::alignToPixels(final_rect.d_max.d_x); - final_rect.d_max.d_y = CoordConverter::alignToPixels(final_rect.d_max.d_y); - - Vertex vbuffer[6]; - - // vertex 0 - vbuffer[0].position = Vector3f(final_rect.left(), final_rect.top(), 0.0f); - vbuffer[0].colour_val = colours.d_top_left; - vbuffer[0].tex_coords = Vector2f(tex_rect.left(), tex_rect.top()); - - // vertex 1 - vbuffer[1].position = Vector3f(final_rect.left(), final_rect.bottom(), 0.0f); - vbuffer[1].colour_val = colours.d_bottom_left; - vbuffer[1].tex_coords = Vector2f(tex_rect.left(), tex_rect.bottom()); - - // vertex 2 - vbuffer[2].position.d_x = final_rect.right(); - vbuffer[2].position.d_z = 0.0f; - vbuffer[2].colour_val = colours.d_bottom_right; - vbuffer[2].tex_coords.d_x = tex_rect.right(); - - // top-left to bottom-right diagonal - if (quad_split_mode == TopLeftToBottomRight) - { - vbuffer[2].position.d_y = final_rect.bottom(); - vbuffer[2].tex_coords.d_y = tex_rect.bottom(); - } - // bottom-left to top-right diagonal - else - { - vbuffer[2].position.d_y = final_rect.top(); - vbuffer[2].tex_coords.d_y = tex_rect.top(); - } - - // vertex 3 - vbuffer[3].position = Vector3f(final_rect.right(), final_rect.top(), 0.0f); - vbuffer[3].colour_val = colours.d_top_right; - vbuffer[3].tex_coords = Vector2f(tex_rect.right(), tex_rect.top()); - - // vertex 4 - vbuffer[4].position.d_x = final_rect.left(); - vbuffer[4].position.d_z = 0.0f; - vbuffer[4].colour_val = colours.d_top_left; - vbuffer[4].tex_coords.d_x = tex_rect.left(); - - // top-left to bottom-right diagonal - if (quad_split_mode == TopLeftToBottomRight) - { - vbuffer[4].position.d_y = final_rect.top(); - vbuffer[4].tex_coords.d_y = tex_rect.top(); - } - // bottom-left to top-right diagonal - else - { - vbuffer[4].position.d_y = final_rect.bottom(); - vbuffer[4].tex_coords.d_y = tex_rect.bottom(); - } - - // vertex 5 - vbuffer[5].position = Vector3f(final_rect.right(), final_rect.bottom(), 0.0f); - vbuffer[5].colour_val= colours.d_bottom_right; - vbuffer[5].tex_coords = Vector2f(tex_rect.right(), tex_rect.bottom()); - - buffer.setActiveTexture(d_texture); - buffer.appendGeometry(vbuffer, 6); -} - -//----------------------------------------------------------------------------// -void BasicImage::notifyDisplaySizeChanged(const Sizef& renderer_display_size) -{ - //If we use autoscaling of any sort we must update the scaled size and offset - if (d_autoScaled != ASM_Disabled) - updateScaledSizeAndOffset(renderer_display_size); -} - -//----------------------------------------------------------------------------// - -void BasicImage::updateScaledSizeAndOffset(const Sizef& renderer_display_size) -{ - Vector2f scaleFactors; - - computeScalingFactors(d_autoScaled, renderer_display_size, d_nativeResolution, - scaleFactors.d_x, scaleFactors.d_y); - - d_scaledSize = d_pixelSize * scaleFactors; - d_scaledOffset = d_pixelOffset * scaleFactors; -} - -//----------------------------------------------------------------------------// -void BasicImage::updateScaledSize(const Sizef& renderer_display_size) -{ - Vector2f scaleFactors; - - computeScalingFactors(d_autoScaled, renderer_display_size, d_nativeResolution, - scaleFactors.d_x, scaleFactors.d_y); - - d_scaledSize = d_pixelSize * scaleFactors; -} - -//----------------------------------------------------------------------------// -void BasicImage::updateScaledOffset(const Sizef& renderer_display_size) -{ - Vector2f scaleFactors; - - computeScalingFactors(d_autoScaled, renderer_display_size, d_nativeResolution, - scaleFactors.d_x, scaleFactors.d_y); - - d_scaledOffset = d_pixelOffset * scaleFactors; -} - -} // End of CEGUI namespace section - diff --git a/cegui/src/BitmapImage.cpp b/cegui/src/BitmapImage.cpp new file mode 100644 index 000000000..7dda7ed28 --- /dev/null +++ b/cegui/src/BitmapImage.cpp @@ -0,0 +1,209 @@ +/*********************************************************************** + created: Wed Feb 16 2011 + author: Paul D Turner +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/BitmapImage.h" +#include "CEGUI/GeometryBuffer.h" +#include "CEGUI/Texture.h" +#include "CEGUI/Vertex.h" +#include "CEGUI/ColourRect.h" +#include "CEGUI/XMLAttributes.h" +#include "CEGUI/System.h" // this being here is a bit nasty IMO +#include "CEGUI/CoordConverter.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +const String ImageTypeAttribute( "type" ); +const String ImageNameAttribute( "name" ); +const String ImageTextureAttribute( "texture" ); +const String ImageXPosAttribute( "xPos" ); +const String ImageYPosAttribute( "yPos" ); +const String ImageWidthAttribute( "width" ); +const String ImageHeightAttribute( "height" ); +const String ImageXOffsetAttribute( "xOffset" ); +const String ImageYOffsetAttribute( "yOffset" ); +const String ImageAutoScaledAttribute( "autoScaled" ); +const String ImageNativeHorzResAttribute( "nativeHorzRes" ); +const String ImageNativeVertResAttribute( "nativeVertRes" ); + +//----------------------------------------------------------------------------// +BitmapImage::BitmapImage(const String& name) : + Image(name), + d_texture(0) +{ +} + +//----------------------------------------------------------------------------// +BitmapImage::BitmapImage(const XMLAttributes& attributes) : + Image(attributes.getValueAsString(ImageNameAttribute), + glm::vec2(static_cast(attributes.getValueAsInteger(ImageXOffsetAttribute, 0)), + static_cast(attributes.getValueAsInteger(ImageYOffsetAttribute, 0))), + Rectf(glm::vec2(static_cast(attributes.getValueAsInteger(ImageXPosAttribute, 0)), + static_cast(attributes.getValueAsInteger(ImageYPosAttribute, 0))), + Sizef(static_cast(attributes.getValueAsInteger(ImageWidthAttribute, 0)), + static_cast(attributes.getValueAsInteger(ImageHeightAttribute, 0)))), + PropertyHelper::fromString(attributes.getValueAsString(ImageAutoScaledAttribute)), + Sizef(static_cast(attributes.getValueAsInteger(ImageNativeHorzResAttribute, 640)), + static_cast(attributes.getValueAsInteger(ImageNativeVertResAttribute, 480)))), + d_texture(&System::getSingleton().getRenderer()->getTexture( + attributes.getValueAsString(ImageTextureAttribute))) +{ +} + +//----------------------------------------------------------------------------// +BitmapImage::BitmapImage(const String& name, Texture* texture, + const Rectf& pixel_area, const glm::vec2& pixel_offset, + const AutoScaledMode autoscaled, const Sizef& native_res) : + Image(name, + pixel_offset, + pixel_area, + autoscaled, + native_res), + d_texture(texture) +{} + +//----------------------------------------------------------------------------// +void BitmapImage::setTexture(Texture* texture) +{ + d_texture = texture; +} + +//----------------------------------------------------------------------------// +void BitmapImage::render(std::vector& geometry_buffers, + const ImageRenderSettings& render_settings) const +{ + const QuadSplitMode quad_split_mode(TopLeftToBottomRight); + + Rectf dest(render_settings.d_destArea); + // apply rendering offset to the destination Rect + dest.offset(d_scaledOffset); + + const CEGUI::Rectf*const& clip_area = render_settings.d_clipArea; + // get the rect area that we will actually draw to (i.e. perform clipping) + Rectf final_rect(clip_area ? dest.getIntersection(*clip_area) : dest ); + + // check if rect was totally clipped + if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0)) + return; + + // Obtain correct scale values from the texture + const glm::vec2& texel_scale = d_texture->getTexelScaling(); + const glm::vec2 tex_per_pix(d_imageArea.getWidth() / dest.getWidth(), d_imageArea.getHeight() / dest.getHeight()); + + // calculate final, clipped, texture co-ordinates + const Rectf tex_rect((d_imageArea + ((final_rect - dest) * tex_per_pix)) * texel_scale); + + // URGENT FIXME: Shouldn't this be in the hands of the user? + final_rect.d_min.d_x = CoordConverter::alignToPixels(final_rect.d_min.d_x); + final_rect.d_min.d_y = CoordConverter::alignToPixels(final_rect.d_min.d_y); + final_rect.d_max.d_x = CoordConverter::alignToPixels(final_rect.d_max.d_x); + final_rect.d_max.d_y = CoordConverter::alignToPixels(final_rect.d_max.d_y); + + TexturedColouredVertex vbuffer[6]; + const CEGUI::ColourRect& colours = render_settings.d_multiplyColours; + + // vertex 0 + vbuffer[0].setColour(colours.d_top_left); + vbuffer[0].d_position = glm::vec3(final_rect.left(), final_rect.top(), 0.0f); + vbuffer[0].d_texCoords = glm::vec2(tex_rect.left(), tex_rect.top()); + + // vertex 1 + vbuffer[1].setColour(colours.d_bottom_left); + vbuffer[1].d_position = glm::vec3(final_rect.left(), final_rect.bottom(), 0.0f); + vbuffer[1].d_texCoords = glm::vec2(tex_rect.left(), tex_rect.bottom()); + + // vertex 2 + vbuffer[2].setColour(colours.d_bottom_right); + vbuffer[2].d_position.x = final_rect.right(); + vbuffer[2].d_position.z = 0.0f; + vbuffer[2].d_texCoords.x = tex_rect.right(); + + // top-left to bottom-right diagonal + if (quad_split_mode == TopLeftToBottomRight) + { + vbuffer[2].d_position.y = final_rect.bottom(); + vbuffer[2].d_texCoords.y = tex_rect.bottom(); + } + // bottom-left to top-right diagonal + else + { + vbuffer[2].d_position.y = final_rect.top(); + vbuffer[2].d_texCoords.y = tex_rect.top(); + } + + // vertex 3 + vbuffer[3].setColour(colours.d_top_right); + vbuffer[3].d_position = glm::vec3(final_rect.right(), final_rect.top(), 0.0f); + vbuffer[3].d_texCoords = glm::vec2(tex_rect.right(), tex_rect.top()); + + // vertex 4 + vbuffer[4].setColour(colours.d_top_left); + vbuffer[4].d_position.x = final_rect.left(); + vbuffer[4].d_position.z = 0.0f; + vbuffer[4].d_texCoords.x = tex_rect.left(); + + // top-left to bottom-right diagonal + if (quad_split_mode == TopLeftToBottomRight) + { + vbuffer[4].d_position.y = final_rect.top(); + vbuffer[4].d_texCoords.y = tex_rect.top(); + } + // bottom-left to top-right diagonal + else + { + vbuffer[4].d_position.y = final_rect.bottom(); + vbuffer[4].d_texCoords.y = tex_rect.bottom(); + } + + // vertex 5 + vbuffer[5].setColour(colours.d_bottom_right); + vbuffer[5].d_position = glm::vec3(final_rect.right(), final_rect.bottom(), 0.0f); + vbuffer[5].d_texCoords = glm::vec2(tex_rect.right(), tex_rect.bottom()); + + CEGUI::GeometryBuffer& buffer = System::getSingleton().getRenderer()->createGeometryBufferTextured(); + geometry_buffers.push_back(&buffer); + + buffer.setClippingActive(render_settings.d_clippingEnabled); + if(render_settings.d_clippingEnabled) + buffer.setClippingRegion(*render_settings.d_clipArea); + buffer.setTexture("texture0", d_texture); + buffer.appendGeometry(vbuffer, 6); + buffer.setAlpha(render_settings.d_alpha); +} + + + + +//----------------------------------------------------------------------------// +const Texture* BitmapImage::getTexture() const +{ + return d_texture; +} + +} // End of CEGUI namespace section + diff --git a/cegui/src/BoundSlot.cpp b/cegui/src/BoundSlot.cpp index 6731f5252..d1bbb74d6 100644 --- a/cegui/src/BoundSlot.cpp +++ b/cegui/src/BoundSlot.cpp @@ -32,7 +32,7 @@ namespace CEGUI { BoundSlot::BoundSlot(Group group, const SubscriberSlot& subscriber, Event& event) : d_group(group), - d_subscriber(CEGUI_NEW_AO SubscriberSlot(subscriber)), + d_subscriber(new SubscriberSlot(subscriber)), d_event(&event) {} @@ -47,7 +47,7 @@ BoundSlot::BoundSlot(const BoundSlot& other) : BoundSlot::~BoundSlot() { disconnect(); - CEGUI_DELETE_AO d_subscriber; + delete d_subscriber; } diff --git a/cegui/src/CMakeLists.txt b/cegui/src/CMakeLists.txt index d1bbfbc15..aa294a259 100644 --- a/cegui/src/CMakeLists.txt +++ b/cegui/src/CMakeLists.txt @@ -2,13 +2,17 @@ set( CEGUI_TARGET_NAME ${CEGUI_BASE_LIBNAME} ) # we do not use cegui_gather_files() here since our needs are more complex. file (GLOB CORE_SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" *.cpp) +file (GLOB VIEW_SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" views/*.cpp) file (GLOB WIDGET_SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" widgets/*.cpp) file (GLOB FALAGARD_SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" falagard/*.cpp) -set (CORE_SOURCE_FILES ${CORE_SOURCE_FILES} ${WIDGET_SOURCE_FILES} ${FALAGARD_SOURCE_FILES}) +file (GLOB SVG_SOURCE_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" svg/*.cpp) +set (CORE_SOURCE_FILES ${CORE_SOURCE_FILES} ${VIEW_SOURCE_FILES} ${WIDGET_SOURCE_FILES} ${FALAGARD_SOURCE_FILES} ${SVG_SOURCE_FILES}) file (GLOB CORE_HEADER_FILES ../include/CEGUI/*.h) +file (GLOB VIEW_HEADER_FILES ../include/CEGUI/views/*.h) file (GLOB WIDGET_HEADER_FILES ../include/CEGUI/widgets/*.h) file (GLOB FALAGARD_HEADER_FILES ../include/CEGUI/falagard/*.h) +file (GLOB SVG_HEADER_FILES ../include/CEGUI/svg/*.h) list (APPEND CORE_HEADER_FILES ${CMAKE_CURRENT_BINARY_DIR}/../include/CEGUI/Config.h @@ -18,7 +22,7 @@ list (APPEND CORE_HEADER_FILES # We don't append all to CORE_HEADER_FILES since that would mess up installation # on systems where files are installed. -set (ALL_HEADER_FILES ${CORE_HEADER_FILES} ${WIDGET_HEADER_FILES} ${FALAGARD_HEADER_FILES}) +set (ALL_HEADER_FILES ${CORE_HEADER_FILES} ${VIEW_HEADER_FILES} ${WIDGET_HEADER_FILES} ${FALAGARD_HEADER_FILES} ${SVG_HEADER_FILES}) # never compile this directly, it's included in another file list (REMOVE_ITEM CORE_SOURCE_FILES minibidi.cpp) @@ -53,16 +57,28 @@ else() list (REMOVE_ITEM CORE_SOURCE_FILES Win32StringTranscoder.cpp) endif() +if (NOT WIN32) + list (REMOVE_ITEM CORE_SOURCE_FILES Win32ClipboardProvider.cpp) +endif() + +if (NOT ANDROID) + list (REMOVE_ITEM CORE_SOURCE_FILES AndroidUtils.cpp) + list (REMOVE_ITEM CORE_HEADER_FILES AndroidUtils.h) +endif() # we do not use the common header install function since we need to install to # multiple sub-dirs. cegui_add_library_impl(${CEGUI_TARGET_NAME} FALSE CORE_SOURCE_FILES ALL_HEADER_FILES TRUE FALSE) +source_group("Source Files\\view" FILES ${VIEW_SOURCE_FILES}) source_group("Source Files\\widget" FILES ${WIDGET_SOURCE_FILES}) source_group("Source Files\\falagard" FILES ${FALAGARD_SOURCE_FILES}) +source_group("Source Files\\svg" FILES ${SVG_SOURCE_FILES}) +source_group("Header Files\\view" FILES ${VIEW_HEADER_FILES}) source_group("Header Files\\widget" FILES ${WIDGET_HEADER_FILES}) source_group("Header Files\\falagard" FILES ${FALAGARD_HEADER_FILES}) +source_group("Header Files\\svg" FILES ${SVG_HEADER_FILES}) if (NOT WIN32) cegui_add_dependency(${CEGUI_TARGET_NAME} ICONV) @@ -86,7 +102,7 @@ endif () if (WIN32 AND NOT MINGW) cegui_target_link_libraries(${CEGUI_TARGET_NAME} winmm debug DbgHelp) -elseif (UNIX AND NOT APPLE) +elseif (UNIX AND NOT APPLE AND NOT ANDROID) # This is intentionally not using 'cegui_target_link_libraries' target_link_libraries(${CEGUI_TARGET_NAME} ${CMAKE_DL_LIBS}) elseif (MINGW) @@ -98,6 +114,8 @@ if (APPLE AND CEGUI_BUILD_SHARED_LIBS_WITH_STATIC_DEPENDENCIES) endif() install(FILES ${CORE_HEADER_FILES} DESTINATION ${CEGUI_INCLUDE_INSTALL_DIR}/CEGUI) +install(FILES ${VIEW_HEADER_FILES} DESTINATION ${CEGUI_INCLUDE_INSTALL_DIR}/CEGUI/views) install(FILES ${WIDGET_HEADER_FILES} DESTINATION ${CEGUI_INCLUDE_INSTALL_DIR}/CEGUI/widgets) install(FILES ${FALAGARD_HEADER_FILES} DESTINATION ${CEGUI_INCLUDE_INSTALL_DIR}/CEGUI/falagard) +install(FILES ${SVG_HEADER_FILES} DESTINATION ${CEGUI_INCLUDE_INSTALL_DIR}/CEGUI/svg) diff --git a/cegui/src/CentredRenderedString.cpp b/cegui/src/CentredRenderedString.cpp index f19330b21..cc731c16a 100644 --- a/cegui/src/CentredRenderedString.cpp +++ b/cegui/src/CentredRenderedString.cpp @@ -48,19 +48,19 @@ void CentredRenderedString::format(const Window* ref_wnd, const Sizef& area_size } //----------------------------------------------------------------------------// -void CentredRenderedString::draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, +void CentredRenderedString::draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const { - Vector2f draw_pos; - draw_pos.d_y = position.d_y; + glm::vec2 draw_pos; + draw_pos.y = position.y; for (size_t i = 0; i < d_renderedString->getLineCount(); ++i) { - draw_pos.d_x = position.d_x + d_offsets[i]; - d_renderedString->draw(ref_wnd, i, buffer, draw_pos, mod_colours, clip_rect, 0.0f); - draw_pos.d_y += d_renderedString->getPixelSize(ref_wnd, i).d_height; + draw_pos.x = position.x + d_offsets[i]; + d_renderedString->draw(ref_wnd, i, geometry_buffers, draw_pos, mod_colours, clip_rect, 0.0f); + draw_pos.y += d_renderedString->getPixelSize(ref_wnd, i).d_height; } } diff --git a/cegui/src/ChainedXMLHandler.cpp b/cegui/src/ChainedXMLHandler.cpp index cf4c263a4..573bd1efb 100644 --- a/cegui/src/ChainedXMLHandler.cpp +++ b/cegui/src/ChainedXMLHandler.cpp @@ -33,7 +33,7 @@ namespace CEGUI ChainedXMLHandler::ChainedXMLHandler() : d_chainedHandler(0), d_completed(false), - d_deleteChaniedHandler(true) + d_deleteChainedHandler(true) { } @@ -99,8 +99,8 @@ bool ChainedXMLHandler::completed() const //----------------------------------------------------------------------------// void ChainedXMLHandler::cleanupChainedHandler() { - if (d_deleteChaniedHandler) - CEGUI_DELETE_AO d_chainedHandler; + if (d_deleteChainedHandler) + delete d_chainedHandler; d_chainedHandler = 0; } diff --git a/cegui/src/Clipboard.cpp b/cegui/src/Clipboard.cpp index 647ddaa0a..e1847fd3c 100644 --- a/cegui/src/Clipboard.cpp +++ b/cegui/src/Clipboard.cpp @@ -40,7 +40,6 @@ Clipboard::Clipboard(): d_mimeType("text/plain"), // reasonable default I think d_buffer(0), d_bufferSize(0), - d_nativeProvider(0) {} @@ -49,7 +48,7 @@ Clipboard::~Clipboard() { if (d_buffer != 0) { - CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); + delete[] d_buffer; } } @@ -74,12 +73,12 @@ void Clipboard::setData(const String& mimeType, const void* buffer, size_t size) { if (d_buffer != 0) { - CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); + delete[] d_buffer; d_buffer = 0; } d_bufferSize = size; - d_buffer = CEGUI_NEW_ARRAY_PT(BufferElement, d_bufferSize, Clipboard); + d_buffer = new BufferElement[d_bufferSize]; } memcpy(d_buffer, buffer, d_bufferSize); @@ -108,12 +107,12 @@ void Clipboard::getData(String& mimeType, const void*& buffer, size_t& size) { if (d_buffer != 0) { - CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); + delete[] d_buffer; d_buffer = 0; } d_bufferSize = retrievedSize; - d_buffer = CEGUI_NEW_ARRAY_PT(BufferElement, d_bufferSize, Clipboard); + d_buffer = new BufferElement[d_bufferSize]; } memcpy(d_buffer, retrievedBuffer, retrievedSize); diff --git a/cegui/src/CommonDialogs/ColourPicker/ColourPicker.cpp b/cegui/src/CommonDialogs/ColourPicker/ColourPicker.cpp index e370a369e..388607b5f 100644 --- a/cegui/src/CommonDialogs/ColourPicker/ColourPicker.cpp +++ b/cegui/src/CommonDialogs/ColourPicker/ColourPicker.cpp @@ -29,7 +29,7 @@ #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/Editbox.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/WindowManager.h" #include "CEGUI/Exceptions.h" #include "CEGUI/CoordConverter.h" @@ -95,7 +95,7 @@ void ColourPicker::initialiseComponents(void) Window* colourRect = getColourRect(); // bind handler to close button 'Click' event - colourRect->subscribeEvent(Window::EventMouseClick, + colourRect->subscribeEvent(Window::EventCursorActivate, Event::Subscriber(&ColourPicker::colourRect_ColourRectClickedHandler, this)); diff --git a/cegui/src/CommonDialogs/ColourPicker/Controls.cpp b/cegui/src/CommonDialogs/ColourPicker/Controls.cpp index 1bdfb9c34..8fa0f78f1 100644 --- a/cegui/src/CommonDialogs/ColourPicker/Controls.cpp +++ b/cegui/src/CommonDialogs/ColourPicker/Controls.cpp @@ -33,11 +33,11 @@ #include "CEGUI/widgets/Slider.h" #include "CEGUI/widgets/Thumb.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/WindowManager.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageManager.h" -#include "CEGUI/BasicImage.h" +#include "CEGUI/BitmapImage.h" #include "CEGUI/CoordConverter.h" #include "CEGUI/CommonDialogs/ColourPicker/ColourPicker.h" @@ -123,7 +123,7 @@ const String ColourPickerControls::ColourPickerCursorName("__colourpickercursor_ ColourPickerControls::ColourPickerControls(const String& type, const String& name) : Window(type, name), d_callingColourPicker(0), - d_colourPickerCursor(0), + d_colourPickerIndicator(0), d_sliderMode(SliderMode_Lab_L), d_selectedColour(0.75f, 0.75f, 0.75f), d_colourPickerControlsTextureTarget(0), @@ -135,7 +135,7 @@ ColourPickerControls::ColourPickerControls(const String& type, const String& nam d_colourPickerAlphaSliderImageWidth(260), d_colourPickerAlphaSliderImageHeight(60), d_colourPickerControlsTextureSize(512), - d_draggingColourPickerCursor(false), + d_draggingColourPickerIndicator(false), d_colourPickingTexture(new RGB_Colour[d_colourPickerControlsTextureSize * d_colourPickerControlsTextureSize]), d_ignoreEvents(false), @@ -148,8 +148,8 @@ ColourPickerControls::~ColourPickerControls() { deinitColourPickerControlsTexture(); - if (d_colourPickerCursor) - WindowManager::getSingleton().destroyWindow(d_colourPickerCursor); + if (d_colourPickerIndicator) + WindowManager::getSingleton().destroyWindow(d_colourPickerIndicator); delete[] d_colourPickingTexture; @@ -240,7 +240,7 @@ HSV_Colour ColourPickerControls::getColourPickingPositionColourHSV(float xAbs, } //----------------------------------------------------------------------------// -Vector2f ColourPickerControls::getColourPickingColourPosition() +glm::vec2 ColourPickerControls::getColourPickingColourPosition() { float x = 0.0f; float y = 0.0f; @@ -279,7 +279,7 @@ Vector2f ColourPickerControls::getColourPickingColourPosition() break; } - return Vector2f(x, y); + return glm::vec2(x, y); } //----------------------------------------------------------------------------// @@ -370,33 +370,33 @@ void ColourPickerControls::initColourPickerControlsImageSet() const String baseName( d_colourPickerControlsTextureTarget->getTexture().getName()); - BasicImage* image = static_cast( - &ImageManager::getSingleton().create("BasicImage", baseName + '/' + + BitmapImage* image = static_cast( + &ImageManager::getSingleton().create("BitmapImage", baseName + '/' + ColourPickerControlsPickingTextureImageName)); image->setTexture(&d_colourPickerControlsTextureTarget->getTexture()); - image->setArea( - Rectf(Vector2f(0.0f, 0.0f), + image->setImageArea( + Rectf(glm::vec2(0.0f, 0.0f), Sizef(static_cast(d_colourPickerPickingImageWidth), static_cast(d_colourPickerPickingImageHeight)))); - image = static_cast( - &ImageManager::getSingleton().create("BasicImage", baseName + '/' + + image = static_cast( + &ImageManager::getSingleton().create("BitmapImage", baseName + '/' + ColourPickerControlsColourSliderTextureImageName)); image->setTexture(&d_colourPickerControlsTextureTarget->getTexture()); - image->setArea( - Rectf(Vector2f(static_cast(d_colourPickerPickingImageWidth + d_colourPickerImageOffset), 0.0f), + image->setImageArea( + Rectf(glm::vec2(static_cast(d_colourPickerPickingImageWidth + d_colourPickerImageOffset), 0.0f), Sizef(static_cast(d_colourPickerColourSliderImageWidth), static_cast(d_colourPickerColourSliderImageHeight)))); - image = static_cast( - &ImageManager::getSingleton().create("BasicImage", baseName + '/' + + image = static_cast( + &ImageManager::getSingleton().create("BitmapImage", baseName + '/' + ColourPickerControlsAlphaSliderTextureImageName)); image->setTexture(&d_colourPickerControlsTextureTarget->getTexture()); - image->setArea( - Rectf(Vector2f(0.0f, static_cast(d_colourPickerPickingImageHeight + d_colourPickerImageOffset)), + image->setImageArea( + Rectf(glm::vec2(0.0f, static_cast(d_colourPickerPickingImageHeight + d_colourPickerImageOffset)), Sizef(static_cast(d_colourPickerAlphaSliderImageWidth), static_cast(d_colourPickerAlphaSliderImageHeight)))); @@ -582,20 +582,20 @@ void ColourPickerControls::initialiseComponents() Event::Subscriber(&ColourPickerControls::handleAlphaSliderValueChanged, this)); getColourPickerStaticImage()->subscribeEvent( - Window::EventMouseLeavesSurface, - Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImageMouseLeaves, this)); + Window::EventCursorLeavesSurface, + Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImagePointerLeaves, this)); getColourPickerStaticImage()->subscribeEvent( - Window::EventMouseButtonUp, - Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImageMouseButtonUp, this)); + Window::EventCursorActivate, + Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImagePointerActivate, this)); getColourPickerStaticImage()->subscribeEvent( - Window::EventMouseButtonDown, - Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImageMouseButtonDown, this)); + Window::EventCursorPressHold, + Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImagePointerPressHold, this)); getColourPickerStaticImage()->subscribeEvent( - Window::EventMouseMove, - Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImageMouseMove, this)); + Window::EventCursorMove, + Event::Subscriber(&ColourPickerControls::handleColourPickerStaticImagePointerMove, this)); initColourPicker(); @@ -850,7 +850,7 @@ Editbox* ColourPickerControls::getAlphaEditBox() //----------------------------------------------------------------------------// Window* ColourPickerControls::getColourPickerCursorStaticImage() { - return d_colourPickerCursor; + return d_colourPickerIndicator; } //----------------------------------------------------------------------------// @@ -1047,7 +1047,7 @@ bool ColourPickerControls::handleRadioButtonModeSelection(const EventArgs& args) else if (getHSVRadioButtonV() == radioButton) d_sliderMode = SliderMode_HSV_V; - refreshColourPickerCursorPosition(); + refreshColourPickerIndicatorPosition(); refreshColourSliderPosition(); @@ -1133,50 +1133,50 @@ bool ColourPickerControls::handleAlphaSliderValueChanged(const EventArgs& args) } //----------------------------------------------------------------------------// -bool ColourPickerControls::handleColourPickerStaticImageMouseButtonUp( +bool ColourPickerControls::handleColourPickerStaticImagePointerActivate( const EventArgs& args) { - const MouseEventArgs& mouseArgs = static_cast(args); + const CursorInputEventArgs& cursor_args = static_cast(args); - if (mouseArgs.button == LeftButton) - d_draggingColourPickerCursor = false; + if (cursor_args.source == CIS_Left) + d_draggingColourPickerIndicator = false; return true; } //----------------------------------------------------------------------------// -bool ColourPickerControls::handleColourPickerStaticImageMouseButtonDown( +bool ColourPickerControls::handleColourPickerStaticImagePointerPressHold( const EventArgs& args) { - const MouseEventArgs& mouseArgs = static_cast(args); + const CursorInputEventArgs& cursor_args = static_cast(args); - if (mouseArgs.button == LeftButton) + if (cursor_args.source == CIS_Left) { - d_draggingColourPickerCursor = true; + d_draggingColourPickerIndicator = true; - refreshColourPickerCursorPosition(mouseArgs); + refreshColourPickerIndicatorPosition(cursor_args); } return true; } //----------------------------------------------------------------------------// -bool ColourPickerControls::handleColourPickerStaticImageMouseMove( +bool ColourPickerControls::handleColourPickerStaticImagePointerMove( const EventArgs& args) { - if (d_colourPickerCursor && d_draggingColourPickerCursor) - refreshColourPickerCursorPosition( - static_cast(args)); + if (d_colourPickerIndicator && d_draggingColourPickerIndicator) + refreshColourPickerIndicatorPosition( + static_cast(args)); return true; } //----------------------------------------------------------------------------// -bool ColourPickerControls::handleColourPickerStaticImageMouseLeaves( +bool ColourPickerControls::handleColourPickerStaticImagePointerLeaves( const EventArgs&) { - if (d_colourPickerCursor) - d_draggingColourPickerCursor = false; + if (d_colourPickerIndicator) + d_draggingColourPickerIndicator = false; return true; } @@ -1332,58 +1332,58 @@ void ColourPickerControls::initColourPicker() d_sliderMode = SliderMode_Lab_L; getLabRadioButtonL()->setSelected(true); - d_colourPickerCursor = WindowManager::getSingleton().createWindow( + d_colourPickerIndicator = WindowManager::getSingleton().createWindow( getProperty("ColourPickerCursorStyle"), getName() + ColourPickerCursorName); - d_colourPickerCursor->setProperty( + d_colourPickerIndicator->setProperty( "BackgroundEnabled", PropertyHelper::toString(false)); - d_colourPickerCursor->setProperty( + d_colourPickerIndicator->setProperty( "FrameEnabled", PropertyHelper::toString(false)); - d_colourPickerCursor->setProperty( + d_colourPickerIndicator->setProperty( "Image", getProperty("ColourPickerCursorImage")); - d_colourPickerCursor->setProperty( + d_colourPickerIndicator->setProperty( "ImageColours", PropertyHelper::toString( ColourRect(Colour(0.0f, 0.0f, 0.0f)))); - d_colourPickerCursor->setWidth(UDim(0.05f, 0)); - d_colourPickerCursor->setHeight(UDim(0.05f, 0)); - d_colourPickerCursor->setMousePassThroughEnabled(true); - d_colourPickerCursor->setClippedByParent(false); + d_colourPickerIndicator->setWidth(UDim(0.05f, 0)); + d_colourPickerIndicator->setHeight(UDim(0.05f, 0)); + d_colourPickerIndicator->setCursorPassThroughEnabled(true); + d_colourPickerIndicator->setClippedByParent(false); getColourPickerImageSlider()->getThumb()->setHotTracked(false); - getColourPickerStaticImage()->addChild(d_colourPickerCursor); + getColourPickerStaticImage()->addChild(d_colourPickerIndicator); } //----------------------------------------------------------------------------// -void ColourPickerControls::positionColourPickerCursorRelative(float x, float y) +void ColourPickerControls::positionColourPickerIndicatorRelative(float x, float y) { - if (d_colourPickerCursor) + if (d_colourPickerIndicator) { - d_colourPickerCursor->setXPosition( - UDim(d_colourPickerCursor->getWidth().d_scale * -0.5f + x, 0.0f)); - d_colourPickerCursor->setYPosition( - UDim(d_colourPickerCursor->getHeight().d_scale * -0.5f + y, 0.0f)); + d_colourPickerIndicator->setXPosition( + UDim(d_colourPickerIndicator->getWidth().d_scale * -0.5f + x, 0.0f)); + d_colourPickerIndicator->setYPosition( + UDim(d_colourPickerIndicator->getHeight().d_scale * -0.5f + y, 0.0f)); } } //----------------------------------------------------------------------------// -void ColourPickerControls::positionColourPickerCursorAbsolute(float x, float y) +void ColourPickerControls::positionColourPickerIndicatorAbsolute(float x, float y) { - if (d_colourPickerCursor) + if (d_colourPickerIndicator) { - d_colourPickerCursor->setXPosition( - UDim(d_colourPickerCursor->getWidth().d_scale * -0.5f, x)); - d_colourPickerCursor->setYPosition( - UDim(d_colourPickerCursor->getHeight().d_scale * -0.5f, y)); + d_colourPickerIndicator->setXPosition( + UDim(d_colourPickerIndicator->getWidth().d_scale * -0.5f, x)); + d_colourPickerIndicator->setYPosition( + UDim(d_colourPickerIndicator->getHeight().d_scale * -0.5f, y)); } } @@ -1394,24 +1394,24 @@ RGB_Colour ColourPickerControls::getSelectedColourRGB() } //----------------------------------------------------------------------------// -void ColourPickerControls::refreshColourPickerCursorPosition() +void ColourPickerControls::refreshColourPickerIndicatorPosition() { - Vector2f pos = getColourPickingColourPosition(); + const glm::vec2 pos = getColourPickingColourPosition(); - positionColourPickerCursorRelative(pos.d_x, pos.d_y); + positionColourPickerIndicatorRelative(pos.x, pos.y); } //----------------------------------------------------------------------------// -void ColourPickerControls::refreshColourPickerCursorPosition( - const MouseEventArgs& mouseEventArgs) +void ColourPickerControls::refreshColourPickerIndicatorPosition( + const CursorInputEventArgs& pointerEventArgs) { - Vector2f position = mouseEventArgs.position; + const glm::vec2 position = pointerEventArgs.position; - float x = CoordConverter::screenToWindowX( - *mouseEventArgs.window, position.d_x); - float y = CoordConverter::screenToWindowY( - *mouseEventArgs.window, position.d_y); - positionColourPickerCursorAbsolute(x, y); + const float x = CoordConverter::screenToWindowX( + *pointerEventArgs.window, position.x); + const float y = CoordConverter::screenToWindowY( + *pointerEventArgs.window, position.y); + positionColourPickerIndicatorAbsolute(x, y); if (d_sliderMode & (SliderMode_Lab_L | SliderMode_Lab_A | SliderMode_Lab_B)) @@ -1426,7 +1426,7 @@ void ColourPickerControls::refreshColourPickerCursorPosition( setColours(col); } - onColourCursorPositionChanged(); + onColourIndicatorPositionChanged(); } //----------------------------------------------------------------------------// @@ -1528,7 +1528,7 @@ void ColourPickerControls::onColourSliderChanged() { refreshEditboxesAndColourRects(); - refreshColourPickerCursorPosition(); + refreshColourPickerIndicatorPosition(); refreshColourPickerControlsTextures(); } @@ -1588,7 +1588,7 @@ void ColourPickerControls::refreshAllElements() refreshColourSliderPosition(); - refreshColourPickerCursorPosition(); + refreshColourPickerIndicatorPosition(); refreshAlpha(); @@ -1596,7 +1596,7 @@ void ColourPickerControls::refreshAllElements() } //----------------------------------------------------------------------------// -void ColourPickerControls::onColourCursorPositionChanged() +void ColourPickerControls::onColourIndicatorPositionChanged() { refreshEditboxesAndColourRects(); diff --git a/cegui/src/CompositeResourceProvider.cpp b/cegui/src/CompositeResourceProvider.cpp index c0324440f..1dee75b98 100644 --- a/cegui/src/CompositeResourceProvider.cpp +++ b/cegui/src/CompositeResourceProvider.cpp @@ -37,7 +37,7 @@ CompositeResourceProvider::~CompositeResourceProvider(void) ProviderIterator it=getIterator(); for(it.toStart(); !it.isAtEnd(); ++it) { - CEGUI_DELETE_AO it.getCurrentValue(); + delete it.getCurrentValue(); d_providerlist.erase (it.getCurrentKey()); } } diff --git a/cegui/src/Config_xmlHandler.cpp b/cegui/src/Config_xmlHandler.cpp index 082394fc0..114942d04 100644 --- a/cegui/src/Config_xmlHandler.cpp +++ b/cegui/src/Config_xmlHandler.cpp @@ -51,7 +51,7 @@ const String Config_xmlHandler::ScriptingElement("Scripting"); const String Config_xmlHandler::XMLParserElement("DefaultXMLParser"); const String Config_xmlHandler::ImageCodecElement("DefaultImageCodec"); const String Config_xmlHandler::DefaultFontElement("DefaultFont"); -const String Config_xmlHandler::DefaultMouseCursorElement("DefaultMouseCursor"); +const String Config_xmlHandler::DefaultCursorElement("DefaultCursor"); const String Config_xmlHandler::DefaultTooltipElement("DefaultTooltip"); const String Config_xmlHandler::FilenameAttribute("filename"); const String Config_xmlHandler::LevelAttribute("level"); @@ -110,8 +110,8 @@ void Config_xmlHandler::elementStart(const String& element, handleImageCodecElement(attributes); else if (element == DefaultFontElement) handleDefaultFontElement(attributes); - else if (element == DefaultMouseCursorElement) - handleDefaultMouseCursorElement(attributes); + else if (element == DefaultCursorElement) + handleDefaultCursorElement(attributes); else if (element == DefaultTooltipElement) handleDefaultTooltipElement(attributes); else @@ -208,9 +208,9 @@ void Config_xmlHandler::handleDefaultFontElement(const XMLAttributes& attr) } //----------------------------------------------------------------------------// -void Config_xmlHandler::handleDefaultMouseCursorElement(const XMLAttributes& attr) +void Config_xmlHandler::handleDefaultCursorElement(const XMLAttributes& attr) { - d_defaultMouseImage = attr.getValueAsString(ImageAttribute, ""); + d_defaultPointerImage = attr.getValueAsString(ImageAttribute, ""); } //----------------------------------------------------------------------------// @@ -345,11 +345,11 @@ void Config_xmlHandler::initialiseDefaultFont() const } //----------------------------------------------------------------------------// -void Config_xmlHandler::initialiseDefaultMouseCursor() const +void Config_xmlHandler::initialiseDefaultCursor() const { - if (!d_defaultMouseImage.empty()) - System::getSingleton().getDefaultGUIContext().getMouseCursor(). - setDefaultImage(d_defaultMouseImage); + if (!d_defaultPointerImage.empty()) + System::getSingleton().getDefaultGUIContext().getCursor(). + setDefaultImage(d_defaultPointerImage); } //----------------------------------------------------------------------------// diff --git a/cegui/src/CoordConverter.cpp b/cegui/src/CoordConverter.cpp index cb27e41a6..327c2e893 100644 --- a/cegui/src/CoordConverter.cpp +++ b/cegui/src/CoordConverter.cpp @@ -49,7 +49,7 @@ float CoordConverter::screenToWindowY(const Window& window, const UDim& y) //----------------------------------------------------------------------------// -Vector2f CoordConverter::screenToWindow(const Window& window, const UVector2& vec) +glm::vec2 CoordConverter::screenToWindow(const Window& window, const UVector2& vec) { return asAbsolute(vec, window.getRootContainerSize()) - getBaseValue(window); } @@ -57,14 +57,10 @@ Vector2f CoordConverter::screenToWindow(const Window& window, const UVector2& ve //----------------------------------------------------------------------------// Rectf CoordConverter::screenToWindow(const Window& window, const URect& rect) { - Vector2f base(getBaseValue(window)); + const glm::vec2 base(getBaseValue(window)); Rectf pixel(asAbsolute(rect, window.getRootContainerSize())); - // negate base position - base.d_x = -base.d_x; - base.d_y = -base.d_y; - - pixel.offset(base); + pixel.offset(-base); return pixel; } @@ -84,7 +80,7 @@ float CoordConverter::screenToWindowY(const Window& window, const float y) //----------------------------------------------------------------------------// -Vector2f CoordConverter::screenToWindow(const Window& window, const Vector2f& vec) +glm::vec2 CoordConverter::screenToWindow(const Window& window, const glm::vec2& vec) { return vec - getBaseValue(window); } @@ -93,14 +89,10 @@ Vector2f CoordConverter::screenToWindow(const Window& window, const Vector2f& ve Rectf CoordConverter::screenToWindow(const Window& window, const Rectf& rect) { - Vector2f base(getBaseValue(window)); - - // negate base position - base.d_x = -base.d_x; - base.d_y = -base.d_y; + const glm::vec2 base(getBaseValue(window)); Rectf tmp(rect); - tmp.offset(base); + tmp.offset(-base); return tmp; } @@ -118,7 +110,7 @@ float CoordConverter::getBaseXValue(const Window& window) const Rectf parent_rect(parent ? parent->getChildContentArea(window.isNonClient()).get() : - Rectf(Vector2f(0, 0), window.getRootContainerSize()) + Rectf(glm::vec2(0, 0), window.getRootContainerSize()) ); const float parent_width = parent_rect.getWidth(); @@ -149,7 +141,7 @@ float CoordConverter::getBaseYValue(const Window& window) const Rectf parent_rect(parent ? parent->getChildContentArea(window.isNonClient()).get() : - Rectf(Vector2f(0, 0), window.getRootContainerSize()) + Rectf(glm::vec2(0, 0), window.getRootContainerSize()) ); const float parent_height = parent_rect.getHeight(); @@ -174,9 +166,9 @@ float CoordConverter::getBaseYValue(const Window& window) //----------------------------------------------------------------------------// -Vector2f CoordConverter::getBaseValue(const Window& window) +glm::vec2 CoordConverter::getBaseValue(const Window& window) { - return Vector2f(getBaseXValue(window), getBaseYValue(window)); + return glm::vec2(getBaseXValue(window), getBaseYValue(window)); } } // End of CEGUI namespace section diff --git a/cegui/src/MouseCursor.cpp b/cegui/src/Cursor.cpp similarity index 58% rename from cegui/src/MouseCursor.cpp rename to cegui/src/Cursor.cpp index cad0bb790..695f315fe 100644 --- a/cegui/src/MouseCursor.cpp +++ b/cegui/src/Cursor.cpp @@ -2,7 +2,7 @@ created: 21/2/2004 author: Paul D Turner - purpose: Implements MouseCursor class + purpose: Implements the Cursor class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team @@ -26,7 +26,7 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/Exceptions.h" #include "CEGUI/Logger.h" #include "CEGUI/System.h" @@ -42,175 +42,173 @@ namespace CEGUI /************************************************************************* Static Data Definitions *************************************************************************/ -bool MouseCursor::s_initialPositionSet = false; -Vector2f MouseCursor::s_initialPosition(0.0f, 0.0f); +bool Cursor::s_initialPositionSet = false; +glm::vec2 Cursor::s_initialPosition(0.0f, 0.0f); /************************************************************************* Event name constants *************************************************************************/ -const String MouseCursor::EventNamespace("MouseCursor"); -const String MouseCursor::EventImageChanged("ImageChanged"); -const String MouseCursor::EventDefaultImageChanged("DefaultImageChanged"); +const String Cursor::EventNamespace("Cursor"); +const String Cursor::EventImageChanged("ImageChanged"); +const String Cursor::EventDefaultImageChanged("DefaultImageChanged"); /************************************************************************* constructor *************************************************************************/ -MouseCursor::MouseCursor(void) : - d_cursorImage(0), - d_defaultCursorImage(0), +Cursor::Cursor(void) : + d_indicatorImage(0), + d_defaultIndicatorImage(0), d_position(0.0f, 0.0f), d_visible(true), - d_geometry(&System::getSingleton().getRenderer()->createGeometryBuffer()), d_customSize(0.0f, 0.0f), d_customOffset(0.0f, 0.0f), d_cachedGeometryValid(false) { - const Rectf screenArea(Vector2f(0, 0), - System::getSingleton().getRenderer()->getDisplaySize()); - d_geometry->setClippingRegion(screenArea); - + const Rectf screenArea(glm::vec2(0, 0), + System::getSingleton().getRenderer()->getDisplaySize()); // default constraint is to whole screen setConstraintArea(&screenArea); if (s_initialPositionSet) setPosition(s_initialPosition); else - // mouse defaults to middle of the constrained area - setPosition(Vector2f(screenArea.getWidth() / 2, - screenArea.getHeight() / 2)); + // pointer defaults to middle of the constrained area + setPosition(0.5f * glm::vec2(screenArea.getWidth(), + screenArea.getHeight())); } /************************************************************************* Destructor *************************************************************************/ -MouseCursor::~MouseCursor(void) +Cursor::~Cursor(void) { - System::getSingleton().getRenderer()->destroyGeometryBuffer(*d_geometry); + destroyGeometryBuffers(); } /************************************************************************* - Set the current mouse cursor image + Set the current cursor image *************************************************************************/ -void MouseCursor::setImage(const Image* image) +void Cursor::setImage(const Image* image) { - if (image == d_cursorImage) + if (image == d_indicatorImage) return; - d_cursorImage = image; + d_indicatorImage = image; d_cachedGeometryValid = false; - MouseCursorEventArgs args(this); - args.image = image; + CursorEventArgs args(this); + args.d_image = image; onImageChanged(args); } /************************************************************************* - Set the current mouse cursor image + Set the current cursor image *************************************************************************/ -void MouseCursor::setImage(const String& name) +void Cursor::setImage(const String& name) { setImage(&ImageManager::getSingleton().get(name)); } //----------------------------------------------------------------------------// -void MouseCursor::setDefaultImage(const Image* image) +void Cursor::setDefaultImage(const Image* image) { - if (image == d_defaultCursorImage) + if (image == d_defaultIndicatorImage) return; - d_defaultCursorImage = image; - d_cachedGeometryValid = d_cursorImage != 0; + d_defaultIndicatorImage = image; + d_cachedGeometryValid = d_indicatorImage != 0; - MouseCursorEventArgs args(this); - args.image = image; + CursorEventArgs args(this); + args.d_image = image; onDefaultImageChanged(args); } //----------------------------------------------------------------------------// -void MouseCursor::setDefaultImage(const String& name) +void Cursor::setDefaultImage(const String& name) { setDefaultImage(&ImageManager::getSingleton().get(name)); } //----------------------------------------------------------------------------// -const Image* MouseCursor::getDefaultImage() const +const Image* Cursor::getDefaultImage() const { - return d_defaultCursorImage; + return d_defaultIndicatorImage; } /************************************************************************* - Draw the mouse cursor + Draw the cursor *************************************************************************/ -void MouseCursor::draw(void) const +void Cursor::draw() { - if (!d_visible || !d_cursorImage) + if (!d_visible || !d_indicatorImage) return; if (!d_cachedGeometryValid) cacheGeometry(); - d_geometry->draw(); + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + d_geometryBuffers[i]->draw(); } /************************************************************************* - Set the current mouse cursor position + Set the current cursor position *************************************************************************/ -void MouseCursor::setPosition(const Vector2f& position) +void Cursor::setPosition(const glm::vec2& position) { d_position = position; constrainPosition(); - d_geometry->setTranslation(Vector3f(d_position.d_x, d_position.d_y, 0)); + updateGeometryBuffersTranslation(); } /************************************************************************* - Offset the mouse cursor position by the deltas specified in 'offset'. + Offset the cursor position by the deltas specified in 'offset'. *************************************************************************/ -void MouseCursor::offsetPosition(const Vector2f& offset) +void Cursor::offsetPosition(const glm::vec2& offset) { - d_position.d_x += offset.d_x; - d_position.d_y += offset.d_y; + d_position += offset; constrainPosition(); - d_geometry->setTranslation(Vector3f(d_position.d_x, d_position.d_y, 0)); + updateGeometryBuffersTranslation(); } /************************************************************************* - Checks the mouse cursor position is within the current 'constrain' + Checks the cursor position is within the current 'constrain' Rect and adjusts as required. *************************************************************************/ -void MouseCursor::constrainPosition(void) +void Cursor::constrainPosition() { - Rectf absarea(getConstraintArea()); + const Rectf absarea(getConstraintArea()); - if (d_position.d_x >= absarea.d_max.d_x) - d_position.d_x = absarea.d_max.d_x -1; + if (d_position.x >= absarea.d_max.d_x) + d_position.x = absarea.d_max.d_x -1; - if (d_position.d_y >= absarea.d_max.d_y) - d_position.d_y = absarea.d_max.d_y -1; + if (d_position.y >= absarea.d_max.d_y) + d_position.y = absarea.d_max.d_y -1; - if (d_position.d_y < absarea.d_min.d_y) - d_position.d_y = absarea.d_min.d_y; + if (d_position.y < absarea.d_min.d_y) + d_position.y = absarea.d_min.d_y; - if (d_position.d_x < absarea.d_min.d_x) - d_position.d_x = absarea.d_min.d_x; + if (d_position.x < absarea.d_min.d_x) + d_position.x = absarea.d_min.d_x; } /************************************************************************* - Set the area that the mouse cursor is constrained to. + Set the area that the cursor is constrained to. *************************************************************************/ -void MouseCursor::setConstraintArea(const Rectf* area) +void Cursor::setConstraintArea(const Rectf* area) { - const Rectf renderer_area(Vector2f(0, 0), - System::getSingleton().getRenderer()->getDisplaySize()); + const Rectf renderer_area(glm::vec2(0, 0), + System::getSingleton().getRenderer()->getDisplaySize()); if (!area) { @@ -233,12 +231,12 @@ void MouseCursor::setConstraintArea(const Rectf* area) /************************************************************************* - Set the area that the mouse cursor is constrained to. + Set the area that the cursor is constrained to. *************************************************************************/ -void MouseCursor::setUnifiedConstraintArea(const URect* area) +void Cursor::setUnifiedConstraintArea(const URect* area) { - const Rectf renderer_area(Vector2f(0, 0), - System::getSingleton().getRenderer()->getDisplaySize()); + const Rectf renderer_area(glm::vec2(0, 0), + System::getSingleton().getRenderer()->getDisplaySize()); if (area) { @@ -256,114 +254,150 @@ void MouseCursor::setUnifiedConstraintArea(const URect* area) } /************************************************************************* - Set the area that the mouse cursor is constrained to. + Set the area that the cursor is constrained to. *************************************************************************/ -Rectf MouseCursor::getConstraintArea(void) const +Rectf Cursor::getConstraintArea(void) const { return Rectf(CoordConverter::asAbsolute(d_constraints, System::getSingleton().getRenderer()->getDisplaySize())); } /************************************************************************* - Set the area that the mouse cursor is constrained to. + Set the area that the cursor is constrained to. *************************************************************************/ -const URect& MouseCursor::getUnifiedConstraintArea(void) const +const URect& Cursor::getUnifiedConstraintArea(void) const { return d_constraints; } /************************************************************************* - Return the current mouse cursor position in display resolution + Return the current cursor position in display resolution independant values. *************************************************************************/ -Vector2f MouseCursor::getDisplayIndependantPosition(void) const +glm::vec2 Cursor::getDisplayIndependantPosition(void) const { - Sizef dsz(System::getSingleton().getRenderer()->getDisplaySize()); + const Sizef dsz(System::getSingleton().getRenderer()->getDisplaySize()); - return Vector2f(d_position.d_x / (dsz.d_width - 1.0f), - d_position.d_y / (dsz.d_height - 1.0f)); + return glm::vec2(d_position.x / (dsz.d_width - 1.0f), + d_position.y / (dsz.d_height - 1.0f)); } //----------------------------------------------------------------------------// -void MouseCursor::notifyDisplaySizeChanged(const Sizef& new_size) +void Cursor::notifyDisplaySizeChanged(const Sizef& new_size) { - const Rectf screenArea(Vector2f(0, 0), new_size); - d_geometry->setClippingRegion(screenArea); + updateGeometryBuffersClipping(Rectf(glm::vec2(0.0f, 0.0f), new_size)); // invalidate to regenerate geometry at (maybe) new size d_cachedGeometryValid = false; } //----------------------------------------------------------------------------// -void MouseCursor::setExplicitRenderSize(const Sizef& size) +void Cursor::setExplicitRenderSize(const Sizef& size) { d_customSize = size; d_cachedGeometryValid = false; } //----------------------------------------------------------------------------// -const Sizef& MouseCursor::getExplicitRenderSize() const +const Sizef& Cursor::getExplicitRenderSize() const { return d_customSize; } //----------------------------------------------------------------------------// -void MouseCursor::cacheGeometry() const +void Cursor::cacheGeometry() { d_cachedGeometryValid = true; - d_geometry->reset(); + destroyGeometryBuffers(); // if no image, nothing more to do. - if (!d_cursorImage) + if (!d_indicatorImage) return; if (d_customSize.d_width != 0.0f || d_customSize.d_height != 0.0f) { calculateCustomOffset(); - d_cursorImage->render(*d_geometry, d_customOffset, d_customSize); + d_indicatorImage->render(d_geometryBuffers, d_customOffset, d_customSize); } else { - d_cursorImage->render(*d_geometry, Vector2f(0, 0)); + d_indicatorImage->render(d_geometryBuffers, glm::vec2(0, 0)); } + + const Rectf clipping_area(glm::vec2(0, 0), + System::getSingleton().getRenderer()->getDisplaySize()); + updateGeometryBuffersClipping(clipping_area); + updateGeometryBuffersTranslation(); } //----------------------------------------------------------------------------// -void MouseCursor::calculateCustomOffset() const +void Cursor::calculateCustomOffset() const { - const Sizef sz(d_cursorImage->getRenderedSize()); - const Vector2f offset(d_cursorImage->getRenderedOffset()); + const Sizef sz(d_indicatorImage->getRenderedSize()); + const glm::vec2 offset(d_indicatorImage->getRenderedOffset()); - d_customOffset.d_x = - d_customSize.d_width / sz.d_width * offset.d_x - offset.d_x; - d_customOffset.d_y = - d_customSize.d_height / sz.d_height * offset.d_y - offset.d_y; + d_customOffset.x = + d_customSize.d_width / sz.d_width * offset.x - offset.x; + d_customOffset.y = + d_customSize.d_height / sz.d_height * offset.y - offset.y; } //----------------------------------------------------------------------------// -void MouseCursor::setInitialMousePosition(const Vector2f& position) +void Cursor::setInitialPointerPosition(const glm::vec2& position) { - s_initialPosition = position; + s_initialPosition = position; s_initialPositionSet = true; } //----------------------------------------------------------------------------// -void MouseCursor::invalidate() +void Cursor::invalidate() { d_cachedGeometryValid = false; } //----------------------------------------------------------------------------// -void MouseCursor::onImageChanged(MouseCursorEventArgs& e) +void Cursor::onImageChanged(CursorEventArgs& e) { fireEvent(EventImageChanged, e, EventNamespace); } //----------------------------------------------------------------------------// -void MouseCursor::onDefaultImageChanged(MouseCursorEventArgs& e) +void Cursor::onDefaultImageChanged(CursorEventArgs& e) { fireEvent(EventDefaultImageChanged, e, EventNamespace); } +//----------------------------------------------------------------------------// +void Cursor::destroyGeometryBuffers() +{ + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + System::getSingleton().getRenderer()->destroyGeometryBuffer(*d_geometryBuffers.at(i)); + + d_geometryBuffers.clear(); +} + +//----------------------------------------------------------------------------// +void Cursor::updateGeometryBuffersTranslation() +{ + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + { + CEGUI::GeometryBuffer*& currentBuffer = d_geometryBuffers[i]; + currentBuffer->setTranslation(glm::vec3(d_position, 0)); + } +} + +//----------------------------------------------------------------------------// +void Cursor::updateGeometryBuffersClipping(const Rectf& clipping_area) +{ + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + { + CEGUI::GeometryBuffer*& currentBuffer = d_geometryBuffers[i]; + currentBuffer->setClippingRegion(clipping_area); + } +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/DataContainer.cpp b/cegui/src/DataContainer.cpp index eaaadae7f..c87b07d91 100644 --- a/cegui/src/DataContainer.cpp +++ b/cegui/src/DataContainer.cpp @@ -36,7 +36,7 @@ void RawDataContainer::release(void) { if (mData) { - CEGUI_DELETE_ARRAY_PT(mData, uint8, mSize, RawDataContainer); + delete[] mData; mData = 0; mSize = 0; diff --git a/cegui/src/DefaultLogger.cpp b/cegui/src/DefaultLogger.cpp index 1a084ef63..344153dd8 100644 --- a/cegui/src/DefaultLogger.cpp +++ b/cegui/src/DefaultLogger.cpp @@ -29,28 +29,37 @@ #include "CEGUI/DefaultLogger.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" -#include -#include +#ifdef __ANDROID__ +# include +#else +# include +# include +#endif namespace CEGUI { //----------------------------------------------------------------------------// -DefaultLogger::DefaultLogger(void) : - d_caching(true) +DefaultLogger::DefaultLogger(void) +#ifndef __ANDROID__ + : d_caching(true) +#endif { // create log header logEvent("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+"); logEvent("+ Crazy Eddie's GUI System - Event log +"); logEvent("+ (http://www.cegui.org.uk/) +"); logEvent("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n"); +#ifndef __ANDROID__ char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast(this)); logEvent("CEGUI::Logger singleton created. " + String(addr_buff)); +#endif } //----------------------------------------------------------------------------// DefaultLogger::~DefaultLogger(void) { +#ifndef __ANDROID__ if (d_ostream.is_open()) { char addr_buff[32]; @@ -58,12 +67,14 @@ DefaultLogger::~DefaultLogger(void) logEvent("CEGUI::Logger singleton destroyed. " + String(addr_buff)); d_ostream.close(); } +#endif } //----------------------------------------------------------------------------// void DefaultLogger::logEvent(const String& message, LoggingLevel level /* = Standard */) { +#ifndef __ANDROID__ using namespace std; time_t et; @@ -128,25 +139,49 @@ void DefaultLogger::logEvent(const String& message, // buffered. d_ostream.flush(); } +#else + std::string logName = "CEGUILog"; + switch (level) { + case Errors: + __android_log_write (ANDROID_LOG_ERROR, logName.c_str(), message.c_str()); + break; + case Warnings: + __android_log_write (ANDROID_LOG_WARN, logName.c_str(), message.c_str()); + break; + case Standard: + __android_log_write (ANDROID_LOG_INFO, logName.c_str(), message.c_str()); + break; + case Informative: + __android_log_write (ANDROID_LOG_DEBUG, logName.c_str(), message.c_str()); + break; + case Insane: + __android_log_write (ANDROID_LOG_DEBUG, logName.c_str(), message.c_str()); + break; + default: + __android_log_write (ANDROID_LOG_DEBUG, logName.c_str(), message.c_str()); + break; + } +#endif } //----------------------------------------------------------------------------// void DefaultLogger::setLogFilename(const String& filename, bool append) { +#ifndef __ANDROID__ // close current log file (if any) if (d_ostream.is_open()) d_ostream.close(); -#if defined(_MSC_VER) +# if defined(_MSC_VER) d_ostream.open(System::getStringTranscoder().stringToStdWString(filename).c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::trunc)); -#else +# else d_ostream.open(filename.c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::trunc)); -#endif +# endif if (!d_ostream) CEGUI_THROW(FileIOException( @@ -178,6 +213,7 @@ void DefaultLogger::setLogFilename(const String& filename, bool append) d_cache.clear(); } +#endif } //----------------------------------------------------------------------------// diff --git a/cegui/src/DefaultResourceProvider.cpp b/cegui/src/DefaultResourceProvider.cpp index 953bb4e71..1207af476 100644 --- a/cegui/src/DefaultResourceProvider.cpp +++ b/cegui/src/DefaultResourceProvider.cpp @@ -34,6 +34,9 @@ # include # include # include +#elif defined(__ANDROID__) +# include "CEGUI/AndroidUtils.h" +# include #else # include # include @@ -56,27 +59,45 @@ void DefaultResourceProvider::loadRawDataContainer(const String& filename, const String final_filename(getFinalFilename(filename, resourceGroup)); -#if defined(__WIN32__) || defined(_WIN32) - FILE* file = _wfopen(System::getStringTranscoder().stringToStdWString(final_filename).c_str(), L"rb"); +#ifdef __ANDROID__ + if (AndroidUtils::getAndroidApp() == 0) + CEGUI_THROW(FileIOException("AndroidUtils::android_app has not been set for CEGUI")); + struct android_app* app = AndroidUtils::getAndroidApp(); + if (!app->activity->assetManager) + CEGUI_THROW(FileIOException("Android AAssetManager is not valid ")); + //AAsset *file = AAssetManager_open(app->activity->assetManager, final_filename.c_str(), AASSET_MODE_BUFFER); + AAsset *file = AAssetManager_open(app->activity->assetManager, final_filename.c_str(), AASSET_MODE_UNKNOWN); #else +# if defined(__WIN32__) || defined(_WIN32) + FILE* file = _wfopen(System::getStringTranscoder().stringToStdWString(final_filename).c_str(), L"rb"); +# else FILE* file = fopen(final_filename.c_str(), "rb"); +# endif #endif - if (file == 0) CEGUI_THROW(FileIOException(final_filename + " does not exist")); +#ifdef __ANDROID__ + size_t size = AAsset_getLength(file); +#else fseek(file, 0, SEEK_END); const size_t size = ftell(file); fseek(file, 0, SEEK_SET); +#endif - unsigned char* const buffer = CEGUI_NEW_ARRAY_PT(unsigned char, size, RawDataContainer); + unsigned char* const buffer = new unsigned char[size]; +#ifdef __ANDROID__ + const size_t size_read = AAsset_read(file, buffer, size); + AAsset_close(file); +#else const size_t size_read = fread(buffer, sizeof(char), size, file); fclose(file); +#endif if (size_read != size) { - CEGUI_DELETE_ARRAY_PT(buffer, unsigned char, size, BufferAllocator); + delete[] buffer; CEGUI_THROW(FileIOException( "A problem occurred while reading file: " + final_filename)); @@ -191,7 +212,21 @@ size_t DefaultResourceProvider::getResourceGroupFileNames( _findclose(f); } - +#elif defined(__ANDROID__) + if (AndroidUtils::getAndroidApp() == 0) + CEGUI_THROW(FileIOException("AndroidUtils::android_app has not been set for CEGUI")); + struct android_app* app = AndroidUtils::getAndroidApp(); + AAssetDir* dirp; + if ((dirp == AAssetManager_openDir(app->activity->assetManager, dir_name.c_str()))) + { + const char* filename; + while ((filename = AAssetDir_getNextFileName(dirp))) + { + out_vec.push_back(filename); + ++entries; + } + AAssetDir_close(dirp); + } // Everybody else #else DIR* dirp; diff --git a/cegui/src/DynamicModule.cpp b/cegui/src/DynamicModule.cpp index 4b4a60294..6a362bcb6 100644 --- a/cegui/src/DynamicModule.cpp +++ b/cegui/src/DynamicModule.cpp @@ -58,8 +58,7 @@ namespace CEGUI { //----------------------------------------------------------------------------// -struct DynamicModule::Impl : - public AllocatedObject +struct DynamicModule::Impl { Impl(const String& name) : d_moduleName(name), @@ -188,7 +187,7 @@ static DYNLIB_HANDLE DynLibLoad(const String& name) //----------------------------------------------------------------------------// DynamicModule::DynamicModule(const String& name) : - d_pimpl(CEGUI_NEW_AO Impl(name)) + d_pimpl(new Impl(name)) { if (name.empty()) return; @@ -225,7 +224,7 @@ DynamicModule::DynamicModule(const String& name) : //----------------------------------------------------------------------------// DynamicModule::~DynamicModule() { - CEGUI_DELETE_AO d_pimpl; + delete d_pimpl; } //----------------------------------------------------------------------------// diff --git a/cegui/src/Element.cpp b/cegui/src/Element.cpp index daa415adc..8f127743a 100644 --- a/cegui/src/Element.cpp +++ b/cegui/src/Element.cpp @@ -75,7 +75,7 @@ Element::Element(): d_aspectRatio(1.0 / 1.0), d_pixelAligned(true), d_pixelSize(0.0f, 0.0f), - d_rotation(Quaternion::IDENTITY), + d_rotation(1, 0, 0, 0), // <-- IDENTITY d_unclippedOuterRect(this, &Element::getUnclippedOuterRect_impl), d_unclippedInnerRect(this, &Element::getUnclippedInnerRect_impl) @@ -336,7 +336,7 @@ const Sizef& Element::getRootContainerSize() const } //----------------------------------------------------------------------------// -void Element::setRotation(const Quaternion& rotation) +void Element::setRotation(const glm::quat& rotation) { d_rotation = rotation; @@ -476,11 +476,11 @@ void Element::addElementProperties() &Element::setPixelAligned, &Element::isPixelAligned, true ); - CEGUI_DEFINE_PROPERTY(Element, Quaternion, + CEGUI_DEFINE_PROPERTY(Element, glm::quat, "Rotation", "Property to get/set the Element's rotation. Value is a quaternion: " "\"w:[w_float] x:[x_float] y:[y_float] z:[z_float]\"" "or \"x:[x_float] y:[y_float] z:[z_float]\" to convert from Euler angles (in degrees).", - &Element::setRotation, &Element::getRotation, Quaternion(1.0,0.0,0.0,0.0) + &Element::setRotation, &Element::getRotation, glm::quat(1.0, 0.0, 0.0, 0.0) ); CEGUI_DEFINE_PROPERTY(Element, bool, @@ -588,7 +588,7 @@ Rectf Element::getUnclippedOuterRect_impl(bool skipAllPixelAlignment) const { const Sizef pixel_size = skipAllPixelAlignment ? calculatePixelSize(true) : getPixelSize(); - Rectf ret(Vector2f(0, 0), pixel_size); + Rectf ret(glm::vec2(0, 0), pixel_size); const Element* parent = getParentElement(); @@ -600,20 +600,20 @@ Rectf Element::getUnclippedOuterRect_impl(bool skipAllPixelAlignment) const } else { - parent_rect = Rectf(Vector2f(0, 0), getRootContainerSize()); + parent_rect = Rectf(glm::vec2(0, 0), getRootContainerSize()); } const Sizef parent_size = parent_rect.getSize(); - Vector2f offset = parent_rect.d_min + CoordConverter::asAbsolute(getArea().d_min, parent_size, false); + glm::vec2 offset = glm::vec2(parent_rect.d_min.d_x, parent_rect.d_min.d_y) + CoordConverter::asAbsolute(getArea().d_min, parent_size, false); switch (getHorizontalAlignment()) { case HA_CENTRE: - offset.d_x += (parent_size.d_width - pixel_size.d_width) * 0.5f; + offset.x += (parent_size.d_width - pixel_size.d_width) * 0.5f; break; case HA_RIGHT: - offset.d_x += parent_size.d_width - pixel_size.d_width; + offset.x += parent_size.d_width - pixel_size.d_width; break; default: break; @@ -622,10 +622,10 @@ Rectf Element::getUnclippedOuterRect_impl(bool skipAllPixelAlignment) const switch (getVerticalAlignment()) { case VA_CENTRE: - offset.d_y += (parent_size.d_height - pixel_size.d_height) * 0.5f; + offset.y += (parent_size.d_height - pixel_size.d_height) * 0.5f; break; case VA_BOTTOM: - offset.d_y += parent_size.d_height - pixel_size.d_height; + offset.y += parent_size.d_height - pixel_size.d_height; break; default: break; @@ -633,8 +633,8 @@ Rectf Element::getUnclippedOuterRect_impl(bool skipAllPixelAlignment) const if (d_pixelAligned && !skipAllPixelAlignment) { - offset = Vector2f(CoordConverter::alignToPixels(offset.d_x), - CoordConverter::alignToPixels(offset.d_y)); + offset = glm::vec2(CoordConverter::alignToPixels(offset.x), + CoordConverter::alignToPixels(offset.y)); } ret.offset(offset); diff --git a/cegui/src/Event.cpp b/cegui/src/Event.cpp index 945043e2c..24a64e9c2 100644 --- a/cegui/src/Event.cpp +++ b/cegui/src/Event.cpp @@ -86,7 +86,7 @@ Event::Connection Event::subscribe(const Event::Subscriber& slot) Event::Connection Event::subscribe(Event::Group group, const Event::Subscriber& slot) { - Event::Connection c(CEGUI_NEW_AO BoundSlot(group, slot, *this)); + Event::Connection c(new BoundSlot(group, slot, *this)); d_slots.insert(std::pair(group, c)); return c; } diff --git a/cegui/src/EventSet.cpp b/cegui/src/EventSet.cpp index 6c59cd4fa..41e153885 100644 --- a/cegui/src/EventSet.cpp +++ b/cegui/src/EventSet.cpp @@ -50,7 +50,7 @@ EventSet::~EventSet(void) //----------------------------------------------------------------------------// void EventSet::addEvent(const String& name) { - addEvent(*CEGUI_NEW_AO Event(name)); + addEvent(*new Event(name)); } //----------------------------------------------------------------------------// @@ -60,7 +60,7 @@ void EventSet::addEvent(Event& event) if (isEventPresent(name)) { - CEGUI_DELETE_AO &event; + delete &event; CEGUI_THROW(AlreadyExistsException( "An event named '" + name + "' already exists in the EventSet.")); @@ -76,7 +76,7 @@ void EventSet::removeEvent(const String& name) if (pos != d_events.end()) { - CEGUI_DELETE_AO pos->second; + delete pos->second; d_events.erase(pos); } } @@ -94,7 +94,7 @@ void EventSet::removeAllEvents(void) EventMap::const_iterator end = d_events.end() ; for (; pos != end; ++pos) - CEGUI_DELETE_AO pos->second; + delete pos->second; d_events.clear(); } diff --git a/cegui/src/Exceptions.cpp b/cegui/src/Exceptions.cpp index b2ad11391..90659062d 100644 --- a/cegui/src/Exceptions.cpp +++ b/cegui/src/Exceptions.cpp @@ -38,10 +38,12 @@ #if defined(_MSC_VER) #include #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) -#include +#ifndef __ANDROID__ +# include +#endif #include #include -#include +#include #endif // Start of CEGUI namespace section diff --git a/cegui/src/Font.cpp b/cegui/src/Font.cpp index f9a3ce47b..b95647b61 100644 --- a/cegui/src/Font.cpp +++ b/cegui/src/Font.cpp @@ -30,6 +30,7 @@ #include "CEGUI/PropertyHelper.h" #include "CEGUI/System.h" #include "CEGUI/Image.h" +#include "CEGUI/BitmapImage.h" namespace CEGUI { @@ -78,7 +79,7 @@ Font::~Font() const uint old_size = (((d_maxCodepoint + GLYPHS_PER_PAGE) / GLYPHS_PER_PAGE) + BITS_PER_UINT - 1) / BITS_PER_UINT; - CEGUI_DELETE_ARRAY_PT(d_glyphPageLoaded, uint, old_size, Font); + delete[] d_glyphPageLoaded; } } @@ -131,7 +132,7 @@ void Font::setMaxCodepoint(utf32 codepoint) const uint old_size = (((d_maxCodepoint + GLYPHS_PER_PAGE) / GLYPHS_PER_PAGE) + BITS_PER_UINT - 1) / BITS_PER_UINT; - CEGUI_DELETE_ARRAY_PT(d_glyphPageLoaded, uint, old_size, Font); + delete[] d_glyphPageLoaded; } d_maxCodepoint = codepoint; @@ -139,7 +140,7 @@ void Font::setMaxCodepoint(utf32 codepoint) const uint npages = (codepoint + GLYPHS_PER_PAGE) / GLYPHS_PER_PAGE; const uint size = (npages + BITS_PER_UINT - 1) / BITS_PER_UINT; - d_glyphPageLoaded = CEGUI_NEW_ARRAY_PT(uint, size, Font); + d_glyphPageLoaded = new uint[size]; memset(d_glyphPageLoaded, 0, size * sizeof(uint)); } @@ -241,13 +242,14 @@ size_t Font::getCharAtPixel(const String& text, size_t start_char, float pixel, } //----------------------------------------------------------------------------// -float Font::drawText(GeometryBuffer& buffer, const String& text, - const Vector2f& position, const Rectf* clip_rect, +float Font::drawText(std::vector& geom_buffers, + const String& text, const glm::vec2& position, + const Rectf* clip_rect, const bool clipping_enabled, const ColourRect& colours, const float space_extra, const float x_scale, const float y_scale) const { - const float base_y = position.d_y + getBaseline(y_scale); - Vector2f glyph_pos(position); + const float base_y = position.y + getBaseline(y_scale); + glm::vec2 glyph_pos(position); for (size_t c = 0; c < text.length(); ++c) { @@ -255,18 +257,19 @@ float Font::drawText(GeometryBuffer& buffer, const String& text, if ((glyph = getGlyphData(text[c]))) // NB: assignment { const Image* const img = glyph->getImage(); - glyph_pos.d_y = - base_y - (img->getRenderedOffset().d_y - img->getRenderedOffset().d_y * y_scale); - img->render(buffer, glyph_pos, - glyph->getSize(x_scale, y_scale), clip_rect, colours); - glyph_pos.d_x += glyph->getAdvance(x_scale); + + glyph_pos.y = + base_y - (img->getRenderedOffset().y - img->getRenderedOffset().y * y_scale); + img->render(geom_buffers, glyph_pos, + glyph->getSize(x_scale, y_scale), clip_rect, clipping_enabled, colours); + glyph_pos.x += glyph->getAdvance(x_scale); // apply extra spacing to space chars if (text[c] == ' ') - glyph_pos.d_x += space_extra; + glyph_pos.x += space_extra; } } - return glyph_pos.d_x; + return glyph_pos.x; } //----------------------------------------------------------------------------// diff --git a/cegui/src/FontManager.cpp b/cegui/src/FontManager.cpp index fa73487ad..13bdcb190 100644 --- a/cegui/src/FontManager.cpp +++ b/cegui/src/FontManager.cpp @@ -87,7 +87,7 @@ Font& FontManager::createFreeTypeFont(const String& font_name, font_name + "' using font file '" + font_filename + "'."); // create new object ahead of time - Font* object = CEGUI_NEW_AO FreeTypeFont(font_name, point_size, anti_aliased, + Font* object = new FreeTypeFont(font_name, point_size, anti_aliased, font_filename, resource_group, auto_scaled, native_res); @@ -112,7 +112,7 @@ Font& FontManager::createPixmapFont(const String& font_name, font_name + "' using imageset file '" + imageset_filename + "'."); // create new object ahead of time - Font* object = CEGUI_NEW_AO PixmapFont(font_name, imageset_filename, resource_group, + Font* object = new PixmapFont(font_name, imageset_filename, resource_group, auto_scaled, native_res); // return appropriate object instance (deleting any not required) diff --git a/cegui/src/Font_xmlHandler.cpp b/cegui/src/Font_xmlHandler.cpp index 43058d605..70086c230 100644 --- a/cegui/src/Font_xmlHandler.cpp +++ b/cegui/src/Font_xmlHandler.cpp @@ -85,7 +85,7 @@ Font_xmlHandler::Font_xmlHandler(): Font_xmlHandler::~Font_xmlHandler() { if (!d_objectRead) - CEGUI_DELETE_AO d_font; + delete d_font; } //----------------------------------------------------------------------------// @@ -225,7 +225,7 @@ void Font_xmlHandler::createFreeTypeFont(const XMLAttributes& attributes) CEGUI_LOGINSANE("---- Real point size: " + attributes.getValueAsString(FontSizeAttribute, "12")); - d_font = CEGUI_NEW_AO FreeTypeFont(name, + d_font = new FreeTypeFont(name, attributes.getValueAsFloat(FontSizeAttribute, 12.0f), attributes.getValueAsBool(FontAntiAliasedAttribute, true), filename, resource_group, @@ -252,7 +252,7 @@ void Font_xmlHandler::createPixmapFont(const XMLAttributes& attributes) CEGUI_LOGINSANE("---- Source file: " + filename + " in resource group: " + (resource_group.empty() ? "(Default)" : resource_group)); - d_font = CEGUI_NEW_AO PixmapFont(name, filename, resource_group, + d_font = new PixmapFont(name, filename, resource_group, PropertyHelper::fromString( attributes.getValueAsString(FontAutoScaledAttribute)), Sizef(attributes.getValueAsFloat(FontNativeHorzResAttribute, 640.0f), diff --git a/cegui/src/FreeTypeFont.cpp b/cegui/src/FreeTypeFont.cpp index ee5c48cbd..5151170c5 100644 --- a/cegui/src/FreeTypeFont.cpp +++ b/cegui/src/FreeTypeFont.cpp @@ -36,7 +36,7 @@ #include "CEGUI/Font_xmlHandler.h" #include #include -#include +#include #include #ifdef _MSC_VER @@ -195,7 +195,7 @@ void FreeTypeFont::rasterise(utf32 start_codepoint, utf32 end_codepoint) const d_glyphTextures.push_back(&texture); // Create a memory buffer where we will render our glyphs - argb_t* mem_buffer = CEGUI_NEW_ARRAY_PT(argb_t, texsize * texsize, BufferAllocator); + argb_t* mem_buffer = new argb_t[texsize * texsize]; memset(mem_buffer, 0, texsize * texsize * sizeof(argb_t)); // Go ahead, line by line, top-left to bottom-right @@ -232,11 +232,11 @@ void FreeTypeFont::rasterise(utf32 start_codepoint, utf32 end_codepoint) const Logger::getSingleton().logEvent(err.str().c_str(), Errors); // Create a 'null' image for this glyph so we do not seg later - Rectf area(0, 0, 0, 0); - Vector2f offset(0, 0); + const Rectf area(0, 0, 0, 0); + const glm::vec2 offset(0, 0); const String name(PropertyHelper::toString(s->first)); - BasicImage* img = - CEGUI_NEW_AO BasicImage(name, &texture, area, offset, ASM_Disabled, + BitmapImage* img = + new BitmapImage(name, &texture, area, offset, ASM_Disabled, d_nativeResolution); d_glyphImages.push_back(img); s->second.setImage(img); @@ -265,16 +265,17 @@ void FreeTypeFont::rasterise(utf32 start_codepoint, utf32 end_codepoint) const // Create a new image in the imageset const Rectf area(static_cast(x), - static_cast(y), - static_cast(x + glyph_w - INTER_GLYPH_PAD_SPACE), - static_cast(y + glyph_h - INTER_GLYPH_PAD_SPACE)); + static_cast(y), + static_cast(x + glyph_w - INTER_GLYPH_PAD_SPACE), + static_cast(y + glyph_h - INTER_GLYPH_PAD_SPACE)); - Vector2f offset(d_fontFace->glyph->metrics.horiBearingX * static_cast(FT_POS_COEF), - -d_fontFace->glyph->metrics.horiBearingY * static_cast(FT_POS_COEF)); + const glm::vec2 offset( + d_fontFace->glyph->metrics.horiBearingX * static_cast(FT_POS_COEF), + -d_fontFace->glyph->metrics.horiBearingY * static_cast(FT_POS_COEF)); const String name(PropertyHelper::toString(s->first)); - BasicImage* img = - CEGUI_NEW_AO BasicImage(name, &texture, area, offset, ASM_Disabled, + BitmapImage* img = + new BitmapImage(name, &texture, area, offset, ASM_Disabled, d_nativeResolution); d_glyphImages.push_back(img); s->second.setImage(img); @@ -304,7 +305,7 @@ void FreeTypeFont::rasterise(utf32 start_codepoint, utf32 end_codepoint) const // Copy our memory buffer into the texture and free it texture.loadFromMemory(mem_buffer, Sizef(static_cast(texsize), static_cast(texsize)), Texture::PF_RGBA); - CEGUI_DELETE_ARRAY_PT(mem_buffer, argb_t, texsize * texsize, BufferAllocator); + delete[] mem_buffer; if (finished) break; @@ -360,7 +361,7 @@ void FreeTypeFont::free() d_cp_map.clear(); for (size_t i = 0; i < d_glyphImages.size(); ++i) - CEGUI_DELETE_AO d_glyphImages[i]; + delete d_glyphImages[i]; d_glyphImages.clear(); for (size_t i = 0; i < d_glyphTextures.size(); i++) @@ -401,8 +402,8 @@ void FreeTypeFont::updateFont() "cannot be used.")); } - uint horzdpi = static_cast(System::getSingleton().getRenderer()->getDisplayDPI().d_x); - uint vertdpi = static_cast(System::getSingleton().getRenderer()->getDisplayDPI().d_y); + const uint horzdpi = static_cast(System::getSingleton().getRenderer()->getDisplayDPI().x); + const uint vertdpi = static_cast(System::getSingleton().getRenderer()->getDisplayDPI().y); float hps = d_ptSize * 64; float vps = d_ptSize * 64; diff --git a/cegui/src/GUIContext.cpp b/cegui/src/GUIContext.cpp index 164e79536..ae6966adf 100644 --- a/cegui/src/GUIContext.cpp +++ b/cegui/src/GUIContext.cpp @@ -40,39 +40,8 @@ namespace CEGUI { -/*! -\brief - Implementation structure used in tracking up & down mouse button inputs in - order to generate click, double-click, and triple-click events. -*/ -struct MouseClickTracker : - public AllocatedObject -{ - MouseClickTracker() : - d_click_count(0), - d_click_area(0, 0, 0, 0) - {} - - //! Timer used to track clicks for this button. - SimpleTimer d_timer; - //! count of clicks made so far. - int d_click_count; - //! area used to detect multi-clicks - Rectf d_click_area; - //! target window for any events generated. - Window* d_target_window; -}; - //----------------------------------------------------------------------------// -const float GUIContext::DefaultMouseButtonClickTimeout = 0.0f; -const float GUIContext::DefaultMouseButtonMultiClickTimeout = 0.3333f; -const Sizef GUIContext::DefaultMouseButtonMultiClickTolerance(12.0f, 12.0f); - const String GUIContext::EventRootWindowChanged("RootWindowChanged"); -const String GUIContext::EventMouseMoveScalingFactorChanged("MouseMoveScalingFactorChanged"); -const String GUIContext::EventMouseButtonClickTimeoutChanged("MouseButtonClickTimeoutChanged" ); -const String GUIContext::EventMouseButtonMultiClickTimeoutChanged("MouseButtonMultiClickTimeoutChanged" ); -const String GUIContext::EventMouseButtonMultiClickToleranceChanged("MouseButtonMultiClickToleranceChanged" ); const String GUIContext::EventRenderTargetChanged("RenderTargetChanged"); const String GUIContext::EventDefaultFontChanged("DefaultFontChanged"); @@ -81,18 +50,12 @@ GUIContext::GUIContext(RenderTarget& target) : RenderingSurface(target), d_rootWindow(0), d_isDirty(false), - d_mouseMovementScalingFactor(1.0f), - d_generateMouseClickEvents(true), - d_mouseButtonClickTimeout(DefaultMouseButtonClickTimeout), - d_mouseButtonMultiClickTimeout(DefaultMouseButtonMultiClickTimeout), - d_mouseButtonMultiClickTolerance(DefaultMouseButtonMultiClickTolerance), d_defaultTooltipObject(0), d_weCreatedTooltipObject(false), d_defaultFont(0), d_surfaceSize(target.getArea().getSize()), d_modalWindow(0), d_captureWindow(0), - d_mouseClickTrackers(new MouseClickTracker[MouseButtonCount]), d_areaChangedEventConnection( target.subscribeEvent( RenderTarget::EventAreaChanged, @@ -100,27 +63,29 @@ GUIContext::GUIContext(RenderTarget& target) : d_windowDestroyedEventConnection( WindowManager::getSingleton().subscribeEvent( WindowManager::EventWindowDestroyed, - Event::Subscriber(&GUIContext::windowDestroyedHandler, this))) + Event::Subscriber(&GUIContext::windowDestroyedHandler, this))), + d_semanticEventHandlers(), + d_windowNavigator(0) { - resetWindowContainingMouse(); + resetWindowContainingCursor(); + initializeSemanticEventHandlers(); } //----------------------------------------------------------------------------// -void GUIContext::resetWindowContainingMouse() +void GUIContext::resetWindowContainingCursor() { - d_windowContainingMouse = 0; - d_windowContainingMouseIsUpToDate = true; + d_windowContainingCursor = 0; + d_windowContainingCursorIsUpToDate = true; } //----------------------------------------------------------------------------// GUIContext::~GUIContext() { destroyDefaultTooltipWindowInstance(); + deleteSemanticEventHandlers(); if (d_rootWindow) d_rootWindow->setGUIContext(0); - - delete[] d_mouseClickTrackers; } //----------------------------------------------------------------------------// @@ -243,15 +208,15 @@ Window* GUIContext::getModalWindow() const } //----------------------------------------------------------------------------// -Window* GUIContext::getWindowContainingMouse() const +Window* GUIContext::getWindowContainingCursor() const { - if (!d_windowContainingMouseIsUpToDate) + if (!d_windowContainingCursorIsUpToDate) { - updateWindowContainingMouse_impl(); - d_windowContainingMouseIsUpToDate = true; + updateWindowContainingCursor_impl(); + d_windowContainingCursorIsUpToDate = true; } - return d_windowContainingMouse; + return d_windowContainingCursor; } //----------------------------------------------------------------------------// @@ -260,12 +225,6 @@ const Sizef& GUIContext::getSurfaceSize() const return d_surfaceSize; } -//----------------------------------------------------------------------------// -const SystemKeys& GUIContext::getSystemKeys() const -{ - return d_systemKeys; -} - //----------------------------------------------------------------------------// void GUIContext::markAsDirty() { @@ -292,7 +251,7 @@ void GUIContext::drawContent() { RenderingSurface::drawContent(); - d_mouseCursor.draw(); + d_cursor.draw(); } //----------------------------------------------------------------------------// @@ -319,95 +278,23 @@ void GUIContext::renderWindowHierarchyToSurfaces() } //----------------------------------------------------------------------------// -MouseCursor& GUIContext::getMouseCursor() +Cursor& GUIContext::getCursor() { - return const_cast( - static_cast(this)->getMouseCursor()); + return const_cast( + static_cast(this)->getCursor()); } //----------------------------------------------------------------------------// -const MouseCursor& GUIContext::getMouseCursor() const +const Cursor& GUIContext::getCursor() const { - return d_mouseCursor; -} - -//----------------------------------------------------------------------------// -void GUIContext::setMouseMoveScalingFactor(float factor) -{ - d_mouseMovementScalingFactor = factor; - - GUIContextEventArgs args(this); - onMouseMoveScalingFactorChanged(args); -} - -//----------------------------------------------------------------------------// -float GUIContext::getMouseMoveScalingFactor() const -{ - return d_mouseMovementScalingFactor; -} - -//----------------------------------------------------------------------------// -void GUIContext::setMouseButtonClickTimeout(float seconds) -{ - d_mouseButtonClickTimeout = seconds; - - GUIContextEventArgs args(this); - onMouseButtonClickTimeoutChanged(args); -} - -//----------------------------------------------------------------------------// -float GUIContext::getMouseButtonClickTimeout() const -{ - return d_mouseButtonClickTimeout; -} - -//----------------------------------------------------------------------------// -void GUIContext::setMouseButtonMultiClickTimeout(float seconds) -{ - d_mouseButtonMultiClickTimeout = seconds; - - GUIContextEventArgs args(this); - onMouseButtonMultiClickTimeoutChanged(args); -} - -//----------------------------------------------------------------------------// -float GUIContext::getMouseButtonMultiClickTimeout() const -{ - return d_mouseButtonMultiClickTimeout; -} - -//----------------------------------------------------------------------------// -void GUIContext::setMouseButtonMultiClickTolerance(const Sizef& sz) -{ - d_mouseButtonMultiClickTolerance = sz; - - GUIContextEventArgs args(this); - onMouseButtonMultiClickToleranceChanged(args); -} - -//----------------------------------------------------------------------------// -const Sizef& GUIContext::getMouseButtonMultiClickTolerance() const -{ - return d_mouseButtonMultiClickTolerance; -} - -//----------------------------------------------------------------------------// -void GUIContext::setMouseClickEventGenerationEnabled(const bool enable) -{ - d_generateMouseClickEvents = enable; -} - -//----------------------------------------------------------------------------// -bool GUIContext::isMouseClickEventGenerationEnabled() const -{ - return d_generateMouseClickEvents; + return d_cursor; } //----------------------------------------------------------------------------// bool GUIContext::areaChangedHandler(const EventArgs&) { d_surfaceSize = d_target->getArea().getSize(); - d_mouseCursor.notifyDisplaySizeChanged(d_surfaceSize); + d_cursor.notifyDisplaySizeChanged(d_surfaceSize); if (d_rootWindow) updateRootWindowAreaRects(); @@ -424,8 +311,8 @@ bool GUIContext::windowDestroyedHandler(const EventArgs& args) if (window == d_rootWindow) d_rootWindow = 0; - if (window == getWindowContainingMouse()) - resetWindowContainingMouse(); + if (window == getWindowContainingCursor()) + resetWindowContainingCursor(); if (window == d_modalWindow) d_modalWindow = 0; @@ -454,128 +341,60 @@ void GUIContext::onRootWindowChanged(WindowEventArgs& args) } //----------------------------------------------------------------------------// -void GUIContext::onMouseMoveScalingFactorChanged(GUIContextEventArgs& args) -{ - fireEvent(EventMouseMoveScalingFactorChanged, args); -} - -//----------------------------------------------------------------------------// -void GUIContext::onMouseButtonClickTimeoutChanged(GUIContextEventArgs& args) +void GUIContext::updateWindowContainingCursor() { - fireEvent(EventMouseButtonClickTimeoutChanged, args); + d_windowContainingCursorIsUpToDate = false; } //----------------------------------------------------------------------------// -void GUIContext::onMouseButtonMultiClickTimeoutChanged(GUIContextEventArgs& args) +bool GUIContext::updateWindowContainingCursor_impl() const { - fireEvent(EventMouseButtonMultiClickTimeoutChanged, args); -} + CursorInputEventArgs ciea(0); + const glm::vec2 cursor_pos(d_cursor.getPosition()); -//----------------------------------------------------------------------------// -void GUIContext::onMouseButtonMultiClickToleranceChanged(GUIContextEventArgs& args) -{ - fireEvent(EventMouseButtonMultiClickToleranceChanged, args); -} + Window* const window_with_cursor = getTargetWindow(cursor_pos, true); -//----------------------------------------------------------------------------// -bool GUIContext::injectMouseMove(float delta_x, float delta_y) -{ - MouseEventArgs ma(0); - ma.moveDelta.d_x = delta_x * d_mouseMovementScalingFactor; - ma.moveDelta.d_y = delta_y * d_mouseMovementScalingFactor; - - // no movement means no event - if ((ma.moveDelta.d_x == 0) && (ma.moveDelta.d_y == 0)) + // exit if window containing cursor has not changed. + if (window_with_cursor == d_windowContainingCursor) return false; - d_mouseCursor.offsetPosition(ma.moveDelta); - - ma.position = d_mouseCursor.getPosition(); - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - ma.clickCount = 0; - ma.button = NoButton; + ciea.scroll = 0; + ciea.source = CIS_None; - return mouseMoveInjection_impl(ma); -} - -//----------------------------------------------------------------------------// -bool GUIContext::mouseMoveInjection_impl(MouseEventArgs& ma) -{ - updateWindowContainingMouse(); - - // input can't be handled if there is no window to handle it. - if (!getWindowContainingMouse()) - return false; - - // make mouse position sane for this target window - ma.position = getWindowContainingMouse()->getUnprojectedPosition(ma.position); - // inform window about the input. - ma.window = getWindowContainingMouse(); - ma.handled = 0; - ma.window->onMouseMove(ma); + Window* oldWindow = d_windowContainingCursor; + d_windowContainingCursor = window_with_cursor; - // return whether window handled the input. - return ma.handled != 0; -} - -//----------------------------------------------------------------------------// -void GUIContext::updateWindowContainingMouse() -{ - d_windowContainingMouseIsUpToDate = false; -} - -//----------------------------------------------------------------------------// -bool GUIContext::updateWindowContainingMouse_impl() const -{ - MouseEventArgs ma(0); - const Vector2f mouse_pos(d_mouseCursor.getPosition()); - - Window* const curr_wnd_with_mouse = getTargetWindow(mouse_pos, true); - - // exit if window containing mouse has not changed. - if (curr_wnd_with_mouse == d_windowContainingMouse) - return false; - - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - ma.clickCount = 0; - ma.button = NoButton; - - Window* oldWindow = d_windowContainingMouse; - d_windowContainingMouse = curr_wnd_with_mouse; - - // inform previous window the mouse has left it + // inform previous window the cursor has left it if (oldWindow) { - ma.window = oldWindow; - ma.position = oldWindow->getUnprojectedPosition(mouse_pos); - oldWindow->onMouseLeaves(ma); + ciea.window = oldWindow; + ciea.position = oldWindow->getUnprojectedPosition(cursor_pos); + oldWindow->onCursorLeaves(ciea); } - // inform window containing mouse that mouse has entered it - if (d_windowContainingMouse) + // inform window containing cursor that cursor has entered it + if (d_windowContainingCursor) { - ma.handled = 0; - ma.window = d_windowContainingMouse; - ma.position = d_windowContainingMouse->getUnprojectedPosition(mouse_pos); - d_windowContainingMouse->onMouseEnters(ma); + ciea.handled = 0; + ciea.window = d_windowContainingCursor; + ciea.position = d_windowContainingCursor->getUnprojectedPosition(cursor_pos); + d_windowContainingCursor->onCursorEnters(ciea); } // do the 'area' version of the events - Window* root = getCommonAncestor(oldWindow, d_windowContainingMouse); + Window* root = getCommonAncestor(oldWindow, d_windowContainingCursor); if (oldWindow) - notifyMouseTransition(root, oldWindow, &Window::onMouseLeavesArea, ma); + notifyCursorTransition(root, oldWindow, &Window::onCursorLeavesArea, ciea); - if (d_windowContainingMouse) - notifyMouseTransition(root, d_windowContainingMouse, &Window::onMouseEntersArea, ma); + if (d_windowContainingCursor) + notifyCursorTransition(root, d_windowContainingCursor, &Window::onCursorEntersArea, ciea); return true; } //----------------------------------------------------------------------------// -Window* GUIContext::getCommonAncestor(Window* w1, Window* w2) const +Window* GUIContext::getCommonAncestor(Window* w1, Window* w2) const { if (!w2) return w2; @@ -599,17 +418,17 @@ Window* GUIContext::getCommonAncestor(Window* w1, Window* w2) const } //----------------------------------------------------------------------------// -void GUIContext::notifyMouseTransition(Window* top, Window* bottom, - void (Window::*func)(MouseEventArgs&), - MouseEventArgs& args) const +void GUIContext::notifyCursorTransition(Window* top, Window* bottom, + void (Window::*func)(CursorInputEventArgs&), + CursorInputEventArgs& args) const { if (top == bottom) return; - + Window* const parent = bottom->getParent(); if (parent && parent != top) - notifyMouseTransition(top, parent, func, args); + notifyCursorTransition(top, parent, func, args); args.handled = 0; args.window = bottom; @@ -618,8 +437,8 @@ void GUIContext::notifyMouseTransition(Window* top, Window* bottom, } //----------------------------------------------------------------------------// -Window* GUIContext::getTargetWindow(const Vector2f& pt, - const bool allow_disabled) const +Window* GUIContext::getTargetWindow(const glm::vec2& pt, + const bool allow_disabled) const { // if there is no GUI sheet visible, then there is nowhere to send input if (!d_rootWindow || !d_rootWindow->isEffectiveVisible()) @@ -656,7 +475,7 @@ Window* GUIContext::getTargetWindow(const Vector2f& pt, } //----------------------------------------------------------------------------// -Window* GUIContext::getKeyboardTargetWindow() const +Window* GUIContext::getInputTargetWindow() const { // if no active sheet, there is no target widow. if (!d_rootWindow || !d_rootWindow->isEffectiveVisible()) @@ -672,253 +491,23 @@ Window* GUIContext::getKeyboardTargetWindow() const } //----------------------------------------------------------------------------// -bool GUIContext::injectMouseLeaves(void) -{ - if (!getWindowContainingMouse()) - return false; - - MouseEventArgs ma(0); - ma.position = getWindowContainingMouse()->getUnprojectedPosition( - d_mouseCursor.getPosition()); - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = NoButton; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - ma.window = getWindowContainingMouse(); - ma.clickCount = 0; - - getWindowContainingMouse()->onMouseLeaves(ma); - resetWindowContainingMouse(); - - return ma.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectMouseButtonDown(MouseButton button) +bool GUIContext::injectInputEvent(const InputEvent& event) { - d_systemKeys.mouseButtonPressed(button); - - MouseEventArgs ma(0); - ma.position = d_mouseCursor.getPosition(); - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = button; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - ma.window = getTargetWindow(ma.position, false); - // make mouse position sane for this target window - if (ma.window) - ma.position = ma.window->getUnprojectedPosition(ma.position); - - // - // Handling for multi-click generation - // - MouseClickTracker& tkr = d_mouseClickTrackers[button]; - - tkr.d_click_count++; - - // if multi-click requirements are not met - if (((d_mouseButtonMultiClickTimeout > 0) && (tkr.d_timer.elapsed() > d_mouseButtonMultiClickTimeout)) || - (!tkr.d_click_area.isPointInRect(ma.position)) || - (tkr.d_target_window != ma.window) || - (tkr.d_click_count > 3)) - { - // reset to single down event. - tkr.d_click_count = 1; - - // build new allowable area for multi-clicks - tkr.d_click_area.setPosition(ma.position); - tkr.d_click_area.setSize(d_mouseButtonMultiClickTolerance); - tkr.d_click_area.offset(Vector2f(-(d_mouseButtonMultiClickTolerance.d_width / 2), - -(d_mouseButtonMultiClickTolerance.d_height / 2))); - - // set target window for click events on this tracker - tkr.d_target_window = ma.window; - } - - // set click count in the event args - ma.clickCount = tkr.d_click_count; + if (event.d_eventType == IET_TextInputEventType) + return handleTextInputEvent(static_cast(event)); - if (ma.window) + if (event.d_eventType == IET_SemanticInputEventType) { - if (d_generateMouseClickEvents && ma.window->wantsMultiClickEvents()) - { - switch (tkr.d_click_count) - { - case 1: - ma.window->onMouseButtonDown(ma); - break; - - case 2: - ma.window->onMouseDoubleClicked(ma); - break; - - case 3: - ma.window->onMouseTripleClicked(ma); - break; - } - } - // click generation disabled, or current target window does not want - // multi-clicks, so just send a mouse down event instead. - else - { - ma.window->onMouseButtonDown(ma); - } - } - - // reset timer for this tracker. - tkr.d_timer.restart(); - - return ma.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectMouseButtonUp(MouseButton button) -{ - d_systemKeys.mouseButtonReleased(button); - - MouseEventArgs ma(0); - ma.position = d_mouseCursor.getPosition(); - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = button; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - ma.window = getTargetWindow(ma.position, false); - // make mouse position sane for this target window - if (ma.window) - ma.position = ma.window->getUnprojectedPosition(ma.position); - - // get the tracker that holds the number of down events seen so far for this button - MouseClickTracker& tkr = d_mouseClickTrackers[button]; - // set click count in the event args - ma.clickCount = tkr.d_click_count; - - // if there is no window, inputs can not be handled. - if (!ma.window) - return false; + const SemanticInputEvent& semantic_event = + static_cast(event); - // store original window becase we re-use the event args. - Window* const tgt_wnd = ma.window; + if (d_windowNavigator != 0) + d_windowNavigator->handleSemanticEvent(semantic_event); - // send 'up' input to the window - ma.window->onMouseButtonUp(ma); - // store whether the 'up' part was handled so we may reuse the EventArgs - const uint upHandled = ma.handled; - - // restore target window (because Window::on* may have propagated input) - ma.window = tgt_wnd; - - // send MouseClicked event if the requirements for that were met - if (d_generateMouseClickEvents && - ((d_mouseButtonClickTimeout == 0) || (tkr.d_timer.elapsed() <= d_mouseButtonClickTimeout)) && - (tkr.d_click_area.isPointInRect(ma.position)) && - (tkr.d_target_window == ma.window)) - { - ma.handled = 0; - ma.window->onMouseClicked(ma); + return handleSemanticInputEvent(semantic_event); } - return (ma.handled + upHandled) != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectKeyDown(Key::Scan scan_code) -{ - d_systemKeys.keyPressed(scan_code); - - KeyEventArgs args(getKeyboardTargetWindow()); - - // if there's no destination window, input can't be handled. - if (!args.window) - return false; - - args.scancode = scan_code; - args.sysKeys = d_systemKeys.get(); - - args.window->onKeyDown(args); - return args.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectKeyUp(Key::Scan scan_code) -{ - d_systemKeys.keyReleased(scan_code); - - KeyEventArgs args(getKeyboardTargetWindow()); - - // if there's no destination window, input can't be handled. - if (!args.window) - return false; - - args.scancode = scan_code; - args.sysKeys = d_systemKeys.get(); - - args.window->onKeyUp(args); - return args.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectChar(String::value_type code_point) -{ - KeyEventArgs args(getKeyboardTargetWindow()); - - // if there's no destination window, input can't be handled. - if (!args.window) - return false; - - args.codepoint = code_point; - args.sysKeys = d_systemKeys.get(); - - args.window->onCharacter(args); - return args.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectMouseWheelChange(float delta) -{ - MouseEventArgs ma(0); - ma.position = d_mouseCursor.getPosition(); - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = NoButton; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = delta; - ma.clickCount = 0; - ma.window = getTargetWindow(ma.position, false); - // make mouse position sane for this target window - if (ma.window) - ma.position = ma.window->getUnprojectedPosition(ma.position); - - // if there is no target window, input can not be handled. - if (!ma.window) - return false; - - ma.window->onMouseWheel(ma); - return ma.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectMousePosition(float x_pos, float y_pos) -{ - const Vector2f new_position(x_pos, y_pos); - - // setup mouse movement event args object. - MouseEventArgs ma(0); - ma.moveDelta = new_position - d_mouseCursor.getPosition(); - - // no movement means no event - if ((ma.moveDelta.d_x == 0) && (ma.moveDelta.d_y == 0)) - return false; - - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - ma.clickCount = 0; - ma.button = NoButton; - - // move mouse cursor to new position - d_mouseCursor.setPosition(new_position); - // update position in args (since actual position may be constrained) - ma.position = d_mouseCursor.getPosition(); - - return mouseMoveInjection_impl(ma); + return false; } //----------------------------------------------------------------------------// @@ -928,8 +517,8 @@ bool GUIContext::injectTimePulse(float timeElapsed) if (!d_rootWindow || !d_rootWindow->isEffectiveVisible()) return false; - // ensure window containing mouse is now valid - getWindowContainingMouse(); + // ensure window containing cursor is now valid + getWindowContainingCursor(); // else pass to sheet for distribution. d_rootWindow->update(timeElapsed); @@ -938,93 +527,38 @@ bool GUIContext::injectTimePulse(float timeElapsed) } //----------------------------------------------------------------------------// -bool GUIContext::injectMouseButtonClick(const MouseButton button) -{ - MouseEventArgs ma(0); - ma.position = d_mouseCursor.getPosition(); - ma.window = getTargetWindow(ma.position, false); - - if (ma.window) - { - // initialise remainder of args struct. - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = button; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - // make mouse position sane for this target window - ma.position = ma.window->getUnprojectedPosition(ma.position); - // tell the window about the event. - ma.window->onMouseClicked(ma); - } - - return ma.handled != 0; -} - -//----------------------------------------------------------------------------// -bool GUIContext::injectMouseButtonDoubleClick(const MouseButton button) +bool GUIContext::handleCopyRequest(const SemanticInputEvent& event) { - MouseEventArgs ma(0); - ma.position = d_mouseCursor.getPosition(); - ma.window = getTargetWindow(ma.position, false); - - if (ma.window && ma.window->wantsMultiClickEvents()) - { - // initialise remainder of args struct. - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = button; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - // make mouse position sane for this target window - ma.position = ma.window->getUnprojectedPosition(ma.position); - // tell the window about the event. - ma.window->onMouseDoubleClicked(ma); - } - - return ma.handled != 0; + Window* source = getInputTargetWindow(); + return source ? source->performCopy(*System::getSingleton().getClipboard()) : false; } //----------------------------------------------------------------------------// -bool GUIContext::injectMouseButtonTripleClick(const MouseButton button) +bool GUIContext::handleCutRequest(const SemanticInputEvent& event) { - MouseEventArgs ma(0); - ma.position = d_mouseCursor.getPosition(); - ma.window = getTargetWindow(ma.position, false); - - if (ma.window && ma.window->wantsMultiClickEvents()) - { - // initialise remainder of args struct. - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = button; - ma.sysKeys = d_systemKeys.get(); - ma.wheelChange = 0; - // make mouse position sane for this target window - ma.position = ma.window->getUnprojectedPosition(ma.position); - // tell the window about the event. - ma.window->onMouseTripleClicked(ma); - } - - return ma.handled != 0; + Window* source = getInputTargetWindow(); + return source ? source->performCut(*System::getSingleton().getClipboard()) : false; } //----------------------------------------------------------------------------// -bool GUIContext::injectCopyRequest() +bool GUIContext::handlePasteRequest(const SemanticInputEvent& event) { - Window* source = getKeyboardTargetWindow(); - return source ? source->performCopy(*System::getSingleton().getClipboard()) : false; + Window* target = getInputTargetWindow(); + return target ? target->performPaste(*System::getSingleton().getClipboard()) : false; } //----------------------------------------------------------------------------// -bool GUIContext::injectCutRequest() +bool GUIContext::injectUndoRequest() { - Window* source = getKeyboardTargetWindow(); - return source ? source->performCut(*System::getSingleton().getClipboard()) : false; + Window* target = getInputTargetWindow(); + return target ? target->performUndo() : false; } //----------------------------------------------------------------------------// -bool GUIContext::injectPasteRequest() +bool GUIContext::injectRedoRequest() { - Window* target = getKeyboardTargetWindow(); - return target ? target->performPaste(*System::getSingleton().getClipboard()) : false; + Window* target = getInputTargetWindow(); + return target ? target->performRedo() : false; } //----------------------------------------------------------------------------// @@ -1110,7 +644,227 @@ void GUIContext::notifyDefaultFontChanged(Window* hierarchy_root) const } //----------------------------------------------------------------------------// +bool GUIContext::handleTextInputEvent(const TextInputEvent& event) +{ + TextEventArgs args(getInputTargetWindow()); + + // if there's no destination window, input can't be handled. + if (!args.window) + return false; + + args.character = event.d_character; + + args.window->onCharacter(args); + return args.handled != 0; +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleSemanticInputEvent(const SemanticInputEvent& event) +{ + // dispatch to a handler if we have one + std::map*>::const_iterator itor = + d_semanticEventHandlers.find(event.d_value); + if (itor != d_semanticEventHandlers.end()) + { + return (*(*itor).second)(event); + } + + Window* targetWindow = getTargetWindow(d_cursor.getPosition(), false); + // window navigator's window takes precedence + if (d_windowNavigator != 0) + targetWindow = d_windowNavigator->getCurrentFocusedWindow(); + + if (targetWindow != 0) + { + SemanticEventArgs args(targetWindow); + + args.d_payload = event.d_payload; + args.d_semanticValue = event.d_value; + + args.window->onSemanticInputEvent(args); + + return args.handled != 0; + } + + return false; +} + +//----------------------------------------------------------------------------// +void GUIContext::initializeSemanticEventHandlers() +{ + d_semanticEventHandlers.insert(std::make_pair(SV_Cut, + new InputEventHandlerSlot( + &GUIContext::handleCutRequest, this))); + d_semanticEventHandlers.insert(std::make_pair(SV_Copy, + new InputEventHandlerSlot( + &GUIContext::handleCopyRequest, this))); + d_semanticEventHandlers.insert(std::make_pair(SV_Paste, + new InputEventHandlerSlot( + &GUIContext::handlePasteRequest, this))); + d_semanticEventHandlers.insert(std::make_pair(SV_VerticalScroll, + new InputEventHandlerSlot( + &GUIContext::handleScrollEvent, this))); + + d_semanticEventHandlers.insert(std::make_pair(SV_CursorActivate, + new InputEventHandlerSlot( + &GUIContext::handleCursorActivateEvent, this))); + d_semanticEventHandlers.insert(std::make_pair(SV_CursorPressHold, + new InputEventHandlerSlot( + &GUIContext::handleCursorPressHoldEvent, this))); + d_semanticEventHandlers.insert(std::make_pair(SV_CursorMove, + new InputEventHandlerSlot( + &GUIContext::handleCursorMoveEvent, this))); +} + +//----------------------------------------------------------------------------// +void GUIContext::deleteSemanticEventHandlers() +{ + for (std::map*>::iterator itor = d_semanticEventHandlers.begin(); + itor != d_semanticEventHandlers.end(); ++itor) + { + delete itor->second; + } +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleCursorActivateEvent(const SemanticInputEvent& event) +{ + CursorInputEventArgs ciea(0); + ciea.position = d_cursor.getPosition(); + ciea.moveDelta = glm::vec2(0, 0); + ciea.source = event.d_payload.source; + ciea.scroll = 0; + ciea.window = getTargetWindow(ciea.position, false); + // make cursor position sane for this target window + if (ciea.window) + ciea.position = ciea.window->getUnprojectedPosition(ciea.position); + + // if there is no target window, input can not be handled. + if (!ciea.window) + return false; + + if (d_windowNavigator != 0) + d_windowNavigator->setCurrentFocusedWindow(ciea.window); + + ciea.window->onCursorActivate(ciea); + return ciea.handled != 0; +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleCursorPressHoldEvent(const SemanticInputEvent& event) +{ + CursorInputEventArgs ciea(0); + ciea.position = d_cursor.getPosition(); + ciea.moveDelta = glm::vec2(0, 0); + ciea.source = event.d_payload.source; + ciea.scroll = 0; + ciea.window = getTargetWindow(ciea.position, false); + // make cursor position sane for this target window + if (ciea.window) + ciea.position = ciea.window->getUnprojectedPosition(ciea.position); + + if (d_windowNavigator != 0) + d_windowNavigator->setCurrentFocusedWindow(ciea.window); + + ciea.window->onCursorPressHold(ciea); + return ciea.handled != 0; +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleScrollEvent(const SemanticInputEvent& event) +{ + CursorInputEventArgs ciea(0); + ciea.position = d_cursor.getPosition(); + ciea.moveDelta = glm::vec2(0, 0); + ciea.source = CIS_None; + ciea.scroll = event.d_payload.single; + ciea.window = getTargetWindow(ciea.position, false); + // make cursor position sane for this target window + if (ciea.window) + ciea.position = ciea.window->getUnprojectedPosition(ciea.position); + + // if there is no target window, input can not be handled. + if (!ciea.window) + return false; + + ciea.window->onScroll(ciea); + return ciea.handled != 0; +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleCursorMove_impl(CursorInputEventArgs& pa) +{ + updateWindowContainingCursor(); + + // input can't be handled if there is no window to handle it. + if (!getWindowContainingCursor()) + return false; + + // make cursor position sane for this target window + pa.position = getWindowContainingCursor()->getUnprojectedPosition(pa.position); + // inform window about the input. + pa.window = getWindowContainingCursor(); + pa.handled = 0; + pa.window->onCursorMove(pa); + + // return whether window handled the input. + return pa.handled != 0; +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleCursorMoveEvent(const SemanticInputEvent& event) +{ + const glm::vec2 new_position( + event.d_payload.array[0], + event.d_payload.array[1]); + + // setup cursor movement event args object. + CursorInputEventArgs ciea(0); + ciea.moveDelta = new_position - d_cursor.getPosition(); + + // no movement means no event + if ((ciea.moveDelta.x == 0) && (ciea.moveDelta.y == 0)) + return false; + + ciea.scroll = 0; + ciea.source = CIS_None; + ciea.state = d_cursorsState; + + // move cursor to new position + d_cursor.setPosition(new_position); + // update position in args (since actual position may be constrained) + ciea.position = d_cursor.getPosition(); + + return handleCursorMove_impl(ciea); +} + +//----------------------------------------------------------------------------// +bool GUIContext::handleCursorLeave(const SemanticInputEvent& event) +{ + if (!getWindowContainingCursor()) + return false; + + CursorInputEventArgs ciea(0); + ciea.position = getWindowContainingCursor()->getUnprojectedPosition( + d_cursor.getPosition()); + ciea.moveDelta = glm::vec2(0, 0); + ciea.source = CIS_None; + ciea.scroll = 0; + ciea.window = getWindowContainingCursor(); + + getWindowContainingCursor()->onCursorLeaves(ciea); + resetWindowContainingCursor(); + + return ciea.handled != 0; +} + +//----------------------------------------------------------------------------// +void GUIContext::setWindowNavigator(WindowNavigator* navigator) +{ + d_windowNavigator = navigator; +} +//----------------------------------------------------------------------------// #if defined(_MSC_VER) # pragma warning(pop) #endif diff --git a/cegui/src/GeometryBuffer.cpp b/cegui/src/GeometryBuffer.cpp index ad8d906df..f9cee29d5 100644 --- a/cegui/src/GeometryBuffer.cpp +++ b/cegui/src/GeometryBuffer.cpp @@ -25,20 +25,40 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/GeometryBuffer.h" +#include "CEGUI/Vertex.h" +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/RenderTarget.h" + +#include "glm/gtc/matrix_transform.hpp" + +#include +#include +#include +#include -// Start of CEGUI namespace section namespace CEGUI { //---------------------------------------------------------------------------// -GeometryBuffer::GeometryBuffer() : - d_blendMode(BM_NORMAL) -{ -} +GeometryBuffer::GeometryBuffer(RefCounted renderMaterial): + d_translation(0, 0, 0), + d_rotation(1, 0, 0, 0), // <-- IDENTITY + d_scale(1.0f, 1.0f, 1.0f), + d_pivot(0, 0, 0), + d_customTransform(1.0f), + d_effect(0), + d_blendMode(BM_NORMAL), + d_renderMaterial(renderMaterial), + d_polygonFillRule(PFR_NONE), + d_postStencilVertexCount(0), + d_alpha(1.0f), + d_matrixValid(false), + d_lastRenderTarget(0), + d_lastRenderTargetActivationCount(0) +{} //---------------------------------------------------------------------------// GeometryBuffer::~GeometryBuffer() -{ -} +{} //---------------------------------------------------------------------------// void GeometryBuffer::setBlendMode(const BlendMode mode) @@ -53,6 +73,357 @@ BlendMode GeometryBuffer::getBlendMode() const } //---------------------------------------------------------------------------// +void GeometryBuffer::appendGeometry(const std::vector& coloured_vertices) +{ + if(coloured_vertices.empty()) + return; + + appendGeometry(&coloured_vertices[0], coloured_vertices.size()); +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array, + std::size_t vertex_count) +{ + // Create a temporary array to contain our data + static const std::size_t vertexDataSize = 7; + std::size_t fullArraySize = vertexDataSize * vertex_count; + float* vertexData = new float[fullArraySize]; + + // Add the vertex data in their default order into an array + const ColouredVertex* vs = vertex_array; + for (std::size_t i = 0; i < vertex_count; ++i, ++vs) + { + // Add all the elements in the default order for textured and coloured + // geometry into the vector + std::size_t currentIndex = i * vertexDataSize; + + vertexData[currentIndex + 0] = vs->d_position.x; + vertexData[currentIndex + 1] = vs->d_position.y; + vertexData[currentIndex + 2] = vs->d_position.z; + vertexData[currentIndex + 3] = vs->d_colour.x; + vertexData[currentIndex + 4] = vs->d_colour.y; + vertexData[currentIndex + 5] = vs->d_colour.z; + vertexData[currentIndex + 6] = vs->d_colour.w; + } + + // Append the prepared geometry data + appendGeometry(vertexData, fullArraySize); + + delete[] vertexData; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::appendGeometry(const std::vector& textured_vertices) +{ + if(textured_vertices.empty()) + return; + + appendGeometry(&textured_vertices[0], textured_vertices.size()); +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array, + std::size_t vertex_count) +{ + // Create a temporary array to contain our data + static const std::size_t vertexDataSize = 9; + std::size_t fullArraySize = vertexDataSize * vertex_count; + float* vertexData = new float[fullArraySize]; + + // Add the vertex data in their default order into an array + const TexturedColouredVertex* vs = vertex_array; + for (std::size_t i = 0; i < vertex_count; ++i, ++vs) + { + // Add all the elements in the default order for textured and coloured + // geometry into the vector + std::size_t currentIndex = i * vertexDataSize; + + vertexData[currentIndex + 0] = vs->d_position.x; + vertexData[currentIndex + 1] = vs->d_position.y; + vertexData[currentIndex + 2] = vs->d_position.z; + vertexData[currentIndex + 3] = vs->d_colour.x; + vertexData[currentIndex + 4] = vs->d_colour.y; + vertexData[currentIndex + 5] = vs->d_colour.z; + vertexData[currentIndex + 6] = vs->d_colour.w; + vertexData[currentIndex + 7] = vs->d_texCoords.x; + vertexData[currentIndex + 8] = vs->d_texCoords.y; + } + + // Append the prepared geometry data + appendGeometry(vertexData, fullArraySize); + + delete[] vertexData; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::appendGeometry(const float* vertex_data, + std::size_t array_size) +{ + d_vertexData.reserve( d_vertexData.size() + array_size); + std::copy(vertex_data, vertex_data + array_size, std::back_inserter(d_vertexData)); + + // Update size of geometry buffer + d_vertexCount = d_vertexData.size() / getVertexAttributeElementCount(); +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex) +{ + // Add the vertex data in their default order into an array + float vertexData[9]; + + // Copy the vertex attributes into the array + vertexData[0] = vertex.d_position.x; + vertexData[1] = vertex.d_position.y; + vertexData[2] = vertex.d_position.z; + vertexData[3] = vertex.d_colour.x; + vertexData[4] = vertex.d_colour.y; + vertexData[5] = vertex.d_colour.z; + vertexData[6] = vertex.d_colour.w; + vertexData[7] = vertex.d_texCoords.x; + vertexData[8] = vertex.d_texCoords.y; + + appendGeometry(vertexData, 9); +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::appendVertex(const ColouredVertex& vertex) +{ + // Add the vertex data in their default order into an array + float vertexData[7]; + + // Copy the vertex attributes into the array + vertexData[0] = vertex.d_position.x; + vertexData[1] = vertex.d_position.y; + vertexData[2] = vertex.d_position.z; + vertexData[3] = vertex.d_colour.x; + vertexData[4] = vertex.d_colour.y; + vertexData[5] = vertex.d_colour.z; + vertexData[6] = vertex.d_colour.w; + + appendGeometry(vertexData, 7); +} + +//---------------------------------------------------------------------------// +int GeometryBuffer::getVertexAttributeElementCount() const +{ + int count = 0; + + const unsigned int attribute_count = d_vertexAttributes.size(); + for (unsigned int i = 0; i < attribute_count; ++i) + { + switch(d_vertexAttributes.at(i)) + { + case VAT_POSITION0: + count += 3; + break; + case VAT_COLOUR0: + count += 4; + break; + case VAT_TEXCOORD0: + count += 2; + break; + default: + break; + } + } + + return count; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::resetVertexAttributes() +{ + d_vertexAttributes.clear(); +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::addVertexAttribute(VertexAttributeType attribute) +{ + d_vertexAttributes.push_back(attribute); +} + +//---------------------------------------------------------------------------// +RefCounted GeometryBuffer::getRenderMaterial() const +{ + return d_renderMaterial; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::setRenderMaterial(RefCounted render_material) +{ + d_renderMaterial = render_material; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule) +{ + d_polygonFillRule = fill_rule; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count) +{ + d_postStencilVertexCount = vertex_count; +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setRenderEffect(RenderEffect* effect) +{ + d_effect = effect; +} + +//----------------------------------------------------------------------------// +RenderEffect* GeometryBuffer::getRenderEffect() +{ + return d_effect; +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setTranslation(const glm::vec3& translation) +{ + if (d_translation != translation) + { + d_translation = translation; + d_matrixValid = false; + } +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setRotation(const glm::quat& rotationQuat) +{ + if (d_rotation != rotationQuat) + { + d_rotation = rotationQuat; + d_matrixValid = false; + } +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setScale(const glm::vec3& scale) +{ + if (d_scale != scale) + { + d_scale = scale; + d_matrixValid = false; + } +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setScale(const glm::vec2& scale) +{ + setScale(glm::vec3(scale, 0)); +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setPivot(const glm::vec3& p) +{ + if (d_pivot != p) + { + d_pivot = p; + d_matrixValid = false; + } +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation) +{ + if(d_customTransform != transformation) + { + d_customTransform = transformation; + d_matrixValid = false; + } +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setClippingActive(const bool active) +{ + d_clippingActive = active; +} + +//----------------------------------------------------------------------------// +bool GeometryBuffer::isClippingActive() const +{ + return d_clippingActive; +} + + +//----------------------------------------------------------------------------// +std::size_t GeometryBuffer::getVertexCount() const +{ + return d_vertexCount; +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::reset() +{ + d_vertexData.clear(); + d_clippingActive = true; +} + +//----------------------------------------------------------------------------// +void GeometryBuffer::setTexture(const std::string& parameterName, const Texture* texture) +{ + CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings(); + shaderParameterBindings->setParameter(parameterName, texture); +} -} // End of CEGUI namespace section +//---------------------------------------------------------------------------// +void GeometryBuffer::setAlpha(float alpha) +{ + d_alpha = alpha; +} + +//---------------------------------------------------------------------------// +float GeometryBuffer::getAlpha() const +{ + return d_alpha; +} + +//---------------------------------------------------------------------------// +void GeometryBuffer::invalidateMatrix() +{ + d_matrixValid = false; +} + +//---------------------------------------------------------------------------// +const RenderTarget* GeometryBuffer::getLastRenderTarget() const +{ + return d_lastRenderTarget; +} + +//---------------------------------------------------------------------------// +bool GeometryBuffer::isRenderTargetDataValid(const RenderTarget* activeRenderTarget) const +{ + //! The data received from the RenderTarget is only valid if: + //! 1. The RenderTarget is the same as the one used the last time + //! 2. The GeometryBuffer never skipped a RenderTarget activation (Checked via counter) + return (d_lastRenderTarget == activeRenderTarget) && (d_lastRenderTargetActivationCount + 1 == activeRenderTarget->getActivationCounter()); +} + +//--------------------------------------------------------------------------// +void GeometryBuffer::updateRenderTargetData(const RenderTarget* activeRenderTarget) const +{ + d_lastRenderTarget = activeRenderTarget; + d_lastRenderTargetActivationCount = activeRenderTarget->getActivationCounter(); +} + + +//----------------------------------------------------------------------------// +glm::mat4 GeometryBuffer::getModelMatrix() const +{ + glm::mat4 modelMatrix = glm::translate(glm::mat4(1.0f), d_translation + d_pivot); + + const glm::mat4 scale_matrix(glm::scale(glm::mat4(1.0f), d_scale)); + modelMatrix *= glm::mat4_cast(d_rotation) * scale_matrix; + + const glm::mat4 translMatrix = glm::translate(glm::mat4(1.0f), -d_pivot); + modelMatrix *= translMatrix * d_customTransform; + + return modelMatrix; +} + + +} diff --git a/cegui/src/IconvStringTranscoder.cpp b/cegui/src/IconvStringTranscoder.cpp index 1a5df2995..c04960d78 100644 --- a/cegui/src/IconvStringTranscoder.cpp +++ b/cegui/src/IconvStringTranscoder.cpp @@ -99,12 +99,12 @@ static T* iconvTranscode(IconvHelper& ich, const char* in_buf, size_t in_len) // Handle empty strings if (in_len == 0) { - T* ret_buff = CEGUI_NEW_ARRAY_PT(T, 1, CEGUI::BufferAllocator); + T* ret_buff = new T[1]; ret_buff[0] = 0; return ret_buff; } - std::vector out_vec; + std::vector out_vec; out_vec.resize(in_len); size_t out_count = 0; @@ -124,8 +124,7 @@ static T* iconvTranscode(IconvHelper& ich, const char* in_buf, size_t in_len) if (result != static_cast(-1)) { - T* ret_buff = CEGUI_NEW_ARRAY_PT(T, out_count + 1, - CEGUI::BufferAllocator); + T* ret_buff = new T[out_count + 1]; memcpy(ret_buff, &out_vec[0], out_count * sizeof(T)); ret_buff[out_count] = 0; return ret_buff; @@ -160,8 +159,7 @@ static size_t getStringLength(const T* buffer) template static void deleteTranscodeBuffer(T* buffer) { - CEGUI_DELETE_ARRAY_PT( - buffer, T, getStringLength(buffer) + 1, CEGUI::BufferAllocator); + delete[] buffer; } //----------------------------------------------------------------------------// diff --git a/cegui/src/Image.cpp b/cegui/src/Image.cpp index 1a947b3c7..77fe80360 100644 --- a/cegui/src/Image.cpp +++ b/cegui/src/Image.cpp @@ -26,12 +26,48 @@ ***************************************************************************/ #include "CEGUI/Image.h" #include "CEGUI/Logger.h" +#include "CEGUI/System.h" #include // Start of CEGUI namespace section namespace CEGUI { +//----------------------------------------------------------------------------// +Image::Image(const String& name) : + d_name(name), + d_pixelOffset(0.0f, 0.0f), + d_imageArea(0.0f, 0.0f, 0.0f, 0.0f), + d_autoScaled(ASM_Disabled), + d_nativeResolution(640, 480), + d_scaledSize(0, 0), + d_scaledOffset(0, 0) +{ + // force initialisation of the autoscaling fields. + updateScaledSizeAndOffset( + System::getSingleton().getRenderer()->getDisplaySize()); +} + +//----------------------------------------------------------------------------// +Image::Image(const String& name, + const glm::vec2& pixel_offset, + const Rectf& image_area, + AutoScaledMode auto_scaled, + const Sizef& native_resolution + ) : + d_name(name), + d_pixelOffset(pixel_offset), + d_imageArea(image_area), + d_autoScaled(auto_scaled), + d_nativeResolution(native_resolution), + d_scaledSize(0, 0), + d_scaledOffset(0, 0) +{ + // force initialisation of the autoscaling fields. + updateScaledSizeAndOffset( + System::getSingleton().getRenderer()->getDisplaySize()); +} + //----------------------------------------------------------------------------// Image::~Image() @@ -99,6 +135,120 @@ void Image::elementEndLocal(const String& element) } //----------------------------------------------------------------------------// +const String& Image::getName() const +{ + return d_name; +} + +//----------------------------------------------------------------------------// +const Sizef& Image::getRenderedSize() const +{ + return d_scaledSize; +} + +//----------------------------------------------------------------------------// +const glm::vec2& Image::getRenderedOffset() const +{ + return d_scaledOffset; +} + +//----------------------------------------------------------------------------// +void Image::setImageArea(const Rectf& image_area) +{ + d_imageArea = image_area; + + if (d_autoScaled != ASM_Disabled) + updateScaledSizeAndOffset( + System::getSingleton().getRenderer()->getDisplaySize()); + else + { + d_scaledSize = d_imageArea.getSize(); + } +} + +//----------------------------------------------------------------------------// +void Image::setOffset(const glm::vec2& pixel_offset) +{ + d_pixelOffset = pixel_offset; -} // End of CEGUI namespace section + if (d_autoScaled != ASM_Disabled) + updateScaledOffset( + System::getSingleton().getRenderer()->getDisplaySize()); + else + d_scaledOffset = d_pixelOffset; +} + +//----------------------------------------------------------------------------// +void Image::setAutoScaled(const AutoScaledMode autoscaled) +{ + d_autoScaled = autoscaled; + + if (d_autoScaled != ASM_Disabled) + { + updateScaledSizeAndOffset( + System::getSingleton().getRenderer()->getDisplaySize()); + } + else + { + d_scaledSize = d_imageArea.getSize(); + d_scaledOffset = d_pixelOffset; + } +} + +//----------------------------------------------------------------------------// +void Image::setNativeResolution(const Sizef& native_res) +{ + d_nativeResolution = native_res; + + if (d_autoScaled != ASM_Disabled) + updateScaledSizeAndOffset( + System::getSingleton().getRenderer()->getDisplaySize()); +} + + +//----------------------------------------------------------------------------// +void Image::notifyDisplaySizeChanged(const Sizef& renderer_display_size) +{ + //If we use autoscaling of any sort we must update the scaled size and offset + if (d_autoScaled != ASM_Disabled) + updateScaledSizeAndOffset(renderer_display_size); +} + +//----------------------------------------------------------------------------// + +void Image::updateScaledSizeAndOffset(const Sizef& renderer_display_size) +{ + glm::vec2 scaleFactors; + + computeScalingFactors(d_autoScaled, renderer_display_size, d_nativeResolution, + scaleFactors.x, scaleFactors.y); + + d_scaledSize = d_imageArea.getSize() * scaleFactors; + d_scaledOffset = d_pixelOffset * scaleFactors; +} + +//----------------------------------------------------------------------------// +void Image::updateScaledSize(const Sizef& renderer_display_size) +{ + glm::vec2 scaleFactors; + + computeScalingFactors(d_autoScaled, renderer_display_size, d_nativeResolution, + scaleFactors.x, scaleFactors.y); + + d_scaledSize = d_imageArea.getSize() * scaleFactors; +} + +//----------------------------------------------------------------------------// +void Image::updateScaledOffset(const Sizef& renderer_display_size) +{ + glm::vec2 scaleFactors; + + computeScalingFactors(d_autoScaled, renderer_display_size, d_nativeResolution, + scaleFactors.x, scaleFactors.y); + + d_scaledOffset = d_pixelOffset * scaleFactors; +} + +//----------------------------------------------------------------------------// +} \ No newline at end of file diff --git a/cegui/src/ImageCodecModules/Corona/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/Corona/ImageCodecModule.cpp index 170d90f0c..b4a7005a7 100644 --- a/cegui/src/ImageCodecModules/Corona/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/Corona/ImageCodecModule.cpp @@ -31,11 +31,11 @@ CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::CoronaImageCodec(); + return new CEGUI::CoronaImageCodec(); } void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } diff --git a/cegui/src/ImageCodecModules/DevIL/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/DevIL/ImageCodecModule.cpp index 05c8bc801..02c8ccef0 100644 --- a/cegui/src/ImageCodecModules/DevIL/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/DevIL/ImageCodecModule.cpp @@ -31,11 +31,11 @@ CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::DevILImageCodec(); + return new CEGUI::DevILImageCodec(); } void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } diff --git a/cegui/src/ImageCodecModules/FreeImage/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/FreeImage/ImageCodecModule.cpp index 080aa6a43..d48a74a7f 100644 --- a/cegui/src/ImageCodecModules/FreeImage/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/FreeImage/ImageCodecModule.cpp @@ -31,11 +31,11 @@ CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::FreeImageImageCodec(); + return new CEGUI::FreeImageImageCodec(); } void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } diff --git a/cegui/src/ImageCodecModules/PVR/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/PVR/ImageCodecModule.cpp index 254ac395a..8c35ca0bc 100644 --- a/cegui/src/ImageCodecModules/PVR/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/PVR/ImageCodecModule.cpp @@ -29,13 +29,13 @@ //----------------------------------------------------------------------------// CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::PVRImageCodec(); + return new CEGUI::PVRImageCodec(); } //----------------------------------------------------------------------------// void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } //----------------------------------------------------------------------------// diff --git a/cegui/src/ImageCodecModules/SILLY/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/SILLY/ImageCodecModule.cpp index 3e8b32c23..a126d4960 100644 --- a/cegui/src/ImageCodecModules/SILLY/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/SILLY/ImageCodecModule.cpp @@ -31,10 +31,10 @@ CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::SILLYImageCodec(); + return new CEGUI::SILLYImageCodec(); } void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } diff --git a/cegui/src/ImageCodecModules/STB/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/STB/ImageCodecModule.cpp index 75a9e4ecc..28bd588e7 100644 --- a/cegui/src/ImageCodecModules/STB/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/STB/ImageCodecModule.cpp @@ -31,14 +31,14 @@ //----------------------------------------------------------------------------// CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::STBImageCodec(); + return new CEGUI::STBImageCodec(); } //----------------------------------------------------------------------------// void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } //----------------------------------------------------------------------------// diff --git a/cegui/src/ImageCodecModules/TGA/ImageCodecModule.cpp b/cegui/src/ImageCodecModules/TGA/ImageCodecModule.cpp index 5f4e7e3f0..4f2fb9304 100644 --- a/cegui/src/ImageCodecModules/TGA/ImageCodecModule.cpp +++ b/cegui/src/ImageCodecModules/TGA/ImageCodecModule.cpp @@ -32,10 +32,10 @@ CEGUI::ImageCodec* createImageCodec(void) { - return CEGUI_NEW_AO CEGUI::TGAImageCodec(); + return new CEGUI::TGAImageCodec(); } void destroyImageCodec(CEGUI::ImageCodec* imageCodec) { - CEGUI_DELETE_AO imageCodec; + delete imageCodec; } diff --git a/cegui/src/ImageManager.cpp b/cegui/src/ImageManager.cpp index b84f9a9f2..a3fda7a20 100644 --- a/cegui/src/ImageManager.cpp +++ b/cegui/src/ImageManager.cpp @@ -33,7 +33,10 @@ #include "CEGUI/XMLAttributes.h" #include "CEGUI/System.h" #include "CEGUI/Texture.h" -#include "CEGUI/BasicImage.h" +#include "CEGUI/BitmapImage.h" +#include "CEGUI/svg/SVGImage.h" +#include "CEGUI/svg/SVGData.h" +#include "CEGUI/svg/SVGDataManager.h" #include #include @@ -69,13 +72,16 @@ const String ImageElement( "Image" ); const String ImagesetImageFileAttribute( "imagefile" ); const String ImagesetResourceGroupAttribute( "resourceGroup" ); const String ImagesetNameAttribute( "name" ); +const String ImagesetTypeAttribute( "type" ); const String ImagesetNativeHorzResAttribute( "nativeHorzRes" ); const String ImagesetNativeVertResAttribute( "nativeVertRes" ); const String ImagesetAutoScaledAttribute( "autoScaled" ); const String ImageTextureAttribute( "texture" ); -const String ImageTypeAttribute( "type" ); +const String ImageSVGDataAttribute( "SVGData" ); const String ImageNameAttribute( "name" ); const String ImagesetVersionAttribute( "version" ); +// Internal Strings holding XML element and attribute defaults +const String ImageTypeAttributeDefault( "BitmapImage" ); //----------------------------------------------------------------------------// // note: The assets' versions aren't usually the same as CEGUI version, they @@ -90,6 +96,8 @@ const String NativeVersion( "2" ); //----------------------------------------------------------------------------// // Internal variables used when parsing XML static Texture* s_texture = 0; +static SVGData* s_SVGData = 0; +static CEGUI::String s_imagesetType = ""; static AutoScaledMode s_autoScaled = ASM_Disabled; static Sizef s_nativeResolution(640.0f, 480.0f); @@ -101,8 +109,10 @@ ImageManager::ImageManager() Logger::getSingleton().logEvent( "[CEGUI::ImageManager] Singleton created " + String(addr_buff)); - // self-register the built in 'BasicImage' type. - addImageType("BasicImage"); + // self-register the built in 'BitmapImage' type. + addImageType("BitmapImage"); + // self-register the built in 'SVGImage' type. + addImageType("SVGImage"); } //----------------------------------------------------------------------------// @@ -130,7 +140,7 @@ void ImageManager::removeImageType(const String& name) Logger::getSingleton().logEvent( "[CEGUI::ImageManager] Unregistered Image type: " + name); - CEGUI_DELETE_AO i->second; + delete i->second; d_factories.erase(name); } @@ -170,9 +180,6 @@ Image& ImageManager::create(const String& type, const String& name) //----------------------------------------------------------------------------// Image& ImageManager::create(const XMLAttributes& attributes) { - static const String type_default("BasicImage"); - - const String& type(attributes.getValueAsString(ImageTypeAttribute, type_default)); const String& name(attributes.getValueAsString(ImageNameAttribute)); if (name.empty()) @@ -183,11 +190,11 @@ Image& ImageManager::create(const XMLAttributes& attributes) CEGUI_THROW(AlreadyExistsException( "Image already exists: " + name)); - ImageFactoryRegistry::iterator i(d_factories.find(type)); + ImageFactoryRegistry::iterator i(d_factories.find(s_imagesetType)); if (i == d_factories.end()) CEGUI_THROW(UnknownObjectException( - "Unknown Image type: " + type)); + "Unknown Image type: " + s_imagesetType)); ImageFactory* factory = i->second; Image& image = factory->create(attributes); @@ -197,7 +204,7 @@ Image& ImageManager::create(const XMLAttributes& attributes) if (image.getName() != name) { const String message( - "Factory for type: " + type + " created Image named: " + + "Factory for type: " + s_imagesetType + " created Image named: " + image.getName() + ". Was expecting name: " + name); factory->destroy(image); @@ -212,7 +219,7 @@ Image& ImageManager::create(const XMLAttributes& attributes) Logger::getSingleton().logEvent( "[ImageManager] Created image: '" + name + "' (" + addr_buff + - ") of type: " + type); + ") of type: " + s_imagesetType); return image; } @@ -309,7 +316,7 @@ void ImageManager::destroyImageCollection(const String& prefix, } //----------------------------------------------------------------------------// -void ImageManager::addFromImageFile(const String& name, const String& filename, +void ImageManager::addBitmapImageFromFile(const String& name, const String& filename, const String& resource_group) { // create texture from image @@ -317,10 +324,10 @@ void ImageManager::addFromImageFile(const String& name, const String& filename, createTexture(name, filename, resource_group.empty() ? d_imagesetDefaultResourceGroup : resource_group); - BasicImage& image = static_cast(create("BasicImage", name)); + BitmapImage& image = static_cast(create("BitmapImage", name)); image.setTexture(tex); - const Rectf rect(Vector2f(0.0f, 0.0f), tex->getOriginalDataSize()); - image.setArea(rect); + const Rectf rect(glm::vec2(0.0f, 0.0f), tex->getOriginalDataSize()); + image.setImageArea(rect); } //----------------------------------------------------------------------------// @@ -363,8 +370,15 @@ void ImageManager::elementStartLocal(const String& element, } //----------------------------------------------------------------------------// -void ImageManager::elementEndLocal(const String&) +void ImageManager::elementEndLocal(const String& element) { + // ensure that everything is reset to default values when the Imageset ends + if (element == ImagesetElement) + { + s_texture = 0; + s_SVGData = 0; + s_imagesetType = ""; + } } //----------------------------------------------------------------------------// @@ -372,6 +386,10 @@ void ImageManager::elementImagesetStart(const XMLAttributes& attributes) { // get name of the imageset. const String name(attributes.getValueAsString(ImagesetNameAttribute)); + // get name of the imageset. + s_imagesetType = attributes.getValueAsString(ImagesetTypeAttribute, + "BitmapImage"); + // get texture image filename const String filename( attributes.getValueAsString(ImagesetImageFileAttribute)); @@ -382,28 +400,22 @@ void ImageManager::elementImagesetStart(const XMLAttributes& attributes) Logger& logger(Logger::getSingleton()); logger.logEvent("[ImageManager] Started creation of Imageset from XML specification:"); logger.logEvent("[ImageManager] ---- CEGUI Imageset name: " + name); - logger.logEvent("[ImageManager] ---- Source texture file: " + filename); - logger.logEvent("[ImageManager] ---- Source texture resource group: " + + logger.logEvent("[ImageManager] ---- Source image file: " + filename); + logger.logEvent("[ImageManager] ---- Source resource group: " + (resource_group.empty() ? "(Default)" : resource_group)); validateImagesetFileVersion(attributes); - Renderer* const renderer = System::getSingleton().getRenderer(); - - // if the texture already exists, - if (renderer->isTextureDefined(name)) - { - Logger::getSingleton().logEvent( - "[ImageManager] WARNING: Using existing texture: " + name); - s_texture = &renderer->getTexture(name); - } + if(s_imagesetType == "BitmapImage") + retrieveImagesetTexture(name, filename, resource_group); + else if(s_imagesetType == "SVGImage") + retrieveImagesetSVGData(name, filename, resource_group); else { - // create texture from image - s_texture = &renderer->createTexture(name, filename, - resource_group.empty() ? d_imagesetDefaultResourceGroup : - resource_group); + CEGUI::String message = "Imageset type: \"" + s_imagesetType + "\" is unknown."; + CEGUI_THROW(UnknownObjectException(message)); } + // set native resolution for imageset s_nativeResolution = Sizef( @@ -434,7 +446,14 @@ void ImageManager::validateImagesetFileVersion(const XMLAttributes& attrs) //----------------------------------------------------------------------------// void ImageManager::elementImageStart(const XMLAttributes& attributes) { - const String image_name(s_texture->getName() + '/' + + String image_data_name = ""; + + if (s_imagesetType == "BitmapImage") + image_data_name = s_texture->getName(); + else if (s_imagesetType == "SVGImage") + image_data_name = s_SVGData->getName(); + + const String image_name(image_data_name + '/' + attributes.getValueAsString(ImageNameAttribute)); if (isDefined(image_name)) @@ -446,11 +465,20 @@ void ImageManager::elementImageStart(const XMLAttributes& attributes) XMLAttributes rw_attrs(attributes); - // rewrite the name attribute to include the texture name + // rewrite the name attribute to include the underlying image data's (Texture's or + // SVGData's) name rw_attrs.add(ImageNameAttribute, image_name); - if (!rw_attrs.exists(ImageTextureAttribute)) - rw_attrs.add(ImageTextureAttribute, s_texture->getName()); + if (s_imagesetType == "BitmapImage") + { + if (!rw_attrs.exists(ImageTextureAttribute)) + rw_attrs.add(ImageTextureAttribute, image_data_name); + } + else if (s_imagesetType == "SVGImage") + { + if (!rw_attrs.exists(ImageSVGDataAttribute)) + rw_attrs.add(ImageSVGDataAttribute, image_data_name); + } if (!rw_attrs.exists(ImagesetAutoScaledAttribute)) rw_attrs.add(ImagesetAutoScaledAttribute, @@ -464,10 +492,51 @@ void ImageManager::elementImageStart(const XMLAttributes& attributes) rw_attrs.add(ImagesetNativeVertResAttribute, PropertyHelper::toString(s_nativeResolution.d_height)); - d_deleteChaniedHandler = false; + d_deleteChainedHandler = false; d_chainedHandler = &create(rw_attrs); } +//----------------------------------------------------------------------------// +void ImageManager::retrieveImagesetTexture(const String& name, const String& filename, const String &resource_group) +{ + Renderer* const renderer = System::getSingleton().getRenderer(); + + // if the texture already exists + if (renderer->isTextureDefined(name)) + { + Logger::getSingleton().logEvent( + "[ImageManager] WARNING: Using existing texture: " + name); + s_texture = &renderer->getTexture(name); + } + else + { + // create texture from image + s_texture = &renderer->createTexture(name, filename, + resource_group.empty() ? d_imagesetDefaultResourceGroup : + resource_group); + } +} + +//----------------------------------------------------------------------------// +void ImageManager::retrieveImagesetSVGData(const String& name, const String& filename, const String &resource_group) +{ + SVGDataManager& svgDataManager = SVGDataManager::getSingleton(); + + if (svgDataManager.isSVGDataDefined(name)) + { + Logger::getSingleton().logEvent( + "[ImageManager] WARNING: Using existing SVGData: " + name); + s_SVGData = &svgDataManager.getSVGData(name); + } + else + { + // Create SVGData from the specified file + s_SVGData = &svgDataManager.create(name, filename, + resource_group.empty() ? d_imagesetDefaultResourceGroup : + resource_group); + } +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/InputAggregator.cpp b/cegui/src/InputAggregator.cpp new file mode 100644 index 000000000..296fb5135 --- /dev/null +++ b/cegui/src/InputAggregator.cpp @@ -0,0 +1,560 @@ +/*********************************************************************** + created: 10/7/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/CoordConverter.h" +#include "CEGUI/InputAggregator.h" +#include "CEGUI/Rect.h" +#include "CEGUI/SemanticInputEvent.h" +#include "CEGUI/SimpleTimer.h" +#include "CEGUI/System.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4351) +# pragma warning(disable : 4355) +#endif + +// Start of CEGUI namespace section +namespace CEGUI +{ +/*! +\brief + Implementation structure used in tracking up & down mouse button inputs in + order to generate click, double-click, and triple-click events. +*/ +struct MouseClickTracker +{ + MouseClickTracker() : + d_click_count(0), + d_click_area(0, 0, 0, 0) + {} + + //! Timer used to track clicks for this button. + SimpleTimer d_timer; + //! count of clicks made so far. + int d_click_count; + //! area used to detect multi-clicks + Rectf d_click_area; +}; + +//----------------------------------------------------------------------------// +const String InputAggregator::EventMouseButtonClickTimeoutChanged("MouseButtonClickTimeoutChanged" ); +const String InputAggregator::EventMouseButtonMultiClickTimeoutChanged("MouseButtonMultiClickTimeoutChanged" ); +const String InputAggregator::EventMouseButtonMultiClickToleranceChanged("MouseButtonMultiClickToleranceChanged" ); +const String InputAggregator::EventMouseMoveScalingFactorChanged("MouseMoveScalingFactorChanged"); + +//----------------------------------------------------------------------------// +const float InputAggregator::DefaultMouseButtonClickTimeout = 0.0f; +const float InputAggregator::DefaultMouseButtonMultiClickTimeout = 0.3333f; +const Sizef InputAggregator::DefaultMouseButtonMultiClickTolerance(0.01f, 0.01f); + +//----------------------------------------------------------------------------// +InputAggregator::InputAggregator(InputEventReceiver* input_receiver) : + d_inputReceiver(input_receiver), + d_mouseButtonClickTimeout(DefaultMouseButtonClickTimeout), + d_mouseButtonMultiClickTimeout(DefaultMouseButtonMultiClickTimeout), + d_mouseButtonMultiClickTolerance(DefaultMouseButtonMultiClickTolerance), + d_mouseMovementScalingFactor(1.0f), + d_generateMouseClickEvents(true), + d_mouseClickTrackers(new MouseClickTracker[MouseButtonCount]), + d_pointerPosition(0.0f, 0.0f), + d_displaySizeChangedConnection( + System::getSingletonPtr()->subscribeEvent(System::EventDisplaySizeChanged, + Event::Subscriber(&InputAggregator::onDisplaySizeChanged, this))), + d_keysPressed(), + d_handleInKeyUp(true) +{ + // Initialize the array + memset(d_keyValuesMappings, SV_NoValue, sizeof(SemanticValue) * 0xFF); + + // initial absolute tolerance + recomputeMultiClickAbsoluteTolerance(); +} + +//----------------------------------------------------------------------------// +InputAggregator::~InputAggregator() +{ + d_displaySizeChangedConnection->disconnect(); + delete[] d_mouseClickTrackers; +} + +//----------------------------------------------------------------------------// +void InputAggregator::setMouseClickEventGenerationEnabled(const bool enable) +{ + d_generateMouseClickEvents = enable; +} + +//----------------------------------------------------------------------------// +bool InputAggregator::isMouseClickEventGenerationEnabled() const +{ + return d_generateMouseClickEvents; +} + +//----------------------------------------------------------------------------// +void InputAggregator::setMouseButtonClickTimeout(float seconds) +{ + d_mouseButtonClickTimeout = seconds; + + InputAggregatorEventArgs args(this); + onMouseButtonClickTimeoutChanged(args); +} + +//----------------------------------------------------------------------------// +float InputAggregator::getMouseButtonClickTimeout() const +{ + return d_mouseButtonClickTimeout; +} + +//----------------------------------------------------------------------------// +void InputAggregator::setMouseButtonMultiClickTimeout(float seconds) +{ + d_mouseButtonMultiClickTimeout = seconds; + + InputAggregatorEventArgs args(this); + onMouseButtonMultiClickTimeoutChanged(args); +} + +//----------------------------------------------------------------------------// +float InputAggregator::getMouseButtonMultiClickTimeout() const +{ + return d_mouseButtonMultiClickTimeout; +} + +//----------------------------------------------------------------------------// +void InputAggregator::setMouseButtonMultiClickTolerance(const Sizef& sz) +{ + d_mouseButtonMultiClickTolerance = sz; + + InputAggregatorEventArgs args(this); + onMouseButtonMultiClickToleranceChanged(args); +} + +//----------------------------------------------------------------------------// +const Sizef& InputAggregator::getMouseButtonMultiClickTolerance() const +{ + return d_mouseButtonMultiClickTolerance; +} + +//----------------------------------------------------------------------------// +void InputAggregator::setMouseMoveScalingFactor(float factor) +{ + d_mouseMovementScalingFactor = factor; + + InputAggregatorEventArgs args(this); + onMouseMoveScalingFactorChanged(args); +} + +//----------------------------------------------------------------------------// +float InputAggregator::getMouseMoveScalingFactor() const +{ + return d_mouseMovementScalingFactor; +} + +//----------------------------------------------------------------------------// +void InputAggregator::onMouseButtonClickTimeoutChanged(InputAggregatorEventArgs& args) +{ + fireEvent(EventMouseButtonClickTimeoutChanged, args); +} + +//----------------------------------------------------------------------------// +void InputAggregator::onMouseButtonMultiClickTimeoutChanged(InputAggregatorEventArgs& args) +{ + fireEvent(EventMouseButtonMultiClickTimeoutChanged, args); +} + +//----------------------------------------------------------------------------// +void InputAggregator::onMouseButtonMultiClickToleranceChanged(InputAggregatorEventArgs& args) +{ + fireEvent(EventMouseButtonMultiClickToleranceChanged, args); +} + +//----------------------------------------------------------------------------// +int InputAggregator::getSemanticAction(Key::Scan scan_code, bool shift_down, + bool alt_down, bool ctrl_down) const +{ + int value = d_keyValuesMappings[scan_code]; + + // handle combined keys + if (ctrl_down && shift_down) + { + if (scan_code == Key::ArrowLeft) + value = SV_SelectPreviousWord; + else if (scan_code == Key::ArrowRight) + value = SV_SelectNextWord; + else if (scan_code == Key::End) + value = SV_SelectToEndOfDocument; + else if (scan_code == Key::Home) + value = SV_SelectToStartOfDocument; + } + else if (ctrl_down) + { + if (scan_code == Key::ArrowLeft) + value = SV_GoToPreviousWord; + else if (scan_code == Key::ArrowRight) + value = SV_GoToNextWord; + else if (scan_code == Key::End) + value = SV_GoToEndOfDocument; + else if (scan_code == Key::Home) + value = SV_GoToStartOfDocument; + else if (scan_code == Key::A) + value = SV_SelectAll; + else if (scan_code == Key::C) + value = SV_Copy; + else if (scan_code == Key::V) + value = SV_Paste; + else if (scan_code == Key::X) + value = SV_Cut; + else if (scan_code == Key::Tab) + value = SV_NavigateToPrevious; + } + else if (shift_down) + { + if (scan_code == Key::ArrowLeft) + value = SV_SelectPreviousCharacter; + else if (scan_code == Key::ArrowRight) + value = SV_SelectNextCharacter; + else if (scan_code == Key::ArrowUp) + value = SV_SelectUp; + else if (scan_code == Key::ArrowDown) + value = SV_SelectDown; + else if (scan_code == Key::End) + value = SV_SelectToEndOfLine; + else if (scan_code == Key::Home) + value = SV_SelectToStartOfLine; + else if (scan_code == Key::PageUp) + value = SV_SelectPreviousPage; + else if (scan_code == Key::PageDown) + value = SV_SelectNextPage; + } + + return value; +} + +bool InputAggregator::handleScanCode(Key::Scan scan_code, bool shift_down, + bool alt_down, bool ctrl_down) +{ + + int value = getSemanticAction(scan_code, shift_down, alt_down, + ctrl_down); + + if (value != SV_NoValue) + { + SemanticInputEvent semantic_event(value); + return d_inputReceiver->injectInputEvent(semantic_event); + } + + return false; +} +//----------------------------------------------------------------------------// +void InputAggregator::onMouseMoveScalingFactorChanged(InputAggregatorEventArgs& args) +{ + fireEvent(EventMouseMoveScalingFactorChanged, args); +} + +bool InputAggregator::injectMouseMove(float delta_x, float delta_y) +{ + return injectMousePosition( + delta_x + d_pointerPosition.x * d_mouseMovementScalingFactor, + delta_y + d_pointerPosition.y * d_mouseMovementScalingFactor); +} + +bool InputAggregator::injectMousePosition(float x_pos, float y_pos) +{ + if (d_inputReceiver == 0) + return false; + + d_pointerPosition = glm::vec2(x_pos, y_pos); + + SemanticInputEvent semantic_event(SV_CursorMove); + semantic_event.d_payload.array[0] = x_pos; + semantic_event.d_payload.array[1] = y_pos; + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectMouseLeaves() +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_PointerLeave); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectMouseButtonDown(MouseButton button) +{ + if (d_inputReceiver == 0) + return false; + + // + // Handling for multi-click generation + // + MouseClickTracker& tkr = d_mouseClickTrackers[button]; + + tkr.d_click_count++; + + // TODO: re-add the check for different windows? + // if multi-click requirements are not met + if (((d_mouseButtonMultiClickTimeout > 0) && (tkr.d_timer.elapsed() > d_mouseButtonMultiClickTimeout)) || + (!tkr.d_click_area.isPointInRect(d_pointerPosition)) || + (tkr.d_click_count > 3)) + { + // reset to single down event. + tkr.d_click_count = 1; + + // build new allowable area for multi-clicks + tkr.d_click_area.setPosition(d_pointerPosition); + tkr.d_click_area.setSize(d_mouseButtonMultiClickAbsoluteTolerance); + tkr.d_click_area.offset(-0.5f * glm::vec2( + d_mouseButtonMultiClickAbsoluteTolerance.d_width, + d_mouseButtonMultiClickAbsoluteTolerance.d_height)); + } + + // reset timer for this tracker. + tkr.d_timer.restart(); + + if (d_generateMouseClickEvents) + { + switch (tkr.d_click_count) + { + case 2: + return injectMouseButtonDoubleClick(button); + + case 3: + return injectMouseButtonTripleClick(button); + } + } + + SemanticValue value = SV_CursorPressHold; + if (isControlPressed()) + value = SV_SelectCumulative; + else if (isShiftPressed()) + value = SV_SelectRange; + + SemanticInputEvent semantic_event(value); + semantic_event.d_payload.source = convertToCursorInputSource(button); + + return d_inputReceiver->injectInputEvent(semantic_event); +} +bool InputAggregator::injectMouseButtonUp(MouseButton button) +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_CursorActivate); + semantic_event.d_payload.source = convertToCursorInputSource(button); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectKeyDown(Key::Scan scan_code) +{ + if (d_inputReceiver == 0) + return false; + + d_keysPressed[scan_code] = true; + + if (d_handleInKeyUp) + return true; + + return handleScanCode(scan_code, isShiftPressed(), isAltPressed(), + isControlPressed()); +} + +bool InputAggregator::injectKeyUp(Key::Scan scan_code) +{ + if (d_inputReceiver == 0) + return false; + + d_keysPressed[scan_code] = false; + + if (!d_handleInKeyUp) + return true; + + return handleScanCode(scan_code, isShiftPressed(), isAltPressed(), + isControlPressed()); +} + +bool InputAggregator::injectChar(String::value_type code_point) +{ + if (d_inputReceiver == 0) + return false; + + TextInputEvent text_event; + text_event.d_character = code_point; + + return d_inputReceiver->injectInputEvent(text_event); +} + +bool InputAggregator::injectMouseWheelChange(float delta) +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_VerticalScroll); + semantic_event.d_payload.single = delta; + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectMouseButtonClick(const MouseButton button) +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_CursorActivate); + + if (isControlPressed()) + semantic_event.d_value = SV_SelectCumulative; + + semantic_event.d_payload.source = convertToCursorInputSource(button); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectMouseButtonDoubleClick(const MouseButton button) +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_SelectWord); + semantic_event.d_payload.source = convertToCursorInputSource(button); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectMouseButtonTripleClick(const MouseButton button) +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_SelectAll); + semantic_event.d_payload.source = convertToCursorInputSource(button); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectCopyRequest() +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_Copy); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectCutRequest() +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_Cut); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +bool InputAggregator::injectPasteRequest() +{ + if (d_inputReceiver == 0) + return false; + + SemanticInputEvent semantic_event(SV_Paste); + + return d_inputReceiver->injectInputEvent(semantic_event); +} + +void InputAggregator::initialise(bool handle_on_keyup /*= true*/) +{ + d_handleInKeyUp = handle_on_keyup; + + d_keyValuesMappings[Key::Backspace] = SV_DeletePreviousCharacter; + d_keyValuesMappings[Key::Delete] = SV_DeleteNextCharacter; + + d_keyValuesMappings[Key::NumpadEnter] = SV_Confirm; + d_keyValuesMappings[Key::Return] = SV_Confirm; + + d_keyValuesMappings[Key::Tab] = SV_NavigateToNext; + + d_keyValuesMappings[Key::ArrowLeft] = SV_GoToPreviousCharacter; + d_keyValuesMappings[Key::ArrowRight] = SV_GoToNextCharacter; + d_keyValuesMappings[Key::ArrowDown] = SV_GoDown; + d_keyValuesMappings[Key::ArrowUp] = SV_GoUp; + + d_keyValuesMappings[Key::End] = SV_GoToEndOfLine; + d_keyValuesMappings[Key::Home] = SV_GoToStartOfLine; + d_keyValuesMappings[Key::PageDown] = SV_GoToNextPage; + d_keyValuesMappings[Key::PageUp] = SV_GoToPreviousPage; +} + +bool InputAggregator::isShiftPressed() +{ + return d_keysPressed[Key::LeftShift] || d_keysPressed[Key::RightShift]; +} + +bool InputAggregator::isAltPressed() +{ + return d_keysPressed[Key::LeftAlt] || d_keysPressed[Key::RightAlt]; +} + +bool InputAggregator::isControlPressed() +{ + return d_keysPressed[Key::LeftControl] || d_keysPressed[Key::RightControl]; +} +//----------------------------------------------------------------------------// +void InputAggregator::setModifierKeys(bool shift_down, bool alt_down, + bool ctrl_down) +{ + d_keysPressed[Key::LeftShift] = shift_down; + d_keysPressed[Key::RightShift] = shift_down; + + d_keysPressed[Key::LeftAlt] = alt_down; + d_keysPressed[Key::RightAlt] = alt_down; + + d_keysPressed[Key::LeftControl] = ctrl_down; + d_keysPressed[Key::RightControl] = ctrl_down; +} +//----------------------------------------------------------------------------// +void InputAggregator::recomputeMultiClickAbsoluteTolerance() +{ + const Sizef& display_size = System::getSingleton().getRenderer()->getDisplaySize(); + d_mouseButtonMultiClickAbsoluteTolerance = Sizef( + d_mouseButtonMultiClickTolerance.d_width * display_size.d_width, + d_mouseButtonMultiClickTolerance.d_height * display_size.d_height); +} + +bool InputAggregator::onDisplaySizeChanged(const EventArgs& args) +{ + recomputeMultiClickAbsoluteTolerance(); + return true; +} + +#if defined (_MSC_VER) +# pragma warning(pop) +#endif + +} // End of CEGUI namespace section diff --git a/cegui/src/JustifiedRenderedString.cpp b/cegui/src/JustifiedRenderedString.cpp index da80cb307..dd206bda7 100644 --- a/cegui/src/JustifiedRenderedString.cpp +++ b/cegui/src/JustifiedRenderedString.cpp @@ -58,18 +58,18 @@ void JustifiedRenderedString::format(const Window* ref_wnd, } //----------------------------------------------------------------------------// -void JustifiedRenderedString::draw(const Window* ref_wnd, GeometryBuffer& buffer, - const Vector2f& position, +void JustifiedRenderedString::draw(const Window* ref_wnd, std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const { - Vector2f draw_pos(position); + glm::vec2 draw_pos(position); for (size_t i = 0; i < d_renderedString->getLineCount(); ++i) { - d_renderedString->draw(ref_wnd, i, buffer, draw_pos, mod_colours, + d_renderedString->draw(ref_wnd, i, geometry_buffers, draw_pos, mod_colours, clip_rect, d_spaceExtras[i]); - draw_pos.d_y += d_renderedString->getPixelSize(ref_wnd, i).d_height; + draw_pos.y += d_renderedString->getPixelSize(ref_wnd, i).d_height; } } diff --git a/cegui/src/JustifiedRenderedStringWordWrapper.cpp b/cegui/src/JustifiedRenderedStringWordWrapper.cpp index 1e56ffb3a..90e748424 100644 --- a/cegui/src/JustifiedRenderedStringWordWrapper.cpp +++ b/cegui/src/JustifiedRenderedStringWordWrapper.cpp @@ -58,7 +58,7 @@ void RenderedStringWordWrapper::format( // split rstring at width into lstring and remaining rstring rstring.split(ref_wnd, line, area_size.d_width, lstring); - frs = CEGUI_NEW_AO JustifiedRenderedString(*CEGUI_NEW_AO RenderedString(lstring)); + frs = new JustifiedRenderedString(*new RenderedString(lstring)); frs->format(ref_wnd, area_size); d_lines.push_back(frs); line = 0; @@ -66,7 +66,7 @@ void RenderedStringWordWrapper::format( } // last line (which we do not justify) - frs = CEGUI_NEW_AO LeftAlignedRenderedString(*CEGUI_NEW_AO RenderedString(rstring)); + frs = new LeftAlignedRenderedString(*new RenderedString(rstring)); frs->format(ref_wnd, area_size); d_lines.push_back(frs); } diff --git a/cegui/src/LeftAlignedRenderedString.cpp b/cegui/src/LeftAlignedRenderedString.cpp index ff23ff6e8..7d7b64f9e 100644 --- a/cegui/src/LeftAlignedRenderedString.cpp +++ b/cegui/src/LeftAlignedRenderedString.cpp @@ -46,17 +46,17 @@ void LeftAlignedRenderedString::format(const Window* /*ref_wnd*/, //----------------------------------------------------------------------------// void LeftAlignedRenderedString::draw(const Window* ref_wnd, - GeometryBuffer& buffer, - const Vector2f& position, + std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const { - Vector2f draw_pos(position); + glm::vec2 draw_pos(position); for (size_t i = 0; i < d_renderedString->getLineCount(); ++i) { - d_renderedString->draw(ref_wnd, i, buffer, draw_pos, mod_colours, clip_rect, 0.0f); - draw_pos.d_y += d_renderedString->getPixelSize(ref_wnd, i).d_height; + d_renderedString->draw(ref_wnd, i, geometry_buffers, draw_pos, mod_colours, clip_rect, 0.0f); + draw_pos.y += d_renderedString->getPixelSize(ref_wnd, i).d_height; } } diff --git a/cegui/src/MinizipResourceProvider.cpp b/cegui/src/MinizipResourceProvider.cpp index 1d2cf8e09..7234d6c66 100644 --- a/cegui/src/MinizipResourceProvider.cpp +++ b/cegui/src/MinizipResourceProvider.cpp @@ -190,7 +190,7 @@ void MinizipResourceProvider::loadRawDataContainer(const String& filename, } ulong size = file_info.uncompressed_size; - uint8* buffer = CEGUI_NEW_ARRAY_PT(uint8, size, RawDataContainer); + uint8* buffer = new uint8[size]; if (unzReadCurrentFile(d_pimpl->d_zfile, buffer, size) < 0) { diff --git a/cegui/src/PixmapFont.cpp b/cegui/src/PixmapFont.cpp index b6d05518f..37d1421e9 100644 --- a/cegui/src/PixmapFont.cpp +++ b/cegui/src/PixmapFont.cpp @@ -27,7 +27,7 @@ #include "CEGUI/PixmapFont.h" #include "CEGUI/ImageManager.h" -#include "CEGUI/BasicImage.h" +#include "CEGUI/BitmapImage.h" #include "CEGUI/Font_xmlHandler.h" #include "CEGUI/PropertyHelper.h" #include "CEGUI/Logger.h" @@ -124,17 +124,17 @@ void PixmapFont::updateFont() Image* img = i->second.getImage(); - BasicImage* bi = dynamic_cast(img); + BitmapImage* bi = dynamic_cast(img); if (bi) { bi->setAutoScaled(d_autoScaled); bi->setNativeResolution(d_nativeResolution); } - if (img->getRenderedOffset().d_y < d_ascender) - d_ascender = img->getRenderedOffset().d_y; - if (img->getRenderedSize().d_height + img->getRenderedOffset().d_y > d_descender) - d_descender = img->getRenderedSize().d_height + img->getRenderedOffset().d_y; + if (img->getRenderedOffset().y < d_ascender) + d_ascender = img->getRenderedOffset().y; + if (img->getRenderedSize().d_height + img->getRenderedOffset().y > d_descender) + d_descender = img->getRenderedSize().d_height + img->getRenderedOffset().y; } d_ascender = -d_ascender; @@ -170,7 +170,7 @@ void PixmapFont::defineMapping(const utf32 codepoint, const String& image_name, ImageManager::getSingleton().get(d_imageNamePrefix + '/' + image_name)); float adv = (horz_advance == -1.0f) ? - (float)(int)(image.getRenderedSize().d_width + image.getRenderedOffset().d_x) : + (float)(int)(image.getRenderedSize().d_width + image.getRenderedOffset().x) : horz_advance; if (d_autoScaled != ASM_Disabled) @@ -182,10 +182,10 @@ void PixmapFont::defineMapping(const utf32 codepoint, const String& image_name, // create a new FontGlyph with given character code const FontGlyph glyph(adv, &image, true); - if (image.getRenderedOffset().d_y < -d_ascender) - d_ascender = -image.getRenderedOffset().d_y; - if (image.getRenderedSize().d_height + image.getRenderedOffset().d_y > -d_descender) - d_descender = -(image.getRenderedSize().d_height + image.getRenderedOffset().d_y); + if (image.getRenderedOffset().y < -d_ascender) + d_ascender = -image.getRenderedOffset().y; + if (image.getRenderedSize().d_height + image.getRenderedOffset().y > -d_descender) + d_descender = -(image.getRenderedSize().d_height + image.getRenderedOffset().y); d_height = d_ascender - d_descender; diff --git a/cegui/src/Quaternion.cpp b/cegui/src/Quaternion.cpp index 7f89390a3..831fdcf96 100644 --- a/cegui/src/Quaternion.cpp +++ b/cegui/src/Quaternion.cpp @@ -38,111 +38,6 @@ namespace CEGUI { -const Quaternion Quaternion::ZERO(0, 0, 0, 0); -const Quaternion Quaternion::IDENTITY(1, 0, 0, 0); - -//----------------------------------------------------------------------------// -Quaternion Quaternion::eulerAnglesRadians(const float x, const float y, const float z) -{ - // the order of rotation: - // 1) around Z - // 2) around Y - // 3) around X - // even though it's passed in reverse... - - const float sin_z_2 = sinf(0.5f * z); - const float sin_y_2 = sinf(0.5f * y); - const float sin_x_2 = sinf(0.5f * x); - - const float cos_z_2 = cosf(0.5f * z); - const float cos_y_2 = cosf(0.5f * y); - const float cos_x_2 = cosf(0.5f * x); - - return Quaternion( - cos_z_2 * cos_y_2 * cos_x_2 + sin_z_2 * sin_y_2 * sin_x_2, - cos_z_2 * cos_y_2 * sin_x_2 - sin_z_2 * sin_y_2 * cos_x_2, - cos_z_2 * sin_y_2 * cos_x_2 + sin_z_2 * cos_y_2 * sin_x_2, - sin_z_2 * cos_y_2 * cos_x_2 - cos_z_2 * sin_y_2 * sin_x_2 - ); -} - -//----------------------------------------------------------------------------// -Quaternion Quaternion::eulerAnglesDegrees(const float x, const float y, const float z) -{ - static const float d2r = (4.0f * std::atan2(1.0f, 1.0f)) / 180.0f; - - return eulerAnglesRadians(x * d2r, y * d2r, z * d2r); -} - -//----------------------------------------------------------------------------// -Quaternion Quaternion::axisAngleRadians(const Vector3f& axis, const float rotation) -{ - const float halfRotation = 0.5f * rotation; - const float halfSin = sinf(halfRotation); - - return Quaternion(cosf(halfRotation), - halfSin * axis.d_x, halfSin * axis.d_y, halfSin * axis.d_z); -} - -//----------------------------------------------------------------------------// -Quaternion Quaternion::axisAngleDegrees(const Vector3f& axis, const float rotation) -{ - static const float d2r = (4.0f * std::atan2(1.0f, 1.0f)) / 180.0f; - - return axisAngleRadians(axis, rotation * d2r); -} - -//----------------------------------------------------------------------------// -Quaternion Quaternion::slerp(const Quaternion& left, const Quaternion& right, - float position, const bool shortestPath) -{ - // Geometric Tools, LLC - // Copyright (c) 1998-2010 - // Distributed under the Boost Software License, Version 1.0. - // http://www.boost.org/LICENSE_1_0.txt - // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt - - float vcos = left.dot(right); - Quaternion _right; - - // Do we need to invert rotation? - if (vcos < 0.0f && shortestPath) - { - vcos = -vcos; - _right = -right; - } - else - { - _right = right; - } - - if (fabs(vcos) < 1 - std::numeric_limits::epsilon()) - { - // Standard case (slerp) - const float vsin = sqrtf(1.0f - vcos * vcos); - const float angle = atan2(vsin, vcos); - const float invSin = 1.0f / vsin; - const float coeff0 = sin((1.0f - position) * angle) * invSin; - const float coeff1 = sin((position) * angle) * invSin; - - return coeff0 * left + coeff1 * _right; - } - else - { - // There are two situations: - // 1. "left" and "right" are very close (cos ~= +1), so we can do a linear - // interpolation safely. - // 2. "left" and "right" are almost inverse of each other (cos ~= -1), there - // are an infinite number of possibilities interpolation. but we haven't - // have method to fix this case, so just use linear interpolation here. - - Quaternion ret = (1.0f - position) * left + position * _right; - // taking the complement requires renormalisation - ret.normalise(); - return ret; - } -} - //----------------------------------------------------------------------------// const String& QuaternionSlerpInterpolator::getType() const { @@ -159,7 +54,7 @@ String QuaternionSlerpInterpolator::interpolateAbsolute(const String& value1, Helper::return_type val1 = Helper::fromString(value1); Helper::return_type val2 = Helper::fromString(value2); - return Helper::toString(Quaternion::slerp(val1, val2, position)); + return Helper::toString(glm::slerp(val1, val2, position)); } //----------------------------------------------------------------------------// @@ -172,7 +67,7 @@ String QuaternionSlerpInterpolator::interpolateRelative(const String& base, Helper::return_type val1 = Helper::fromString(value1); Helper::return_type val2 = Helper::fromString(value2); - return Helper::toString(bas * Quaternion::slerp(val1, val2, position)); + return Helper::toString(bas * glm::slerp(val1, val2, position)); } //----------------------------------------------------------------------------// @@ -185,7 +80,7 @@ String QuaternionSlerpInterpolator::interpolateRelativeMultiply( CEGUI_THROW(InvalidRequestException("AM_RelativeMultiply doesn't make sense " "with Quaternions! Please use absolute or relative application method.")); - return Helper::toString(Quaternion::IDENTITY); + return Helper::toString(glm::quat(1, 0, 0, 0)); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RenderEffectManager.cpp b/cegui/src/RenderEffectManager.cpp index e080f0474..c9d020e88 100644 --- a/cegui/src/RenderEffectManager.cpp +++ b/cegui/src/RenderEffectManager.cpp @@ -71,7 +71,7 @@ void RenderEffectManager::removeEffect(const String& name) Logger::getSingleton().logEvent( "Unregistered RenderEffect named '" + name + "'"); - CEGUI_DELETE_AO i->second; + delete i->second; d_effectRegistry.erase(name); } diff --git a/cegui/src/RendererModules/Direct3D9/ViewportTarget.cpp b/cegui/src/RenderMaterial.cpp similarity index 61% rename from cegui/src/RendererModules/Direct3D9/ViewportTarget.cpp rename to cegui/src/RenderMaterial.cpp index f8fa8648c..166a2b94d 100644 --- a/cegui/src/RendererModules/Direct3D9/ViewportTarget.cpp +++ b/cegui/src/RenderMaterial.cpp @@ -1,9 +1,9 @@ /*********************************************************************** - created: Fri Feb 13 2009 - author: Paul D Turner + created: 18th July 2013 + author: Lukas Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,52 +24,43 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D9/ViewportTarget.h" -#include "CEGUI/RenderQueue.h" -#include "CEGUI/GeometryBuffer.h" -#include "CEGUI/Exceptions.h" -#include +#include "CEGUI/RenderMaterial.h" +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/ShaderWrapper.h" -// Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// -Direct3D9ViewportTarget::Direct3D9ViewportTarget(Direct3D9Renderer& owner) : - Direct3D9RenderTarget<>(owner) +RenderMaterial::RenderMaterial(ShaderWrapper* shaderWrapper) + : d_shaderWrapper(shaderWrapper) { - // initialise renderer size - D3DVIEWPORT9 vp; - if (FAILED(d_owner.getDevice()->GetViewport(&vp))) - CEGUI_THROW(RendererException("Unable to access " - "required view port information from Direct3DDevice9.")); - - Rectf area( - Vector2f(static_cast(vp.X), static_cast(vp.Y)), - Sizef(static_cast(vp.Width), static_cast(vp.Height)) - ); - - setArea(area); + d_shaderParamBindings = new ShaderParameterBindings(); } //----------------------------------------------------------------------------// -Direct3D9ViewportTarget::Direct3D9ViewportTarget(Direct3D9Renderer& owner, - const Rectf& area) : - Direct3D9RenderTarget<>(owner) +RenderMaterial::~RenderMaterial() { - setArea(area); + delete d_shaderParamBindings; } //----------------------------------------------------------------------------// -bool Direct3D9ViewportTarget::isImageryCache() const +ShaderParameterBindings* RenderMaterial::getShaderParamBindings() const { - return false; + return d_shaderParamBindings; } //----------------------------------------------------------------------------// +void RenderMaterial::prepareForRendering() const +{ + d_shaderWrapper->prepareForRendering(d_shaderParamBindings); +} -} // End of CEGUI namespace section +//----------------------------------------------------------------------------// +const ShaderWrapper* RenderMaterial::getShaderWrapper() const +{ + return d_shaderWrapper; +} //----------------------------------------------------------------------------// -// Implementation of template base class -#include "./RenderTarget.inl" +} diff --git a/cegui/src/RenderQueue.cpp b/cegui/src/RenderQueue.cpp index b3d7fc223..2cbc862e2 100644 --- a/cegui/src/RenderQueue.cpp +++ b/cegui/src/RenderQueue.cpp @@ -41,16 +41,22 @@ void RenderQueue::draw() const } //----------------------------------------------------------------------------// -void RenderQueue::addGeometryBuffer(const GeometryBuffer& buffer) +void RenderQueue::addGeometryBuffers(const std::vector& geometry_buffers) { - d_buffers.push_back(&buffer); + d_buffers.insert(d_buffers.end(), geometry_buffers.begin(), geometry_buffers.end()); } //----------------------------------------------------------------------------// -void RenderQueue::removeGeometryBuffer(const GeometryBuffer& buffer) +void RenderQueue::addGeometryBuffer(const GeometryBuffer& geometry_buffer) +{ + d_buffers.push_back(&geometry_buffer); +} + +//----------------------------------------------------------------------------// +void RenderQueue::removeGeometryBuffer(const GeometryBuffer& geometry_buffer) { BufferList::iterator i = std::find(d_buffers.begin(), d_buffers.end(), - &buffer); + &geometry_buffer); if (i != d_buffers.end()) d_buffers.erase(i); } diff --git a/cegui/src/RenderTarget.cpp b/cegui/src/RenderTarget.cpp index a4e7e1964..7fe526149 100644 --- a/cegui/src/RenderTarget.cpp +++ b/cegui/src/RenderTarget.cpp @@ -25,14 +25,168 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RenderTarget.h" +#include "CEGUI/Renderer.h" +#include "CEGUI/GeometryBuffer.h" +#include "CEGUI/RenderQueue.h" + +#include +#include +#include namespace CEGUI { //----------------------------------------------------------------------------// +const float RenderTarget::d_yfov_tan = 0.267949192431123f; + const String RenderTarget::EventNamespace("RenderTarget"); const String RenderTarget::EventAreaChanged("AreaChanged"); //----------------------------------------------------------------------------// +RenderTarget::RenderTarget(): + d_activationCounter(0), + d_area(0, 0, 0, 0), + d_matrixValid(false), + d_viewDistance(0), + d_matrix(1.0f) +{} + +//----------------------------------------------------------------------------// +RenderTarget::~RenderTarget() +{} + +//----------------------------------------------------------------------------// +void RenderTarget::activate() +{ + Renderer& owner = getOwner(); + + owner.setActiveRenderTarget(this); + ++d_activationCounter; + + if(d_activationCounter == 0) + owner.invalidateGeomBufferMatrices(this); +} + +//----------------------------------------------------------------------------// +void RenderTarget::deactivate() +{ } +//----------------------------------------------------------------------------// +void RenderTarget::draw(const GeometryBuffer& buffer) +{ + buffer.draw(); +} + +//----------------------------------------------------------------------------// +void RenderTarget::draw(const RenderQueue& queue) +{ + queue.draw(); +} + +//----------------------------------------------------------------------------// +unsigned int RenderTarget::getActivationCounter() const +{ + return d_activationCounter; +} + +//----------------------------------------------------------------------------// +void RenderTarget::setArea(const Rectf& area) +{ + d_area = area; + d_matrixValid = false; + + RenderTargetEventArgs args(this); + fireEvent(RenderTarget::EventAreaChanged, args); +} + +//----------------------------------------------------------------------------// +const Rectf& RenderTarget::getArea() const +{ + return d_area; +} + +//----------------------------------------------------------------------------// +glm::mat4 RenderTarget::createViewProjMatrixForOpenGL() const +{ + const float w = d_area.getWidth(); + const float h = d_area.getHeight(); + + // We need to check if width or height are zero and act accordingly to prevent running into issues + // with divisions by zero which would lead to undefined values, as well as faulty clipping planes + // This is mostly important for avoiding asserts + const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); + + const float aspect = widthAndHeightNotZero ? w / h : 1.0f; + const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; + const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; + RenderTarget::d_viewDistance = midx / (aspect * RenderTarget::d_yfov_tan); + + glm::vec3 eye = glm::vec3(midx, midy, -RenderTarget::d_viewDistance); + glm::vec3 center = glm::vec3(midx, midy, 1); + glm::vec3 up = glm::vec3(0, -1, 0); + + glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, RenderTarget::d_viewDistance * 0.5f, RenderTarget::d_viewDistance * 2.0f); + // Projection matrix abuse! + glm::mat4 viewMatrix = glm::lookAt(eye, center, up); + + return projectionMatrix * viewMatrix; +} + +//----------------------------------------------------------------------------// +glm::mat4 RenderTarget::createViewProjMatrixForDirect3D() const +{ + const float w = d_area.getWidth(); + const float h = d_area.getHeight(); + + // We need to check if width or height are zero and act accordingly to prevent running into issues + // with divisions by zero which would lead to undefined values, as well as faulty clipping planes + // This is mostly important for avoiding asserts + const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); + + const float aspect = widthAndHeightNotZero ? w / h : 1.0f; + const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; + const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; + RenderTarget::d_viewDistance = midx / (aspect * RenderTarget::d_yfov_tan); + + glm::vec3 eye = glm::vec3(midx, midy, -d_viewDistance); + glm::vec3 center = glm::vec3(midx, midy, 1); + glm::vec3 up = glm::vec3(0, -1, 0); + + + // We need to have a projection matrix with its depth in clip space ranging from 0 to 1 for nearclip to farclip. + // The regular OpenGL projection matrix would work too, but we would lose 1 bit of depth precision, which the following + // manually filled matrix should fix: + const float fovy = 30.f; + const float zNear = RenderTarget::d_viewDistance * 0.5f; + const float zFar = RenderTarget::d_viewDistance * 2.0f; + const float f = 1.0f / std::tan(fovy * glm::pi() * 0.5f / 180.0f); + const float Q = zFar / (zNear - zFar); + + float projectionMatrixFloat[16] = + { + f/aspect, 0.0f, 0.0f, 0.0f, + 0.0f, f, 0.0f, 0.0f, + 0.0f, 0.0f, Q, -1.0f, + 0.0f, 0.0f, Q * zNear, 0.0f + }; + + glm::mat4 projectionMatrix = glm::make_mat4(projectionMatrixFloat); + + // Projection matrix abuse! + glm::mat4 viewMatrix = glm::lookAt(eye, center, up); + + return projectionMatrix * viewMatrix; +} + +//----------------------------------------------------------------------------// +void RenderTarget::updateMatrix(const glm::mat4& matrix) const +{ + d_matrix = matrix; + + d_matrixValid = true; + //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices + d_activationCounter = -1; +} + +} diff --git a/cegui/src/RenderedString.cpp b/cegui/src/RenderedString.cpp index c04674e40..5d14f06aa 100644 --- a/cegui/src/RenderedString.cpp +++ b/cegui/src/RenderedString.cpp @@ -92,7 +92,7 @@ void RenderedString::cloneComponentList(const ComponentList& list) void RenderedString::clearComponentList(ComponentList& list) { for (size_t i = 0; i < list.size(); ++i) - CEGUI_DELETE_AO list[i]; + delete list[i]; list.clear(); } @@ -281,7 +281,7 @@ size_t RenderedString::getSpaceCount(const size_t line) const //----------------------------------------------------------------------------// void RenderedString::draw(const Window* ref_wnd, const size_t line, - GeometryBuffer& buffer, const Vector2f& position, + std::vector& geometry_buffers, const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float space_extra) const { @@ -291,14 +291,14 @@ void RenderedString::draw(const Window* ref_wnd, const size_t line, const float render_height = getPixelSize(ref_wnd, line).d_height; - Vector2f comp_pos(position); + glm::vec2 comp_pos(position); const size_t end_component = d_lines[line].first + d_lines[line].second; for (size_t i = d_lines[line].first; i < end_component; ++i) { - d_components[i]->draw(ref_wnd, buffer, comp_pos, mod_colours, clip_rect, + d_components[i]->draw(ref_wnd, geometry_buffers, comp_pos, mod_colours, clip_rect, render_height, space_extra); - comp_pos.d_x += d_components[i]->getPixelSize(ref_wnd).d_width; + comp_pos.x += d_components[i]->getPixelSize(ref_wnd).d_width; } } diff --git a/cegui/src/RenderedStringImageComponent.cpp b/cegui/src/RenderedStringImageComponent.cpp index 279c204be..ceaca006b 100644 --- a/cegui/src/RenderedStringImageComponent.cpp +++ b/cegui/src/RenderedStringImageComponent.cpp @@ -28,6 +28,7 @@ #include "CEGUI/ImageManager.h" #include "CEGUI/Image.h" #include "CEGUI/Exceptions.h" +#include "CEGUI/System.h" // Start of CEGUI namespace section namespace CEGUI @@ -112,8 +113,8 @@ void RenderedStringImageComponent::setSelection(const Window* /*ref_wnd*/, //----------------------------------------------------------------------------// void RenderedStringImageComponent::draw(const Window* ref_wnd, - GeometryBuffer& buffer, - const Vector2f& position, + std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float vertical_space, @@ -122,7 +123,7 @@ void RenderedStringImageComponent::draw(const Window* ref_wnd, if (!d_image) return; - CEGUI::Rectf dest(position.d_x, position.d_y, 0, 0); + Rectf dest(position.x, position.y, 0, 0); float y_scale = 1.0f; // handle formatting options @@ -165,7 +166,7 @@ void RenderedStringImageComponent::draw(const Window* ref_wnd, if (d_selectionImage && d_selected) { const Rectf select_area(position, getPixelSize(ref_wnd)); - d_selectionImage->render(buffer, select_area, clip_rect, ColourRect(0xFF002FFF)); + d_selectionImage->render(geometry_buffers, select_area, clip_rect, true, ColourRect(0xFF002FFF)); } // apply modulative colours if needed. @@ -173,8 +174,8 @@ void RenderedStringImageComponent::draw(const Window* ref_wnd, if (mod_colours) final_cols *= *mod_colours; - // draw the image. - d_image->render(buffer, dest, clip_rect, final_cols); + // draw the image. + d_image->render(geometry_buffers, dest, clip_rect, true, final_cols); } //----------------------------------------------------------------------------// @@ -213,7 +214,7 @@ RenderedStringImageComponent* RenderedStringImageComponent::split( //----------------------------------------------------------------------------// RenderedStringImageComponent* RenderedStringImageComponent::clone() const { - return CEGUI_NEW_AO RenderedStringImageComponent(*this); + return new RenderedStringImageComponent(*this); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RenderedStringTextComponent.cpp b/cegui/src/RenderedStringTextComponent.cpp index bcb782794..a4b734d5d 100644 --- a/cegui/src/RenderedStringTextComponent.cpp +++ b/cegui/src/RenderedStringTextComponent.cpp @@ -156,8 +156,8 @@ const Font* RenderedStringTextComponent::getEffectiveFont( //----------------------------------------------------------------------------// void RenderedStringTextComponent::draw(const Window* ref_wnd, - GeometryBuffer& buffer, - const Vector2f& position, + std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect, const float vertical_space, @@ -168,18 +168,18 @@ void RenderedStringTextComponent::draw(const Window* ref_wnd, if (!fnt) return; - Vector2f final_pos(position); + glm::vec2 final_pos(position); float y_scale = 1.0f; // handle formatting options switch (d_verticalFormatting) { case VF_BOTTOM_ALIGNED: - final_pos.d_y += vertical_space - getPixelSize(ref_wnd).d_height; + final_pos.y += vertical_space - getPixelSize(ref_wnd).d_height; break; case VF_CENTRE_ALIGNED: - final_pos.d_y += (vertical_space - getPixelSize(ref_wnd).d_height) / 2 ; + final_pos.y += (vertical_space - getPixelSize(ref_wnd).d_height) / 2 ; break; case VF_STRETCHED: @@ -196,7 +196,7 @@ void RenderedStringTextComponent::draw(const Window* ref_wnd, } // apply padding to position: - final_pos += d_padding.getPosition(); + final_pos += d_padding.getPositionGLM(); // apply modulative colours if needed. ColourRect final_cols(d_colours); @@ -213,16 +213,15 @@ void RenderedStringTextComponent::draw(const Window* ref_wnd, sel_end_extent = fnt->getTextExtent(d_text.substr(0, d_selectionStart + d_selectionLength)); - Rectf sel_rect(position.d_x + sel_start_extent, - position.d_y, - position.d_x + sel_end_extent, - position.d_y + vertical_space); + Rectf sel_rect(position.x + sel_start_extent, + position.y, + position.x + sel_end_extent, + position.y + vertical_space); - d_selectionImage->render(buffer, sel_rect, clip_rect, ColourRect(0xFF002FFF)); + d_selectionImage->render(geometry_buffers, sel_rect, clip_rect, true, ColourRect(0xFF002FFF)); } - // draw the text string. - fnt->drawText(buffer, d_text, final_pos, clip_rect, final_cols, + fnt->drawText(geometry_buffers, d_text, final_pos, clip_rect, true, final_cols, space_extra, 1.0f, y_scale); } @@ -264,7 +263,7 @@ RenderedStringTextComponent* RenderedStringTextComponent::split( "unable to split with no font set.")); // create 'left' side of split and clone our basic configuration - RenderedStringTextComponent* lhs = CEGUI_NEW_AO RenderedStringTextComponent(); + RenderedStringTextComponent* lhs = new RenderedStringTextComponent(); lhs->d_padding = d_padding; lhs->d_verticalFormatting = d_verticalFormatting; lhs->d_font = d_font; @@ -355,7 +354,7 @@ size_t RenderedStringTextComponent::getNextTokenLength(const String& text, //----------------------------------------------------------------------------// RenderedStringTextComponent* RenderedStringTextComponent::clone() const { - RenderedStringTextComponent* c = CEGUI_NEW_AO RenderedStringTextComponent(*this); + RenderedStringTextComponent* c = new RenderedStringTextComponent(*this); return c; } diff --git a/cegui/src/RenderedStringWidgetComponent.cpp b/cegui/src/RenderedStringWidgetComponent.cpp index 56208ae29..1bdb896cd 100644 --- a/cegui/src/RenderedStringWidgetComponent.cpp +++ b/cegui/src/RenderedStringWidgetComponent.cpp @@ -90,8 +90,8 @@ void RenderedStringWidgetComponent::setSelection(const Window* /*ref_wnd*/, //----------------------------------------------------------------------------// void RenderedStringWidgetComponent::draw(const Window* ref_wnd, - GeometryBuffer& buffer, - const Vector2f& position, + std::vector& geometry_buffers, + const glm::vec2& position, const CEGUI::ColourRect* /*mod_colours*/, const Rectf* clip_rect, const float vertical_space, @@ -115,12 +115,12 @@ void RenderedStringWidgetComponent::draw(const Window* ref_wnd, } // HACK: re-adjust for inner-rect of parent (Ends) - Vector2f final_pos(position); + glm::vec2 final_pos(position); // handle formatting options switch (d_verticalFormatting) { case VF_BOTTOM_ALIGNED: - final_pos.d_y += vertical_space - getPixelSize(ref_wnd).d_height; + final_pos.y += vertical_space - getPixelSize(ref_wnd).d_height; break; case VF_STRETCHED: @@ -131,7 +131,7 @@ void RenderedStringWidgetComponent::draw(const Window* ref_wnd, // intentional fall-through. case VF_CENTRE_ALIGNED: - final_pos.d_y += (vertical_space - getPixelSize(ref_wnd).d_height) / 2 ; + final_pos.y += (vertical_space - getPixelSize(ref_wnd).d_height) / 2 ; break; @@ -148,12 +148,12 @@ void RenderedStringWidgetComponent::draw(const Window* ref_wnd, if (d_selectionImage && d_selected) { const Rectf select_area(position, getPixelSize(ref_wnd)); - d_selectionImage->render(buffer, select_area, clip_rect, ColourRect(0xFF002FFF)); + d_selectionImage->render(geometry_buffers, select_area, clip_rect, true, ColourRect(0xFF002FFF)); } // we do not actually draw the widget, we just move it into position. - const UVector2 wpos(UDim(0, final_pos.d_x + d_padding.d_min.d_x - x_adj), - UDim(0, final_pos.d_y + d_padding.d_min.d_y - y_adj)); + const UVector2 wpos(UDim(0, final_pos.x + d_padding.d_min.d_x - x_adj), + UDim(0, final_pos.y + d_padding.d_min.d_y - y_adj)); window->setPosition(wpos); } @@ -206,7 +206,7 @@ RenderedStringWidgetComponent* RenderedStringWidgetComponent::split( //----------------------------------------------------------------------------// RenderedStringWidgetComponent* RenderedStringWidgetComponent::clone() const { - return CEGUI_NEW_AO RenderedStringWidgetComponent(*this); + return new RenderedStringWidgetComponent(*this); } //----------------------------------------------------------------------------// diff --git a/cegui/src/Renderer.cpp b/cegui/src/Renderer.cpp new file mode 100644 index 000000000..0cb12aff6 --- /dev/null +++ b/cegui/src/Renderer.cpp @@ -0,0 +1,122 @@ +/*********************************************************************** + created: 25th July 2013 + author: Lukas Meindl + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/Renderer.h" +#include "CEGUI/RenderMaterial.h" +#include "CEGUI/GeometryBuffer.h" + +#include + +namespace CEGUI +{ + +Renderer::Renderer(): + d_activeRenderTarget(0) +{} + +//----------------------------------------------------------------------------// +void Renderer::addGeometryBuffer(GeometryBuffer& buffer) +{ + d_geometryBuffers.insert(&buffer); +} + +//----------------------------------------------------------------------------// +void Renderer::destroyGeometryBuffer(GeometryBuffer& buffer) +{ + GeometryBufferSet::const_iterator findIter = d_geometryBuffers.find(&buffer); + + if (findIter != d_geometryBuffers.end()) + { + d_geometryBuffers.erase(findIter); + delete &buffer; + } +} + +//----------------------------------------------------------------------------// +void Renderer::destroyAllGeometryBuffers() +{ + while (!d_geometryBuffers.empty()) + destroyGeometryBuffer(*(*d_geometryBuffers.begin())); +} + +//----------------------------------------------------------------------------// +GeometryBuffer& Renderer::createGeometryBufferTextured() +{ + GeometryBuffer& geometry_buffer = createGeometryBufferTextured(createRenderMaterial(DS_TEXTURED)); + + return geometry_buffer; +} + +//----------------------------------------------------------------------------// +GeometryBuffer& Renderer::createGeometryBufferColoured() +{ + GeometryBuffer& geometry_buffer = createGeometryBufferColoured(createRenderMaterial(DS_SOLID)); + + return geometry_buffer; +} + +//----------------------------------------------------------------------------// +void Renderer::invalidateGeomBufferMatrices(const CEGUI::RenderTarget* renderTarget) +{ + GeometryBufferSet::iterator currentIter = d_geometryBuffers.begin(); + GeometryBufferSet::iterator iterEnd = d_geometryBuffers.end(); + + for(; currentIter != iterEnd; ++currentIter) + { + GeometryBuffer* geomBuffer = *currentIter; + if(geomBuffer->getLastRenderTarget() == renderTarget) + geomBuffer->invalidateMatrix(); + } +} + +//----------------------------------------------------------------------------// +void Renderer::setActiveRenderTarget(RenderTarget* renderTarget) +{ + d_activeRenderTarget = renderTarget; +} + + +//----------------------------------------------------------------------------// +RenderTarget* Renderer::getActiveRenderTarget() +{ + return d_activeRenderTarget; +} + +//----------------------------------------------------------------------------// +void Renderer::setViewProjectionMatrix(const glm::mat4& viewProjectionMatrix) +{ + d_viewProjectionMatrix = viewProjectionMatrix; +} + +//----------------------------------------------------------------------------// +const glm::mat4& Renderer::getViewProjectionMatrix() const +{ + return d_viewProjectionMatrix; +} + +//----------------------------------------------------------------------------// + +} diff --git a/cegui/src/RendererModules/CMakeLists.txt b/cegui/src/RendererModules/CMakeLists.txt index 7ddbe1310..4e1f0125e 100644 --- a/cegui/src/RendererModules/CMakeLists.txt +++ b/cegui/src/RendererModules/CMakeLists.txt @@ -1,15 +1,7 @@ -if (CEGUI_BUILD_RENDERER_OPENGL OR CEGUI_BUILD_RENDERER_OPENGL3) +if (CEGUI_BUILD_RENDERER_OPENGL OR CEGUI_BUILD_RENDERER_OPENGL3 OR CEGUI_BUILD_RENDERER_OPENGLES2) add_subdirectory(OpenGL) endif() -if (CEGUI_BUILD_RENDERER_DIRECT3D9) - add_subdirectory(Direct3D9) -endif() - -if (CEGUI_BUILD_RENDERER_DIRECT3D10) - add_subdirectory(Direct3D10) -endif() - if (CEGUI_BUILD_RENDERER_DIRECT3D11) add_subdirectory(Direct3D11) endif() diff --git a/cegui/src/RendererModules/Direct3D10/CMakeLists.txt b/cegui/src/RendererModules/Direct3D10/CMakeLists.txt deleted file mode 100644 index d6b0a74d9..000000000 --- a/cegui/src/RendererModules/Direct3D10/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -set (CEGUI_TARGET_NAME ${CEGUI_DIRECT3D10_RENDERER_LIBNAME}) - -include_directories(${DIRECTXSDK_INCLUDE_DIR}) -link_directories(${DIRECTXSDK_LIBRARY_DIR}) - -cegui_gather_files() -cegui_add_library(${CEGUI_TARGET_NAME} CORE_SOURCE_FILES CORE_HEADER_FILES) - -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME} d3d10) -cegui_target_link_libraries(${CEGUI_TARGET_NAME} optimized d3dx10 debug d3dx10d) - diff --git a/cegui/src/RendererModules/Direct3D10/GeometryBuffer.cpp b/cegui/src/RendererModules/Direct3D10/GeometryBuffer.cpp deleted file mode 100644 index 799b8369b..000000000 --- a/cegui/src/RendererModules/Direct3D10/GeometryBuffer.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2010 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D10/GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D10/Texture.h" -#include "CEGUI/RenderEffect.h" -#include "CEGUI/Vertex.h" -#include "CEGUI/Exceptions.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -Direct3D10GeometryBuffer::Direct3D10GeometryBuffer(Direct3D10Renderer& owner) : - d_owner(owner), - d_device(d_owner.getDirect3DDevice()), - d_activeTexture(0), - d_vertexBuffer(0), - d_bufferSize(0), - d_bufferSynched(false), - d_clipRect(0, 0, 0, 0), - d_clippingActive(true), - d_translation(0, 0, 0), - d_rotation(0, 0, 0), - d_pivot(0, 0, 0), - d_effect(0), - d_matrixValid(false) -{ -} - -//----------------------------------------------------------------------------// -Direct3D10GeometryBuffer::~Direct3D10GeometryBuffer() -{ - cleanupVertexBuffer(); -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::draw() const -{ - // setup clip region - D3D10_RECT clip; - clip.left = static_cast(d_clipRect.left()); - clip.top = static_cast(d_clipRect.top()); - clip.right = static_cast(d_clipRect.right()); - clip.bottom = static_cast(d_clipRect.bottom()); - d_device.RSSetScissorRects(1, &clip); - - if (!d_bufferSynched) - syncHardwareBuffer(); - - // apply the transformations we need to use. - if (!d_matrixValid) - updateMatrix(); - - d_owner.setWorldMatrix(d_matrix); - - // set our buffer as the vertex source. - const UINT stride = sizeof(D3DVertex); - const UINT offset = 0; - d_device.IASetVertexBuffers(0, 1, &d_vertexBuffer, &stride, &offset); - - const int pass_count = d_effect ? d_effect->getPassCount() : 1; - for (int pass = 0; pass < pass_count; ++pass) - { - // set up RenderEffect - if (d_effect) - d_effect->performPreRenderFunctions(pass); - - // draw the batches - size_t pos = 0; - BatchList::const_iterator i = d_batches.begin(); - for ( ; i != d_batches.end(); ++i) - { - // Set Texture - d_owner.setCurrentTextureShaderResource( - const_cast(i->texture)); - // Draw this batch - d_owner.bindTechniquePass(d_blendMode, i->clip); - d_device.Draw(i->vertexCount, pos); - pos += i->vertexCount; - } - } - - // clean up RenderEffect - if (d_effect) - d_effect->performPostRenderFunctions(); -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setTranslation(const Vector3f& v) -{ - d_translation = v; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setRotation(const Quaternion& r) -{ - d_rotation = r; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setPivot(const Vector3f& p) -{ - d_pivot = p; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setClippingRegion(const Rectf& region) -{ - d_clipRect.top(ceguimax(0.0f, region.top())); - d_clipRect.bottom(ceguimax(0.0f, region.bottom())); - d_clipRect.left(ceguimax(0.0f, region.left())); - d_clipRect.right(ceguimax(0.0f, region.right())); -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::appendVertex(const Vertex& vertex) -{ - appendGeometry(&vertex, 1); -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::appendGeometry(const Vertex* const vbuff, - uint vertex_count) -{ - const ID3D10ShaderResourceView* srv = - d_activeTexture ? d_activeTexture->getDirect3DShaderResourceView() : 0; - - // create a new batch if there are no batches yet, or if the active texture - // differs from that used by the current batch. - if (d_batches.empty() || - srv != d_batches.back().texture || - d_clippingActive != d_batches.back().clip) - { - const BatchInfo batch = {srv, 0, d_clippingActive}; - d_batches.push_back(batch); - } - - // update size of current batch - d_batches.back().vertexCount += vertex_count; - - // buffer these vertices - D3DVertex vd; - const Vertex* vs = vbuff; - for (uint i = 0; i < vertex_count; ++i, ++vs) - { - // copy vertex info the buffer, converting from CEGUI::Vertex to - // something directly usable by D3D as needed. - vd.x = vs->position.d_x; - vd.y = vs->position.d_y; - vd.z = vs->position.d_z; - vd.diffuse = vs->colour_val.getARGB(); - vd.tu = vs->tex_coords.d_x; - vd.tv = vs->tex_coords.d_y; - d_vertices.push_back(vd); - } - - d_bufferSynched = false; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setActiveTexture(Texture* texture) -{ - d_activeTexture = static_cast(texture); -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::reset() -{ - d_batches.clear(); - d_vertices.clear(); - d_activeTexture = 0; -} - -//----------------------------------------------------------------------------// -Texture* Direct3D10GeometryBuffer::getActiveTexture() const -{ - return d_activeTexture; -} - -//----------------------------------------------------------------------------// -uint Direct3D10GeometryBuffer::getVertexCount() const -{ - return d_vertices.size(); -} - -//----------------------------------------------------------------------------// -uint Direct3D10GeometryBuffer::getBatchCount() const -{ - return d_batches.size(); -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setRenderEffect(RenderEffect* effect) -{ - d_effect = effect; -} - -//----------------------------------------------------------------------------// -RenderEffect* Direct3D10GeometryBuffer::getRenderEffect() -{ - return d_effect; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::updateMatrix() const -{ - const D3DXVECTOR3 p(d_pivot.d_x, d_pivot.d_y, d_pivot.d_z); - const D3DXVECTOR3 t(d_translation.d_x, - d_translation.d_y, - d_translation.d_z); - - D3DXQUATERNION r; - r.x = d_rotation.d_x; - r.y = d_rotation.d_y; - r.z = d_rotation.d_z; - r.w = d_rotation.d_w; - - D3DXMatrixTransformation(&d_matrix, 0, 0, 0, &p, &r, &t); - - d_matrixValid = true; -} - -//----------------------------------------------------------------------------// -const D3DXMATRIX* Direct3D10GeometryBuffer::getMatrix() const -{ - if (!d_matrixValid) - updateMatrix(); - - return &d_matrix; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::syncHardwareBuffer() const -{ - const size_t vertex_count = d_vertices.size(); - - if (vertex_count > d_bufferSize) - { - cleanupVertexBuffer(); - allocateVertexBuffer(vertex_count); - } - - if (vertex_count > 0) - { - void* buff; - if (FAILED(d_vertexBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &buff))) - CEGUI_THROW(RendererException("failed to map buffer.")); - - std::memcpy(buff, &d_vertices[0], sizeof(D3DVertex) * vertex_count); - d_vertexBuffer->Unmap(); - } - - d_bufferSynched = true; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::allocateVertexBuffer(const size_t count) const -{ - D3D10_BUFFER_DESC buffer_desc; - buffer_desc.Usage = D3D10_USAGE_DYNAMIC; - buffer_desc.ByteWidth = count * sizeof(D3DVertex); - buffer_desc.BindFlags = D3D10_BIND_VERTEX_BUFFER; - buffer_desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE; - buffer_desc.MiscFlags = 0; - - if (FAILED(d_device.CreateBuffer(&buffer_desc, 0, &d_vertexBuffer))) - CEGUI_THROW(RendererException("failed to allocate vertex buffer.")); - - d_bufferSize = count; -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::cleanupVertexBuffer() const -{ - if (d_vertexBuffer) - { - d_vertexBuffer->Release(); - d_vertexBuffer = 0; - d_bufferSize = 0; - } -} - -//----------------------------------------------------------------------------// -void Direct3D10GeometryBuffer::setClippingActive(const bool active) -{ - d_clippingActive = active; -} - -//----------------------------------------------------------------------------// -bool Direct3D10GeometryBuffer::isClippingActive() const -{ - return d_clippingActive; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D10/RenderTarget.inl b/cegui/src/RendererModules/Direct3D10/RenderTarget.inl deleted file mode 100644 index 2be308c48..000000000 --- a/cegui/src/RendererModules/Direct3D10/RenderTarget.inl +++ /dev/null @@ -1,196 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D10/RenderTarget.h" -#include "CEGUI/RendererModules/Direct3D10/GeometryBuffer.h" -#include "CEGUI/RenderQueue.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -template -Direct3D10RenderTarget::Direct3D10RenderTarget(Direct3D10Renderer& owner) : - d_owner(owner), - d_device(d_owner.getDirect3DDevice()), - d_area(0, 0, 0, 0), - d_viewDistance(0), - d_matrixValid(false) -{ -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::draw(const GeometryBuffer& buffer) -{ - buffer.draw(); -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::draw(const RenderQueue& queue) -{ - queue.draw(); -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::setArea(const Rectf& area) -{ - d_area = area; - d_matrixValid = false; - - RenderTargetEventArgs args(this); - T::fireEvent(RenderTarget::EventAreaChanged, args); -} - -//----------------------------------------------------------------------------// -template -const Rectf& Direct3D10RenderTarget::getArea() const -{ - return d_area; -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::activate() -{ - if (!d_matrixValid) - updateMatrix(); - - D3D10_VIEWPORT vp; - setupViewport(vp); - d_device.RSSetViewports(1, &vp); - - d_owner.setProjectionMatrix(d_matrix); -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::deactivate() -{ -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const -{ - if (!d_matrixValid) - updateMatrix(); - - const Direct3D10GeometryBuffer& gb = - static_cast(buff); - - D3D10_VIEWPORT vp; - setupViewport(vp); - - D3DXVECTOR3 in_vec; - in_vec.z = 0.0f; - - // project points to create a plane orientated with GeometryBuffer's data - D3DXVECTOR3 p1; - D3DXVECTOR3 p2; - D3DXVECTOR3 p3; - in_vec.x = 0; - in_vec.y = 0; - D3DXVec3Project(&p1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = 1; - in_vec.y = 0; - D3DXVec3Project(&p2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = 0; - in_vec.y = 1; - D3DXVec3Project(&p3, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - // create plane from projected points - D3DXPLANE surface_plane; - D3DXPlaneFromPoints(&surface_plane, &p1, &p2, &p3); - - // unproject ends of ray - in_vec.x = vp.Width * 0.5f; - in_vec.y = vp.Height * 0.5f; - in_vec.z = -d_viewDistance; - D3DXVECTOR3 t1; - D3DXVec3Unproject(&t1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = p_in.d_x; - in_vec.y = p_in.d_y; - in_vec.z = 0.0f; - D3DXVECTOR3 t2; - D3DXVec3Unproject(&t2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - // get intersection of ray and plane - D3DXVECTOR3 intersect; - D3DXPlaneIntersectLine(&intersect, &surface_plane, &t1, &t2); - - p_out.d_x = intersect.x; - p_out.d_y = intersect.y; -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::updateMatrix() const -{ - const float fov = 0.523598776f; - const float w = d_area.getWidth(); - const float h = d_area.getHeight(); - const float aspect = w / h; - const float midx = w * 0.5f; - const float midy = h * 0.5f; - d_viewDistance = midx / (aspect * 0.267949192431123f); - - D3DXVECTOR3 eye(midx, midy, -d_viewDistance); - D3DXVECTOR3 at(midx, midy, 1); - D3DXVECTOR3 up(0, -1, 0); - - D3DXMATRIX tmp; - D3DXMatrixMultiply(&d_matrix, - D3DXMatrixLookAtRH(&d_matrix, &eye, &at, &up), - D3DXMatrixPerspectiveFovRH(&tmp, fov, aspect, - d_viewDistance * 0.5f, - d_viewDistance * 2.0f)); - - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -template -void Direct3D10RenderTarget::setupViewport(D3D10_VIEWPORT& vp) const -{ - vp.TopLeftX = static_cast(d_area.left()); - vp.TopLeftY = static_cast(d_area.top()); - vp.Width = static_cast(d_area.getWidth()); - vp.Height = static_cast(d_area.getHeight()); - vp.MinDepth = 0.0f; - vp.MaxDepth = 1.0f; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D10/Renderer.cpp b/cegui/src/RendererModules/Direct3D10/Renderer.cpp deleted file mode 100644 index 490f723e1..000000000 --- a/cegui/src/RendererModules/Direct3D10/Renderer.cpp +++ /dev/null @@ -1,470 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D10/Renderer.h" -#include "CEGUI/RendererModules/Direct3D10/GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D10/TextureTarget.h" -#include "CEGUI/RendererModules/Direct3D10/ViewportTarget.h" -#include "CEGUI/RendererModules/Direct3D10/Texture.h" -#include "CEGUI/Exceptions.h" -#include "CEGUI/System.h" -#include "CEGUI/DefaultResourceProvider.h" -#include "CEGUI/Logger.h" -#include - -#include "shader.txt" - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -String Direct3D10Renderer::d_rendererID( -"CEGUI::Direct3D10Renderer - Official Direct3D 10 based 2nd generation renderer" -" module."); - -//----------------------------------------------------------------------------// -Direct3D10Renderer& Direct3D10Renderer::bootstrapSystem(ID3D10Device* device, - const int abi) -{ - System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - - if (System::getSingletonPtr()) - CEGUI_THROW(InvalidRequestException( - "CEGUI::System object is already initialised.")); - - Direct3D10Renderer& renderer(create(device)); - DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); - System::create(renderer, rp); - - return renderer; -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroySystem() -{ - System* sys; - if (!(sys = System::getSingletonPtr())) - CEGUI_THROW(InvalidRequestException( - "CEGUI::System object is not created or was already destroyed.")); - - Direct3D10Renderer* renderer = - static_cast(sys->getRenderer()); - DefaultResourceProvider* rp = - static_cast(sys->getResourceProvider()); - - System::destroy(); - delete rp; - destroy(*renderer); -} - -//----------------------------------------------------------------------------// -Direct3D10Renderer& Direct3D10Renderer::create(ID3D10Device* device, - const int abi) -{ - System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - - return *new Direct3D10Renderer(device); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroy(Direct3D10Renderer& renderer) -{ - delete &renderer; -} - -//----------------------------------------------------------------------------// -RenderTarget& Direct3D10Renderer::getDefaultRenderTarget() -{ - return *d_defaultTarget; -} - -//----------------------------------------------------------------------------// -GeometryBuffer& Direct3D10Renderer::createGeometryBuffer() -{ - Direct3D10GeometryBuffer* b = new Direct3D10GeometryBuffer(*this); - d_geometryBuffers.push_back(b); - return *b; -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyGeometryBuffer(const GeometryBuffer& buffer) -{ - GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), - d_geometryBuffers.end(), - &buffer); - - if (d_geometryBuffers.end() != i) - { - d_geometryBuffers.erase(i); - delete &buffer; - } -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyAllGeometryBuffers() -{ - while (!d_geometryBuffers.empty()) - destroyGeometryBuffer(**d_geometryBuffers.begin()); -} - -//----------------------------------------------------------------------------// -TextureTarget* Direct3D10Renderer::createTextureTarget() -{ - TextureTarget* t = new Direct3D10TextureTarget(*this); - d_textureTargets.push_back(t); - return t; -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyTextureTarget(TextureTarget* target) -{ - TextureTargetList::iterator i = std::find(d_textureTargets.begin(), - d_textureTargets.end(), - target); - - if (d_textureTargets.end() != i) - { - d_textureTargets.erase(i); - delete target; - } -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyAllTextureTargets() -{ - while (!d_textureTargets.empty()) - destroyTextureTarget(*d_textureTargets.begin()); -} - -//----------------------------------------------------------------------------// -Texture& Direct3D10Renderer::createTexture(const String& name) -{ - throwIfNameExists(name); - - Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -Texture& Direct3D10Renderer::createTexture(const String& name, - const String& filename, - const String& resourceGroup) -{ - throwIfNameExists(name); - - Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name, filename, - resourceGroup); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -Texture& Direct3D10Renderer::createTexture(const String& name, - const Sizef& size) -{ - throwIfNameExists(name); - - Direct3D10Texture* tex = new Direct3D10Texture(*d_device, name, size); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::throwIfNameExists(const String& name) const -{ - if (d_textures.find(name) != d_textures.end()) - CEGUI_THROW(AlreadyExistsException( - "[Direct3D10Renderer] Texture already exists: " + name)); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::logTextureCreation(const String& name) -{ - Logger* logger = Logger::getSingletonPtr(); - if (logger) - logger->logEvent("[Direct3D10Renderer] Created texture: " + name); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyTexture(Texture& texture) -{ - destroyTexture(texture.getName()); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyTexture(const String& name) -{ - TextureMap::iterator i = d_textures.find(name); - - if (d_textures.end() != i) - { - logTextureDestruction(name); - delete i->second; - d_textures.erase(i); - } -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::logTextureDestruction(const String& name) -{ - Logger* logger = Logger::getSingletonPtr(); - if (logger) - logger->logEvent("[Direct3D10Renderer] Destroyed texture: " + name); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::destroyAllTextures() -{ - while (!d_textures.empty()) - destroyTexture(d_textures.begin()->first); -} - -//----------------------------------------------------------------------------// -Texture& Direct3D10Renderer::getTexture(const String& name) const -{ - TextureMap::const_iterator i = d_textures.find(name); - - if (i == d_textures.end()) - CEGUI_THROW(UnknownObjectException("Texture does not exist: " + name)); - - return *i->second; -} - -//----------------------------------------------------------------------------// -bool Direct3D10Renderer::isTextureDefined(const String& name) const -{ - return d_textures.find(name) != d_textures.end(); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::beginRendering() -{ - d_device->IASetInputLayout(d_inputLayout); - d_device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::endRendering() -{ -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::setDisplaySize(const Sizef& sz) -{ - if (sz != d_displaySize) - { - d_displaySize = sz; - - // FIXME: This is probably not the right thing to do in all cases. - Rectf area(d_defaultTarget->getArea()); - area.setSize(sz); - d_defaultTarget->setArea(area); - } - -} - -//----------------------------------------------------------------------------// -const Sizef& Direct3D10Renderer::getDisplaySize() const -{ - return d_displaySize; -} - -//----------------------------------------------------------------------------// -const Vector2f& Direct3D10Renderer::getDisplayDPI() const -{ - return d_displayDPI; -} - -//----------------------------------------------------------------------------// -uint Direct3D10Renderer::getMaxTextureSize() const -{ - return 8192; -} - -//----------------------------------------------------------------------------// -const String& Direct3D10Renderer::getIdentifierString() const -{ - return d_rendererID; -} - -//----------------------------------------------------------------------------// -Direct3D10Renderer::Direct3D10Renderer(ID3D10Device* device) : - d_device(device), - d_displaySize(getViewportSize()), - d_displayDPI(96, 96), - d_defaultTarget(0), - d_effect(0), - d_normalClippedTechnique(0), - d_normalUnclippedTechnique(0), - d_premultipliedClippedTechnique(0), - d_premultipliedUnclippedTechnique(0), - d_inputLayout(0), - d_boundTextureVariable(0), - d_worldMatrixVariable(0), - d_projectionMatrixVariable(0) -{ - // create the main effect from the shader source. - ID3D10Blob* errors = 0; - if (FAILED(D3DX10CreateEffectFromMemory(shaderSource, sizeof(shaderSource), - 0, 0, 0, "fx_4_0", 0, 0, d_device, - 0, 0, &d_effect, &errors, 0))) - { - std::string msg(static_cast(errors->GetBufferPointer()), - errors->GetBufferSize()); - errors->Release(); - CEGUI_THROW(RendererException(msg)); - } - - // extract the rendering techniques - d_normalClippedTechnique = - d_effect->GetTechniqueByName("BM_NORMAL_Clipped_Rendering"); - d_normalUnclippedTechnique = - d_effect->GetTechniqueByName("BM_NORMAL_Unclipped_Rendering"); - d_premultipliedClippedTechnique = - d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Clipped_Rendering"); - d_premultipliedClippedTechnique = - d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Unclipped_Rendering"); - - // Get the variables from the shader we need to be able to access - d_boundTextureVariable = - d_effect->GetVariableByName("BoundTexture")->AsShaderResource(); - d_worldMatrixVariable = - d_effect->GetVariableByName("WorldMatrix")->AsMatrix(); - d_projectionMatrixVariable = - d_effect->GetVariableByName("ProjectionMatrix")->AsMatrix(); - - // Create the input layout - const D3D10_INPUT_ELEMENT_DESC vertex_layout[] = - { - { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D10_INPUT_PER_VERTEX_DATA, 0 }, - }; - - const UINT element_count = sizeof(vertex_layout) / sizeof(vertex_layout[0]); - - D3D10_PASS_DESC pass_desc; - if (FAILED(d_normalClippedTechnique->GetPassByIndex(0)->GetDesc(&pass_desc))) - CEGUI_THROW(RendererException( - "failed to obtain technique description for pass 0.")); - - if (FAILED(d_device->CreateInputLayout(vertex_layout, element_count, - pass_desc.pIAInputSignature, - pass_desc.IAInputSignatureSize, - &d_inputLayout))) - { - CEGUI_THROW(RendererException("failed to create D3D 10 input layout.")); - } - - d_defaultTarget = new Direct3D10ViewportTarget(*this); -} - -//----------------------------------------------------------------------------// -Direct3D10Renderer::~Direct3D10Renderer() -{ - destroyAllTextureTargets(); - destroyAllTextures(); - destroyAllGeometryBuffers(); - - delete d_defaultTarget; - - if (d_effect) - d_effect->Release(); - - if (d_inputLayout) - d_inputLayout->Release(); - -} - -//----------------------------------------------------------------------------// -Sizef Direct3D10Renderer::getViewportSize() -{ - D3D10_VIEWPORT vp; - UINT vp_count = 1; - - d_device->RSGetViewports(&vp_count, &vp); - - if (vp_count != 1) - CEGUI_THROW(RendererException( - "Unable to access required view port information from " - "IDirect3DDevice10.")); - else - return Sizef(static_cast(vp.Width), - static_cast(vp.Height)); -} - -//----------------------------------------------------------------------------// -ID3D10Device& Direct3D10Renderer::getDirect3DDevice() const -{ - return *d_device; -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::bindTechniquePass(const BlendMode mode, - const bool clipped) -{ - if (mode == BM_RTT_PREMULTIPLIED) - if (clipped) - d_premultipliedClippedTechnique->GetPassByIndex(0)->Apply(0); - else - d_premultipliedUnclippedTechnique->GetPassByIndex(0)->Apply(0); - else if (clipped) - d_normalClippedTechnique->GetPassByIndex(0)->Apply(0); - else - d_normalUnclippedTechnique->GetPassByIndex(0)->Apply(0); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::setCurrentTextureShaderResource( - ID3D10ShaderResourceView* srv) -{ - d_boundTextureVariable->SetResource(srv); -} - -//----------------------------------------------------------------------------// -void Direct3D10Renderer::setProjectionMatrix(D3DXMATRIX& matrix) -{ - d_projectionMatrixVariable->SetMatrix(reinterpret_cast(&matrix)); -} -//----------------------------------------------------------------------------// -void Direct3D10Renderer::setWorldMatrix(D3DXMATRIX& matrix) -{ - d_worldMatrixVariable->SetMatrix(reinterpret_cast(&matrix)); -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D10/Texture.cpp b/cegui/src/RendererModules/Direct3D10/Texture.cpp deleted file mode 100644 index 02ce0598f..000000000 --- a/cegui/src/RendererModules/Direct3D10/Texture.cpp +++ /dev/null @@ -1,516 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D10/Texture.h" -#include "CEGUI/System.h" -#include "CEGUI/Exceptions.h" -#include "CEGUI/ImageCodec.h" -#include - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -// helper to convert cegui pixel format enum to equivalent D3D format. -static DXGI_FORMAT toD3DPixelFormat(const Texture::PixelFormat fmt) -{ - switch (fmt) - { - case Texture::PF_RGBA: return DXGI_FORMAT_R8G8B8A8_UNORM; - case Texture::PF_RGB: return DXGI_FORMAT_R8G8B8A8_UNORM; - case Texture::PF_RGBA_DXT1: return DXGI_FORMAT_BC1_UNORM; - case Texture::PF_RGBA_DXT3: return DXGI_FORMAT_BC2_UNORM; - case Texture::PF_RGBA_DXT5: return DXGI_FORMAT_BC3_UNORM; - default: return DXGI_FORMAT_UNKNOWN; - } -} - -//----------------------------------------------------------------------------// -// helper function to return byte width of given pixel width in given format -static size_t calculateDataWidth(const size_t width, Texture::PixelFormat fmt) -{ - switch (fmt) - { - case Texture::PF_RGBA: - case Texture::PF_RGB: // also 4 because we convert to RGBA - return width * 4; - - case Texture::PF_RGBA_DXT1: - return ((width + 3) / 4) * 8; - - case Texture::PF_RGBA_DXT3: - case Texture::PF_RGBA_DXT5: - return ((width + 3) / 4) * 16; - - default: - return 0; - } -} - -//----------------------------------------------------------------------------// -// Helper utility function that copies an RGBA buffer into a region of a second -// buffer as D3DCOLOR data values -static void blitToSurface(const uint32* src, uint32* dst, - const Sizef& sz, size_t dest_pitch) -{ - for (uint i = 0; i < sz.d_height; ++i) - { - for (uint j = 0; j < sz.d_width; ++j) - { - const uint32 pixel = src[j]; - const uint32 tmp = pixel & 0x00FF00FF; - dst[j] = pixel & 0xFF00FF00 | (tmp << 16) | (tmp >> 16); - } - - dst += dest_pitch / sizeof(uint32); - src += static_cast(sz.d_width); - } -} - -//----------------------------------------------------------------------------// -// Helper utility function that copies a region of a buffer containing D3DCOLOR -// values into a second buffer as RGBA values. -static void blitFromSurface(const uint32* src, uint32* dst, - const Sizef& sz, size_t source_pitch) -{ - for (uint i = 0; i < sz.d_height; ++i) - { - for (uint j = 0; j < sz.d_width; ++j) - { - const uint32 pixel = src[j]; - const uint32 tmp = pixel & 0x00FF00FF; - dst[j] = pixel & 0xFF00FF00 | (tmp << 16) | (tmp >> 16); - } - - src += source_pitch / sizeof(uint32); - dst += static_cast(sz.d_width); - } -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::setDirect3DTexture(ID3D10Texture2D* tex) -{ - if (d_texture != tex) - { - cleanupDirect3D10Texture(); - d_dataSize.d_width = d_dataSize.d_height = 0; - - d_texture = tex; - if (d_texture) - d_texture->AddRef(); - } - - initialiseShaderResourceView(); - - updateTextureSize(); - d_dataSize = d_size; - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -ID3D10Texture2D* Direct3D10Texture::getDirect3DTexture() const -{ - return d_texture; -} - -//----------------------------------------------------------------------------// -ID3D10ShaderResourceView* Direct3D10Texture::getDirect3DShaderResourceView() const -{ - return d_resourceView; -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::setOriginalDataSize(const Sizef& sz) -{ - d_dataSize = sz; - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -const String& Direct3D10Texture::getName() const -{ - return d_name; -} - -//----------------------------------------------------------------------------// -const Sizef& Direct3D10Texture::getSize() const -{ - return d_size; -} - -//----------------------------------------------------------------------------// -const Sizef& Direct3D10Texture::getOriginalDataSize() const -{ - return d_dataSize; -} - -//----------------------------------------------------------------------------// -const Vector2f& Direct3D10Texture::getTexelScaling() const -{ - return d_texelScaling; -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::loadFromFile(const String& filename, - const String& resourceGroup) -{ - // get and check existence of CEGUI::System object - System* sys = System::getSingletonPtr(); - if (!sys) - CEGUI_THROW(RendererException( - "CEGUI::System object has not been created!")); - - // load file to memory via resource provider - RawDataContainer texFile; - sys->getResourceProvider()->loadRawDataContainer(filename, texFile, - resourceGroup); - - Texture* res = sys->getImageCodec().load(texFile, this); - - // unload file data buffer - sys->getResourceProvider()->unloadRawDataContainer(texFile); - - if (!res) - // It's an error - CEGUI_THROW(RendererException( - sys->getImageCodec().getIdentifierString() + - " failed to load image '" + filename + "'.")); -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::loadFromMemory(const void* buffer, - const Sizef& buffer_size, - PixelFormat pixel_format) -{ - if (!isPixelFormatSupported(pixel_format)) - CEGUI_THROW(InvalidRequestException( - "Data was supplied in an unsupported pixel format.")); - - cleanupDirect3D10Texture(); - - const void* img_src = buffer; - if (pixel_format == PF_RGB) - { - const unsigned char* src = static_cast(buffer); - unsigned char* dest = new unsigned char[static_cast( buffer_size.d_width * buffer_size.d_height * 4 )]; - - for (int i = 0; i < buffer_size.d_width * buffer_size.d_height; ++i) - { - dest[i * 4 + 0] = src[i * 3 + 0]; - dest[i * 4 + 1] = src[i * 3 + 1]; - dest[i * 4 + 2] = src[i * 3 + 2]; - dest[i * 4 + 3] = 0xFF; - } - - img_src = dest; - } - - D3D10_TEXTURE2D_DESC tex_desc; - ZeroMemory(&tex_desc, sizeof(tex_desc)); - tex_desc.Width = static_cast(buffer_size.d_width); - tex_desc.Height = static_cast(buffer_size.d_height); - tex_desc.ArraySize = 1; - tex_desc.SampleDesc.Count = 1; - tex_desc.SampleDesc.Quality = 0; - tex_desc.Format = toD3DPixelFormat(pixel_format); - tex_desc.Usage = D3D10_USAGE_DEFAULT; - tex_desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; - tex_desc.CPUAccessFlags = 0; - tex_desc.MiscFlags = 0; - tex_desc.MipLevels = 1; - - D3D10_SUBRESOURCE_DATA data; - ZeroMemory(&data, sizeof(D3D10_SUBRESOURCE_DATA)); - data.pSysMem = img_src; - data.SysMemPitch = calculateDataWidth(tex_desc.Width, pixel_format); - - HRESULT hr = d_device.CreateTexture2D(&tex_desc, &data, &d_texture); - - if (pixel_format == PF_RGB) - delete[] img_src; - - if (FAILED(hr)) - CEGUI_THROW(RendererException( - "Failed to create texture from memory buffer.")); - - initialiseShaderResourceView(); - - d_dataSize = buffer_size; - updateTextureSize(); - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::blitFromMemory(const void* sourceData, const Rectf& area) -{ - if (!d_texture) - return; - - uint32* buff = new uint32[static_cast(area.getWidth()) * - static_cast(area.getHeight())]; - blitFromSurface(static_cast(sourceData), buff, - area.getSize(), static_cast(area.getWidth()) * 4); - - D3D10_BOX dst_box = {static_cast(area.left()), - static_cast(area.top()), - 0, - static_cast(area.right()), - static_cast(area.bottom()), - 1}; - - d_device.UpdateSubresource(d_texture, 0, &dst_box, buff, - static_cast(area.getWidth()) * 4, 0); - - delete[] buff; -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::blitToMemory(void* targetData) -{ - if (!d_texture) - return; - - String exception_msg; - - D3D10_TEXTURE2D_DESC tex_desc; - d_texture->GetDesc(&tex_desc); - - tex_desc.Usage = D3D10_USAGE_STAGING; - tex_desc.BindFlags = 0; - tex_desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ; - - ID3D10Texture2D* offscreen; - if (SUCCEEDED(d_device.CreateTexture2D(&tex_desc, 0, &offscreen))) - { - d_device.CopyResource(offscreen, d_texture); - - D3D10_MAPPED_TEXTURE2D mapped_tex; - if (SUCCEEDED(offscreen->Map(0, D3D10_MAP_READ, 0, &mapped_tex))) - { - blitFromSurface(static_cast(mapped_tex.pData), - static_cast(targetData), - Sizef(static_cast(tex_desc.Width), - static_cast(tex_desc.Height)), - mapped_tex.RowPitch); - - offscreen->Unmap(0); - } - else - exception_msg.assign("ID3D10Texture2D::Map failed."); - - offscreen->Release(); - } - else - exception_msg.assign( - "ID3D10Device::CreateTexture2D failed for 'offscreen'."); - - if (!exception_msg.empty()) - CEGUI_THROW(RendererException(exception_msg)); -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::cleanupDirect3D10Texture() -{ - if (d_resourceView) - { - d_resourceView->Release(); - d_resourceView = 0; - } - - if (d_texture) - { - d_texture->Release(); - d_texture = 0; - } -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::updateCachedScaleValues() -{ - // - // calculate what to use for x scale - // - const float orgW = d_dataSize.d_width; - const float texW = d_size.d_width; - - // if texture and original data width are the same, scale is based - // on the original size. - // if texture is wider (and source data was not stretched), scale - // is based on the size of the resulting texture. - d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); - - // - // calculate what to use for y scale - // - const float orgH = d_dataSize.d_height; - const float texH = d_size.d_height; - - // if texture and original data height are the same, scale is based - // on the original size. - // if texture is taller (and source data was not stretched), scale - // is based on the size of the resulting texture. - d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::updateTextureSize() -{ - if (d_texture) - { - D3D10_TEXTURE2D_DESC surfDesc; - d_texture->GetDesc(&surfDesc); - d_size.d_width = static_cast(surfDesc.Width); - d_size.d_height = static_cast(surfDesc.Height); - } - else - d_size.d_height = d_size.d_width = 0.0f; -} - -//----------------------------------------------------------------------------// -Direct3D10Texture::Direct3D10Texture(ID3D10Device& device, const String& name) : - d_device(device), - d_texture(0), - d_resourceView(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_name(name) -{ -} - -//----------------------------------------------------------------------------// -Direct3D10Texture::Direct3D10Texture(ID3D10Device& device, const String& name, - const String& filename, - const String& resourceGroup) : - d_device(device), - d_texture(0), - d_resourceView(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_name(name) -{ - loadFromFile(filename, resourceGroup); -} - -//----------------------------------------------------------------------------// -Direct3D10Texture::Direct3D10Texture(ID3D10Device& device, const String& name, - const Sizef& sz) : - d_device(device), - d_texture(0), - d_resourceView(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_name(name) -{ - D3D10_TEXTURE2D_DESC tex_desc; - ZeroMemory(&tex_desc, sizeof(tex_desc)); - tex_desc.Width = static_cast(sz.d_width); - tex_desc.Height = static_cast(sz.d_height); - tex_desc.ArraySize = 1; - tex_desc.SampleDesc.Count = 1; - tex_desc.SampleDesc.Quality = 0; - tex_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - tex_desc.Usage = D3D10_USAGE_DEFAULT; - tex_desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; - tex_desc.CPUAccessFlags = 0; - tex_desc.MiscFlags = 0; - tex_desc.MipLevels = 1; - - if (FAILED(d_device.CreateTexture2D(&tex_desc, 0, &d_texture))) - CEGUI_THROW(RendererException( - "Failed to create texture with specified size.")); - - initialiseShaderResourceView(); - - d_dataSize = sz; - updateTextureSize(); - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -Direct3D10Texture::Direct3D10Texture(ID3D10Device& device, const String& name, - ID3D10Texture2D* tex) : - d_device(device), - d_texture(0), - d_resourceView(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_name(name) -{ - setDirect3DTexture(tex); -} - -//----------------------------------------------------------------------------// -Direct3D10Texture::~Direct3D10Texture() -{ - cleanupDirect3D10Texture(); -} - -//----------------------------------------------------------------------------// -void Direct3D10Texture::initialiseShaderResourceView() -{ - if (!d_texture) - return; - - D3D10_TEXTURE2D_DESC tex_desc; - d_texture->GetDesc(&tex_desc); - - ID3D10Resource* resource = 0; - d_texture->QueryInterface(__uuidof(ID3D10Resource), - reinterpret_cast(&resource)); - - D3D10_SHADER_RESOURCE_VIEW_DESC srvd; - srvd.Format = tex_desc.Format; - srvd.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D; - srvd.Texture2D.MostDetailedMip = 0; - srvd.Texture2D.MipLevels = tex_desc.MipLevels; - d_device.CreateShaderResourceView(resource, &srvd, &d_resourceView); - resource->Release(); -} - -//----------------------------------------------------------------------------// -bool Direct3D10Texture::isPixelFormatSupported(const PixelFormat fmt) const -{ - switch (fmt) - { - case PF_RGBA: - case PF_RGB: - case PF_RGBA_DXT1: - case PF_RGBA_DXT3: - case PF_RGBA_DXT5: - return true; - - default: - return false; - } -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D10/TextureTarget.cpp b/cegui/src/RendererModules/Direct3D10/TextureTarget.cpp deleted file mode 100644 index c7646da3a..000000000 --- a/cegui/src/RendererModules/Direct3D10/TextureTarget.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D10/TextureTarget.h" -#include "CEGUI/RendererModules/Direct3D10/Texture.h" -#include "CEGUI/PropertyHelper.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -const float Direct3D10TextureTarget::DEFAULT_SIZE = 128.0f; -uint Direct3D10TextureTarget::s_textureNumber = 0; - -//----------------------------------------------------------------------------// -Direct3D10TextureTarget::Direct3D10TextureTarget(Direct3D10Renderer& owner) : - Direct3D10RenderTarget(owner), - d_texture(0), - d_renderTargetView(0), - d_previousRenderTargetView(0), - d_previousDepthStencilView(0) -{ - // this essentially creates a 'null' CEGUI::Texture - d_CEGUITexture = &static_cast( - d_owner.createTexture(generateTextureName())); - - // setup area and cause the initial texture to be generated. - declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE)); -} - -//----------------------------------------------------------------------------// -Direct3D10TextureTarget::~Direct3D10TextureTarget() -{ - cleanupRenderTexture(); - d_owner.destroyTexture(*d_CEGUITexture); -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::activate() -{ - enableRenderTexture(); - Direct3D10RenderTarget::activate(); -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::deactivate() -{ - Direct3D10RenderTarget::deactivate(); - disableRenderTexture(); -} - -//----------------------------------------------------------------------------// -bool Direct3D10TextureTarget::isImageryCache() const -{ - return true; -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::clear() -{ - const float colour[] = { 0, 0, 0, 0 }; - d_device.ClearRenderTargetView(d_renderTargetView, colour); -} - -//----------------------------------------------------------------------------// -Texture& Direct3D10TextureTarget::getTexture() const -{ - return *d_CEGUITexture; -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::declareRenderSize(const Sizef& sz) -{ - // exit if current size is enough - if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height)) - return; - - setArea(Rectf(d_area.getPosition(), sz)); - resizeRenderTexture(); - clear(); -} - -//----------------------------------------------------------------------------// -bool Direct3D10TextureTarget::isRenderingInverted() const -{ - return false; -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::initialiseRenderTexture() -{ - // Create the render target texture - D3D10_TEXTURE2D_DESC tex_desc; - ZeroMemory(&tex_desc, sizeof(tex_desc)); - tex_desc.Width = static_cast(d_area.getSize().d_width); - tex_desc.Height = static_cast(d_area.getSize().d_height); - tex_desc.MipLevels = 1; - tex_desc.ArraySize = 1; - tex_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - tex_desc.SampleDesc.Count = 1; - tex_desc.Usage = D3D10_USAGE_DEFAULT; - tex_desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE; - d_device.CreateTexture2D(&tex_desc, 0, &d_texture); - - // create render target view, so we can render to the thing - D3D10_RENDER_TARGET_VIEW_DESC rtv_desc; - rtv_desc.Format = tex_desc.Format; - rtv_desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D; - rtv_desc.Texture2D.MipSlice = 0; - d_device.CreateRenderTargetView(d_texture, &rtv_desc, &d_renderTargetView); - - d_CEGUITexture->setDirect3DTexture(d_texture); - d_CEGUITexture->setOriginalDataSize(d_area.getSize()); -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::cleanupRenderTexture() -{ - if (d_renderTargetView) - { - d_renderTargetView->Release(); - d_renderTargetView = 0; - } - if (d_texture) - { - d_CEGUITexture->setDirect3DTexture(0); - d_texture->Release(); - d_texture = 0; - } -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::resizeRenderTexture() -{ - cleanupRenderTexture(); - initialiseRenderTexture(); -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::enableRenderTexture() -{ - d_device.OMGetRenderTargets(1, &d_previousRenderTargetView, - &d_previousDepthStencilView); - - d_device.OMSetRenderTargets(1, &d_renderTargetView, 0); -} - -//----------------------------------------------------------------------------// -void Direct3D10TextureTarget::disableRenderTexture() -{ - if (d_previousRenderTargetView) - d_previousRenderTargetView->Release(); - if (d_previousDepthStencilView) - d_previousDepthStencilView->Release(); - - d_device.OMSetRenderTargets(1, &d_previousRenderTargetView, - d_previousDepthStencilView); - - d_previousRenderTargetView = 0; - d_previousDepthStencilView = 0; -} - -//----------------------------------------------------------------------------// -String Direct3D10TextureTarget::generateTextureName() -{ - String tmp("_d3d10_tt_tex_"); - tmp.append(PropertyHelper::toString(s_textureNumber++)); - - return tmp; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section - -//----------------------------------------------------------------------------// -// Implementation of template base class -#include "./RenderTarget.inl" - diff --git a/cegui/src/RendererModules/Direct3D10/shader.txt b/cegui/src/RendererModules/Direct3D10/shader.txt deleted file mode 100644 index 7a87c1383..000000000 --- a/cegui/src/RendererModules/Direct3D10/shader.txt +++ /dev/null @@ -1,146 +0,0 @@ -const char shaderSource[] = -"//--------------------------------------------------------------------------//\n" -"Texture2D BoundTexture;\n" -"matrix WorldMatrix;\n" -"matrix ProjectionMatrix;\n" -"//--------------------------------------------------------------------------//\n" -"\n" -"\n" -"struct VSSceneIn\n" -"{\n" -" float3 pos : POSITION;\n" -" float4 colour : COLOR;\n" -" float2 tex : TEXCOORD;\n" -"};\n" -"\n" -"struct PSSceneIn\n" -"{\n" -" float4 pos : SV_Position;\n" -" float4 colour : COLOR;\n" -" float2 tex : TEXCOORD;\n" -"};\n" -"\n" -"DepthStencilState DisableDepth\n" -"{\n" -" DepthEnable = FALSE;\n" -" DepthWriteMask = ZERO;\n" -"};\n" -"\n" -"BlendState BM_NORMAL\n" -"{\n" -" AlphaToCoverageEnable = false;\n" -" BlendEnable[0] = true;\n" -" SrcBlendAlpha = INV_DEST_ALPHA;\n" -" DestBlendAlpha = ONE;\n" -" SrcBlend = SRC_ALPHA;\n" -" DestBlend = INV_SRC_ALPHA;\n" -"};\n" -"\n" -"BlendState BM_RTT_PREMULTIPLIED\n" -"{\n" -" AlphaToCoverageEnable = false;\n" -" BlendEnable[0] = true;\n" -" SrcBlendAlpha = ONE;\n" -" DestBlendAlpha = INV_SRC_ALPHA;\n" -" SrcBlend = ONE;\n" -" DestBlend = INV_SRC_ALPHA;\n" -"};\n" -"\n" -"SamplerState LinearSampler\n" -"{\n" -" Filter = MIN_MAG_MIP_LINEAR;\n" -" AddressU = Clamp;\n" -" AddressV = Clamp;\n" -"};\n" -"\n" -"RasterizerState clipRasterstate\n" -"{\n" -" DepthClipEnable = false;\n" -" FillMode = Solid;\n" -" CullMode = None;\n" -" ScissorEnable = true;\n" -"};\n" -"RasterizerState noclipRasterstate\n" -"{\n" -" DepthClipEnable = false;\n" -" FillMode = Solid;\n" -" CullMode = None;\n" -" ScissorEnable = false;\n" -"};\n" -"\n" -"// Vertex shader\n" -"PSSceneIn VSMain(VSSceneIn input)\n" -"{\n" -" PSSceneIn output = (PSSceneIn)0.0;\n" -"\n" -" //output our final position\n" -" output.pos = mul( float4(input.pos, 1), WorldMatrix );\n" -" output.pos = mul( output.pos, ProjectionMatrix );\n" -" output.tex = input.tex;\n" -" output.colour.rgba = input.colour.bgra;\n" -"\n" -" return output;\n" -"}\n" -"\n" -"// Pixel shader\n" -"float4 PSMain(PSSceneIn input) : SV_Target\n" -"{\n" -" float4 colour = BoundTexture.Sample(LinearSampler, input.tex) * input.colour;\n" -" return colour;\n" -"}\n" -"\n" -"// Techniques\n" -"technique10 BM_NORMAL_Clipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_NORMAL, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(clipRasterstate);\n" -" }\n" -"}\n" -"\n" -"technique10 BM_NORMAL_Unclipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_NORMAL, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(noclipRasterstate);\n" -" }\n" -"}\n" -"\n" -"technique10 BM_RTT_PREMULTIPLIED_Clipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_RTT_PREMULTIPLIED, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(clipRasterstate);\n" -" }\n" -"}\n" -"\n" -"technique10 BM_RTT_PREMULTIPLIED_Unclipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_RTT_PREMULTIPLIED, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(noclipRasterstate);\n" -" }\n" -"}\n" -"\n" -"//--------------------------------------------------------------------------//\n" -; diff --git a/cegui/src/RendererModules/Direct3D11/CMakeLists.txt b/cegui/src/RendererModules/Direct3D11/CMakeLists.txt index dc47400c4..9da6781fc 100644 --- a/cegui/src/RendererModules/Direct3D11/CMakeLists.txt +++ b/cegui/src/RendererModules/Direct3D11/CMakeLists.txt @@ -7,7 +7,9 @@ cegui_gather_files() cegui_add_library(${CEGUI_TARGET_NAME} CORE_SOURCE_FILES CORE_HEADER_FILES) cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME} d3d11 d3dcompiler) -cegui_target_link_libraries(${CEGUI_TARGET_NAME} optimized d3dx11 d3dx10 debug d3dx11d d3dx10d) + +# this is required for resolving GUID symbols such as "IID_ID3D11ShaderReflection" on older Direct3D versions, such as in June 2010 SDK +add_definitions( -DINITGUID ) cegui_add_dependency(${CEGUI_TARGET_NAME} D3DX11EFFECTS) diff --git a/cegui/src/RendererModules/Direct3D11/GeometryBuffer.cpp b/cegui/src/RendererModules/Direct3D11/GeometryBuffer.cpp index 50f696309..141af4050 100644 --- a/cegui/src/RendererModules/Direct3D11/GeometryBuffer.cpp +++ b/cegui/src/RendererModules/Direct3D11/GeometryBuffer.cpp @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -25,28 +26,29 @@ ***************************************************************************/ #include "CEGUI/RendererModules/Direct3D11/GeometryBuffer.h" #include "CEGUI/RendererModules/Direct3D11/Texture.h" +#include "CEGUI/RendererModules/Direct3D11/ShaderWrapper.h" +#include "CEGUI/ShaderParameterBindings.h" #include "CEGUI/RenderEffect.h" #include "CEGUI/Vertex.h" #include "CEGUI/Exceptions.h" +#include "glm/glm.hpp" +#include "glm/gtc/quaternion.hpp" +#include "glm/gtc/type_ptr.hpp" + // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// -Direct3D11GeometryBuffer::Direct3D11GeometryBuffer(Direct3D11Renderer& owner) : - d_owner(owner), - d_device(d_owner.getDirect3DDevice()), - d_activeTexture(0), - d_vertexBuffer(0), - d_bufferSize(0), - d_bufferSynched(false), - d_clipRect(0, 0, 0, 0), - d_clippingActive(true), - d_translation(0, 0, 0), - d_rotation(0, 0, 0), - d_pivot(0, 0, 0), - d_effect(0), - d_matrixValid(false) +Direct3D11GeometryBuffer::Direct3D11GeometryBuffer(Direct3D11Renderer& owner, CEGUI::RefCounted renderMaterial) + : GeometryBuffer(renderMaterial) + , d_owner(owner) + , d_device(d_owner.getDirect3DDevice()) + , d_deviceContext(d_owner.getDirect3DDeviceContext()) + , d_bufferSize(0) + , d_clipRect(0, 0, 0, 0) + , d_inputLayout(0) + , d_vertexBuffer(0) { } @@ -54,32 +56,39 @@ Direct3D11GeometryBuffer::Direct3D11GeometryBuffer(Direct3D11Renderer& owner) : Direct3D11GeometryBuffer::~Direct3D11GeometryBuffer() { cleanupVertexBuffer(); + + if (d_inputLayout) + d_inputLayout->Release(); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::draw() const { - // setup clip region - D3D11_RECT clip; - clip.left = static_cast(d_clipRect.left()); - clip.top = static_cast(d_clipRect.top()); - clip.right = static_cast(d_clipRect.right()); - clip.bottom = static_cast(d_clipRect.bottom()); - d_device.d_context->RSSetScissorRects(1, &clip); + if(d_vertexData.empty()) + return; - if (!d_bufferSynched) - syncHardwareBuffer(); + // setup clip region + if(d_clippingActive) + setScissorRects(); - // apply the transformations we need to use. - if (!d_matrixValid) - updateMatrix(); + // Update the model view projection matrix + updateMatrix(); + + CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings(); - d_owner.setWorldMatrix(d_matrix); + // Set the uniform variables for this GeometryBuffer in the Shader + shaderParameterBindings->setParameter("modelViewProjMatrix", d_matrix); + shaderParameterBindings->setParameter("alphaPercentage", d_alpha); // set our buffer as the vertex source. - const UINT stride = sizeof(D3DVertex); + const UINT stride = getVertexAttributeElementCount() * sizeof(float); const UINT offset = 0; - d_device.d_context->IASetVertexBuffers(0, 1, &d_vertexBuffer, &stride, &offset); + d_deviceContext->IASetVertexBuffers(0, 1, &d_vertexBuffer, &stride, &offset); + //Update the input layout + d_deviceContext->IASetInputLayout(d_inputLayout); + + d_owner.bindBlendMode(d_blendMode); + d_owner.bindRasterizerState(d_clippingActive); const int pass_count = d_effect ? d_effect->getPassCount() : 1; for (int pass = 0; pass < pass_count; ++pass) @@ -88,45 +97,18 @@ void Direct3D11GeometryBuffer::draw() const if (d_effect) d_effect->performPreRenderFunctions(pass); - // draw the batches - size_t pos = 0; - BatchList::const_iterator i = d_batches.begin(); - for ( ; i != d_batches.end(); ++i) - { - // Set Texture - d_owner.setCurrentTextureShaderResource( - const_cast(i->texture)); - // Draw this batch - d_owner.bindTechniquePass(d_blendMode, i->clip); - d_device.d_context->Draw(i->vertexCount, pos); - pos += i->vertexCount; - } + //Prepare for the rendering process according to the used render material + d_renderMaterial->prepareForRendering(); + + // draw the geometry + drawDependingOnFillRule(); } // clean up RenderEffect if (d_effect) d_effect->performPostRenderFunctions(); -} - -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::setTranslation(const Vector3f& v) -{ - d_translation = v; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::setRotation(const Quaternion& r) -{ - d_rotation = r; - d_matrixValid = false; -} -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::setPivot(const Vector3f& p) -{ - d_pivot = p; - d_matrixValid = false; + updateRenderTargetData(d_owner.getActiveRenderTarget()); } //----------------------------------------------------------------------------// @@ -138,163 +120,76 @@ void Direct3D11GeometryBuffer::setClippingRegion(const Rectf& region) d_clipRect.right(ceguimax(0.0f, region.right())); } -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::appendVertex(const Vertex& vertex) -{ - appendGeometry(&vertex, 1); -} - -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::appendGeometry(const Vertex* const vbuff, - uint vertex_count) -{ - const ID3D11ShaderResourceView* srv = - d_activeTexture ? d_activeTexture->getDirect3DShaderResourceView() : 0; - - // create a new batch if there are no batches yet, or if the active texture - // differs from that used by the current batch. - if (d_batches.empty() || - srv != d_batches.back().texture || - d_clippingActive != d_batches.back().clip) - { - BatchInfo batch = {srv, 0, d_clippingActive}; - d_batches.push_back(batch); - } - - // update size of current batch - d_batches.back().vertexCount += vertex_count; - - // buffer these vertices - D3DVertex vd; - const Vertex* vs = vbuff; - for (uint i = 0; i < vertex_count; ++i, ++vs) - { - // copy vertex info the buffer, converting from CEGUI::Vertex to - // something directly usable by D3D as needed. - vd.x = vs->position.d_x; - vd.y = vs->position.d_y; - vd.z = vs->position.d_z; - vd.diffuse = vs->colour_val.getARGB(); - vd.tu = vs->tex_coords.d_x; - vd.tv = vs->tex_coords.d_y; - d_vertices.push_back(vd); - } - - d_bufferSynched = false; -} - -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::setActiveTexture(Texture* texture) -{ - d_activeTexture = static_cast(texture); -} - -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::reset() -{ - d_batches.clear(); - d_vertices.clear(); - d_activeTexture = 0; -} - -//----------------------------------------------------------------------------// -Texture* Direct3D11GeometryBuffer::getActiveTexture() const -{ - return d_activeTexture; -} - -//----------------------------------------------------------------------------// -uint Direct3D11GeometryBuffer::getVertexCount() const -{ - return d_vertices.size(); -} //----------------------------------------------------------------------------// -uint Direct3D11GeometryBuffer::getBatchCount() const +void Direct3D11GeometryBuffer::appendGeometry(const float* vertex_data, std::size_t array_size) { - return d_batches.size(); -} + GeometryBuffer::appendGeometry(vertex_data, array_size); -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::setRenderEffect(RenderEffect* effect) -{ - d_effect = effect; -} - -//----------------------------------------------------------------------------// -RenderEffect* Direct3D11GeometryBuffer::getRenderEffect() -{ - return d_effect; + updateVertexBuffer(); } //----------------------------------------------------------------------------// void Direct3D11GeometryBuffer::updateMatrix() const { - const D3DXVECTOR3 p(d_pivot.d_x, d_pivot.d_y, d_pivot.d_z); - const D3DXVECTOR3 t(d_translation.d_x, - d_translation.d_y, - d_translation.d_z); - - D3DXQUATERNION r; - r.x = d_rotation.d_x; - r.y = d_rotation.d_y; - r.z = d_rotation.d_z; - r.w = d_rotation.d_w; - - D3DXMatrixTransformation(&d_matrix, 0, 0, 0, &p, &r, &t); + if ( !d_matrixValid || !isRenderTargetDataValid(d_owner.getActiveRenderTarget()) ) + { + // Apply the view projection matrix to the model matrix and save the result as cached matrix + d_matrix = d_owner.getViewProjectionMatrix() * getModelMatrix(); - d_matrixValid = true; + d_matrixValid = true; + } } //----------------------------------------------------------------------------// -const D3DXMATRIX* Direct3D11GeometryBuffer::getMatrix() const +void Direct3D11GeometryBuffer::updateVertexBuffer() const { - if (!d_matrixValid) - updateMatrix(); + bool needNewBuffer = false; + size_t vertexCount = d_vertexData.size(); + UINT dataSize = vertexCount * sizeof(float); - return &d_matrix; -} + if(d_bufferSize < dataSize) + { + needNewBuffer = true; + d_bufferSize = dataSize; + } + + const float* vertexData; + if(d_vertexData.empty()) + vertexData = 0; + else + vertexData = &d_vertexData[0]; -//----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::syncHardwareBuffer() const -{ - const size_t vertex_count = d_vertices.size(); - if (vertex_count > d_bufferSize) + if(needNewBuffer) { cleanupVertexBuffer(); - allocateVertexBuffer(vertex_count); + allocateVertexBuffer(dataSize); } - if (vertex_count > 0) - { - void* buff; - D3D11_MAPPED_SUBRESOURCE SubRes; - if (FAILED(d_device.d_context->Map(d_vertexBuffer,0,D3D11_MAP_WRITE_DISCARD, 0, &SubRes))) - CEGUI_THROW(RendererException("failed to map buffer.")); - buff=SubRes.pData; - - std::memcpy(buff, &d_vertices[0], sizeof(D3DVertex) * vertex_count); - d_device.d_context->Unmap(d_vertexBuffer,0); - } + D3D11_BOX box; + box.left = 0; //We copy everything + box.right = dataSize; //Number of bytes to copy + box.top = 0; + box.bottom = 1; + box.front = 0; + box.back = 1; - d_bufferSynched = true; + d_deviceContext->UpdateSubresource( d_vertexBuffer, 0, &box, vertexData, 0, 0 ); } //----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::allocateVertexBuffer(const size_t count) const +void Direct3D11GeometryBuffer::allocateVertexBuffer(const UINT dataSize) const { D3D11_BUFFER_DESC buffer_desc; - buffer_desc.Usage = D3D11_USAGE_DYNAMIC; - buffer_desc.ByteWidth = count * sizeof(D3DVertex); + buffer_desc.Usage = D3D11_USAGE_DEFAULT; + buffer_desc.ByteWidth = dataSize; buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + buffer_desc.CPUAccessFlags = 0; buffer_desc.MiscFlags = 0; - if (FAILED(d_device.d_device->CreateBuffer(&buffer_desc, 0, &d_vertexBuffer))) + if (FAILED(d_device->CreateBuffer(&buffer_desc, 0, &d_vertexBuffer))) CEGUI_THROW(RendererException("failed to allocate vertex buffer.")); - - d_bufferSize = count; } //----------------------------------------------------------------------------// @@ -309,15 +204,92 @@ void Direct3D11GeometryBuffer::cleanupVertexBuffer() const } //----------------------------------------------------------------------------// -void Direct3D11GeometryBuffer::setClippingActive(const bool active) +void Direct3D11GeometryBuffer::drawDependingOnFillRule() const { - d_clippingActive = active; + //TODO IDENT +/* if(d_polygonFillRule == PFR_NONE) + { + */ + + d_deviceContext->Draw(d_vertexCount, 0); + /* + } + else if(d_polygonFillRule == PFR_EVEN_ODD) +//.... +*/ +} + +//----------------------------------------------------------------------------// +void Direct3D11GeometryBuffer::finaliseVertexAttributes() +{ + // Create the input layout + std::vector vertexLayoutVector; + + //Update the vertex attrib pointers of the vertex array object depending on the saved attributes + int dataOffset = 0; + const size_t attribute_count = d_vertexAttributes.size(); + for (size_t i = 0; i < attribute_count; ++i) + { + switch(d_vertexAttributes.at(i)) + { + case VAT_POSITION0: + { + D3D11_INPUT_ELEMENT_DESC inputEleDescription = {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, dataOffset, D3D11_INPUT_PER_VERTEX_DATA, 0}; + vertexLayoutVector.push_back( inputEleDescription ); + + dataOffset += 12; + } + break; + case VAT_COLOUR0: + { + D3D11_INPUT_ELEMENT_DESC inputEleDescription = {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, dataOffset, D3D11_INPUT_PER_VERTEX_DATA, 0}; + vertexLayoutVector.push_back(inputEleDescription); + + dataOffset += 16; + } + break; + case VAT_TEXCOORD0: + { + D3D11_INPUT_ELEMENT_DESC inputEleDescription = {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, dataOffset, D3D11_INPUT_PER_VERTEX_DATA, 0}; + vertexLayoutVector.push_back(inputEleDescription); + + dataOffset += 8; + } + break; + default: + break; + } + } + + if(vertexLayoutVector.size() == 0) + CEGUI_THROW(RendererException( + "The empty vertex layout is invalid because it is empty.")); + + + const CEGUI::Direct3D11ShaderWrapper* shaderWrapper = static_cast(d_renderMaterial->getShaderWrapper()); + + if (d_inputLayout) + d_inputLayout->Release(); + + if (FAILED(d_device->CreateInputLayout(&vertexLayoutVector[0], vertexLayoutVector.size(), + shaderWrapper->getVertShaderBufferPointer(), + shaderWrapper->getVertShaderBufferSize(), + &d_inputLayout))) + { + CEGUI_THROW(RendererException( + "Failed to create D3D InputLayout.")); + } } //----------------------------------------------------------------------------// -bool Direct3D11GeometryBuffer::isClippingActive() const +void Direct3D11GeometryBuffer::setScissorRects() const { - return d_clippingActive; + D3D11_RECT clip; + clip.left = static_cast(d_clipRect.left()); + clip.top = static_cast(d_clipRect.top()); + clip.right = static_cast(d_clipRect.right()); + clip.bottom = static_cast(d_clipRect.bottom()); + d_deviceContext->RSSetScissorRects(1, &clip); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RendererModules/Direct3D11/RenderTarget.inl b/cegui/src/RendererModules/Direct3D11/RenderTarget.inl index 2b1f0fc49..9b6f8748c 100644 --- a/cegui/src/RendererModules/Direct3D11/RenderTarget.inl +++ b/cegui/src/RendererModules/Direct3D11/RenderTarget.inl @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -25,7 +26,10 @@ ***************************************************************************/ #include "CEGUI/RendererModules/Direct3D11/RenderTarget.h" #include "CEGUI/RendererModules/Direct3D11/GeometryBuffer.h" -#include "CEGUI/RenderQueue.h" + +#include + +#include // Start of CEGUI namespace section namespace CEGUI @@ -34,45 +38,11 @@ namespace CEGUI template Direct3D11RenderTarget::Direct3D11RenderTarget(Direct3D11Renderer& owner) : d_owner(owner), - d_device(d_owner.getDirect3DDevice()), - d_area(0, 0, 0, 0), - d_viewDistance(0), - d_matrixValid(false) + d_device(*d_owner.getDirect3DDevice()), + d_deviceContext(*d_owner.getDirect3DDeviceContext()) { } -//----------------------------------------------------------------------------// -template -void Direct3D11RenderTarget::draw(const GeometryBuffer& buffer) -{ - buffer.draw(); -} - -//----------------------------------------------------------------------------// -template -void Direct3D11RenderTarget::draw(const RenderQueue& queue) -{ - queue.draw(); -} - -//----------------------------------------------------------------------------// -template -void Direct3D11RenderTarget::setArea(const Rectf& area) -{ - d_area = area; - d_matrixValid = false; - - RenderTargetEventArgs args(this); - T::fireEvent(RenderTarget::EventAreaChanged, args); -} - -//----------------------------------------------------------------------------// -template -const Rectf& Direct3D11RenderTarget::getArea() const -{ - return d_area; -} - //----------------------------------------------------------------------------// template void Direct3D11RenderTarget::activate() @@ -82,110 +52,91 @@ void Direct3D11RenderTarget::activate() D3D11_VIEWPORT vp; setupViewport(vp); - d_device.d_context->RSSetViewports(1, &vp); + d_deviceContext.RSSetViewports(1, &vp); - d_owner.setProjectionMatrix(d_matrix); -} + d_owner.setViewProjectionMatrix(RenderTarget::d_matrix); -//----------------------------------------------------------------------------// -template -void Direct3D11RenderTarget::deactivate() -{ + RenderTarget::activate(); } //----------------------------------------------------------------------------// template void Direct3D11RenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const + const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); - + const Direct3D11GeometryBuffer& gb = static_cast(buff); - D3D11_VIEWPORT vp_; - setupViewport(vp_); - - //ToDo - //ms didn't update their math for 11, so use 10 - D3D10_VIEWPORT vp; - vp.Width=static_cast(vp_.Width); - vp.Height=static_cast(vp_.Height); - vp.TopLeftX=static_cast(vp_.TopLeftX); - vp.TopLeftY=static_cast(vp_.TopLeftY); - vp.MinDepth=vp_.MinDepth; - vp.MaxDepth=vp_.MaxDepth; - - D3DXVECTOR3 in_vec; - in_vec.z = 0.0f; - - // project points to create a plane orientated with GeometryBuffer's data - D3DXVECTOR3 p1; - D3DXVECTOR3 p2; - D3DXVECTOR3 p3; - in_vec.x = 0; - in_vec.y = 0; - D3DXVec3Project(&p1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = 1; - in_vec.y = 0; - D3DXVec3Project(&p2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = 0; - in_vec.y = 1; - D3DXVec3Project(&p3, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - // create plane from projected points - D3DXPLANE surface_plane; - D3DXPlaneFromPoints(&surface_plane, &p1, &p2, &p3); - - // unproject ends of ray - in_vec.x = vp.Width * 0.5f; - in_vec.y = vp.Height * 0.5f; - in_vec.z = -d_viewDistance; - D3DXVECTOR3 t1; - D3DXVec3Unproject(&t1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = p_in.d_x; - in_vec.y = p_in.d_y; - in_vec.z = 0.0f; - D3DXVECTOR3 t2; - D3DXVec3Unproject(&t2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - // get intersection of ray and plane - D3DXVECTOR3 intersect; - D3DXPlaneIntersectLine(&intersect, &surface_plane, &t1, &t2); - - p_out.d_x = intersect.x; - p_out.d_y = intersect.y; + const int vp[4] = { + static_cast(d_area.left()), + static_cast(d_area.top()), + static_cast(d_area.getWidth()), + static_cast(d_area.getHeight()) + }; + + double in_x, in_y, in_z; + + glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); + const glm::mat4& projMatrix = RenderTarget::d_matrix; + const glm::mat4& modelMatrix = gb.getModelMatrix(); + + // unproject the ends of the ray + glm::vec3 unprojected1; + glm::vec3 unprojected2; + in_x = vp[2] * 0.5; + in_y = vp[3] * 0.5; + in_z = -d_viewDistance; + unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); + in_x = p_in.x; + in_y = vp[3] - p_in.y; + in_z = 0.0; + unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); + + // project points to orientate them with GeometryBuffer plane + glm::vec3 projected1; + glm::vec3 projected2; + glm::vec3 projected3; + in_x = 0.0; + in_y = 0.0; + projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); + in_x = 1.0; + in_y = 0.0; + projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); + in_x = 0.0; + in_y = 1.0; + projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); + + // calculate vectors for generating the plane + const glm::vec3 pv1 = projected2 - projected1; + const glm::vec3 pv2 = projected3 - projected1; + // given the vectors, calculate the plane normal + const glm::vec3 planeNormal = glm::cross(pv1, pv2); + // calculate plane + const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal); + const double pl_d = - glm::dot(projected1, planeNormalNormalized); + // calculate vector of picking ray + const glm::vec3 rv = unprojected1 - unprojected2; + // calculate intersection of ray and plane + const double pn_dot_r1 = glm::dot(unprojected1, planeNormal); + const double pn_dot_rv = glm::dot(rv, planeNormal); + const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0; + const double is_x = unprojected1.x - rv.x * tmp1; + const double is_y = unprojected1.y - rv.y * tmp1; + + p_out.x = static_cast(is_x); + p_out.y = static_cast(is_y); + + p_out = p_in; // CrazyEddie wanted this } //----------------------------------------------------------------------------// template void Direct3D11RenderTarget::updateMatrix() const { - const float fov = 0.523598776f; - const float w = d_area.getWidth(); - const float h = d_area.getHeight(); - const float aspect = w / h; - const float midx = w * 0.5f; - const float midy = h * 0.5f; - d_viewDistance = midx / (aspect * 0.267949192431123f); - - D3DXVECTOR3 eye(midx, midy, -d_viewDistance); - D3DXVECTOR3 at(midx, midy, 1); - D3DXVECTOR3 up(0, -1, 0); - - D3DXMATRIX tmp; - D3DXMatrixMultiply(&d_matrix, - D3DXMatrixLookAtRH(&d_matrix, &eye, &at, &up), - D3DXMatrixPerspectiveFovRH(&tmp, fov, aspect, - d_viewDistance * 0.5f, - d_viewDistance * 2.0f)); - - d_matrixValid = false; + RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForDirect3D() ); } //----------------------------------------------------------------------------// @@ -200,6 +151,13 @@ void Direct3D11RenderTarget::setupViewport(D3D11_VIEWPORT& vp) const vp.MaxDepth = 1.0f; } +//----------------------------------------------------------------------------// +template +Direct3D11Renderer& Direct3D11RenderTarget::getOwner() +{ + return d_owner; +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D11/Renderer.cpp b/cegui/src/RendererModules/Direct3D11/Renderer.cpp index ec07f783c..632f03973 100644 --- a/cegui/src/RendererModules/Direct3D11/Renderer.cpp +++ b/cegui/src/RendererModules/Direct3D11/Renderer.cpp @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -28,29 +29,74 @@ #include "CEGUI/RendererModules/Direct3D11/TextureTarget.h" #include "CEGUI/RendererModules/Direct3D11/ViewportTarget.h" #include "CEGUI/RendererModules/Direct3D11/Texture.h" +#include "CEGUI/RendererModules/Direct3D11/ShaderWrapper.h" +#include "CEGUI/RendererModules/Direct3D11/Shader.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/Logger.h" -#include - -#include "d3dx11effect.h" +#include "Shaders.inl" -#include "shader.txt" +#include // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// -String Direct3D11Renderer::d_rendererID( -"CEGUI::Direct3D11Renderer - Official Direct3D 11 based 2nd generation renderer" -" module."); +const String Direct3D11Renderer::d_rendererID( +"CEGUI::Direct3D11Renderer - Official Direct3D 11 based 3rd generation renderer module."); + //----------------------------------------------------------------------------// -Direct3D11Renderer& Direct3D11Renderer::bootstrapSystem( - ID3D11Device* device, - ID3D11DeviceContext* context, - const int abi) +Direct3D11Renderer::Direct3D11Renderer(ID3D11Device* device, + ID3D11DeviceContext*deviceContext) + : d_device(device) + , d_deviceContext(deviceContext) + , d_displayDPI(96, 96) + , d_defaultTarget(0) + , d_samplerState(0) + , d_currentBlendState(0) + , d_currentRasterizerState(0) +{ + + if(!device || !deviceContext) + { + std::string msg("In Order To Use Direct3D11 Module, You Must Provide Both Device And Context"); + CEGUI_THROW(RendererException(msg)); + } + + d_displaySize = getViewportSize(); + + d_defaultTarget = new Direct3D11ViewportTarget(*this); + + initialiseSamplerStates(); + initialiseBlendStates(); + initialiseRasterizerStates(); + initialiseDepthStencilState(); + + initialiseShaders(); +} + +//----------------------------------------------------------------------------// +Direct3D11Renderer::~Direct3D11Renderer() +{ + destroyAllTextureTargets(); + destroyAllTextures(); + destroyAllGeometryBuffers(); + + d_blendStateNormal->Release(); + d_blendStatePreMultiplied->Release(); + + delete d_defaultTarget; + + delete d_shaderWrapperTextured; + delete d_shaderWrapperSolid; +} + +//----------------------------------------------------------------------------// +Direct3D11Renderer& Direct3D11Renderer::bootstrapSystem(ID3D11Device* device, + ID3D11DeviceContext* context, + const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); @@ -90,7 +136,7 @@ Direct3D11Renderer& Direct3D11Renderer::create(ID3D11Device* device, { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *new Direct3D11Renderer(device,context); + return *new Direct3D11Renderer(device, context); } //----------------------------------------------------------------------------// @@ -105,35 +151,6 @@ RenderTarget& Direct3D11Renderer::getDefaultRenderTarget() return *d_defaultTarget; } -//----------------------------------------------------------------------------// -GeometryBuffer& Direct3D11Renderer::createGeometryBuffer() -{ - Direct3D11GeometryBuffer* b = new Direct3D11GeometryBuffer(*this); - d_geometryBuffers.push_back(b); - return *b; -} - -//----------------------------------------------------------------------------// -void Direct3D11Renderer::destroyGeometryBuffer(const GeometryBuffer& buffer) -{ - GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), - d_geometryBuffers.end(), - &buffer); - - if (d_geometryBuffers.end() != i) - { - d_geometryBuffers.erase(i); - delete &buffer; - } -} - -//----------------------------------------------------------------------------// -void Direct3D11Renderer::destroyAllGeometryBuffers() -{ - while (!d_geometryBuffers.empty()) - destroyGeometryBuffer(**d_geometryBuffers.begin()); -} - //----------------------------------------------------------------------------// TextureTarget* Direct3D11Renderer::createTextureTarget() { @@ -168,7 +185,7 @@ Texture& Direct3D11Renderer::createTexture(const String& name) { throwIfNameExists(name); - Direct3D11Texture* tex = new Direct3D11Texture(d_device, name); + Direct3D11Texture* tex = new Direct3D11Texture(*d_device, *d_deviceContext, name); d_textures[name] = tex; logTextureCreation(name); @@ -183,7 +200,8 @@ Texture& Direct3D11Renderer::createTexture(const String& name, { throwIfNameExists(name); - Direct3D11Texture* tex = new Direct3D11Texture(d_device, name, filename, + Direct3D11Texture* tex = new Direct3D11Texture(*d_device, *d_deviceContext, + name, filename, resourceGroup); d_textures[name] = tex; @@ -198,7 +216,7 @@ Texture& Direct3D11Renderer::createTexture(const String& name, { throwIfNameExists(name); - Direct3D11Texture* tex = new Direct3D11Texture(d_device, name, size); + Direct3D11Texture* tex = new Direct3D11Texture(*d_device, *d_deviceContext, name, size); d_textures[name] = tex; logTextureCreation(name); @@ -276,8 +294,12 @@ bool Direct3D11Renderer::isTextureDefined(const String& name) const //----------------------------------------------------------------------------// void Direct3D11Renderer::beginRendering() { - d_device.d_context->IASetInputLayout(d_inputLayout); - d_device.d_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + d_currentBlendState = 0; + d_currentRasterizerState = 0; + + d_deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + d_deviceContext->OMSetDepthStencilState(d_depthStencilStateDefault, 0); + d_deviceContext->PSSetSamplers(0, 1, &d_samplerState); } //----------------------------------------------------------------------------// @@ -297,7 +319,6 @@ void Direct3D11Renderer::setDisplaySize(const Sizef& sz) area.setSize(sz); d_defaultTarget->setArea(area); } - } //----------------------------------------------------------------------------// @@ -307,7 +328,7 @@ const Sizef& Direct3D11Renderer::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& Direct3D11Renderer::getDisplayDPI() const +const glm::vec2& Direct3D11Renderer::getDisplayDPI() const { return d_displayDPI; } @@ -315,7 +336,31 @@ const Vector2f& Direct3D11Renderer::getDisplayDPI() const //----------------------------------------------------------------------------// uint Direct3D11Renderer::getMaxTextureSize() const { - return 8192;//DIRECTX11 may support even 16384, but most users will use it as feauture level 10, so keep it for now + //Values taken from http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876%28v=vs.85%29.aspx + D3D_FEATURE_LEVEL featureLevel = d_device->GetFeatureLevel(); + + switch(featureLevel) + { + default: + case D3D_FEATURE_LEVEL_11_0: + return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; + break; + case D3D_FEATURE_LEVEL_10_1: + return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; + break; + case D3D_FEATURE_LEVEL_10_0: + return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; + break; + case D3D_FEATURE_LEVEL_9_3: + return 4096; + break; + case D3D_FEATURE_LEVEL_9_2: + return 2048; + break; + case D3D_FEATURE_LEVEL_9_1: + return 2048; + break; + } } //----------------------------------------------------------------------------// @@ -325,178 +370,280 @@ const String& Direct3D11Renderer::getIdentifierString() const } //----------------------------------------------------------------------------// -Direct3D11Renderer::Direct3D11Renderer(ID3D11Device* device,ID3D11DeviceContext *context) : - - d_displayDPI(96, 96), - d_defaultTarget(0), - d_effect(0), - d_normalClippedTechnique(0), - d_normalUnclippedTechnique(0), - d_premultipliedClippedTechnique(0), - d_premultipliedUnclippedTechnique(0), - d_inputLayout(0), - d_boundTextureVariable(0), - d_worldMatrixVariable(0), - d_projectionMatrixVariable(0) -{ - - if(!device || !context) - { - std::string msg("In Order To Use Direct3D11 Module, You Must Provide Both Device And Context"); - CEGUI_THROW(RendererException(msg)); - } +Sizef Direct3D11Renderer::getViewportSize() +{ + D3D11_VIEWPORT vp; + UINT vp_count = 1; - //ToDo - //For Perfomance Reasons this little struct can be replaced with pointer - d_device.d_device=device; - d_device.d_context=context; + d_deviceContext->RSGetViewports(&vp_count, &vp); - d_displaySize=getViewportSize(); + if (vp_count != 1) + CEGUI_THROW(RendererException( + "Unable to access required view port information from " + "ID3D11Device.")); + else + return Sizef(static_cast(vp.Width), + static_cast(vp.Height)); +} - // create the main effect from the shader source. - ID3D10Blob* errors = 0; +//----------------------------------------------------------------------------// +GeometryBuffer& Direct3D11Renderer::createGeometryBufferTextured(CEGUI::RefCounted renderMaterial) +{ + Direct3D11GeometryBuffer* geom_buffer = new Direct3D11GeometryBuffer(*this, renderMaterial); - DWORD DefaultOptions=NULL;//D3D10_SHADER_PACK_MATRIX_ROW_MAJOR|D3D10_SHADER_PARTIAL_PRECISION|D3D10_SHADER_SKIP_VALIDATION; + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->addVertexAttribute(VAT_TEXCOORD0); + geom_buffer->finaliseVertexAttributes(); - ID3D10Blob* ShaderBlob=NULL;//first we compile shader, then create effect from it + addGeometryBuffer(*geom_buffer); + return *geom_buffer; +} - if (FAILED(D3DX11CompileFromMemory(shaderSource,sizeof(shaderSource), - "shaderSource",NULL,NULL,NULL,"fx_5_0", - DefaultOptions,NULL,NULL,&ShaderBlob,&errors,NULL))) - { - std::string msg(static_cast(errors->GetBufferPointer()), - errors->GetBufferSize()); - errors->Release(); - CEGUI_THROW(RendererException(msg)); - } +//----------------------------------------------------------------------------// +GeometryBuffer& Direct3D11Renderer::createGeometryBufferColoured(CEGUI::RefCounted renderMaterial) +{ + Direct3D11GeometryBuffer* geom_buffer = new Direct3D11GeometryBuffer(*this, renderMaterial); - if (FAILED(D3DX11CreateEffectFromMemory(ShaderBlob->GetBufferPointer(), ShaderBlob->GetBufferSize(),0, - d_device.d_device, &d_effect) )) - { - CEGUI_THROW(RendererException("failed to create effect!")); - } + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->finaliseVertexAttributes(); - if(ShaderBlob) - ShaderBlob->Release(); - - // extract the rendering techniques - d_normalClippedTechnique = - d_effect->GetTechniqueByName("BM_NORMAL_Clipped_Rendering"); - d_normalUnclippedTechnique = - d_effect->GetTechniqueByName("BM_NORMAL_Unclipped_Rendering"); - d_premultipliedClippedTechnique = - d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Clipped_Rendering"); - d_premultipliedClippedTechnique = - d_effect->GetTechniqueByName("BM_RTT_PREMULTIPLIED_Unclipped_Rendering"); - - // Get the variables from the shader we need to be able to access - d_boundTextureVariable = - d_effect->GetVariableByName("BoundTexture")->AsShaderResource(); - d_worldMatrixVariable = - d_effect->GetVariableByName("WorldMatrix")->AsMatrix(); - d_projectionMatrixVariable = - d_effect->GetVariableByName("ProjectionMatrix")->AsMatrix(); - - // Create the input layout - const D3D11_INPUT_ELEMENT_DESC vertex_layout[] = - { - { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, - }; + addGeometryBuffer(*geom_buffer); + return *geom_buffer; +} - const UINT element_count = sizeof(vertex_layout) / sizeof(vertex_layout[0]); +//----------------------------------------------------------------------------// +RefCounted Direct3D11Renderer::createRenderMaterial(const DefaultShaderType shaderType) const +{ + if(shaderType == DS_TEXTURED) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperTextured)); - D3DX11_PASS_DESC pass_desc; - if (FAILED(d_normalClippedTechnique->GetPassByIndex(0)->GetDesc(&pass_desc))) - CEGUI_THROW(RendererException( - "failed to obtain technique description for pass 0.")); + return render_material; + } + else if(shaderType == DS_SOLID) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperSolid)); - if (FAILED(d_device.d_device->CreateInputLayout(vertex_layout, element_count, - pass_desc.pIAInputSignature, - pass_desc.IAInputSignatureSize, - &d_inputLayout))) + return render_material; + } + else { - CEGUI_THROW(RendererException( - "failed to create D3D 11 input layout.")); + CEGUI_THROW(RendererException("A default shader of this type does not exist.")); + + return RefCounted(); } +} - d_defaultTarget = new Direct3D11ViewportTarget(*this); +//----------------------------------------------------------------------------// +void Direct3D11Renderer::initialiseStandardTexturedShaderWrapper() +{ + Direct3D11Shader* shader_standard_textured = new Direct3D11Shader(*this, VertexShaderTextured, PixelShaderTextured); + d_shaderWrapperTextured = new Direct3D11ShaderWrapper(*shader_standard_textured, this); + + d_shaderWrapperTextured->addUniformVariable("texture0", ST_PIXEL, SPT_TEXTURE); + + d_shaderWrapperTextured->addUniformVariable("modelViewProjMatrix", ST_VERTEX, SPT_MATRIX_4X4); + d_shaderWrapperTextured->addUniformVariable("alphaPercentage", ST_PIXEL, + SPT_FLOAT); } //----------------------------------------------------------------------------// -Direct3D11Renderer::~Direct3D11Renderer() +void Direct3D11Renderer::initialiseStandardColouredShaderWrapper() { - destroyAllTextureTargets(); - destroyAllTextures(); - destroyAllGeometryBuffers(); + Direct3D11Shader* shader_standard_solid = new Direct3D11Shader(*this, VertexShaderColoured, PixelShaderColoured); + d_shaderWrapperSolid = new Direct3D11ShaderWrapper(*shader_standard_solid, this); - delete d_defaultTarget; + d_shaderWrapperSolid->addUniformVariable("modelViewProjMatrix", ST_VERTEX, SPT_MATRIX_4X4); + d_shaderWrapperSolid->addUniformVariable("alphaPercentage", ST_PIXEL, + SPT_FLOAT); +} - if (d_effect) - d_effect->Release(); +//----------------------------------------------------------------------------// +void Direct3D11Renderer::initialiseShaders() +{ + initialiseStandardColouredShaderWrapper(); + initialiseStandardTexturedShaderWrapper(); +} - if (d_inputLayout) - d_inputLayout->Release(); +//----------------------------------------------------------------------------// +ID3D11DeviceContext* Direct3D11Renderer::getDirect3DDeviceContext() +{ + return d_deviceContext; +} +//----------------------------------------------------------------------------// +ID3D11Device* Direct3D11Renderer::getDirect3DDevice() +{ + return d_device; } //----------------------------------------------------------------------------// -Sizef Direct3D11Renderer::getViewportSize() +void Direct3D11Renderer::initialiseBlendStates() { - D3D11_VIEWPORT vp; - UINT vp_count = 1; + HRESULT result; - d_device.d_context->RSGetViewports(&vp_count, &vp); + D3D11_BLEND_DESC blendDesc; + ZeroMemory(&blendDesc, sizeof(blendDesc)); - if (vp_count != 1) - CEGUI_THROW(RendererException( - "Unable to access required view port information from " - "ID3D11Device.")); - else - return Sizef(static_cast(vp.Width), - static_cast(vp.Height)); + D3D11_RENDER_TARGET_BLEND_DESC rtbd; + ZeroMemory(&rtbd, sizeof(rtbd)); + + blendDesc.AlphaToCoverageEnable = FALSE; + blendDesc.IndependentBlendEnable = FALSE; + + rtbd.BlendEnable = TRUE; + rtbd.SrcBlend = D3D11_BLEND_SRC_ALPHA; + rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + rtbd.BlendOp = D3D11_BLEND_OP_ADD; + rtbd.SrcBlendAlpha = D3D11_BLEND_INV_DEST_ALPHA; + rtbd.DestBlendAlpha = D3D11_BLEND_ONE; + rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD; + rtbd.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; + blendDesc.RenderTarget[0] = rtbd; + + result = d_device->CreateBlendState(&blendDesc, &d_blendStateNormal); + if(FAILED(result)) + CEGUI_THROW(RendererException("Creation of BlendState failed")); + + ZeroMemory(&blendDesc, sizeof(blendDesc)); + ZeroMemory(&rtbd, sizeof(rtbd)); + + blendDesc.AlphaToCoverageEnable = FALSE; + blendDesc.IndependentBlendEnable = FALSE; + + rtbd.BlendEnable = TRUE; + rtbd.SrcBlend = D3D11_BLEND_ONE; + rtbd.DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + rtbd.BlendOp = D3D11_BLEND_OP_ADD; + rtbd.SrcBlendAlpha = D3D11_BLEND_ONE; + rtbd.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; + rtbd.BlendOpAlpha = D3D11_BLEND_OP_ADD; + rtbd.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; + blendDesc.RenderTarget[0] = rtbd; + + result = d_device->CreateBlendState(&blendDesc, &d_blendStatePreMultiplied); + if(FAILED(result)) + CEGUI_THROW(RendererException("Creation of BlendState failed")); } //----------------------------------------------------------------------------// -IDevice11& Direct3D11Renderer::getDirect3DDevice() +void Direct3D11Renderer::bindBlendMode(BlendMode d_blendMode) { - return d_device; + const FLOAT blendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + + if (d_blendMode == BM_NORMAL) + { + if (d_currentBlendState != d_blendStateNormal) + { + d_deviceContext->OMSetBlendState(d_blendStateNormal, blendFactor, 0xFFFFFFFF); + d_currentBlendState = d_blendStateNormal; + } + } + + if (d_blendMode == BM_RTT_PREMULTIPLIED) + { + if (d_currentBlendState != d_blendStatePreMultiplied) + { + d_deviceContext->OMSetBlendState(d_blendStatePreMultiplied, blendFactor, 0xFFFFFFFF); + d_currentBlendState = d_blendStatePreMultiplied; + } + } } //----------------------------------------------------------------------------// -void Direct3D11Renderer::bindTechniquePass(const BlendMode mode, - const bool clipped) +void Direct3D11Renderer::bindRasterizerState(bool scissorEnabled) { - if (mode == BM_RTT_PREMULTIPLIED) - if (clipped) - d_premultipliedClippedTechnique->GetPassByIndex(0)->Apply(0, d_device.d_context); - else - d_premultipliedUnclippedTechnique->GetPassByIndex(0)->Apply(0, d_device.d_context); - else if (clipped) - d_normalClippedTechnique->GetPassByIndex(0)->Apply(0, d_device.d_context); + if (scissorEnabled) + { + if (d_currentRasterizerState != d_rasterizerStateScissorEnabled) + { + d_deviceContext->RSSetState(d_rasterizerStateScissorEnabled); + d_currentRasterizerState = d_rasterizerStateScissorEnabled; + } + } else - d_normalUnclippedTechnique->GetPassByIndex(0)->Apply(0, d_device.d_context); + { + if (d_currentRasterizerState != d_rasterizerStateScissorDisabled) + { + d_deviceContext->RSSetState(d_rasterizerStateScissorDisabled); + d_currentRasterizerState = d_rasterizerStateScissorDisabled; + } + } } //----------------------------------------------------------------------------// -void Direct3D11Renderer::setCurrentTextureShaderResource( - ID3D11ShaderResourceView* srv) +void Direct3D11Renderer::initialiseRasterizerStates() { - d_boundTextureVariable->SetResource(srv); + D3D11_RASTERIZER_DESC cmdesc; + ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC)); + + cmdesc.FillMode = D3D11_FILL_SOLID; + cmdesc.CullMode = D3D11_CULL_NONE; + cmdesc.DepthClipEnable = TRUE; + cmdesc.ScissorEnable = TRUE; + + HRESULT result = d_device->CreateRasterizerState(&cmdesc, &d_rasterizerStateScissorEnabled); + + ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC)); + + cmdesc.FillMode = D3D11_FILL_SOLID; + cmdesc.CullMode = D3D11_CULL_NONE; + cmdesc.DepthClipEnable = TRUE; + cmdesc.ScissorEnable = FALSE; + + result = d_device->CreateRasterizerState(&cmdesc, &d_rasterizerStateScissorDisabled); + + ZeroMemory(&cmdesc, sizeof(D3D11_RASTERIZER_DESC)); } //----------------------------------------------------------------------------// -void Direct3D11Renderer::setProjectionMatrix(D3DXMATRIX& matrix) +void Direct3D11Renderer::initialiseDepthStencilState() { - d_projectionMatrixVariable->SetMatrix(reinterpret_cast(&matrix)); + D3D11_DEPTH_STENCIL_DESC depthStencilDesc; + ZeroMemory(&depthStencilDesc, sizeof(D3D11_DEPTH_STENCIL_DESC)); + + depthStencilDesc.DepthEnable = FALSE; + depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO; + depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; + depthStencilDesc.StencilEnable = FALSE; + depthStencilDesc.StencilReadMask = 0x00; + depthStencilDesc.StencilWriteMask = 0x00; + depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; + depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; + + HRESULT result = d_device->CreateDepthStencilState(&depthStencilDesc, &d_depthStencilStateDefault); + if(FAILED(result)) + CEGUI_THROW(RendererException("SamplerDescription creation failed")); } + //----------------------------------------------------------------------------// -void Direct3D11Renderer::setWorldMatrix(D3DXMATRIX& matrix) +void CEGUI::Direct3D11Renderer::initialiseSamplerStates() { - d_worldMatrixVariable->SetMatrix(reinterpret_cast(&matrix)); + D3D11_SAMPLER_DESC samplerDescription; + ZeroMemory( &samplerDescription, sizeof(samplerDescription) ); + samplerDescription.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + samplerDescription.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; + samplerDescription.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; + samplerDescription.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + samplerDescription.ComparisonFunc = D3D11_COMPARISON_NEVER; + samplerDescription.MinLOD = 0; + samplerDescription.MaxLOD = D3D11_FLOAT32_MAX; + + HRESULT result = d_device->CreateSamplerState( &samplerDescription, &d_samplerState ); + if(FAILED(result)) + CEGUI_THROW(RendererException("SamplerDescription creation failed")); } + //----------------------------------------------------------------------------// } // End of CEGUI namespace section + diff --git a/cegui/src/RendererModules/Direct3D11/Shader.cpp b/cegui/src/RendererModules/Direct3D11/Shader.cpp new file mode 100644 index 000000000..558d9b974 --- /dev/null +++ b/cegui/src/RendererModules/Direct3D11/Shader.cpp @@ -0,0 +1,316 @@ +/*********************************************************************** + created: Sun, 6th April 2014 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "CEGUI/RendererModules/Direct3D11/Shader.h" +#include "CEGUI/Logger.h" +#include "CEGUI/Exceptions.h" + +#include + +#include +#include + +namespace CEGUI +{ +//----------------------------------------------------------------------------// +static const size_t LOG_BUFFER_SIZE = 8096; + +//----------------------------------------------------------------------------// +Direct3D11Shader::Direct3D11Shader(Direct3D11Renderer& owner, + const std::string& vertexShaderSource, + const std::string& pixelShaderSource) + : d_device(owner.getDirect3DDevice()) + , d_deviceContext(owner.getDirect3DDeviceContext()) + , d_vertShader(0) + , d_pixelShader(0) + , d_vertexShaderBuffer(0) + , d_pixelShaderBuffer(0) + , d_vertexShaderReflection(0) + , d_pixelShaderReflection(0) +{ + createVertexShader(vertexShaderSource); + createPixelShader(pixelShaderSource); +} + +//----------------------------------------------------------------------------// +Direct3D11Shader::~Direct3D11Shader() +{ + if(d_vertexShaderBuffer) + d_vertexShaderBuffer->Release(); + + if(d_vertexShaderReflection) + d_vertexShaderReflection->Release(); + + if(d_pixelShaderBuffer) + d_pixelShaderBuffer->Release(); + + if(d_pixelShaderReflection) + d_pixelShaderReflection->Release(); +} + +//----------------------------------------------------------------------------// +void Direct3D11Shader::bind() const +{ + //Set Vertex and Pixel Shaders + d_deviceContext->VSSetShader(d_vertShader, 0, 0); + d_deviceContext->PSSetShader(d_pixelShader, 0, 0); + d_deviceContext->CSSetShader(0, 0, 0); + d_deviceContext->DSSetShader(0, 0, 0); + d_deviceContext->GSSetShader(0, 0, 0); +} + +//----------------------------------------------------------------------------// +void Direct3D11Shader::createVertexShader(const std::string& vertexShaderSource) +{ + HRESULT result; + ID3D10Blob* errorMessage; + + UINT flags1 = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR; + +#if defined(DEBUG) || defined (_DEBUG) + flags1 |= D3DCOMPILE_DEBUG; +#else + flags1 |= 0; +#endif + + result = D3DCompile(static_cast(vertexShaderSource.c_str()), vertexShaderSource.size(), "CEGUI Vertex Shader", + 0, 0, "main", getVertexShaderVersion().c_str(), flags1, 0, &d_vertexShaderBuffer, &errorMessage); + if(FAILED(result)) + { + std::string msg(static_cast(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()); + + errorMessage->Release(); + CEGUI_THROW(RendererException(msg)); + } + + result = d_device->CreateVertexShader(d_vertexShaderBuffer->GetBufferPointer(), d_vertexShaderBuffer->GetBufferSize(), 0, &d_vertShader); + if(FAILED(result)) + { + std::string msg("Direct3D11Shader: Failed to create the vertex shader"); + CEGUI_THROW(RendererException(msg)); + } + + result = D3DReflect(d_vertexShaderBuffer->GetBufferPointer(), d_vertexShaderBuffer->GetBufferSize(), IID_ID3D11ShaderReflection, reinterpret_cast(&d_vertexShaderReflection)); + if(FAILED(result)) + { + std::string msg("D3DReflect: Shader reflection failed"); + CEGUI_THROW(RendererException(msg)); + } +} + +//----------------------------------------------------------------------------// +void Direct3D11Shader::createPixelShader(const std::string& pixelShaderSource) +{ + HRESULT result; + ID3D10Blob* errorMessage; + + UINT flags1 = D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR; + +#if defined(DEBUG) || defined (_DEBUG) + flags1 |= D3DCOMPILE_DEBUG; +#else + flags1 |= 0; +#endif + + result = D3DCompile(static_cast(pixelShaderSource.c_str()), pixelShaderSource.size(), "D3D11 Pixel Shader", + 0, 0, "main", getPixelShaderVersion().c_str(), flags1, 0, &d_pixelShaderBuffer, &errorMessage); + if(FAILED(result)) + { + std::string msg(static_cast(errorMessage->GetBufferPointer()), errorMessage->GetBufferSize()); + + errorMessage->Release(); + CEGUI_THROW(RendererException(msg)); + } + + + result = d_device->CreatePixelShader(d_pixelShaderBuffer->GetBufferPointer(), d_pixelShaderBuffer->GetBufferSize(), 0, &d_pixelShader); + if(FAILED(result)) + { + std::string msg("Direct3D11Shader: Failed to create the pixel shader"); + CEGUI_THROW(RendererException(msg)); + } + + result = D3DReflect(d_pixelShaderBuffer->GetBufferPointer(), d_pixelShaderBuffer->GetBufferSize(), IID_ID3D11ShaderReflection, reinterpret_cast(&d_pixelShaderReflection)); + if(FAILED(result)) + { + std::string msg("D3DReflect: Shader reflection failed"); + CEGUI_THROW(RendererException(msg)); + } +} + + +//----------------------------------------------------------------------------// +std::string Direct3D11Shader::getVertexShaderVersion() const +{ + //Values taken from http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876%28v=vs.85%29.aspx + D3D_FEATURE_LEVEL featureLevel = d_device->GetFeatureLevel(); + + switch(featureLevel) + { + default: + case D3D_FEATURE_LEVEL_11_0: + return "vs_5_0"; + break; + case D3D_FEATURE_LEVEL_10_1: + return "vs_4_0"; + break; + case D3D_FEATURE_LEVEL_10_0: + return "vs_4_0"; + break; + case D3D_FEATURE_LEVEL_9_3: + return "vs_4_0_level_9_3"; + break; + case D3D_FEATURE_LEVEL_9_2: + return "vs_4_0_level_9_1"; + break; + case D3D_FEATURE_LEVEL_9_1: + return "vs_4_0_level_9_1"; + break; + } +} + +//----------------------------------------------------------------------------// +std::string Direct3D11Shader::getPixelShaderVersion() const +{ + //Values taken from http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876%28v=vs.85%29.aspx + D3D_FEATURE_LEVEL featureLevel = d_device->GetFeatureLevel(); + + switch(featureLevel) + { + default: + case D3D_FEATURE_LEVEL_11_0: + return "ps_5_0"; + break; + case D3D_FEATURE_LEVEL_10_1: + return "ps_4_0"; + break; + case D3D_FEATURE_LEVEL_10_0: + return "ps_4_0"; + break; + case D3D_FEATURE_LEVEL_9_3: + return "ps_4_0_level_9_3"; + break; + case D3D_FEATURE_LEVEL_9_2: + return "ps_4_0_level_9_1"; + break; + case D3D_FEATURE_LEVEL_9_1: + return "ps_4_0_level_9_1"; + break; + } +} + +//----------------------------------------------------------------------------// +D3D11_SHADER_INPUT_BIND_DESC Direct3D11Shader::getTextureBindingDesc(const std::string& variableName, ShaderType shaderType) +{ + HRESULT result; + + ID3D11ShaderReflection* shaderReflection = 0; + if(shaderType == ST_VERTEX) + shaderReflection = d_vertexShaderReflection; + else if(shaderType == ST_PIXEL) + shaderReflection = d_pixelShaderReflection; + + D3D11_SHADER_DESC shaderDescription; + result = shaderReflection->GetDesc(&shaderDescription); + if(FAILED(result)) + { + std::string errorMessage("ID3D11ShaderReflection::GetDesc() call failed. Could not retrieve shader description."); + CEGUI_THROW(RendererException(errorMessage)); + } + + UINT resourceCount = shaderDescription.BoundResources; + D3D11_SHADER_INPUT_BIND_DESC shaderInputBindDesc; + + for(UINT i = 0; i < resourceCount; ++i) + { + result = shaderReflection->GetResourceBindingDesc(i, &shaderInputBindDesc); + if(SUCCEEDED(result)) + { + int comparisonResult = variableName.compare(shaderInputBindDesc.Name); + if(comparisonResult == 0) + return shaderInputBindDesc; + } + } + + std::string errorMessage = std::string("Variable was not found in shader for variable of name \"") + variableName + "\""; + CEGUI_THROW(RendererException(errorMessage)); + + return shaderInputBindDesc; +} + + +//----------------------------------------------------------------------------// +D3D11_SHADER_VARIABLE_DESC Direct3D11Shader::getUniformVariableDescription(const std::string& variableName, ShaderType shaderType) +{ + HRESULT result; + + ID3D11ShaderReflectionConstantBuffer* shaderReflectConstBuffer = getShaderReflectionConstBuffer(shaderType); + + ID3D11ShaderReflectionVariable* shaderReflectVariable = shaderReflectConstBuffer->GetVariableByName(variableName.c_str()); + + D3D11_SHADER_VARIABLE_DESC varDesc; + result = shaderReflectVariable->GetDesc(&varDesc); + if(FAILED(result)) + CEGUI_THROW(RendererException("Could not retrieve variable \"" + variableName + "\" from the buffer \"$Globals\"")); + + return varDesc; +} + +//----------------------------------------------------------------------------// +ID3D11ShaderReflectionConstantBuffer* Direct3D11Shader::getShaderReflectionConstBuffer(ShaderType shaderType) +{ + HRESULT result; + + ID3D11ShaderReflection* shaderReflection = 0; + if(shaderType == ST_VERTEX) + shaderReflection = d_vertexShaderReflection; + else if(shaderType == ST_PIXEL) + shaderReflection = d_pixelShaderReflection; + + D3D11_SHADER_DESC shaderDescription; + result = shaderReflection->GetDesc(&shaderDescription); + if(FAILED(result)) + { + std::string errorMessage("ID3D11ShaderReflection::GetDesc() call failed. Could not retrieve shader description."); + CEGUI_THROW(RendererException(errorMessage)); + } + + ID3D11ShaderReflectionConstantBuffer* shaderReflectConstBufferGlobals = shaderReflection->GetConstantBufferByName("$Globals"); + if(shaderReflectConstBufferGlobals == 0) + CEGUI_THROW(RendererException("Could not retrieve constant buffer \"$Globals\" from the shader")); + + return shaderReflectConstBufferGlobals; +} + +//----------------------------------------------------------------------------// +ID3D10Blob* Direct3D11Shader::getVertexShaderBuffer() const +{ + return d_vertexShaderBuffer; +} + +//----------------------------------------------------------------------------// +} \ No newline at end of file diff --git a/cegui/src/RendererModules/Direct3D11/ShaderWrapper.cpp b/cegui/src/RendererModules/Direct3D11/ShaderWrapper.cpp new file mode 100644 index 000000000..72534bc6e --- /dev/null +++ b/cegui/src/RendererModules/Direct3D11/ShaderWrapper.cpp @@ -0,0 +1,281 @@ +/*********************************************************************** + created: Sun, 6th April 2014 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "CEGUI/RendererModules/Direct3D11/ShaderWrapper.h" +#include "CEGUI/RendererModules/Direct3D11/Texture.h" +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/Exceptions.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +Direct3D11ShaderWrapper::Direct3D11ShaderWrapper(Direct3D11Shader& shader, + Direct3D11Renderer* renderer) + : d_shader(shader) + , d_device(renderer->getDirect3DDevice()) + , d_deviceContext(renderer->getDirect3DDeviceContext()) + , d_perObjectUniformVarBufferVert(0) + , d_perObjectUniformVarBufferPixel(0) +{ + createPerObjectBuffer(ST_VERTEX); + createPerObjectBuffer(ST_PIXEL); +} + +//----------------------------------------------------------------------------// +Direct3D11ShaderWrapper::~Direct3D11ShaderWrapper() +{ + if(d_perObjectUniformVarBufferVert != 0) + d_perObjectUniformVarBufferVert->Release(); + + if(d_perObjectUniformVarBufferPixel != 0) + d_perObjectUniformVarBufferPixel->Release(); +} + +//----------------------------------------------------------------------------// +void Direct3D11ShaderWrapper::addUniformVariable(const std::string& variableName, ShaderType shaderType, ShaderParamType paramType) +{ + UINT variableBindingLoc = -1; + UINT size = -1; + + if(paramType == SPT_TEXTURE) + { + D3D11_SHADER_INPUT_BIND_DESC variableDesc = d_shader.getTextureBindingDesc(variableName, shaderType); + variableBindingLoc = variableDesc.BindPoint; + size = variableDesc.BindCount; + } + else + { + D3D11_SHADER_VARIABLE_DESC variableDesc = d_shader.getUniformVariableDescription(variableName, shaderType); + variableBindingLoc = variableDesc.StartOffset; + size = variableDesc.Size; + } + + Direct3D11ParamDesc parameter = {variableBindingLoc, size, shaderType, paramType}; + + d_uniformVariables.insert(std::pair(variableName, parameter)); +} + +//----------------------------------------------------------------------------// +void Direct3D11ShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) +{ + d_shader.bind(); + + // The pointers to the mapped resource data + unsigned char* resourceDataVS = 0; + unsigned char* resourceDataPS = 0; + prepareUniformVariableMapping(resourceDataVS, resourceDataPS); + + const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings->getShaderParameterBindings(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); + + while(iter != end) + { + const CEGUI::ShaderParameter* parameter = iter->second; + const ShaderParamType parameterType = parameter->getType(); + + std::map::iterator foundIter = d_uniformVariables.find(iter->first); + if(foundIter == d_uniformVariables.end()) + { + std::string errorMessage = std::string("Variable was not found in the set of uniform variables of the shader. Variable name was: \"") + iter->first + "\""; + CEGUI_THROW(RendererException(errorMessage)); + } + + const Direct3D11ParamDesc& parameterDescription = foundIter->second; + + if(parameterType != parameterDescription.d_shaderParamType) + { + std::string errorMessage = std::string("Supplied parameter type doesn't match the shader parameter type for variable \"") + iter->first + "\""; + CEGUI_THROW(RendererException(errorMessage)); + } + + std::map::iterator found_iterator = d_shaderParameterStates.find(iter->first); + if(found_iterator != d_shaderParameterStates.end()) + { + ShaderParameter* last_shader_parameter = found_iterator->second; + + if(last_shader_parameter->getType() != parameterDescription.d_shaderParamType) + { + std::string errorMessage = std::string("The last shader parameter type doesn't match the shader parameter type for variable \"") + iter->first + "\""; + CEGUI_THROW(RendererException(errorMessage)); + } + + if(parameter->equal(last_shader_parameter)) + { + ++iter; + continue; + } + else + last_shader_parameter->takeOverParameterValue(parameter); + } + + // Get the data pointer pointing to the memory position of our current uniform variable + unsigned char* paramDataPointer = 0; + if (parameterDescription.d_shaderType == ST_VERTEX) + paramDataPointer = resourceDataVS + parameterDescription.d_boundLocation; + else if (parameterDescription.d_shaderType == ST_PIXEL) + paramDataPointer = resourceDataPS + parameterDescription.d_boundLocation; + + switch(parameterType) + { + case SPT_INT: + { + const CEGUI::ShaderParameterInt* parameterInt = static_cast(parameter); + + //Copy the data + memcpy(paramDataPointer, &(parameterInt->d_parameterValue), parameterDescription.d_boundSize); + } + break; + case SPT_FLOAT: + { + const CEGUI::ShaderParameterFloat* parameterFloat = static_cast(parameter); + + //Copy the data + memcpy(paramDataPointer, &(parameterFloat->d_parameterValue), parameterDescription.d_boundSize); + } + break; + case SPT_MATRIX_4X4: + { + const CEGUI::ShaderParameterMatrix* parameterMatrix = static_cast(parameter); + + //Copy the data + memcpy(paramDataPointer, glm::value_ptr(parameterMatrix->d_parameterValue), parameterDescription.d_boundSize); + } + break; + case SPT_TEXTURE: + { + const CEGUI::ShaderParameterTexture* parameterTexture = static_cast(parameter); + const CEGUI::Direct3D11Texture* texture = static_cast(parameterTexture->d_parameterValue); + + ID3D11ShaderResourceView* shaderResourceView = texture->getDirect3DShaderResourceView(); + + if (parameterDescription.d_shaderType == ST_PIXEL) + d_deviceContext->PSSetShaderResources(parameterDescription.d_boundLocation, 1, &shaderResourceView); + else if (parameterDescription.d_shaderType == ST_VERTEX) + d_deviceContext->VSSetShaderResources(parameterDescription.d_boundLocation, 1, &shaderResourceView); + } + break; + default: + break; + } + + ++iter; + } + + finishUniformVariableMapping(); +} + +//----------------------------------------------------------------------------// +void* Direct3D11ShaderWrapper::getVertShaderBufferPointer() const +{ + ID3D10Blob* vertexShaderBuffer = d_shader.getVertexShaderBuffer(); + + return vertexShaderBuffer->GetBufferPointer(); +} + +//----------------------------------------------------------------------------// +SIZE_T Direct3D11ShaderWrapper::getVertShaderBufferSize() const +{ + ID3D10Blob* vertexShaderBuffer = d_shader.getVertexShaderBuffer(); + + return vertexShaderBuffer->GetBufferSize(); +} + +//----------------------------------------------------------------------------// +void Direct3D11ShaderWrapper::createPerObjectBuffer(ShaderType shaderType) +{ + HRESULT result; + + ID3D11ShaderReflectionConstantBuffer* shaderReflectionConstBuff = d_shader.getShaderReflectionConstBuffer(shaderType); + + D3D11_SHADER_BUFFER_DESC shaderBufferDesc; + result = shaderReflectionConstBuff->GetDesc(&shaderBufferDesc); + if (FAILED(result)) + return; + + if(shaderBufferDesc.Size > 0) + { + // create the constant buffers + D3D11_BUFFER_DESC bufferDescription; + ZeroMemory(&bufferDescription, sizeof(bufferDescription)); + + bufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bufferDescription.Usage = D3D11_USAGE_DYNAMIC; + bufferDescription.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + bufferDescription.MiscFlags = 0; + bufferDescription.ByteWidth = shaderBufferDesc.Size; + + if (shaderType == ST_VERTEX) + d_device->CreateBuffer(&bufferDescription, 0, &d_perObjectUniformVarBufferVert); + else if (shaderType == ST_PIXEL) + d_device->CreateBuffer(&bufferDescription, 0, &d_perObjectUniformVarBufferPixel); + } +} + +//----------------------------------------------------------------------------// +void Direct3D11ShaderWrapper::prepareUniformVariableMapping(unsigned char*& resourceDataVS, unsigned char*& resourceDataPS) +{ + if(d_perObjectUniformVarBufferVert != 0) + { + d_deviceContext->VSSetConstantBuffers(0, 1, &d_perObjectUniformVarBufferVert); + + D3D11_MAPPED_SUBRESOURCE mappedResourceVertShader; + HRESULT result = d_deviceContext->Map(d_perObjectUniformVarBufferVert, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourceVertShader); + if(FAILED(result)) + CEGUI_THROW(RendererException("Failed to map constant shader buffer.\n")); + + resourceDataVS = static_cast(mappedResourceVertShader.pData); + } + if(d_perObjectUniformVarBufferPixel != 0) + { + d_deviceContext->PSSetConstantBuffers(0, 1, &d_perObjectUniformVarBufferPixel); + + D3D11_MAPPED_SUBRESOURCE mappedResourcePixelShader; + HRESULT result = d_deviceContext->Map(d_perObjectUniformVarBufferPixel, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourcePixelShader); + if(FAILED(result)) + CEGUI_THROW(RendererException("Failed to map constant shader buffer.\n")); + + resourceDataPS = static_cast(mappedResourcePixelShader.pData); + } +} + +//----------------------------------------------------------------------------// +void Direct3D11ShaderWrapper::finishUniformVariableMapping() +{ + if(d_perObjectUniformVarBufferVert != 0) + d_deviceContext->Unmap(d_perObjectUniformVarBufferVert, 0); + if(d_perObjectUniformVarBufferPixel != 0) + d_deviceContext->Unmap(d_perObjectUniformVarBufferPixel, 0); +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/RendererModules/Direct3D11/Shaders.inl b/cegui/src/RendererModules/Direct3D11/Shaders.inl new file mode 100644 index 000000000..a3d0cdc17 --- /dev/null +++ b/cegui/src/RendererModules/Direct3D11/Shaders.inl @@ -0,0 +1,127 @@ +/*********************************************************************** + created: Sun, 6th April 2014 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +namespace CEGUI +{ + +//! A string containing an HLSL vertex shader for solid colouring of a polygon +const char VertexShaderColoured[] = "" +"float4x4 modelViewProjMatrix;\n" +"\n" +"struct VertOut\n" +"{\n" +" float4 pos : SV_Position;\n" +" float4 colour : COLOR;\n" +"};\n" +"\n" +"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n" +"{\n" +" VertOut output;\n" +"\n" +" output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n" +" output.colour = inColour;\n" +"\n" +" return output;\n" +"}\n" +; + +//! A string containing an HLSL fragment shader for solid colouring of a polygon +const char PixelShaderColoured[] = "" +"Texture2D texture0;\n" +"uniform float alphaPercentage;\n" +"\n" +"struct VertOut\n" +"{\n" +" float4 pos : SV_Position;\n" +" float4 colour : COLOR;\n" +"};\n" +"\n" +"float4 main(VertOut input) : SV_Target\n" +"{\n" +" float4 colour = input.colour;\n" +" colour.a *= alphaPercentage;\n" +" return colour;\n" +"}\n" +"\n" +; + + +/*! +A string containing an HLSL vertex shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +const char VertexShaderTextured[] = "" +"float4x4 modelViewProjMatrix;\n" +"\n" +"struct VertOut\n" +"{\n" +" float4 pos : SV_Position;\n" +" float4 colour : COLOR;\n" +" float2 texcoord0 : TEXCOORD;\n" +"};\n" +"\n" +"// Vertex shader\n" +"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n" +"{\n" +" VertOut output;\n" +"\n" +" output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n" +" output.texcoord0 = inTexCoord0;\n" +" output.colour = inColour;\n" +"\n" +" return output;\n" +"}\n" +; + +/*! +A string containing an HLSL fragment shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +const char PixelShaderTextured[] = "" +"Texture2D texture0;\n" +"SamplerState textureSamplerState;\n" +"uniform float alphaPercentage;\n" +"\n" +"struct VertOut\n" +"{\n" +" float4 pos : SV_Position;\n" +" float4 colour : COLOR;\n" +" float2 texcoord0 : TEXCOORD;\n" +"};\n" +"\n" +"float4 main(VertOut input) : SV_Target\n" +"{\n" +" float4 colour = texture0.Sample(textureSamplerState, input.texcoord0) * input.colour;\n" +" colour.a *= alphaPercentage;\n" +" return colour;\n" +"}\n" +"\n" +; + +} \ No newline at end of file diff --git a/cegui/src/RendererModules/Direct3D11/Texture.cpp b/cegui/src/RendererModules/Direct3D11/Texture.cpp index f32244719..af503dacd 100644 --- a/cegui/src/RendererModules/Direct3D11/Texture.cpp +++ b/cegui/src/RendererModules/Direct3D11/Texture.cpp @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -23,12 +24,13 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ + #include "CEGUI/RendererModules/Direct3D11/Texture.h" #include "CEGUI/System.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" + #include -#include // Start of CEGUI namespace section @@ -169,7 +171,7 @@ const Sizef& Direct3D11Texture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& Direct3D11Texture::getTexelScaling() const +const glm::vec2& Direct3D11Texture::getTexelScaling() const { return d_texelScaling; } @@ -248,7 +250,7 @@ void Direct3D11Texture::loadFromMemory(const void* buffer, data.pSysMem = img_src; data.SysMemPitch = calculateDataWidth(tex_desc.Width, pixel_format); - HRESULT hr = d_device.d_device->CreateTexture2D(&tex_desc, &data, &d_texture); + HRESULT hr = d_device.CreateTexture2D(&tex_desc, &data, &d_texture); if (pixel_format == PF_RGB) delete[] img_src; @@ -282,9 +284,9 @@ void Direct3D11Texture::blitFromMemory(const void* sourceData, const Rectf& area static_cast(area.bottom()), 1}; - d_device.d_context->UpdateSubresource(d_texture, 0, &dst_box, buff, - static_cast(area.getWidth()) * 4, - 0); + d_deviceContext.UpdateSubresource(d_texture, 0, &dst_box, buff, + static_cast(area.getWidth()) * 4, + 0); delete[] buff; } @@ -305,12 +307,12 @@ void Direct3D11Texture::blitToMemory(void* targetData) tex_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; ID3D11Texture2D* offscreen; - if (SUCCEEDED(d_device.d_device->CreateTexture2D(&tex_desc, 0, &offscreen))) + if (SUCCEEDED(d_device.CreateTexture2D(&tex_desc, 0, &offscreen))) { - d_device.d_context->CopyResource(offscreen, d_texture); + d_deviceContext.CopyResource(offscreen, d_texture); D3D11_MAPPED_SUBRESOURCE mapped_tex; - if (SUCCEEDED(d_device.d_context->Map(offscreen, 0, D3D11_MAP_READ, + if (SUCCEEDED(d_deviceContext.Map(offscreen, 0, D3D11_MAP_READ, 0, &mapped_tex))) { blitFromSurface(static_cast(mapped_tex.pData), @@ -319,7 +321,7 @@ void Direct3D11Texture::blitToMemory(void* targetData) static_cast(tex_desc.Height)), mapped_tex.RowPitch); - d_device.d_context->Unmap(offscreen, 0); + d_deviceContext.Unmap(offscreen, 0); } else exception_msg.assign("ID3D11Texture2D::Map failed."); @@ -363,7 +365,7 @@ void Direct3D11Texture::updateCachedScaleValues() // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. - d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); + d_texelScaling.x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale @@ -375,7 +377,7 @@ void Direct3D11Texture::updateCachedScaleValues() // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. - d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); + d_texelScaling.y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// @@ -393,8 +395,9 @@ void Direct3D11Texture::updateTextureSize() } //----------------------------------------------------------------------------// -Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name) : +Direct3D11Texture::Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, const String& name) : d_device(device), + d_deviceContext(deviceContext), d_texture(0), d_resourceView(0), d_size(0, 0), @@ -405,10 +408,12 @@ Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name) : } //----------------------------------------------------------------------------// -Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name, +Direct3D11Texture::Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, + const String& name, const String& filename, const String& resourceGroup) : d_device(device), + d_deviceContext(deviceContext), d_texture(0), d_resourceView(0), d_size(0, 0), @@ -420,9 +425,11 @@ Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name, } //----------------------------------------------------------------------------// -Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name, +Direct3D11Texture::Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, + const String& name, const Sizef& sz) : d_device(device), + d_deviceContext(deviceContext), d_texture(0), d_resourceView(0), d_size(0, 0), @@ -444,7 +451,7 @@ Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name, tex_desc.MiscFlags = 0; tex_desc.MipLevels = 1; - if (FAILED(d_device.d_device->CreateTexture2D(&tex_desc, 0, &d_texture))) + if (FAILED(d_device.CreateTexture2D(&tex_desc, 0, &d_texture))) CEGUI_THROW(RendererException( "Failed to create texture with specified size.")); @@ -456,9 +463,11 @@ Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name, } //----------------------------------------------------------------------------// -Direct3D11Texture::Direct3D11Texture(IDevice11& device, const String& name, +Direct3D11Texture::Direct3D11Texture(ID3D11Device& device, ID3D11DeviceContext& deviceContext, + const String& name, ID3D11Texture2D* tex) : d_device(device), + d_deviceContext(deviceContext), d_texture(0), d_resourceView(0), d_size(0, 0), @@ -493,7 +502,7 @@ void Direct3D11Texture::initialiseShaderResourceView() srvd.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvd.Texture2D.MostDetailedMip = 0; srvd.Texture2D.MipLevels = tex_desc.MipLevels; - d_device.d_device->CreateShaderResourceView(resource, &srvd, &d_resourceView); + d_device.CreateShaderResourceView(resource, &srvd, &d_resourceView); resource->Release(); } diff --git a/cegui/src/RendererModules/Direct3D11/TextureTarget.cpp b/cegui/src/RendererModules/Direct3D11/TextureTarget.cpp index ac76cb38a..c701357b7 100644 --- a/cegui/src/RendererModules/Direct3D11/TextureTarget.cpp +++ b/cegui/src/RendererModules/Direct3D11/TextureTarget.cpp @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -81,7 +82,7 @@ bool Direct3D11TextureTarget::isImageryCache() const void Direct3D11TextureTarget::clear() { const float colour[] = { 0, 0, 0, 0 }; - d_device.d_context->ClearRenderTargetView(d_renderTargetView, colour); + d_deviceContext.ClearRenderTargetView(d_renderTargetView, colour); } //----------------------------------------------------------------------------// @@ -122,14 +123,14 @@ void Direct3D11TextureTarget::initialiseRenderTexture() tex_desc.SampleDesc.Count = 1; tex_desc.Usage = D3D11_USAGE_DEFAULT; tex_desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - d_device.d_device->CreateTexture2D(&tex_desc, 0, &d_texture); + d_device.CreateTexture2D(&tex_desc, 0, &d_texture); // create render target view, so we can render to the thing D3D11_RENDER_TARGET_VIEW_DESC rtv_desc; rtv_desc.Format = tex_desc.Format; rtv_desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtv_desc.Texture2D.MipSlice = 0; - d_device.d_device->CreateRenderTargetView(d_texture, &rtv_desc, &d_renderTargetView); + d_device.CreateRenderTargetView(d_texture, &rtv_desc, &d_renderTargetView); d_CEGUITexture->setDirect3DTexture(d_texture); d_CEGUITexture->setOriginalDataSize(d_area.getSize()); @@ -161,10 +162,10 @@ void Direct3D11TextureTarget::resizeRenderTexture() //----------------------------------------------------------------------------// void Direct3D11TextureTarget::enableRenderTexture() { - d_device.d_context->OMGetRenderTargets(1, &d_previousRenderTargetView, + d_deviceContext.OMGetRenderTargets(1, &d_previousRenderTargetView, &d_previousDepthStencilView); - d_device.d_context->OMSetRenderTargets(1, &d_renderTargetView, 0); + d_deviceContext.OMSetRenderTargets(1, &d_renderTargetView, 0); } //----------------------------------------------------------------------------// @@ -175,7 +176,7 @@ void Direct3D11TextureTarget::disableRenderTexture() if (d_previousDepthStencilView) d_previousDepthStencilView->Release(); - d_device.d_context->OMSetRenderTargets(1, &d_previousRenderTargetView, + d_deviceContext.OMSetRenderTargets(1, &d_previousRenderTargetView, d_previousDepthStencilView); d_previousRenderTargetView = 0; diff --git a/cegui/src/RendererModules/Direct3D11/ViewportTarget.cpp b/cegui/src/RendererModules/Direct3D11/ViewportTarget.cpp index cf78d3b0c..b78dd5f65 100644 --- a/cegui/src/RendererModules/Direct3D11/ViewportTarget.cpp +++ b/cegui/src/RendererModules/Direct3D11/ViewportTarget.cpp @@ -1,8 +1,9 @@ /*********************************************************************** - created: Wed May 5 2010 + created: Sun, 6th April 2014 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -36,14 +37,14 @@ Direct3D11ViewportTarget::Direct3D11ViewportTarget(Direct3D11Renderer& owner) : // initialise renderer size D3D11_VIEWPORT vp; UINT vp_count = 1; - d_device.d_context->RSGetViewports(&vp_count, &vp); + d_deviceContext.RSGetViewports(&vp_count, &vp); if (vp_count != 1) CEGUI_THROW(RendererException( "Unable to access required view port information from " "ID3D11Device.")); Rectf area( - Vector2f(static_cast(vp.TopLeftX), static_cast(vp.TopLeftY)), + glm::vec2(static_cast(vp.TopLeftX), static_cast(vp.TopLeftY)), Sizef(static_cast(vp.Width), static_cast(vp.Height)) ); diff --git a/cegui/src/RendererModules/Direct3D11/shader.txt b/cegui/src/RendererModules/Direct3D11/shader.txt deleted file mode 100644 index 88a57964e..000000000 --- a/cegui/src/RendererModules/Direct3D11/shader.txt +++ /dev/null @@ -1,147 +0,0 @@ -const char shaderSource[] = -"//--------------------------------------------------------------------------//\n" -"Texture2D BoundTexture;\n" -"matrix WorldMatrix;\n" -"matrix ProjectionMatrix;\n" -"//--------------------------------------------------------------------------//\n" -"\n" -"\n" -"struct VSSceneIn\n" -"{\n" -" float3 pos : POSITION;\n" -" float4 colour : COLOR;\n" -" float2 tex : TEXCOORD;\n" -"};\n" -"\n" -"struct PSSceneIn\n" -"{\n" -" float4 pos : SV_Position;\n" -" float4 colour : COLOR;\n" -" float2 tex : TEXCOORD;\n" -"};\n" -"\n" -"DepthStencilState DisableDepth\n" -"{\n" -" DepthEnable = FALSE;\n" -" DepthWriteMask = ZERO;\n" -"};\n" -"\n" -"BlendState BM_NORMAL\n" -"{\n" -" AlphaToCoverageEnable = false;\n" -" BlendEnable[0] = true;\n" -" SrcBlendAlpha = INV_DEST_ALPHA;\n" -" DestBlendAlpha = ONE;\n" -" SrcBlend = SRC_ALPHA;\n" -" DestBlend = INV_SRC_ALPHA;\n" -"};\n" -"\n" -"BlendState BM_RTT_PREMULTIPLIED\n" -"{\n" -" AlphaToCoverageEnable = false;\n" -" BlendEnable[0] = true;\n" -" SrcBlendAlpha = ONE;\n" -" DestBlendAlpha = INV_SRC_ALPHA;\n" -" SrcBlend = ONE;\n" -" DestBlend = INV_SRC_ALPHA;\n" -"};\n" -"\n" -"SamplerState LinearSampler\n" -"{\n" -" Filter = MIN_MAG_MIP_LINEAR;\n" -" AddressU = Clamp;\n" -" AddressV = Clamp;\n" -"};\n" -"\n" -"RasterizerState clipRasterstate\n" -"{\n" -" DepthClipEnable = false;\n" -" FillMode = Solid;\n" -" CullMode = None;\n" -" ScissorEnable = true;\n" -"};\n" -"\n" -"RasterizerState noclipRasterstate\n" -"{\n" -" DepthClipEnable = false;\n" -" FillMode = Solid;\n" -" CullMode = None;\n" -" ScissorEnable = false;\n" -"};\n" -"\n" -"// Vertex shader\n" -"PSSceneIn VSMain(VSSceneIn input)\n" -"{\n" -" PSSceneIn output = (PSSceneIn)0.0;\n" -"\n" -" //output our final position\n" -" output.pos = mul( float4(input.pos, 1), WorldMatrix );\n" -" output.pos = mul( output.pos, ProjectionMatrix );\n" -" output.tex = input.tex;\n" -" output.colour.rgba = input.colour.bgra;\n" -"\n" -" return output;\n" -"}\n" -"\n" -"// Pixel shader\n" -"float4 PSMain(PSSceneIn input) : SV_Target\n" -"{\n" -" float4 colour = BoundTexture.Sample(LinearSampler, input.tex) * input.colour;\n" -" return colour;\n" -"}\n" -"\n" -"// Techniques\n" -"technique11 BM_NORMAL_Clipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_NORMAL, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(clipRasterstate);\n" -" }\n" -"}\n" -"\n" -"technique11 BM_NORMAL_Unclipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_NORMAL, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(noclipRasterstate);\n" -" }\n" -"}\n" -"\n" -"technique11 BM_RTT_PREMULTIPLIED_Clipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_RTT_PREMULTIPLIED, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(clipRasterstate);\n" -" }\n" -"}\n" -"\n" -"technique11 BM_RTT_PREMULTIPLIED_Unclipped_Rendering\n" -"{\n" -" pass P0\n" -" {\n" -" SetVertexShader(CompileShader(vs_4_0, VSMain()));\n" -" SetGeometryShader(NULL);\n" -" SetPixelShader(CompileShader(ps_4_0, PSMain()));\n" -" SetDepthStencilState(DisableDepth, 0);\n" -" SetBlendState(BM_RTT_PREMULTIPLIED, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xFFFFFFFF);\n" -" SetRasterizerState(noclipRasterstate);\n" -" }\n" -"}\n" -"\n" -"//--------------------------------------------------------------------------//\n" -; diff --git a/cegui/src/RendererModules/Direct3D9/CMakeLists.txt b/cegui/src/RendererModules/Direct3D9/CMakeLists.txt deleted file mode 100644 index 46c03b505..000000000 --- a/cegui/src/RendererModules/Direct3D9/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -set (CEGUI_TARGET_NAME ${CEGUI_DIRECT3D9_RENDERER_LIBNAME}) - -include_directories(${DIRECTXSDK_INCLUDE_DIR}) -link_directories(${DIRECTXSDK_LIBRARY_DIR}) - -cegui_gather_files() -cegui_add_library(${CEGUI_TARGET_NAME} CORE_SOURCE_FILES CORE_HEADER_FILES) - -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME} d3d9) -cegui_target_link_libraries(${CEGUI_TARGET_NAME} optimized d3dx9 debug d3dx9d) - diff --git a/cegui/src/RendererModules/Direct3D9/GeometryBuffer.cpp b/cegui/src/RendererModules/Direct3D9/GeometryBuffer.cpp deleted file mode 100644 index fdae2f54c..000000000 --- a/cegui/src/RendererModules/Direct3D9/GeometryBuffer.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/*********************************************************************** - created: Mon Feb 9 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D9/GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D9/Texture.h" -#include "CEGUI/RenderEffect.h" -#include "CEGUI/Vertex.h" -#include - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -Direct3D9GeometryBuffer::Direct3D9GeometryBuffer(Direct3D9Renderer& owner, - LPDIRECT3DDEVICE9 device) : - d_owner(owner), - d_activeTexture(0), - d_clipRect(0, 0, 0, 0), - d_clippingActive(true), - d_translation(0, 0, 0), - d_rotation(0, 0, 0), - d_pivot(0, 0, 0), - d_effect(0), - d_device(device), - d_matrixValid(false) -{ -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::draw() const -{ - RECT saved_clip; - d_device->GetScissorRect(&saved_clip); - - // setup clip region - RECT clip; - clip.left = static_cast(d_clipRect.left()); - clip.top = static_cast(d_clipRect.top()); - clip.right = static_cast(d_clipRect.right()); - clip.bottom = static_cast(d_clipRect.bottom()); - - // apply the transformations we need to use. - if (!d_matrixValid) - updateMatrix(); - - d_device->SetTransform(D3DTS_WORLD, &d_matrix); - - d_owner.setupRenderingBlendMode(d_blendMode); - - const int pass_count = d_effect ? d_effect->getPassCount() : 1; - for (int pass = 0; pass < pass_count; ++pass) - { - // set up RenderEffect - if (d_effect) - d_effect->performPreRenderFunctions(pass); - - // draw the batches - size_t pos = 0; - BatchList::const_iterator i = d_batches.begin(); - for ( ; i != d_batches.end(); ++i) - { - if (i->clip) - d_device->SetScissorRect(&clip); - - d_device->SetTexture(0, i->texture); - d_device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, i->vertexCount / 3, - &d_vertices[pos], sizeof(D3DVertex)); - pos += i->vertexCount; - - if (i->clip) - d_device->SetScissorRect(&saved_clip); - } - } - - // clean up RenderEffect - if (d_effect) - d_effect->performPostRenderFunctions(); -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setTranslation(const Vector3f& t) -{ - d_translation = t; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setRotation(const Quaternion& r) -{ - d_rotation = r; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setPivot(const Vector3f& p) -{ - d_pivot = p; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setClippingRegion(const Rectf& region) -{ - d_clipRect.top(ceguimax(0.0f, region.top())); - d_clipRect.bottom(ceguimax(0.0f, region.bottom())); - d_clipRect.left(ceguimax(0.0f, region.left())); - d_clipRect.right(ceguimax(0.0f, region.right())); -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::appendVertex(const Vertex& vertex) -{ - appendGeometry(&vertex, 1); -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::appendGeometry(const Vertex* const vbuff, - uint vertex_count) -{ - performBatchManagement(); - - // update size of current batch - d_batches.back().vertexCount += vertex_count; - - // buffer these vertices - D3DVertex vd; - const Vertex* vs = vbuff; - for (uint i = 0; i < vertex_count; ++i, ++vs) - { - // copy vertex info the buffer, converting from CEGUI::Vertex to - // something directly usable by D3D as needed. - vd.x = vs->position.d_x - 0.5f; - vd.y = vs->position.d_y - 0.5f; - vd.z = vs->position.d_z; - vd.diffuse = vs->colour_val.getARGB(); - vd.tu = vs->tex_coords.d_x; - vd.tv = vs->tex_coords.d_y; - d_vertices.push_back(vd); - } -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setActiveTexture(Texture* texture) -{ - d_activeTexture = static_cast(texture); -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::reset() -{ - d_batches.clear(); - d_vertices.clear(); - d_activeTexture = 0; -} - -//----------------------------------------------------------------------------// -Texture* Direct3D9GeometryBuffer::getActiveTexture() const -{ - return d_activeTexture; -} - -//----------------------------------------------------------------------------// -uint Direct3D9GeometryBuffer::getVertexCount() const -{ - return d_vertices.size(); -} - -//----------------------------------------------------------------------------// -uint Direct3D9GeometryBuffer::getBatchCount() const -{ - return d_batches.size(); -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setRenderEffect(RenderEffect* effect) -{ - d_effect = effect; -} - -//----------------------------------------------------------------------------// -RenderEffect* Direct3D9GeometryBuffer::getRenderEffect() -{ - return d_effect; -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::performBatchManagement() -{ - const LPDIRECT3DTEXTURE9 t = d_activeTexture ? - d_activeTexture->getDirect3D9Texture() : 0; - - // create a new batch if there are no batches yet, or if the active texture - // differs from that used by the current batch. - if (d_batches.empty() || - t != d_batches.back().texture || - d_clippingActive != d_batches.back().clip) - { - BatchInfo batch = {t, 0, d_clippingActive}; - d_batches.push_back(batch); - } -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::updateMatrix() const -{ - const D3DXVECTOR3 p(d_pivot.d_x, d_pivot.d_y, d_pivot.d_z); - const D3DXVECTOR3 t(d_translation.d_x, d_translation.d_y, d_translation.d_z); - - D3DXQUATERNION r; - r.x = d_rotation.d_x; - r.y = d_rotation.d_y; - r.z = d_rotation.d_z; - r.w = d_rotation.d_w; - - D3DXMatrixTransformation(&d_matrix, 0, 0, 0, &p, &r, &t); - - d_matrixValid = true; -} - -//----------------------------------------------------------------------------// -const D3DXMATRIX* Direct3D9GeometryBuffer::getMatrix() const -{ - if (!d_matrixValid) - updateMatrix(); - - return &d_matrix; -} - -//----------------------------------------------------------------------------// -void Direct3D9GeometryBuffer::setClippingActive(const bool active) -{ - d_clippingActive = active; -} - -//----------------------------------------------------------------------------// -bool Direct3D9GeometryBuffer::isClippingActive() const -{ - return d_clippingActive; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D9/RenderTarget.inl b/cegui/src/RendererModules/Direct3D9/RenderTarget.inl deleted file mode 100644 index 796492d54..000000000 --- a/cegui/src/RendererModules/Direct3D9/RenderTarget.inl +++ /dev/null @@ -1,198 +0,0 @@ -/*********************************************************************** - created: Tue Feb 10 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D9/RenderTarget.h" -#include "CEGUI/RendererModules/Direct3D9/GeometryBuffer.h" -#include "CEGUI/RenderQueue.h" -#include "CEGUI/Exceptions.h" -#include - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -template -Direct3D9RenderTarget::Direct3D9RenderTarget(Direct3D9Renderer& owner) : - d_owner(owner), - d_device(owner.getDevice()), - d_area(0, 0, 0, 0), - d_viewDistance(0), - d_matrixValid(false) -{ -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::draw(const GeometryBuffer& buffer) -{ - buffer.draw(); -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::draw(const RenderQueue& queue) -{ - queue.draw(); -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::setArea(const Rectf& area) -{ - d_area = area; - d_matrixValid = false; - - RenderTargetEventArgs args(this); - T::fireEvent(RenderTarget::EventAreaChanged, args); -} - -//----------------------------------------------------------------------------// -template -const Rectf& Direct3D9RenderTarget::getArea() const -{ - return d_area; -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::activate() -{ - if (!d_matrixValid) - updateMatrix(); - - D3DVIEWPORT9 vp; - setupViewport(vp); - d_device->SetViewport(&vp); - - d_owner.getDevice()->SetTransform(D3DTS_PROJECTION, &d_matrix); -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::deactivate() -{ -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const -{ - if (!d_matrixValid) - updateMatrix(); - - const Direct3D9GeometryBuffer& gb = - static_cast(buff); - - D3DVIEWPORT9 vp; - setupViewport(vp); - - D3DXVECTOR3 in_vec; - in_vec.z = 0.0f; - - // project points to create a plane orientated with GeometryBuffer's data - D3DXVECTOR3 p1; - D3DXVECTOR3 p2; - D3DXVECTOR3 p3; - in_vec.x = 0; - in_vec.y = 0; - D3DXVec3Project(&p1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = 1; - in_vec.y = 0; - D3DXVec3Project(&p2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = 0; - in_vec.y = 1; - D3DXVec3Project(&p3, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - // create plane from projected points - D3DXPLANE surface_plane; - D3DXPlaneFromPoints(&surface_plane, &p1, &p2, &p3); - - // unproject ends of ray - in_vec.x = vp.Width * 0.5f; - in_vec.y = vp.Height * 0.5f; - in_vec.z = -d_viewDistance; - D3DXVECTOR3 t1; - D3DXVec3Unproject(&t1, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - in_vec.x = p_in.d_x; - in_vec.y = p_in.d_y; - in_vec.z = 0.0f; - D3DXVECTOR3 t2; - D3DXVec3Unproject(&t2, &in_vec, &vp, &d_matrix, 0, gb.getMatrix()); - - // get intersection of ray and plane - D3DXVECTOR3 intersect; - D3DXPlaneIntersectLine(&intersect, &surface_plane, &t1, &t2); - - p_out.d_x = intersect.x; - p_out.d_y = intersect.y; -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::updateMatrix() const -{ - const float fov = 0.523598776f; - const float w = d_area.getWidth(); - const float h = d_area.getHeight(); - const float aspect = w / h; - const float midx = w * 0.5f; - const float midy = h * 0.5f; - d_viewDistance = midx / (aspect * 0.267949192431123f); - - D3DXVECTOR3 eye(midx, midy, -d_viewDistance); - D3DXVECTOR3 at(midx, midy, 1); - D3DXVECTOR3 up(0, -1, 0); - - D3DXMATRIX tmp; - D3DXMatrixMultiply(&d_matrix, - D3DXMatrixLookAtRH(&d_matrix, &eye, &at, &up), - D3DXMatrixPerspectiveFovRH(&tmp, fov, aspect, - d_viewDistance * 0.5f, - d_viewDistance * 2.0f)); - - d_matrixValid = true; -} - -//----------------------------------------------------------------------------// -template -void Direct3D9RenderTarget::setupViewport(D3DVIEWPORT9& vp) const -{ - vp.X = static_cast(d_area.left()); - vp.Y = static_cast(d_area.top()); - vp.Width = static_cast(d_area.getWidth()); - vp.Height = static_cast(d_area.getHeight()); - vp.MinZ = 0.0f; - vp.MaxZ = 1.0f; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D9/Renderer.cpp b/cegui/src/RendererModules/Direct3D9/Renderer.cpp deleted file mode 100644 index c245e9083..000000000 --- a/cegui/src/RendererModules/Direct3D9/Renderer.cpp +++ /dev/null @@ -1,552 +0,0 @@ -/*********************************************************************** - created: Mon Feb 9 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" -#include "CEGUI/RendererModules/Direct3D9/Texture.h" -#include "CEGUI/RendererModules/Direct3D9/GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D9/RenderTarget.h" -#include "CEGUI/Exceptions.h" -#include "CEGUI/RendererModules/Direct3D9/ViewportTarget.h" -#include "CEGUI/RendererModules/Direct3D9/TextureTarget.h" -#include "CEGUI/System.h" -#include "CEGUI/DefaultResourceProvider.h" -#include "CEGUI/Logger.h" - -#include - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -String Direct3D9Renderer::d_rendererID( -"CEGUI::Direct3D9Renderer - Official Direct3D 9 based 2nd generation renderer " -"module."); - -//----------------------------------------------------------------------------// -static const D3DMATRIX s_identityMatrix = -{ - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0 -}; - -//----------------------------------------------------------------------------// -Direct3D9Renderer& Direct3D9Renderer::bootstrapSystem(LPDIRECT3DDEVICE9 device, - const int abi) -{ - System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - - if (System::getSingletonPtr()) - CEGUI_THROW(InvalidRequestException( - "CEGUI::System object is already initialised.")); - - Direct3D9Renderer& renderer(create(device)); - DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); - System::create(renderer, rp); - - return renderer; -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroySystem() -{ - System* sys; - if (!(sys = System::getSingletonPtr())) - CEGUI_THROW(InvalidRequestException( - "CEGUI::System object is not created or was already destroyed.")); - - Direct3D9Renderer* renderer = - static_cast(sys->getRenderer()); - DefaultResourceProvider* rp = - static_cast(sys->getResourceProvider()); - - System::destroy(); - delete rp; - destroy(*renderer); -} - -//----------------------------------------------------------------------------// -Direct3D9Renderer& Direct3D9Renderer::create(LPDIRECT3DDEVICE9 device, - const int abi) -{ - System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - - return *new Direct3D9Renderer(device); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroy(Direct3D9Renderer& renderer) -{ - delete &renderer; -} - -//----------------------------------------------------------------------------// -RenderTarget& Direct3D9Renderer::getDefaultRenderTarget() -{ - return *d_defaultTarget; -} - -//----------------------------------------------------------------------------// -GeometryBuffer& Direct3D9Renderer::createGeometryBuffer() -{ - Direct3D9GeometryBuffer* b = new Direct3D9GeometryBuffer(*this, d_device); - d_geometryBuffers.push_back(b); - return *b; -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyGeometryBuffer(const GeometryBuffer& buffer) -{ - GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), - d_geometryBuffers.end(), - &buffer); - - if (d_geometryBuffers.end() != i) - { - d_geometryBuffers.erase(i); - delete &buffer; - } -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyAllGeometryBuffers() -{ - while (!d_geometryBuffers.empty()) - destroyGeometryBuffer(**d_geometryBuffers.begin()); -} - -//----------------------------------------------------------------------------// -TextureTarget* Direct3D9Renderer::createTextureTarget() -{ - TextureTarget* t = new Direct3D9TextureTarget(*this); - d_textureTargets.push_back(t); - return t; -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyTextureTarget(TextureTarget* target) -{ - TextureTargetList::iterator i = std::find(d_textureTargets.begin(), - d_textureTargets.end(), - target); - - if (d_textureTargets.end() != i) - { - d_textureTargets.erase(i); - delete target; - } -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyAllTextureTargets() -{ - while (!d_textureTargets.empty()) - destroyTextureTarget(*d_textureTargets.begin()); -} - -//----------------------------------------------------------------------------// -Texture& Direct3D9Renderer::createTexture(const String& name) -{ - throwIfNameExists(name); - - Direct3D9Texture* tex = new Direct3D9Texture(*this, name); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -Texture& Direct3D9Renderer::createTexture(const String& name, - const String& filename, - const String& resourceGroup) -{ - throwIfNameExists(name); - - Direct3D9Texture* tex = - new Direct3D9Texture(*this, name, filename, resourceGroup); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -Texture& Direct3D9Renderer::createTexture(const String& name, const Sizef& size) -{ - throwIfNameExists(name); - - Direct3D9Texture* tex = new Direct3D9Texture(*this, name, size); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::throwIfNameExists(const String& name) const -{ - if (d_textures.find(name) != d_textures.end()) - CEGUI_THROW(AlreadyExistsException( - "[Direct3D9Renderer] Texture already exists: " + name)); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::logTextureCreation(const String& name) -{ - Logger* logger = Logger::getSingletonPtr(); - if (logger) - logger->logEvent("[Direct3D9Renderer] Created texture: " + name); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyTexture(Texture& texture) -{ - destroyTexture(texture.getName()); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyTexture(const String& name) -{ - TextureMap::iterator i = d_textures.find(name); - - if (d_textures.end() != i) - { - logTextureDestruction(name); - delete i->second; - d_textures.erase(i); - } -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::logTextureDestruction(const String& name) -{ - Logger* logger = Logger::getSingletonPtr(); - if (logger) - logger->logEvent("[Direct3D9Renderer] Destroyed texture: " + name); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::destroyAllTextures() -{ - while (!d_textures.empty()) - destroyTexture(d_textures.begin()->first); -} - -//----------------------------------------------------------------------------// -Texture& Direct3D9Renderer::getTexture(const String& name) const -{ - TextureMap::const_iterator i = d_textures.find(name); - - if (i == d_textures.end()) - CEGUI_THROW(UnknownObjectException( - "[Direct3D9Renderer] Texture does not exist: " + name)); - - return *i->second; -} - -//----------------------------------------------------------------------------// -bool Direct3D9Renderer::isTextureDefined(const String& name) const -{ - return d_textures.find(name) != d_textures.end(); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::beginRendering() -{ - d_device->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); - - // no shaders initially - d_device->SetVertexShader(0); - d_device->SetPixelShader(0); - - // set device states - d_device->SetRenderState(D3DRS_LIGHTING, FALSE); - d_device->SetRenderState(D3DRS_FOGENABLE, FALSE); - d_device->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE); - d_device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); - d_device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); - d_device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID); - d_device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE); - d_device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); - - // setup texture addressing settings - d_device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); - d_device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); - - // setup colour calculations - d_device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); - d_device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - d_device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); - - // setup alpha calculations - d_device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); - d_device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); - d_device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - - // setup filtering - d_device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); - d_device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); - - // disable texture stages we do not need. - d_device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); - - // setup scene alpha blending - d_device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); - - // put alpha blend operations into a known state - setupRenderingBlendMode(BM_NORMAL, true); - - // set view matrix back to identity. - d_device->SetTransform(D3DTS_VIEW, &s_identityMatrix); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::endRendering() -{ -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::setDisplaySize(const Sizef& sz) -{ - if (sz != d_displaySize) - { - d_displaySize = sz; - - // FIXME: This is probably not the right thing to do in all cases. - Rectf area(d_defaultTarget->getArea()); - area.setSize(sz); - d_defaultTarget->setArea(area); - } -} - -//----------------------------------------------------------------------------// -const Sizef& Direct3D9Renderer::getDisplaySize() const -{ - return d_displaySize; -} - -//----------------------------------------------------------------------------// -const Vector2f& Direct3D9Renderer::getDisplayDPI() const -{ - return d_displayDPI; -} - -//----------------------------------------------------------------------------// -uint Direct3D9Renderer::getMaxTextureSize() const -{ - return d_maxTextureSize; -} - -//----------------------------------------------------------------------------// -const String& Direct3D9Renderer::getIdentifierString() const -{ - return d_rendererID; -} - -//----------------------------------------------------------------------------// -Direct3D9Renderer::Direct3D9Renderer(LPDIRECT3DDEVICE9 device) : - d_device(device), - d_displaySize(getViewportSize()), - d_displayDPI(96, 96), - d_defaultTarget(0) -{ - D3DCAPS9 caps; - device->GetDeviceCaps(&caps); - - if (!caps.RasterCaps && D3DPRASTERCAPS_SCISSORTEST) - CEGUI_THROW(RendererException( - "Hardware does not support D3DPRASTERCAPS_SCISSORTEST. " - "Unable to proceed.")); - - d_maxTextureSize = ceguimin(caps.MaxTextureHeight, caps.MaxTextureWidth); - - d_supportNonSquareTex = !(caps.TextureCaps & D3DPTEXTURECAPS_SQUAREONLY); - - d_supportNPOTTex = !(caps.TextureCaps & D3DPTEXTURECAPS_POW2) || - (caps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL); - - d_defaultTarget = new Direct3D9ViewportTarget(*this); -} - -//----------------------------------------------------------------------------// -Direct3D9Renderer::~Direct3D9Renderer() -{ - destroyAllGeometryBuffers(); - destroyAllTextureTargets(); - destroyAllTextures(); - - delete d_defaultTarget; -} - -//----------------------------------------------------------------------------// -Sizef Direct3D9Renderer::getViewportSize() -{ - D3DVIEWPORT9 vp; - - if (FAILED(d_device->GetViewport(&vp))) - CEGUI_THROW(RendererException( - "Unable to access required view port information from " - "Direct3DDevice9.")); - else - return Sizef(static_cast(vp.Width), - static_cast(vp.Height)); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::preD3DReset() -{ - // perform pre-reset on texture targets - TextureTargetList::iterator target_iterator = d_textureTargets.begin(); - for (; target_iterator != d_textureTargets.end(); ++target_iterator) - static_cast(*target_iterator)->preD3DReset(); - - // perform pre-reset on textures - TextureMap::iterator texture_iterator = d_textures.begin(); - for (; texture_iterator != d_textures.end(); ++texture_iterator) - texture_iterator->second->preD3DReset(); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::postD3DReset() -{ - // perform post-reset on textures - TextureMap::iterator texture_iterator = d_textures.begin(); - for (; texture_iterator != d_textures.end(); ++texture_iterator) - texture_iterator->second->postD3DReset(); - - // perform post-reset on texture targets - TextureTargetList::iterator target_iterator = d_textureTargets.begin(); - for (; target_iterator != d_textureTargets.end(); ++target_iterator) - static_cast(*target_iterator)->postD3DReset(); - - // notify system about the (possibly) new viewport size. - System::getSingleton().notifyDisplaySizeChanged(getViewportSize()); -} - -//----------------------------------------------------------------------------// -LPDIRECT3DDEVICE9 Direct3D9Renderer::getDevice() const -{ - return d_device; -} - -//----------------------------------------------------------------------------// -Texture& Direct3D9Renderer::createTexture(const String& name, - LPDIRECT3DTEXTURE9 texture) -{ - throwIfNameExists(name); - - Direct3D9Texture* tex = new Direct3D9Texture(*this, name, texture); - d_textures[name] = tex; - - logTextureCreation(name); - - return *tex; -} - -//----------------------------------------------------------------------------// -bool Direct3D9Renderer::supportsNonSquareTexture() -{ - return d_supportNonSquareTex; -} - -//----------------------------------------------------------------------------// -bool Direct3D9Renderer::supportsNPOTTextures() -{ - return d_supportNPOTTex; -} - -//----------------------------------------------------------------------------// -Sizef Direct3D9Renderer::getAdjustedSize(const Sizef& sz) -{ - Sizef s(sz); - - if (!d_supportNPOTTex) - { - s.d_width = getSizeNextPOT(sz.d_width); - s.d_height = getSizeNextPOT(sz.d_height); - } - if (!d_supportNonSquareTex) - s.d_width = s.d_height = - ceguimax(s.d_width, s.d_height); - - return s; -} - -//----------------------------------------------------------------------------// -float Direct3D9Renderer::getSizeNextPOT(float sz) const -{ - uint size = static_cast(sz); - - // if not power of 2 - if ((size & (size - 1)) || !size) - { - int log = 0; - - // get integer log of 'size' to base 2 - while (size >>= 1) - ++log; - - // use log to calculate value to use as size. - size = (2 << log); - } - - return static_cast(size); -} - -//----------------------------------------------------------------------------// -void Direct3D9Renderer::setupRenderingBlendMode(const BlendMode mode, - const bool force) -{ - // exit if no change (and setup not forced) - if ((d_activeBlendMode == mode) && !force) - return; - - d_activeBlendMode = mode; - - if (d_activeBlendMode == BM_RTT_PREMULTIPLIED) - { - d_device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE); - d_device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); - d_device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - } - else - { - d_device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE); - d_device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); - d_device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); - d_device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_INVDESTALPHA); - d_device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_ONE); - } -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D9/Texture.cpp b/cegui/src/RendererModules/Direct3D9/Texture.cpp deleted file mode 100644 index 98aa72e78..000000000 --- a/cegui/src/RendererModules/Direct3D9/Texture.cpp +++ /dev/null @@ -1,734 +0,0 @@ -/*********************************************************************** - created: Mon Feb 9 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include -#include "CEGUI/RendererModules/Direct3D9/Texture.h" -#include "CEGUI/Exceptions.h" -#include "CEGUI/System.h" -#include "CEGUI/ImageCodec.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -// helper to convert cegui pixel format enum to equivalent D3D format. -static D3DFORMAT toD3DPixelFormat(const Texture::PixelFormat fmt) -{ - switch (fmt) - { - case Texture::PF_RGBA: return D3DFMT_A8R8G8B8; - case Texture::PF_RGB: return D3DFMT_X8R8G8B8; - case Texture::PF_RGB_565: return D3DFMT_R5G6B5; - case Texture::PF_RGBA_4444: return D3DFMT_A4R4G4B4; - case Texture::PF_RGBA_DXT1: return D3DFMT_DXT1; - case Texture::PF_RGBA_DXT3: return D3DFMT_DXT3; - case Texture::PF_RGBA_DXT5: return D3DFMT_DXT5; - default: return D3DFMT_UNKNOWN; - } -} - -//----------------------------------------------------------------------------// -// helper function to return byte width of given pixel width in given format -static size_t calculateDataWidth(const size_t width, Texture::PixelFormat fmt) -{ - switch (fmt) - { - case Texture::PF_RGBA: - return width * 4; - - case Texture::PF_RGB: - return width * 3; - - case Texture::PF_RGB_565: - case Texture::PF_RGBA_4444: - return width * 2; - - case Texture::PF_RGBA_DXT1: - return ((width + 3) / 4) * 8; - - case Texture::PF_RGBA_DXT3: - case Texture::PF_RGBA_DXT5: - return ((width + 3) / 4) * 16; - - default: - return 0; - } -} - -//----------------------------------------------------------------------------// -// Helper utility function that copies an RGB buffer into a region of a second -// buffer as BGR data values (i.e swap red and blue) -static void blitRGBToBGRSurface(const uchar* src, uchar* dst, const Sizef& sz) -{ - for (uint i = 0; i < sz.d_height; ++i) - { - for (uint j = 0; j < sz.d_width; ++j) - { - *dst++ = src[2]; - *dst++ = src[1]; - *dst++ = src[0]; - src += 3; - } - } -} - -//----------------------------------------------------------------------------// -// Helper utility function that copies an RGBA buffer into a region of a second -// buffer as D3DCOLOR data values -static void blitRGBAToD3DCOLORSurface(const uint32* src, uint32* dst, - const Sizef& sz, size_t dest_pitch) -{ - for (uint i = 0; i < sz.d_height; ++i) - { - for (uint j = 0; j < sz.d_width; ++j) - { - const uint32 pixel = src[j]; - const uint32 tmp = pixel & 0x00FF00FF; - dst[j] = pixel & 0xFF00FF00 | (tmp << 16) | (tmp >> 16); - } - - dst += dest_pitch / sizeof(uint32); - src += static_cast(sz.d_width); - } -} - -//----------------------------------------------------------------------------// -// Helper utility function that copies a region of a buffer containing D3DCOLOR -// values into a second buffer as RGBA values. -static void blitD3DCOLORSurfaceToRGBA(const uint32* src, uint32* dst, - const Sizef& sz, size_t source_pitch) -{ - for (uint i = 0; i < sz.d_height; ++i) - { - for (uint j = 0; j < sz.d_width; ++j) - { - const uint32 pixel = src[j]; - const uint32 tmp = pixel & 0x00FF00FF; - dst[j] = pixel & 0xFF00FF00 | (tmp << 16) | (tmp >> 16); - } - - src += source_pitch / sizeof(uint32); - dst += static_cast(sz.d_width); - } -} - -//----------------------------------------------------------------------------// -// Helper class to wrap an image pixel buffer. The main purpose of this is -// to prevent the need to have lots of conditionals and raw pointers that need -// managing in places where exceptions are used (i.e this prevents leaks while -// keeping code clean). -class PixelBuffer -{ - const uchar* d_sourceBuffer; - uchar* d_workBuffer; - size_t d_pitch; - -public: - //------------------------------------------------------------------------// - PixelBuffer(const void* data, const Sizef& size, Texture::PixelFormat format) : - d_sourceBuffer(static_cast(data)), - d_workBuffer(0), - d_pitch(calculateDataWidth(static_cast(size.d_width), format)) - { - if (format != Texture::PF_RGBA && format != Texture::PF_RGB) - return; - - d_workBuffer = new uchar[d_pitch * static_cast(size.d_height)]; - - if (format == Texture::PF_RGBA) - blitRGBAToD3DCOLORSurface(reinterpret_cast(d_sourceBuffer), - reinterpret_cast(d_workBuffer), - size, d_pitch); - else - blitRGBToBGRSurface(d_sourceBuffer, d_workBuffer, size); - } - - //------------------------------------------------------------------------// - ~PixelBuffer() - { - delete[] d_workBuffer; - } - - //------------------------------------------------------------------------// - size_t getPitch() const - { - return d_pitch; - } - - //------------------------------------------------------------------------// - const uchar* getPixelDataPtr() const - { - return d_workBuffer ? d_workBuffer : d_sourceBuffer; - } - - //------------------------------------------------------------------------// -}; - -//----------------------------------------------------------------------------// -// Internal helper class to wrap the internal handling needed to copy data to -// and from a D3D9 texture. -class D3DSurfaceBlitter -{ -public: - //------------------------------------------------------------------------// - D3DSurfaceBlitter(LPDIRECT3DDEVICE9 d3d_device, LPDIRECT3DTEXTURE9 tex) : - d_device(d3d_device), - d_texture(tex), - d_renderTarget(0), - d_offscreen(0) - { - populateTextureSurfaceDescription(); - } - - //------------------------------------------------------------------------// - ~D3DSurfaceBlitter() - { - cleanupSurfaces(); - } - - //------------------------------------------------------------------------// - void blitFromMemory(const uint32* source, const Rectf& area) - { - if (!d_texture) - return; - - RECT target_rect = {static_cast(area.left()), static_cast(area.top()), - static_cast(area.right()), static_cast(area.bottom())}; - - lockRect(&target_rect); - - blitRGBAToD3DCOLORSurface( - source, static_cast(d_lockedRect.pBits), - area.getSize(), d_lockedRect.Pitch); - - unlockRect(&target_rect, true); - } - - //------------------------------------------------------------------------// - void blitToMemory(uint32* dest) - { - if (!d_texture) - return; - - lockRect(0, true); - - blitD3DCOLORSurfaceToRGBA( - static_cast(d_lockedRect.pBits), dest, - Sizef(static_cast(d_surfDesc.Width), static_cast(d_surfDesc.Height)), - d_lockedRect.Pitch); - - unlockRect(); - } - - //------------------------------------------------------------------------// - bool isRenderTarget() const - { - return d_surfDesc.Usage == D3DUSAGE_RENDERTARGET; - } - - //------------------------------------------------------------------------// - -private: - LPDIRECT3DDEVICE9 d_device; - LPDIRECT3DTEXTURE9 d_texture; - LPDIRECT3DSURFACE9 d_renderTarget; - LPDIRECT3DSURFACE9 d_offscreen; - D3DSURFACE_DESC d_surfDesc; - D3DLOCKED_RECT d_lockedRect; - RECT d_fullArea; - - //------------------------------------------------------------------------// - void initialiseSurfaces() - { - if (!d_offscreen) - createOffscreenSurface(); - - if (!d_renderTarget) - getTextureSurface(); - } - - //------------------------------------------------------------------------// - void cleanupSurfaces() - { - if (d_renderTarget) - { - d_renderTarget->Release(); - d_renderTarget = 0; - } - - if (d_offscreen) - { - d_offscreen->Release(); - d_offscreen = 0; - } - } - - //------------------------------------------------------------------------// - void lockRect(RECT* area = 0, bool for_reading = false) - { - if (isRenderTarget()) - { - initialiseSurfaces(); - - if (for_reading) - getRenderTargetData(); - - lockSurfaceRect(area); - } - else - { - lockTextureRect(area); - } - } - - //------------------------------------------------------------------------// - void unlockRect(RECT* area = 0, bool needs_update = false) - { - if (isRenderTarget()) - { - d_offscreen->UnlockRect(); - - if (needs_update) - updateRenderTarget(area); - } - else - d_texture->UnlockRect(0); - } - - //------------------------------------------------------------------------// - void populateTextureSurfaceDescription() - { - if (FAILED(d_texture->GetLevelDesc(0, &d_surfDesc))) - CEGUI_THROW(RendererException( - "IDirect3DTexture9::GetLevelDesc failed.")); - - d_fullArea.left = 0; - d_fullArea.top = 0; - d_fullArea.right = d_surfDesc.Width; - d_fullArea.bottom = d_surfDesc.Height; - } - - //------------------------------------------------------------------------// - void createOffscreenSurface() - { - if (FAILED(d_device->CreateOffscreenPlainSurface( - d_surfDesc.Width, d_surfDesc.Height, d_surfDesc.Format, - D3DPOOL_SYSTEMMEM, &d_offscreen, 0))) - { - CEGUI_THROW(RendererException( - "IDirect3DDevice9::CreateOffscreenPlainSurface failed.")); - } - } - - //------------------------------------------------------------------------// - void getTextureSurface() - { - if (FAILED(d_texture->GetSurfaceLevel(0, &d_renderTarget))) - CEGUI_THROW(RendererException( - "IDirect3DTexture9::GetSurfaceLevel failed.")); - } - - //------------------------------------------------------------------------// - void lockSurfaceRect(RECT* area) - { - if (FAILED(d_offscreen->LockRect(&d_lockedRect, area, 0))) - CEGUI_THROW(RendererException( - "IDirect3DSurface9::LockRect failed.")); - } - - //------------------------------------------------------------------------// - void lockTextureRect(RECT* area) - { - if (FAILED(d_texture->LockRect(0, &d_lockedRect, area, 0))) - CEGUI_THROW(RendererException( - "IDirect3DTexture9::LockRect failed.")); - } - - //------------------------------------------------------------------------// - void updateRenderTarget(RECT* area) - { - POINT pt = {area ? area->left : 0, area ? area->top : 0}; - if (FAILED(d_device->UpdateSurface(d_offscreen, - area ? area : &d_fullArea, - d_renderTarget, &pt))) - { - CEGUI_THROW(RendererException( - "IDirect3DDevice9::UpdateSurface failed.")); - } - } - - //------------------------------------------------------------------------// - void getRenderTargetData() - { - if (FAILED(d_device->GetRenderTargetData(d_renderTarget, d_offscreen))) - CEGUI_THROW(RendererException( - "IDirect3DDevice9::GetRenderTargetData failed.")); - } - - //------------------------------------------------------------------------// -}; - -//----------------------------------------------------------------------------// -Direct3D9Texture::Direct3D9Texture(Direct3D9Renderer& owner, - const String& name) : - d_owner(owner), - d_texture(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_savedSurfaceDescValid(false), - d_name(name) -{ -} - -//----------------------------------------------------------------------------// -Direct3D9Texture::Direct3D9Texture(Direct3D9Renderer& owner, - const String& name, - const String& filename, - const String& resourceGroup) : - d_owner(owner), - d_texture(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_savedSurfaceDescValid(false), - d_name(name) -{ - loadFromFile(filename, resourceGroup); -} - -//----------------------------------------------------------------------------// -Direct3D9Texture::Direct3D9Texture(Direct3D9Renderer& owner, - const String& name, const Sizef& sz) : - d_owner(owner), - d_texture(0), - d_size(0, 0), - d_dataSize(sz), - d_texelScaling(0, 0), - d_savedSurfaceDescValid(false), - d_name(name) -{ - createDirect3D9Texture(sz, D3DFMT_A8R8G8B8); -} - -//----------------------------------------------------------------------------// -Direct3D9Texture::Direct3D9Texture(Direct3D9Renderer& owner, - const String& name, - LPDIRECT3DTEXTURE9 tex) : - d_owner(owner), - d_texture(0), - d_size(0, 0), - d_dataSize(0, 0), - d_texelScaling(0, 0), - d_savedSurfaceDescValid(false), - d_name(name) -{ - setDirect3D9Texture(tex); -} - -//----------------------------------------------------------------------------// -Direct3D9Texture::~Direct3D9Texture() -{ - cleanupDirect3D9Texture(); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::setDirect3D9Texture(LPDIRECT3DTEXTURE9 tex) -{ - if (d_texture != tex) - { - cleanupDirect3D9Texture(); - d_dataSize.d_width = d_dataSize.d_height = 0; - - d_texture = tex; - if (d_texture) - d_texture->AddRef(); - } - - updateTextureSize(); - d_dataSize = d_size; - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -LPDIRECT3DTEXTURE9 Direct3D9Texture::getDirect3D9Texture() const -{ - return d_texture; -} - -//----------------------------------------------------------------------------// -const String& Direct3D9Texture::getName() const -{ - return d_name; -} - -//----------------------------------------------------------------------------// -const Sizef& Direct3D9Texture::getSize() const -{ - return d_size; -} - -//----------------------------------------------------------------------------// -const Sizef& Direct3D9Texture::getOriginalDataSize() const -{ - return d_dataSize; -} - -//----------------------------------------------------------------------------// -const Vector2f& Direct3D9Texture::getTexelScaling() const -{ - return d_texelScaling; -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::loadFromFile(const String& filename, - const String& resourceGroup) -{ - // get and check existence of CEGUI::System object - System* sys = System::getSingletonPtr(); - if (!sys) - CEGUI_THROW(RendererException( - "CEGUI::System object has not been created!")); - - // load file to memory via resource provider - RawDataContainer texFile; - sys->getResourceProvider()->loadRawDataContainer(filename, texFile, - resourceGroup); - - Texture* res = sys->getImageCodec().load(texFile, this); - - // unload file data buffer - sys->getResourceProvider()->unloadRawDataContainer(texFile); - - if (!res) - // It's an error - CEGUI_THROW(RendererException( - sys->getImageCodec().getIdentifierString() + - " failed to load image '" + filename + "'.")); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::loadFromMemory(const void* buffer, - const Sizef& buffer_size, - PixelFormat pixel_format) -{ - if (!isPixelFormatSupported(pixel_format)) - CEGUI_THROW(InvalidRequestException( - "Data was supplied in an unsupported pixel format.")); - - const D3DFORMAT pixfmt = toD3DPixelFormat(pixel_format); - createDirect3D9Texture(buffer_size, pixfmt); - - LPDIRECT3DSURFACE9 surface = getTextureSurface(); - const PixelBuffer pixel_buffer(buffer, buffer_size, pixel_format); - - const RECT src_rect = { 0, 0, - static_cast(buffer_size.d_width), - static_cast(buffer_size.d_height) }; - - HRESULT hr = D3DXLoadSurfaceFromMemory( - surface, 0, 0, pixel_buffer.getPixelDataPtr(), - pixfmt == D3DFMT_X8R8G8B8 ? D3DFMT_R8G8B8 : pixfmt, - pixel_buffer.getPitch(), 0, &src_rect, D3DX_FILTER_NONE, 0); - - surface->Release(); - - if (FAILED(hr)) - CEGUI_THROW(RendererException( - "D3DXLoadSurfaceFromMemory failed.")); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::createDirect3D9Texture(const Sizef sz, D3DFORMAT format) -{ - cleanupDirect3D9Texture(); - - const Sizef tex_sz(d_owner.getAdjustedSize(sz)); - - HRESULT hr = D3DXCreateTexture(d_owner.getDevice(), - static_cast(tex_sz.d_width), - static_cast(tex_sz.d_height), - 1, 0, format, D3DPOOL_MANAGED, &d_texture); - - if (FAILED(hr)) - CEGUI_THROW(RendererException("D3DXCreateTexture failed.")); - - d_dataSize = sz; - updateTextureSize(); - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -IDirect3DSurface9* Direct3D9Texture::getTextureSurface() const -{ - LPDIRECT3DSURFACE9 surface; - HRESULT hr = d_texture->GetSurfaceLevel(0, &surface); - - if (FAILED(hr)) - CEGUI_THROW(RendererException( - "IDirect3DTexture9::GetSurfaceLevel failed.")); - - return surface; -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::blitFromMemory(const void* sourceData, const Rectf& area) -{ - D3DSurfaceBlitter blitter(d_owner.getDevice(), d_texture); - blitter.blitFromMemory(static_cast(sourceData), area); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::blitToMemory(void* targetData) -{ - D3DSurfaceBlitter blitter(d_owner.getDevice(), d_texture); - blitter.blitToMemory(static_cast(targetData)); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::cleanupDirect3D9Texture() -{ - if (d_texture) - { - d_texture->Release(); - d_texture = 0; - } -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::updateCachedScaleValues() -{ - // - // calculate what to use for x scale - // - const float orgW = d_dataSize.d_width; - const float texW = d_size.d_width; - - // if texture and original data width are the same, scale is based - // on the original size. - // if texture is wider (and source data was not stretched), scale - // is based on the size of the resulting texture. - d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); - - // - // calculate what to use for y scale - // - const float orgH = d_dataSize.d_height; - const float texH = d_size.d_height; - - // if texture and original data height are the same, scale is based - // on the original size. - // if texture is taller (and source data was not stretched), scale - // is based on the size of the resulting texture. - d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::updateTextureSize() -{ - D3DSURFACE_DESC surfDesc; - - // obtain details of the size of the texture - if (d_texture && SUCCEEDED(d_texture->GetLevelDesc(0, &surfDesc))) - { - d_size.d_width = static_cast(surfDesc.Width); - d_size.d_height = static_cast(surfDesc.Height); - } - // use the original size if query failed. - // NB: This should probably be an exception. - else - d_size = d_dataSize; -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::setOriginalDataSize(const Sizef& sz) -{ - d_dataSize = sz; - updateCachedScaleValues(); -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::preD3DReset() -{ - // if already saved surface info, or we have no texture, do nothing - if (d_savedSurfaceDescValid || !d_texture) - return; - - // get info about our texture - d_texture->GetLevelDesc(0, &d_savedSurfaceDesc); - - // if texture is managed, we have nothing more to do - if (d_savedSurfaceDesc.Pool == D3DPOOL_MANAGED) - return; - - // otherwise release texture. - d_texture->Release(); - d_texture = 0; - d_savedSurfaceDescValid = true; -} - -//----------------------------------------------------------------------------// -void Direct3D9Texture::postD3DReset() -{ - // if texture has no saved surface info, we do nothing. - if (!d_savedSurfaceDescValid) - return; - - // otherwise, create a new texture using saved details. - d_owner.getDevice()-> - CreateTexture(d_savedSurfaceDesc.Width, - d_savedSurfaceDesc.Height, - 1, d_savedSurfaceDesc.Usage, d_savedSurfaceDesc.Format, - d_savedSurfaceDesc.Pool, &d_texture, 0); - - d_savedSurfaceDescValid = false; -} - -//----------------------------------------------------------------------------// -bool Direct3D9Texture::isPixelFormatSupported(const PixelFormat fmt) const -{ - D3DDEVICE_CREATION_PARAMETERS dev_params; - d_owner.getDevice()->GetCreationParameters(&dev_params); - - LPDIRECT3D9 d3d; - d_owner.getDevice()->GetDirect3D(&d3d); - - D3DDISPLAYMODE dmode; - d3d->GetAdapterDisplayMode(dev_params.AdapterOrdinal, &dmode); - - const D3DFORMAT d3d_format = toD3DPixelFormat(fmt); - - if (d3d_format == D3DFMT_UNKNOWN) - return false; - - return SUCCEEDED(d3d->CheckDeviceFormat( - dev_params.AdapterOrdinal, dev_params.DeviceType, - dmode.Format, 0, D3DRTYPE_TEXTURE, d3d_format)); -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Direct3D9/TextureTarget.cpp b/cegui/src/RendererModules/Direct3D9/TextureTarget.cpp deleted file mode 100644 index 5de54cb99..000000000 --- a/cegui/src/RendererModules/Direct3D9/TextureTarget.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/*********************************************************************** - created: Fri Feb 13 2009 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D9/TextureTarget.h" -#include "CEGUI/Exceptions.h" -#include "CEGUI/Logger.h" -#include "CEGUI/RenderQueue.h" -#include "CEGUI/GeometryBuffer.h" -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" -#include "CEGUI/RendererModules/Direct3D9/Texture.h" -#include "CEGUI/PropertyHelper.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -const float Direct3D9TextureTarget::DEFAULT_SIZE = 128.0f; -uint Direct3D9TextureTarget::s_textureNumber = 0; - -//----------------------------------------------------------------------------// -Direct3D9TextureTarget::Direct3D9TextureTarget(Direct3D9Renderer& owner) : - Direct3D9RenderTarget(owner), - d_texture(0), - d_surface(0) -{ - // this essentially creates a 'null' CEGUI::Texture - d_CEGUITexture = &static_cast( - d_owner.createTexture(generateTextureName(), 0)); - - // setup area and cause the initial texture to be generated. - declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE)); -} - -//----------------------------------------------------------------------------// -Direct3D9TextureTarget::~Direct3D9TextureTarget() -{ - cleanupRenderTexture(); - d_owner.destroyTexture(*d_CEGUITexture); -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::declareRenderSize(const Sizef& sz) -{ - // exit if current size is enough - if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height)) - return; - - setArea(Rectf(d_area.getPosition(), sz)); - resizeRenderTexture(); - clear(); -} - -//----------------------------------------------------------------------------// -bool Direct3D9TextureTarget::isImageryCache() const -{ - return true; -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::activate() -{ - enableRenderTexture(); - Direct3D9RenderTarget::activate(); -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::deactivate() -{ - Direct3D9RenderTarget::deactivate(); - disableRenderTexture(); -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::clear() -{ - // switch to targetting our texture - enableRenderTexture(); - // Clear it. - d_device->Clear(0, 0, D3DCLEAR_TARGET, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0f, 0); - // switch back to rendering to previous target - disableRenderTexture(); -} - -//----------------------------------------------------------------------------// -Texture& Direct3D9TextureTarget::getTexture() const -{ - return *d_CEGUITexture; -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::initialiseRenderTexture() -{ - Sizef tex_sz(d_owner.getAdjustedSize(d_area.getSize())); - - d_device->CreateTexture(static_cast(tex_sz.d_width), - static_cast(tex_sz.d_height), - 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, - D3DPOOL_DEFAULT, &d_texture, 0); - - d_texture->GetSurfaceLevel(0, &d_surface); - - // wrap the created texture with the CEGUI::Texture - d_CEGUITexture->setDirect3D9Texture(d_texture); - d_CEGUITexture->setOriginalDataSize(d_area.getSize()); -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::resizeRenderTexture() -{ - cleanupRenderTexture(); - initialiseRenderTexture(); -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::cleanupRenderTexture() -{ - if (d_surface) - { - d_surface->Release(); - d_surface = 0; - } - if (d_texture) - { - d_CEGUITexture->setDirect3D9Texture(0); - d_texture->Release(); - d_texture = 0; - } -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::enableRenderTexture() -{ - LPDIRECT3DSURFACE9 oldSurface = 0; - d_device->GetRenderTarget(0, &oldSurface); - - if (oldSurface && oldSurface != d_surface) - { - d_prevColourSurface = oldSurface; - d_device->SetRenderTarget(0, d_surface); - } - else if (oldSurface) - oldSurface->Release(); -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::disableRenderTexture() -{ - d_device->SetRenderTarget(0, d_prevColourSurface); - - if (d_prevColourSurface) - { - d_prevColourSurface->Release(); - d_prevColourSurface = 0; - } -} - -//----------------------------------------------------------------------------// -bool Direct3D9TextureTarget::isRenderingInverted() const -{ - return false; -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::preD3DReset() -{ - if (d_surface) - { - d_surface->Release(); - d_surface = 0; - } - - if (d_CEGUITexture) - d_CEGUITexture->preD3DReset(); - - if (d_texture) - { - d_texture->Release(); - d_texture = 0; - } -} - -//----------------------------------------------------------------------------// -void Direct3D9TextureTarget::postD3DReset() -{ - if (!d_CEGUITexture) - return; - - // this will recreate the texture - d_CEGUITexture->postD3DReset(); - // we now obtain a reference to that created texture - d_texture = d_CEGUITexture->getDirect3D9Texture(); - if (d_texture) - { - d_texture->AddRef(); - // now obtain the surface - d_texture->GetSurfaceLevel(0, &d_surface); - } -} - -//----------------------------------------------------------------------------// -String Direct3D9TextureTarget::generateTextureName() -{ - String tmp("_d3d9_tt_tex_"); - tmp.append(PropertyHelper::toString(s_textureNumber++)); - - return tmp; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section - -//----------------------------------------------------------------------------// -// Implementation of template base class -#include "./RenderTarget.inl" - diff --git a/cegui/src/RendererModules/DirectFB/GeometryBuffer.cpp b/cegui/src/RendererModules/DirectFB/GeometryBuffer.cpp index f00dd5646..a0e27ed93 100644 --- a/cegui/src/RendererModules/DirectFB/GeometryBuffer.cpp +++ b/cegui/src/RendererModules/DirectFB/GeometryBuffer.cpp @@ -103,21 +103,21 @@ void DirectFBGeometryBuffer::draw() const } //----------------------------------------------------------------------------// -void DirectFBGeometryBuffer::setTranslation(const Vector3f& v) +void DirectFBGeometryBuffer::setTranslation(const glm::vec3& v) { d_translation = v; d_matrixValid = false; } //----------------------------------------------------------------------------// -void DirectFBGeometryBuffer::setRotation(const Quaternion& r) +void DirectFBGeometryBuffer::setRotation(const glm::quat& r) { d_rotation = r; d_matrixValid = false; } //----------------------------------------------------------------------------// -void DirectFBGeometryBuffer::setPivot(const Vector3f& p) +void DirectFBGeometryBuffer::setPivot(const glm::vec3& p) { d_pivot = p; d_matrixValid = false; diff --git a/cegui/src/RendererModules/DirectFB/RenderTarget.cpp b/cegui/src/RendererModules/DirectFB/RenderTarget.cpp index 4499cff2c..d4078aad0 100644 --- a/cegui/src/RendererModules/DirectFB/RenderTarget.cpp +++ b/cegui/src/RendererModules/DirectFB/RenderTarget.cpp @@ -91,7 +91,7 @@ void DirectFBRenderTarget::deactivate() //----------------------------------------------------------------------------// void DirectFBRenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const + const glm::vec2& p_in, glm::vec2& p_out) const { // TODO: p_out = p_in; diff --git a/cegui/src/RendererModules/DirectFB/Renderer.cpp b/cegui/src/RendererModules/DirectFB/Renderer.cpp index 9529b3f71..aa64617da 100644 --- a/cegui/src/RendererModules/DirectFB/Renderer.cpp +++ b/cegui/src/RendererModules/DirectFB/Renderer.cpp @@ -286,7 +286,7 @@ const Sizef& DirectFBRenderer::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& DirectFBRenderer::getDisplayDPI() const +const glm::vec2& DirectFBRenderer::getDisplayDPI() const { return d_displayDPI; } diff --git a/cegui/src/RendererModules/DirectFB/Texture.cpp b/cegui/src/RendererModules/DirectFB/Texture.cpp index 9c9c5538c..4328ad00a 100644 --- a/cegui/src/RendererModules/DirectFB/Texture.cpp +++ b/cegui/src/RendererModules/DirectFB/Texture.cpp @@ -57,7 +57,7 @@ const Sizef& DirectFBTexture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& DirectFBTexture::getTexelScaling() const +const glm::vec2& DirectFBTexture::getTexelScaling() const { return d_texelScaling; } diff --git a/cegui/src/RendererModules/Irrlicht/GeometryBuffer.cpp b/cegui/src/RendererModules/Irrlicht/GeometryBuffer.cpp index 2d47f76c5..3111d71d9 100644 --- a/cegui/src/RendererModules/Irrlicht/GeometryBuffer.cpp +++ b/cegui/src/RendererModules/Irrlicht/GeometryBuffer.cpp @@ -32,7 +32,6 @@ #include "CEGUI/RenderEffect.h" #include "CEGUI/RendererModules/Irrlicht/Texture.h" #include "CEGUI/Vertex.h" -#include "CEGUI/Quaternion.h" // Start of CEGUI namespace section namespace CEGUI @@ -149,30 +148,30 @@ void IrrlichtGeometryBuffer::cleanupClipping() const } //----------------------------------------------------------------------------// -void IrrlichtGeometryBuffer::setTranslation(const Vector3f& v) +void IrrlichtGeometryBuffer::setTranslation(const glm::vec3& v) { - d_translation.X = v.d_x; - d_translation.Y = v.d_y; - d_translation.Z = v.d_z; + d_translation.X = v.x; + d_translation.Y = v.y; + d_translation.Z = v.z; d_matrixValid = false; } //----------------------------------------------------------------------------// -void IrrlichtGeometryBuffer::setRotation(const Quaternion& r) +void IrrlichtGeometryBuffer::setRotation(const glm::quat& r) { - d_rotation.W = -r.d_w; - d_rotation.X = r.d_x; - d_rotation.Y = r.d_y; - d_rotation.Z = r.d_z; + d_rotation.W = -r.w; + d_rotation.X = r.x; + d_rotation.Y = r.y; + d_rotation.Z = r.z; d_matrixValid = false; } //----------------------------------------------------------------------------// -void IrrlichtGeometryBuffer::setPivot(const Vector3f& p) +void IrrlichtGeometryBuffer::setPivot(const glm::vec3& p) { - d_pivot.X = p.d_x; - d_pivot.Y = p.d_y; - d_pivot.Z = p.d_z; + d_pivot.X = p.x; + d_pivot.Y = p.y; + d_pivot.Z = p.z; d_matrixValid = false; } diff --git a/cegui/src/RendererModules/Irrlicht/RenderTarget.inl b/cegui/src/RendererModules/Irrlicht/RenderTarget.inl index d7ad50f9c..8abab44aa 100644 --- a/cegui/src/RendererModules/Irrlicht/RenderTarget.inl +++ b/cegui/src/RendererModules/Irrlicht/RenderTarget.inl @@ -113,8 +113,8 @@ void IrrlichtRenderTarget::deactivate() //----------------------------------------------------------------------------// template void IrrlichtRenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const + const glm::vec& p_in, + glm::vec& p_out) const { if (!d_matrixValid) updateMatrix(); diff --git a/cegui/src/RendererModules/Irrlicht/Renderer.cpp b/cegui/src/RendererModules/Irrlicht/Renderer.cpp index b36629a14..4fd125a1e 100644 --- a/cegui/src/RendererModules/Irrlicht/Renderer.cpp +++ b/cegui/src/RendererModules/Irrlicht/Renderer.cpp @@ -342,7 +342,7 @@ const Sizef& IrrlichtRenderer::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& IrrlichtRenderer::getDisplayDPI() const +const glm::vec2& IrrlichtRenderer::getDisplayDPI() const { return d_displayDPI; } diff --git a/cegui/src/RendererModules/Irrlicht/Texture.cpp b/cegui/src/RendererModules/Irrlicht/Texture.cpp index 26fc7da00..a1632df0b 100644 --- a/cegui/src/RendererModules/Irrlicht/Texture.cpp +++ b/cegui/src/RendererModules/Irrlicht/Texture.cpp @@ -80,7 +80,7 @@ const Sizef& IrrlichtTexture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& IrrlichtTexture::getTexelScaling() const +const glm::vec2& IrrlichtTexture::getTexelScaling() const { return d_texelScaling; } @@ -358,7 +358,7 @@ void IrrlichtTexture::updateCachedScaleValues() // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. - d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); + d_texelScaling.x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale @@ -370,7 +370,7 @@ void IrrlichtTexture::updateCachedScaleValues() // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. - d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); + d_texelScaling.y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RendererModules/Null/GeometryBuffer.cpp b/cegui/src/RendererModules/Null/GeometryBuffer.cpp index 7284f932e..e3370c24c 100644 --- a/cegui/src/RendererModules/Null/GeometryBuffer.cpp +++ b/cegui/src/RendererModules/Null/GeometryBuffer.cpp @@ -33,14 +33,8 @@ namespace CEGUI { //----------------------------------------------------------------------------// -NullGeometryBuffer::NullGeometryBuffer() : - d_activeTexture(0), - d_clipRect(0, 0, 0, 0), - d_clippingActive(true), - d_translation(0, 0, 0), - d_rotation(), - d_pivot(0, 0, 0), - d_effect(0) +NullGeometryBuffer::NullGeometryBuffer(CEGUI::RefCounted renderMaterial) + : GeometryBuffer(renderMaterial) { } @@ -65,24 +59,6 @@ void NullGeometryBuffer::draw() const d_effect->performPostRenderFunctions(); } -//----------------------------------------------------------------------------// -void NullGeometryBuffer::setTranslation(const Vector3f& v) -{ - d_translation = v; -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::setRotation(const Quaternion& r) -{ - d_rotation = r; -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::setPivot(const Vector3f& p) -{ - d_pivot = p; -} - //----------------------------------------------------------------------------// void NullGeometryBuffer::setClippingRegion(const Rectf& region) { @@ -93,74 +69,11 @@ void NullGeometryBuffer::setClippingRegion(const Rectf& region) } //----------------------------------------------------------------------------// -void NullGeometryBuffer::appendVertex(const Vertex& vertex) -{ - appendGeometry(&vertex, 1); -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::appendGeometry(const Vertex* const vbuff, - uint vertex_count) -{ - // buffer these vertices - for (uint i = 0; i < vertex_count; ++i) - { - d_vertices.push_back(vbuff[i]); - } -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::setActiveTexture(Texture* texture) -{ - d_activeTexture = static_cast(texture); -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::reset() -{ - d_vertices.clear(); -} - -//----------------------------------------------------------------------------// -Texture* NullGeometryBuffer::getActiveTexture() const -{ - return d_activeTexture; -} - -//----------------------------------------------------------------------------// -uint NullGeometryBuffer::getVertexCount() const -{ - return d_vertices.size(); -} - -//----------------------------------------------------------------------------// -uint NullGeometryBuffer::getBatchCount() const -{ - return 1; -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::setRenderEffect(RenderEffect* effect) -{ - d_effect = effect; -} - -//----------------------------------------------------------------------------// -RenderEffect* NullGeometryBuffer::getRenderEffect() -{ - return d_effect; -} - -//----------------------------------------------------------------------------// -void NullGeometryBuffer::setClippingActive(const bool active) -{ - d_clippingActive = active; -} - -//----------------------------------------------------------------------------// -bool NullGeometryBuffer::isClippingActive() const +void NullGeometryBuffer::appendGeometry(const std::vector& vertex_data) { - return d_clippingActive; + d_vertexData.insert(d_vertexData.end(), vertex_data.begin(), vertex_data.end()); + // Update size of geometry buffer + d_vertexCount = d_vertexData.size(); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RendererModules/Null/RenderTarget.inl b/cegui/src/RendererModules/Null/RenderTarget.inl index 0a7ef6e90..b9aadf11d 100644 --- a/cegui/src/RendererModules/Null/RenderTarget.inl +++ b/cegui/src/RendererModules/Null/RenderTarget.inl @@ -25,8 +25,6 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/Null/RenderTarget.h" -#include "CEGUI/GeometryBuffer.h" -#include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/Null/GeometryBuffer.h" // Start of CEGUI namespace section @@ -35,8 +33,7 @@ namespace CEGUI //----------------------------------------------------------------------------// template NullRenderTarget::NullRenderTarget(NullRenderer& owner) : - d_owner(owner), - d_area(0, 0, 0, 0) + d_owner(owner) { } @@ -46,53 +43,17 @@ NullRenderTarget::~NullRenderTarget() { } -//----------------------------------------------------------------------------// -template -void NullRenderTarget::draw(const GeometryBuffer& buffer) -{ - buffer.draw(); -} - -//----------------------------------------------------------------------------// -template -void NullRenderTarget::draw(const RenderQueue& queue) -{ - queue.draw(); -} - -//----------------------------------------------------------------------------// -template -void NullRenderTarget::setArea(const Rectf& area) -{ - d_area = area; - - RenderTargetEventArgs args(this); - T::fireEvent(RenderTarget::EventAreaChanged, args); -} - -//----------------------------------------------------------------------------// -template -const Rectf& NullRenderTarget::getArea() const -{ - return d_area; -} - //----------------------------------------------------------------------------// template void NullRenderTarget::activate() -{ -} - -//----------------------------------------------------------------------------// -template -void NullRenderTarget::deactivate() -{ +{ + RenderTarget::activate(); } //----------------------------------------------------------------------------// template void NullRenderTarget::unprojectPoint(const GeometryBuffer&, - const Vector2f& p_in, Vector2f& p_out) const + const glm::vec2& p_in, glm::vec2& p_out) const { p_out = p_in; } @@ -104,4 +65,12 @@ bool NullRenderTarget::isImageryCache() const return false; } +//----------------------------------------------------------------------------// +template +NullRenderer& NullRenderTarget::getOwner() +{ + return d_owner; +} + + } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Null/Renderer.cpp b/cegui/src/RendererModules/Null/Renderer.cpp index 7ee245c90..e3a1d54d0 100644 --- a/cegui/src/RendererModules/Null/Renderer.cpp +++ b/cegui/src/RendererModules/Null/Renderer.cpp @@ -28,6 +28,7 @@ #include "CEGUI/RendererModules/Null/GeometryBuffer.h" #include "CEGUI/RendererModules/Null/TextureTarget.h" #include "CEGUI/RendererModules/Null/Texture.h" +#include "CEGUI/RendererModules/Null/ShaderWrapper.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" @@ -54,7 +55,7 @@ NullRenderer& NullRenderer::bootstrapSystem(const int abi) NullRenderer& renderer = create(); - DefaultResourceProvider* rp(CEGUI_NEW_AO DefaultResourceProvider()); + DefaultResourceProvider* rp(new DefaultResourceProvider()); // TODO: Create image codec? // NullImageCodec& ic = createNullImageCodec(); @@ -79,8 +80,8 @@ void NullRenderer::destroySystem() System::destroy(); // ImageCodec used is currently the system default, so we do not destroy // it here (since System already did that). - //CEGUI_DELETE_AO ic; - CEGUI_DELETE_AO rp; + //delete ic; + delete rp; destroy(*renderer); } @@ -89,13 +90,13 @@ NullRenderer& NullRenderer::create(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO NullRenderer(); + return *(new NullRenderer()); } //----------------------------------------------------------------------------// void NullRenderer::destroy(NullRenderer& renderer) { - CEGUI_DELETE_AO &renderer; + delete &renderer; } //----------------------------------------------------------------------------// @@ -105,39 +106,58 @@ RenderTarget& NullRenderer::getDefaultRenderTarget() } //----------------------------------------------------------------------------// -GeometryBuffer& NullRenderer::createGeometryBuffer() +RefCounted NullRenderer::createRenderMaterial(const DefaultShaderType shaderType) const { - NullGeometryBuffer* gb = CEGUI_NEW_AO NullGeometryBuffer(); + if(shaderType == DS_TEXTURED) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperTextured)); + + return render_material; + } + else if(shaderType == DS_SOLID) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperSolid)); - d_geometryBuffers.push_back(gb); - return *gb; + return render_material; + } + else + { + CEGUI_THROW(RendererException( + "A default shader of this type does not exist.")); + + return RefCounted(); + } } //----------------------------------------------------------------------------// -void NullRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) +GeometryBuffer& NullRenderer::createGeometryBufferTextured(RefCounted renderMaterial) { - GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), - d_geometryBuffers.end(), - &buffer); + NullGeometryBuffer* geom_buffer = new NullGeometryBuffer(renderMaterial); - if (d_geometryBuffers.end() != i) - { - d_geometryBuffers.erase(i); - CEGUI_DELETE_AO &buffer; - } + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->addVertexAttribute(VAT_TEXCOORD0); + + addGeometryBuffer(*geom_buffer); + return *geom_buffer; } //----------------------------------------------------------------------------// -void NullRenderer::destroyAllGeometryBuffers() +GeometryBuffer& NullRenderer::createGeometryBufferColoured(RefCounted renderMaterial) { - while (!d_geometryBuffers.empty()) - destroyGeometryBuffer(**d_geometryBuffers.begin()); + NullGeometryBuffer* geom_buffer = new NullGeometryBuffer(renderMaterial); + + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + + addGeometryBuffer(*geom_buffer); + return *geom_buffer; } //----------------------------------------------------------------------------// TextureTarget* NullRenderer::createTextureTarget() { - TextureTarget* tt = CEGUI_NEW_AO NullTextureTarget(*this); + TextureTarget* tt = new NullTextureTarget(*this); d_textureTargets.push_back(tt); return tt; } @@ -152,7 +172,7 @@ void NullRenderer::destroyTextureTarget(TextureTarget* target) if (d_textureTargets.end() != i) { d_textureTargets.erase(i); - CEGUI_DELETE_AO target; + delete target; } } @@ -168,7 +188,7 @@ Texture& NullRenderer::createTexture(const String& name) { throwIfNameExists(name); - NullTexture* t = CEGUI_NEW_AO NullTexture(name); + NullTexture* t = new NullTexture(name); d_textures[name] = t; logTextureCreation(name); @@ -182,7 +202,7 @@ Texture& NullRenderer::createTexture(const String& name, const String& filename, { throwIfNameExists(name); - NullTexture* t = CEGUI_NEW_AO NullTexture(name, filename, resourceGroup); + NullTexture* t = new NullTexture(name, filename, resourceGroup); d_textures[name] = t; logTextureCreation(name); @@ -195,7 +215,7 @@ Texture& NullRenderer::createTexture(const String& name, const Sizef& size) { throwIfNameExists(name); - NullTexture* t = CEGUI_NEW_AO NullTexture(name, size); + NullTexture* t = new NullTexture(name, size); d_textures[name] = t; logTextureCreation(name); @@ -233,7 +253,7 @@ void NullRenderer::destroyTexture(const String& name) if (d_textures.end() != i) { logTextureDestruction(name); - CEGUI_DELETE_AO i->second; + delete i->second; d_textures.erase(i); } } @@ -288,7 +308,7 @@ const Sizef& NullRenderer::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& NullRenderer::getDisplayDPI() const +const glm::vec2& NullRenderer::getDisplayDPI() const { return d_displayDPI; } @@ -317,6 +337,9 @@ NullRenderer::NullRenderer() : //----------------------------------------------------------------------------// NullRenderer::~NullRenderer() { + delete d_shaderWrapperTextured; + delete d_shaderWrapperSolid; + destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); @@ -327,8 +350,11 @@ NullRenderer::~NullRenderer() //----------------------------------------------------------------------------// void NullRenderer::constructor_impl() { + d_shaderWrapperTextured = new NullShaderWrapper(); + d_shaderWrapperSolid = new NullShaderWrapper(); + // create default target & rendering root (surface) that uses it - d_defaultTarget = CEGUI_NEW_AO NullRenderTarget<>(*this); + d_defaultTarget = new NullRenderTarget<>(*this); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RendererModules/Null/ShaderWrapper.cpp b/cegui/src/RendererModules/Null/ShaderWrapper.cpp new file mode 100644 index 000000000..662c5cc05 --- /dev/null +++ b/cegui/src/RendererModules/Null/ShaderWrapper.cpp @@ -0,0 +1,50 @@ +/*********************************************************************** + created: 7th December 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/Null/ShaderWrapper.h" +#include "CEGUI/ShaderParameterBindings.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +NullShaderWrapper::NullShaderWrapper() +{ +} + +//----------------------------------------------------------------------------// +NullShaderWrapper::~NullShaderWrapper() +{ +} + +//----------------------------------------------------------------------------// +void NullShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) +{ +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/RendererModules/Null/Texture.cpp b/cegui/src/RendererModules/Null/Texture.cpp index 0f5400bae..9508779a2 100644 --- a/cegui/src/RendererModules/Null/Texture.cpp +++ b/cegui/src/RendererModules/Null/Texture.cpp @@ -54,7 +54,7 @@ const Sizef& NullTexture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& NullTexture::getTexelScaling() const +const glm::vec2& NullTexture::getTexelScaling() const { return d_texelScaling; } diff --git a/cegui/src/RendererModules/Null/TextureTarget.cpp b/cegui/src/RendererModules/Null/TextureTarget.cpp index 7c3b298b5..099b3abe0 100644 --- a/cegui/src/RendererModules/Null/TextureTarget.cpp +++ b/cegui/src/RendererModules/Null/TextureTarget.cpp @@ -75,7 +75,7 @@ void NullTextureTarget::declareRenderSize(const Sizef& sz) { Rectf r; r.setSize(sz); - r.setPosition(Vector2f(0, 0)); + r.setPosition(glm::vec2(0, 0)); setArea(r); } diff --git a/cegui/src/RendererModules/Ogre/GeometryBuffer.cpp b/cegui/src/RendererModules/Ogre/GeometryBuffer.cpp index 93ffdfe3b..e8e4edd3a 100644 --- a/cegui/src/RendererModules/Ogre/GeometryBuffer.cpp +++ b/cegui/src/RendererModules/Ogre/GeometryBuffer.cpp @@ -1,6 +1,6 @@ /*********************************************************************** created: Tue Feb 17 2009 - author: Paul D Turner + author: Henri I Hyyryläinen (based on code by Paul D Turner) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team @@ -26,124 +26,88 @@ ***************************************************************************/ #include "CEGUI/RendererModules/Ogre/GeometryBuffer.h" #include "CEGUI/RendererModules/Ogre/Texture.h" +#include "CEGUI/RendererModules/Ogre/ShaderWrapper.h" #include "CEGUI/Vertex.h" #include "CEGUI/RenderEffect.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/ShaderParameterBindings.h" #include -#include #include +#include +#include +#include +#include -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -static const Ogre::LayerBlendModeEx S_colourBlendMode = -{ - Ogre::LBT_COLOUR, - Ogre::LBX_MODULATE, - Ogre::LBS_TEXTURE, - Ogre::LBS_DIFFUSE, - Ogre::ColourValue(0, 0, 0, 0), - Ogre::ColourValue(0, 0, 0, 0), - 0, 0, 0 -}; - -//----------------------------------------------------------------------------// -static const Ogre::LayerBlendModeEx S_alphaBlendMode = -{ - Ogre::LBT_ALPHA, - Ogre::LBX_MODULATE, - Ogre::LBS_TEXTURE, - Ogre::LBS_DIFFUSE, - Ogre::ColourValue(0, 0, 0, 0), - Ogre::ColourValue(0, 0, 0, 0), - 0, 0, 0 -}; - -//----------------------------------------------------------------------------// -static const Ogre::TextureUnitState::UVWAddressingMode S_textureAddressMode = -{ - Ogre::TextureUnitState::TAM_CLAMP, - Ogre::TextureUnitState::TAM_CLAMP, - Ogre::TextureUnitState::TAM_CLAMP -}; - -//----------------------------------------------------------------------------// -// Helper to allocate a vertex buffer and initialse a Ogre::RenderOperation -static void initialiseRenderOp(Ogre::RenderOperation& rop, - Ogre::HardwareVertexBufferSharedPtr& vb, - size_t count) -{ - using namespace Ogre; - - // basic initialisation of render op - rop.vertexData = OGRE_NEW VertexData(); - rop.operationType = RenderOperation::OT_TRIANGLE_LIST; - rop.useIndexes = false; - - // setup vertex declaration for format we will use - VertexDeclaration* vd = rop.vertexData->vertexDeclaration; - size_t vd_offset = 0; - vd->addElement(0, vd_offset, VET_FLOAT3, VES_POSITION); - vd_offset += VertexElement::getTypeSize(VET_FLOAT3); - vd->addElement(0, vd_offset, VET_COLOUR, VES_DIFFUSE); - vd_offset += VertexElement::getTypeSize(VET_COLOUR); - vd->addElement(0, vd_offset, VET_FLOAT2, VES_TEXTURE_COORDINATES); - - // create hardware vertex buffer - vb = HardwareBufferManager::getSingleton().createVertexBuffer( - vd->getVertexSize(0), count, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, - false); +#include "glm/glm.hpp" +#include "glm/gtc/quaternion.hpp" +#include "glm/gtc/type_ptr.hpp" - // bind vertex buffer - rop.vertexData->vertexBufferBinding->setBinding(0, vb); -} +#define FLOATS_PER_TEXTURED 9 +#define FLOATS_PER_COLOURED 7 -//----------------------------------------------------------------------------// -// Helper to cleanup what initialiseRenderOp did. -static void cleanupRenderOp(Ogre::RenderOperation& rop, - Ogre::HardwareVertexBufferSharedPtr& vb) +// Start of CEGUI namespace section +namespace CEGUI { - OGRE_DELETE rop.vertexData; - rop.vertexData = 0; - vb.setNull(); -} -//----------------------------------------------------------------------------// -OgreGeometryBuffer::OgreGeometryBuffer(OgreRenderer& owner, - Ogre::RenderSystem& rs) : +OgreGeometryBuffer::OgreGeometryBuffer(OgreRenderer& owner, + Ogre::RenderSystem& rs, CEGUI::RefCounted renderMaterial) : + GeometryBuffer(renderMaterial), d_owner(owner), d_renderSystem(rs), - d_activeTexture(0), d_clipRect(0, 0, 0, 0), - d_clippingActive(true), - d_translation(0, 0, 0), - d_rotation(Quaternion::IDENTITY), - d_pivot(0, 0, 0), - d_effect(0), - d_texelOffset(rs.getHorizontalTexelOffset(), rs.getVerticalTexelOffset()), - d_matrixValid(false), - d_sync(false) + d_expectedData(MT_INVALID), + d_dataAppended(false), + d_matrix(1.0), + d_previousAlphaValue(-1.f) { - initialiseRenderOp(d_renderOp, d_hwBuffer, 64); + } //----------------------------------------------------------------------------// OgreGeometryBuffer::~OgreGeometryBuffer() { - cleanupRenderOp(d_renderOp, d_hwBuffer); + cleanUpVertexAttributes(); } //----------------------------------------------------------------------------// void OgreGeometryBuffer::draw() const { - if (!d_sync) - syncHardwareBuffer(); + if (d_vertexData.empty()) + return; + + if (d_dataAppended) + syncVertexData(); + + if (d_hwBuffer.isNull()) + return; + + // setup clip region + if (d_clippingActive) + { + setScissorRects(); + } + + // Update the matrix + updateMatrix(); - d_owner.setWorldMatrix(getMatrix()); - d_owner.setupRenderingBlendMode(d_blendMode); - d_owner.updateShaderParams(); + CEGUI::ShaderParameterBindings* shaderParameterBindings = + (*d_renderMaterial).getShaderParamBindings(); + + // Set the ModelViewProjection matrix in the bindings + shaderParameterBindings->setParameter("modelViewProjMatrix", d_matrix); + + + if (d_alpha != d_previousAlphaValue) + { + d_previousAlphaValue = d_alpha; + + shaderParameterBindings->setParameter("alphaPercentage", + d_previousAlphaValue); + } + + // activate the desired blending mode + d_owner.bindBlendMode(d_blendMode); const int pass_count = d_effect ? d_effect->getPassCount() : 1; for (int pass = 0; pass < pass_count; ++pass) @@ -152,49 +116,24 @@ void OgreGeometryBuffer::draw() const if (d_effect) d_effect->performPreRenderFunctions(pass); - // draw the batches - size_t pos = 0; - BatchList::const_iterator i = d_batches.begin(); - for ( ; i != d_batches.end(); ++i) - { - // Set up clipping for this buffer - d_renderSystem.setScissorTest( - i->clip, d_clipRect.left(), d_clipRect.top(), - d_clipRect.right(), d_clipRect.bottom()); - - d_renderOp.vertexData->vertexStart = pos; - d_renderOp.vertexData->vertexCount = i->vertexCount; - d_renderSystem._setTexture(0, true, i->texture); - initialiseTextureStates(); - d_renderSystem._render(d_renderOp); - pos += i->vertexCount; - } + //Prepare for the rendering process according to the used render material + d_renderMaterial->prepareForRendering(); + + // draw the geometry + d_renderSystem._render(d_renderOp); } // clean up RenderEffect if (d_effect) d_effect->performPostRenderFunctions(); -} - -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::setTranslation(const Vector3f& v) -{ - d_translation = v; - d_matrixValid = false; -} -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::setRotation(const Quaternion& r) -{ - d_rotation = r; - d_matrixValid = false; -} + // Disable clipping after rendering + if (d_clippingActive) + { + d_renderSystem.setScissorTest(false); + } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::setPivot(const Vector3f& p) -{ - d_pivot = p; - d_matrixValid = false; + updateRenderTargetData(d_owner.getActiveRenderTarget()); } //----------------------------------------------------------------------------// @@ -207,197 +146,192 @@ void OgreGeometryBuffer::setClippingRegion(const Rectf& region) } //----------------------------------------------------------------------------// -void OgreGeometryBuffer::appendVertex(const Vertex& vertex) +void OgreGeometryBuffer::appendGeometry(const float* vertex_data, std::size_t array_size) { - appendGeometry(&vertex, 1); + GeometryBuffer::appendGeometry(vertex_data, array_size); + + d_dataAppended = true; } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::appendGeometry(const Vertex* const vbuff, - uint vertex_count) +void OgreGeometryBuffer::syncVertexData() const { - // see if we should start a new batch - Ogre::TexturePtr t; - if (d_activeTexture) - t = d_activeTexture->getOgreTexture(); - - if (d_batches.empty() || - d_batches.back().texture != t || - d_batches.back().clip != d_clippingActive) - { - const BatchInfo batch = {t, 0, d_clippingActive}; - d_batches.push_back(batch); - } + if (!d_dataAppended) + return; - // update size of current batch - d_batches.back().vertexCount += vertex_count; + // Make sure that our vertex buffer is large enough + size_t current_size; - // buffer these vertices - OgreVertex v; - for (uint i = 0; i < vertex_count; ++i) + if (!d_hwBuffer.isNull() && + (current_size = d_hwBuffer->getNumVertices()) < d_vertexCount) { - const Vertex& vs = vbuff[i]; - // convert from CEGUI::Vertex to something directly usable by Ogre. - v.x = vs.position.d_x + d_texelOffset.d_x; - v.y = vs.position.d_y + d_texelOffset.d_y; - v.z = vs.position.d_z; - v.diffuse = colourToOgre(vs.colour_val); - v.u = vs.tex_coords.d_x; - v.v = vs.tex_coords.d_y; - - d_vertices.push_back(v); + size_t new_size = current_size; + + // Reallocate the buffer to be large enough + while(new_size < d_vertexCount) + new_size *= 2; + + setVertexBuffer(new_size); } - d_sync = false; -} + // copy vertex data into the Ogre hardware buffer + if (d_vertexCount > 0) + { + if (d_hwBuffer.isNull()) + { -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::setActiveTexture(Texture* texture) -{ - d_activeTexture = static_cast(texture); -} + setVertexBuffer(d_vertexCount); + } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::reset() -{ - d_vertices.clear(); - d_batches.clear(); - d_activeTexture = 0; - d_sync = false; -} + void* copy_target = d_hwBuffer->lock( + Ogre::HardwareVertexBuffer::HBL_DISCARD); -//----------------------------------------------------------------------------// -Texture* OgreGeometryBuffer::getActiveTexture() const -{ - return d_activeTexture; -} + assert(copy_target && "Ogre vertex buffer is invalid"); -//----------------------------------------------------------------------------// -uint OgreGeometryBuffer::getVertexCount() const -{ - return d_vertices.size(); -} + std::memcpy(copy_target, &d_vertexData[0], d_vertexData.size()* + sizeof(float)); -//----------------------------------------------------------------------------// -uint OgreGeometryBuffer::getBatchCount() const -{ - return d_batches.size(); -} + d_hwBuffer->unlock(); + } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::setRenderEffect(RenderEffect* effect) -{ - d_effect = effect; -} + // Update rendering for the new vertices + d_renderOp.vertexData->vertexStart = 0; + d_renderOp.vertexData->vertexCount = d_vertexCount; -//----------------------------------------------------------------------------// -RenderEffect* OgreGeometryBuffer::getRenderEffect() -{ - return d_effect; + d_dataAppended = false; } //----------------------------------------------------------------------------// -Ogre::RGBA OgreGeometryBuffer::colourToOgre(const Colour& col) const +void OgreGeometryBuffer::updateMatrix() const { - Ogre::ColourValue ocv(col.getRed(), - col.getGreen(), - col.getBlue(), - col.getAlpha()); + d_matrixValid = false; + if ( !d_matrixValid || !isRenderTargetDataValid(d_owner.getActiveRenderTarget()) ) + { + // Apply the view projection matrix to the model matrix and save the result as cached matrix + d_matrix = d_owner.getViewProjectionMatrix() * getModelMatrix(); - uint32 final; - d_renderSystem.convertColourValue(ocv, &final); + //If necessary: transpose + const OgreShaderWrapper* ogreShader = static_cast(d_renderMaterial->getShaderWrapper()); + if (!ogreShader->getVertexParameters()->getTransposeMatrices()) + d_matrix = glm::transpose(d_matrix); - return final; + d_matrixValid = true; + } } //----------------------------------------------------------------------------// -void OgreGeometryBuffer::updateMatrix() const +void OgreGeometryBuffer::finaliseVertexAttributes(MANUALOBJECT_TYPE type) { - // translation to position geometry and offset to pivot point - Ogre::Matrix4 trans; - trans.makeTrans(d_translation.d_x + d_pivot.d_x, - d_translation.d_y + d_pivot.d_y, - d_translation.d_z + d_pivot.d_z); + d_expectedData = type; - // rotation - Ogre::Matrix4 rot(Ogre::Quaternion( - d_rotation.d_w, d_rotation.d_x, d_rotation.d_y, d_rotation.d_z)); + // basic initialisation of render op + d_renderOp.vertexData = OGRE_NEW Ogre::VertexData(); + d_renderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; + d_renderOp.useIndexes = false; - // translation to remove rotation pivot offset - Ogre::Matrix4 inv_pivot_trans; - inv_pivot_trans.makeTrans(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z); + // Setup our render operation to match the type + Ogre::VertexDeclaration* vd = d_renderOp.vertexData->vertexDeclaration; - // calculate final matrix - d_matrix = trans * rot * inv_pivot_trans; + switch(d_expectedData) + { + case MT_COLOURED: + { + vd->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION); + + vd->addElement(0, sizeof(float)*3, Ogre::VET_COLOUR, + Ogre::VES_DIFFUSE); + break; + } + case MT_TEXTURED: + { + vd->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION); + + vd->addElement(0, sizeof(float)*3, Ogre::VET_FLOAT4, + Ogre::VES_DIFFUSE); + + vd->addElement(0, sizeof(float)*(3+4), Ogre::VET_FLOAT2, + Ogre::VES_TEXTURE_COORDINATES); + break; + } + default: + CEGUI_THROW(RendererException( + "Unknown d_expectedData type.")); + } - d_matrixValid = true; } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::syncHardwareBuffer() const +void OgreGeometryBuffer::setVertexBuffer(size_t count) const { - // Reallocate h/w buffer as requied - size_t size = d_hwBuffer->getNumVertices(); - const size_t required_size = d_vertices.size(); - if(size < required_size) + // We first check if some other buffer has already allocated a suited buffer + // for us + Ogre::HardwareVertexBufferSharedPtr already_created = + d_owner.getVertexBuffer(count); + + if (!already_created.isNull()) { - // calculate new size to use - while(size < required_size) - size *= 2; - // Reallocate the buffer - cleanupRenderOp(d_renderOp, d_hwBuffer); - initialiseRenderOp(d_renderOp, d_hwBuffer, size); + d_hwBuffer = already_created; + + } else { + + // Create the a new vertex buffer + d_hwBuffer = Ogre::HardwareBufferManager::getSingleton(). + createVertexBuffer(getVertexAttributeElementCount()*sizeof(float), count, + Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, + false); } - // copy vertex data into hw buffer - if (required_size > 0) + if (d_hwBuffer.isNull()) { - std::memcpy(d_hwBuffer->lock(Ogre::HardwareVertexBuffer::HBL_DISCARD), - &d_vertices[0], sizeof(OgreVertex) * d_vertices.size()); - - d_hwBuffer->unlock(); + CEGUI_THROW(RendererException("Failed to create Ogre vertex buffer, " + "probably because the vertex layout is invalid.")); } - d_sync = true; + // bind the vertex buffer for rendering + d_renderOp.vertexData->vertexBufferBinding->setBinding(0, d_hwBuffer); } -//----------------------------------------------------------------------------// -const Ogre::Matrix4& OgreGeometryBuffer::getMatrix() const +void OgreGeometryBuffer::cleanUpVertexAttributes() { - if (!d_matrixValid) - updateMatrix(); + OGRE_DELETE d_renderOp.vertexData; + d_renderOp.vertexData = 0; - return d_matrix; + // Store the hardware buffer so that other instances can use it later + // This check should also help prevent there being nullptrs in the pool + if (d_hwBuffer.get()) + d_owner.returnVertexBuffer(d_hwBuffer); + + d_hwBuffer.setNull(); } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::initialiseTextureStates() const +// ------------------------------------ // +void OgreGeometryBuffer::setScissorRects() const { - using namespace Ogre; - d_renderSystem._setTextureCoordCalculation(0, TEXCALC_NONE); - d_renderSystem._setTextureCoordSet(0, 0); - d_renderSystem._setTextureUnitFiltering(0, FO_LINEAR, FO_LINEAR, FO_POINT); - d_renderSystem._setTextureAddressingMode(0, S_textureAddressMode); - d_renderSystem._setTextureMatrix(0, Matrix4::IDENTITY); - d_renderSystem._setAlphaRejectSettings(CMPF_ALWAYS_PASS, 0, false); - d_renderSystem._setTextureBlendMode(0, S_colourBlendMode); - d_renderSystem._setTextureBlendMode(0, S_alphaBlendMode); - d_renderSystem._disableTextureUnitsFrom(1); + d_renderSystem.setScissorTest(true, static_cast(d_clipRect.left()), + static_cast(d_clipRect.top()), static_cast(d_clipRect.right()), static_cast(d_clipRect.bottom())); } -//----------------------------------------------------------------------------// -void OgreGeometryBuffer::setClippingActive(const bool active) +// ------------------------------------ // +void OgreGeometryBuffer::reset() { - d_clippingActive = active; + d_vertexData.clear(); + d_clippingActive = true; } -//----------------------------------------------------------------------------// -bool OgreGeometryBuffer::isClippingActive() const +// ------------------------------------ // +int OgreGeometryBuffer::getVertexAttributeElementCount() const { - return d_clippingActive; + switch(d_expectedData) + { + case MT_COLOURED: + return FLOATS_PER_COLOURED; + break; + case MT_TEXTURED: + return FLOATS_PER_TEXTURED; + break; + default: + return 0; + break; + } } -//----------------------------------------------------------------------------// - } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Ogre/ImageCodec.cpp b/cegui/src/RendererModules/Ogre/ImageCodec.cpp index c37a0194e..d57cb8413 100644 --- a/cegui/src/RendererModules/Ogre/ImageCodec.cpp +++ b/cegui/src/RendererModules/Ogre/ImageCodec.cpp @@ -108,8 +108,8 @@ Texture* OgreImageCodec::load(const RawDataContainer& data, Texture* result) // load the resulting image into the texture result->loadFromMemory(image.getData(), - Sizef(image.getWidth(), - image.getHeight()), + Sizef(static_cast(image.getWidth()), + static_cast(image.getHeight()) ), cegui_pf); return result; diff --git a/cegui/src/RendererModules/Ogre/RenderTarget.inl b/cegui/src/RendererModules/Ogre/RenderTarget.inl index 5e62d5eda..db33d5733 100644 --- a/cegui/src/RendererModules/Ogre/RenderTarget.inl +++ b/cegui/src/RendererModules/Ogre/RenderTarget.inl @@ -25,31 +25,31 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/Ogre/RenderTarget.h" -#include "CEGUI/GeometryBuffer.h" -#include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/Ogre/GeometryBuffer.h" +#include "CEGUI/Exceptions.h" #include #include #include +#include +#include +#include + // Start of CEGUI namespace section namespace CEGUI { + //----------------------------------------------------------------------------// template OgreRenderTarget::OgreRenderTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : d_owner(owner), d_renderSystem(rs), - d_area(0, 0, 0, 0), d_renderTarget(0), d_viewport(0), - d_matrix(Ogre::Matrix3::ZERO), - d_matrixValid(false), - d_viewportValid(false), - d_viewDistance(0), - d_ogreViewportDimensions(0, 0, 0, 0) + d_ogreViewportDimensions(0, 0, 0, 0), + d_viewportValid(false) { } @@ -60,33 +60,6 @@ OgreRenderTarget::~OgreRenderTarget() delete d_viewport; } -//----------------------------------------------------------------------------// -template -void OgreRenderTarget::draw(const GeometryBuffer& buffer) -{ - buffer.draw(); -} - -//----------------------------------------------------------------------------// -template -void OgreRenderTarget::draw(const RenderQueue& queue) -{ - queue.draw(); -} - -//----------------------------------------------------------------------------// -template -void OgreRenderTarget::setArea(const Rectf& area) -{ - d_area = area; - setOgreViewportDimensions(area); - - d_matrixValid = false; - - RenderTargetEventArgs args(this); - T::fireEvent(RenderTarget::EventAreaChanged, args); -} - //----------------------------------------------------------------------------// template void OgreRenderTarget::setOgreViewportDimensions(const Rectf& area) @@ -106,7 +79,8 @@ void OgreRenderTarget::updateOgreViewportDimensions( { if (rt) { - d_viewport->setDimensions( + if(d_viewport) + d_viewport->setDimensions( d_ogreViewportDimensions.left() / rt->getWidth(), d_ogreViewportDimensions.top() / rt->getHeight(), d_ogreViewportDimensions.getWidth() / rt->getWidth(), @@ -114,59 +88,48 @@ void OgreRenderTarget::updateOgreViewportDimensions( } } -//----------------------------------------------------------------------------// -template -const Rectf& OgreRenderTarget::getArea() const -{ - return d_area; -} - //----------------------------------------------------------------------------// template void OgreRenderTarget::activate() { - if (!d_matrixValid) + if (!RenderTarget::d_matrixValid) updateMatrix(); if (!d_viewportValid) updateViewport(); d_renderSystem._setViewport(d_viewport); - d_owner.setProjectionMatrix(d_matrix); - d_owner.setViewMatrix(Ogre::Matrix4::IDENTITY); -} -//----------------------------------------------------------------------------// -template -void OgreRenderTarget::deactivate() -{ - // currently nothing to do in the basic case + d_owner.setViewProjectionMatrix(RenderTarget::d_matrix); + + RenderTarget::activate(); } //----------------------------------------------------------------------------// template void OgreRenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, - Vector2f& p_out) const + const glm::vec2& p_in, + glm::vec2& p_out) const { - if (!d_matrixValid) + if (!RenderTarget::d_matrixValid) updateMatrix(); const OgreGeometryBuffer& gb = static_cast(buff); - const Ogre::Real midx = d_area.getWidth() * 0.5f; - const Ogre::Real midy = d_area.getHeight() * 0.5f; + const Ogre::Real midx = RenderTarget::d_area.getWidth() * 0.5f; + const Ogre::Real midy = RenderTarget::d_area.getHeight() * 0.5f; // viewport matrix const Ogre::Matrix4 vpmat( - midx, 0, 0, d_area.left() + midx, - 0, -midy, 0, d_area.top() + midy, + midx, 0, 0, RenderTarget::d_area.left() + midx, + 0, -midy, 0, RenderTarget::d_area.top() + midy, 0, 0, 1, 0, 0, 0, 0, 1 ); // matrices used for projecting and unprojecting points - const Ogre::Matrix4 proj(gb.getMatrix() * d_matrix * vpmat); + + const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix() * RenderTarget::d_matrix) * vpmat); const Ogre::Matrix4 unproj(proj.inverse()); Ogre::Vector3 in; @@ -174,10 +137,10 @@ void OgreRenderTarget::unprojectPoint(const GeometryBuffer& buff, // unproject the ends of the ray in.x = midx; in.y = midy; - in.z = -d_viewDistance; + in.z = -RenderTarget::d_viewDistance; const Ogre::Vector3 r1(unproj * in); - in.x = p_in.d_x; - in.y = p_in.d_y; + in.x = p_in.x; + in.y = p_in.y; in.z = 0; // calculate vector of picking ray const Ogre::Vector3 rv(r1 - unproj * in); @@ -205,37 +168,22 @@ void OgreRenderTarget::unprojectPoint(const GeometryBuffer& buff, const Ogre::Real pn_dot_rv = pn.dotProduct(rv); const Ogre::Real tmp = pn_dot_rv != 0.0 ? (pn.dotProduct(r1) + dist) / pn_dot_rv : - 0.0; + 0.0f; - p_out.d_x = static_cast(r1.x - rv.x * tmp); - p_out.d_y = static_cast(r1.y - rv.y * tmp); + p_out.x = static_cast(r1.x - rv.x * tmp); + p_out.y = static_cast(r1.y - rv.y * tmp); } //----------------------------------------------------------------------------// template void OgreRenderTarget::updateMatrix() const { - const float w = d_area.getWidth(); - const float h = d_area.getHeight(); - const float aspect = w / h; - const float midx = w * 0.5f; - d_viewDistance = midx / (aspect * 0.267949192431123f); - - const float nearZ = d_viewDistance * 0.5f; - const float farZ = d_viewDistance * 2.0f; - const float nr_sub_far = nearZ - farZ; - - Ogre::Matrix4 tmp(Ogre::Matrix4::ZERO); - tmp[0][0] = 3.732050808f / aspect; - tmp[0][3] = -d_viewDistance; - tmp[1][1] = -3.732050808f; - tmp[1][3] = d_viewDistance; - tmp[2][2] = -((farZ + nearZ) / nr_sub_far); - tmp[3][2] = 1.0f; - tmp[3][3] = d_viewDistance; - d_renderSystem._convertProjectionMatrix(tmp, d_matrix); - - d_matrixValid = true; + if (d_owner.usesOpenGL()) + RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() ); + else if (d_owner.usesDirect3D()) + RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForDirect3D() ); + else + CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team.")); } //----------------------------------------------------------------------------// @@ -244,14 +192,37 @@ void OgreRenderTarget::updateViewport() { if (!d_viewport) { +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + + d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1); +#else d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 + updateOgreViewportDimensions(d_renderTarget); } d_viewport->_updateDimensions(); + d_viewportValid = true; } +//----------------------------------------------------------------------------// +template +OgreRenderer& OgreRenderTarget::getOwner() +{ + return d_owner; +} + +//----------------------------------------------------------------------------// +template +void OgreRenderTarget::setArea(const Rectf& area) +{ + setOgreViewportDimensions(area); + + RenderTarget::setArea(area); +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Ogre/Renderer.cpp b/cegui/src/RendererModules/Ogre/Renderer.cpp index b17e5d03b..4810206ea 100644 --- a/cegui/src/RendererModules/Ogre/Renderer.cpp +++ b/cegui/src/RendererModules/Ogre/Renderer.cpp @@ -1,6 +1,6 @@ /*********************************************************************** created: Tue Feb 17 2009 - author: Paul D Turner + author: Paul D Turner, Henri I Hyyryläinen *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team @@ -46,94 +46,51 @@ #include #include #include +#include + +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +#include +#include +#include +#include +#include +#include +#include +#include +#endif // CEGUI_USE_OGRE_COMPOSITOR2 +#include "CEGUI/RendererModules/Ogre/ShaderWrapper.h" + +#include "Shaders.inl" + +#include "glm/gtc/type_ptr.hpp" + +#define VERTEXBUFFER_POOL_SIZE_STARTCLEAR 60 // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// -// shader source code strings -static Ogre::String S_hlsl_vs_source( - "uniform float4x4 worldViewProjMatrix;" - "struct VS_OUT {" - " float4 position : POSITION;" - " float2 uv : TEXCOORD0;" - " float4 colour : COLOR;" - "};" - "VS_OUT main(float4 position : POSITION," - " float2 uv : TEXCOORD0," - " float4 colour : COLOR)" - "{" - " VS_OUT o;" - " o.uv = uv;" - " o.colour = colour;" - " o.position = mul(worldViewProjMatrix, position);" - " return o;" - "}" -); - -static Ogre::String S_hlsl_ps_source( - "float4 main(float4 colour : COLOR," - " float2 texCoord : TEXCOORD0," - " uniform sampler2D texture0 : TEXUNIT0) : COLOR" - "{" - " return tex2D(texture0, texCoord) * colour;" - "}" -); - -static Ogre::String S_glsl_compat_vs_source( - "void main(void)" - "{" - " gl_TexCoord[0] = gl_MultiTexCoord0;" - " gl_FrontColor = gl_Color;" - " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;" - "}" -); -static Ogre::String S_glsl_compat_ps_source( - "uniform sampler2D texture0;" - "void main(void)" - "{" - " gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;" - "}" -); - -static Ogre::String S_glsl_core_vs_source( - "#version 150 core \n" - - "uniform mat4 modelViewPerspMatrix;" - - "in vec4 vertex;" - "in vec2 uv0;" - "in vec4 colour;" - - "out vec2 exTexCoord;" - "out vec4 exColour;" - - "void main(void)" - "{" - " exTexCoord = uv0;" - " exColour = colour;" - - " gl_Position = modelViewPerspMatrix * vertex;" - "}" -); - -static Ogre::String S_glsl_core_ps_source( - "#version 150 core \n" - - "uniform sampler2D texture0;" - - "in vec2 exTexCoord;" - "in vec4 exColour;" - - "out vec4 fragColour;" - - "void main(void)" - "{" - " fragColour = texture(texture0, exTexCoord) * exColour;" - "}" -); +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +// The new method will be used +// Internal Ogre::CompositorWorkspaceListener. This is how the renderer gets notified +// of workspaces that need rendering +class OgreGUIRenderQueueListener : public Ogre::CompositorWorkspaceListener +{ +public: + OgreGUIRenderQueueListener(OgreRenderer* owner); -//----------------------------------------------------------------------------// + void setCEGUIRenderEnabled(bool enabled); + bool isCEGUIRenderEnabled() const; + + virtual void passPreExecute(Ogre::CompositorPass *pass); + +private: + bool d_enabled; + OgreRenderer* d_owner; + +}; + +#else // Use the old method // Internal Ogre::FrameListener based class. This is how we noew hook into the // rendering process (as opposed to render queues previously) static class OgreGUIFrameListener : public Ogre::FrameListener @@ -151,44 +108,49 @@ static class OgreGUIFrameListener : public Ogre::FrameListener } S_frameListener; +#endif // CEGUI_USE_OGRE_COMPOSITOR2 //----------------------------------------------------------------------------// //! container type used to hold TextureTargets we create. typedef std::vector TextureTargetList; //! container type used to hold GeometryBuffers we create. typedef std::vector GeometryBufferList; //! container type used to hold Textures we create. -typedef std::map TextureMap; +typedef std::map TextureMap; //----------------------------------------------------------------------------// // Implementation data for the OgreRenderer -struct OgreRenderer_impl : - public AllocatedObject +struct OgreRenderer_impl { OgreRenderer_impl() : d_displayDPI(96, 96), - // TODO: should be set to correct value + //! TODO: Currently there is no way to do this easily using Ogre d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()), +#if !defined(CEGUI_USE_OGRE_COMPOSITOR2) d_previousVP(0), +#else + d_frameListener(0), + d_dummyScene(0), + d_dummyCamera(0), + d_workspace(0), +#endif d_activeBlendMode(BM_INVALID), d_makeFrameControlCalls(true), - d_useShaders(false), - d_worldMatrix(Ogre::Matrix4::IDENTITY), - d_viewMatrix(Ogre::Matrix4::IDENTITY), - d_projectionMatrix(Ogre::Matrix4::IDENTITY), - d_worldViewProjMatrix(Ogre::Matrix4::IDENTITY), - d_combinedMatrixValid(true), d_useGLSL(false), - d_useGLSLCore(false) + d_useGLSLES(false), + d_useGLSLCore(false), + d_useHLSL(false), + d_texturedShaderWrapper(0), + d_colouredShaderWrapper(0) {} + //! String holding the renderer identification text. static String d_rendererID; //! What the renderer considers to be the current display size. Sizef d_displaySize; //! What the renderer considers to be the current display DPI resolution. - Vector2f d_displayDPI; + glm::vec2 d_displayDPI; //! The default RenderTarget OgreWindowTarget* d_defaultTarget; //! Container used to track texture targets. @@ -203,36 +165,63 @@ struct OgreRenderer_impl : Ogre::Root* d_ogreRoot; //! Pointer to the render system for Ogre. Ogre::RenderSystem* d_renderSystem; +#if !defined(CEGUI_USE_OGRE_COMPOSITOR2) //! Pointer to the previous viewport set in render system. Ogre::Viewport* d_previousVP; //! Previous projection matrix set on render system. Ogre::Matrix4 d_previousProjMatrix; +#else + //! This is used to get notifications when our scene is rendered + //! no longer static because it requires a pointer to this + OgreGUIRenderQueueListener* d_frameListener; + + //! Used to render at the correct time + Ogre::SceneManager* d_dummyScene; + //! This might not be needed, but it's here + Ogre::Camera* d_dummyCamera; + + Ogre::CompositorWorkspace* d_workspace; + + //! Makes all scene names unique + static int s_createdSceneNumber; + + //! Allows the initialization to remain the same by automatically + //! initializing the Compositor if it isn't already + static bool s_compositorResourcesInitialized; + +#endif //! What we think is the current blend mode to use BlendMode d_activeBlendMode; //! Whether _beginFrame and _endFrame will be called. bool d_makeFrameControlCalls; - //! Whether shaders will be used for basic rendering - bool d_useShaders; //! Whether shaders are glsl or hlsl bool d_useGLSL; + //! Whether shaders are glsles + bool d_useGLSLES; + //! Whether shaders are hlsl + bool d_useHLSL; //! Whether we use the ARB glsl shaders or the OpenGL 3.2 Core shader profile (140 core) bool d_useGLSLCore; - Ogre::HighLevelGpuProgramPtr d_vertexShader; - Ogre::HighLevelGpuProgramPtr d_pixelShader; - Ogre::GpuProgramParametersSharedPtr d_vertexShaderParameters; - Ogre::GpuProgramParametersSharedPtr d_pixelShaderParameters; + //! Vector containing vertex buffers that can be reused + std::vector d_vbPool; - Ogre::Matrix4 d_worldMatrix; - Ogre::Matrix4 d_viewMatrix; - Ogre::Matrix4 d_projectionMatrix; - Ogre::Matrix4 d_worldViewProjMatrix; - bool d_combinedMatrixValid; + OgreShaderWrapper* d_texturedShaderWrapper; + OgreShaderWrapper* d_colouredShaderWrapper; }; //----------------------------------------------------------------------------// String OgreRenderer_impl::d_rendererID( -"CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module."); +"CEGUI::OgreRenderer - OGRE based 3rd generation renderer module" +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +" with Ogre::Compositor2 enabled" +#endif // CEGUI_USE_OGRE_COMPOSITOR2 +"."); + +#if defined(CEGUI_USE_OGRE_COMPOSITOR2) +int OgreRenderer_impl::s_createdSceneNumber = 0; +bool OgreRenderer_impl::s_compositorResourcesInitialized = false; +#endif //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem(const int abi) @@ -241,7 +230,11 @@ OgreRenderer& OgreRenderer::bootstrapSystem(const int abi) if (System::getSingletonPtr()) CEGUI_THROW(InvalidRequestException( - "CEGUI::System object is already initialised.")); + "CEGUI::System object is already initialised.")); + +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + createOgreCompositorResources(); +#endif OgreRenderer& renderer = create(); OgreResourceProvider& rp = createOgreResourceProvider(); @@ -261,6 +254,10 @@ OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target, CEGUI_THROW(InvalidRequestException( "CEGUI::System object is already initialised.")); +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + createOgreCompositorResources(); +#endif + OgreRenderer& renderer = OgreRenderer::create(target); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); @@ -294,7 +291,7 @@ OgreRenderer& OgreRenderer::create(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO OgreRenderer(); + return *new OgreRenderer(); } //----------------------------------------------------------------------------// @@ -303,92 +300,161 @@ OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target, { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO OgreRenderer(target); + return *new OgreRenderer(target); } //----------------------------------------------------------------------------// void OgreRenderer::destroy(OgreRenderer& renderer) { - CEGUI_DELETE_AO &renderer; + delete &renderer; } //----------------------------------------------------------------------------// OgreResourceProvider& OgreRenderer::createOgreResourceProvider() { - return *CEGUI_NEW_AO OgreResourceProvider(); + return *new OgreResourceProvider(); } //----------------------------------------------------------------------------// -void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp) +OgreRenderer& OgreRenderer::registerWindow(OgreRenderer& main_window, + Ogre::RenderTarget &new_window) { - CEGUI_DELETE_AO &rp; -} + // Link the second renderer to the first for them to share some resources + return *new OgreRenderer(new_window); +} + //----------------------------------------------------------------------------// -OgreImageCodec& OgreRenderer::createOgreImageCodec() +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +void OgreRenderer::createOgreCompositorResources() { - return *CEGUI_NEW_AO OgreImageCodec(); + // Create all the definitions for the workspaces and nodes + + Ogre::CompositorManager2* manager = Ogre::Root::getSingleton(). + getCompositorManager2(); + + // We want this to fail if it isn't initialized + if (!manager) + CEGUI_THROW(RendererException( + "Ogre CompositorManager2 is not initialized, " + "you must call Ogre::Root::initialiseCompositor() after " + "creating at least one window.")); + + Ogre::CompositorWorkspaceDef* templatedworkspace = + manager->addWorkspaceDefinition("CEGUI_workspace"); + + // Create a node for rendering on top of everything + Ogre::CompositorNodeDef* rendernode = + manager->addNodeDefinition("CEGUIRenderNode"); + + // Use the render target passed from the workspace for rendering on top of + // everything + rendernode->addTextureSourceName("renderwindow", 0, + Ogre::TextureDefinitionBase::TEXTURE_INPUT); + + rendernode->setNumTargetPass(1); + + // Pass for it + Ogre::CompositorTargetDef* targetpasses = + rendernode->addTargetPass("renderwindow"); + targetpasses->setNumPasses(2); + + Ogre::CompositorPassClearDef* clearpass = + static_cast(targetpasses-> + addPass(Ogre::PASS_CLEAR)); + + // Only clear depth and stencil since we are rendering on top + // of an existing image + clearpass->mClearBufferFlags = Ogre::FBT_DEPTH | Ogre::FBT_STENCIL; + + // Now the render scene pass during which the render queue listener + // should render the GUI + Ogre::CompositorPassSceneDef* scenepass = + static_cast(targetpasses-> + addPass(Ogre::PASS_SCENE)); + + // Just render the overlay group since it is the only one used + scenepass->mFirstRQ = Ogre::RENDER_QUEUE_OVERLAY; + scenepass->mLastRQ = Ogre::RENDER_QUEUE_OVERLAY+1; + + // Connect the main render target to the node + templatedworkspace->connectOutput("CEGUIRenderNode", 0); + + // Resources now created + OgreRenderer_impl::s_compositorResourcesInitialized = true; + } +#endif //----------------------------------------------------------------------------// -void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic) +void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp) { - CEGUI_DELETE_AO ⁣ + delete &rp; } //----------------------------------------------------------------------------// -void OgreRenderer::setRenderingEnabled(const bool enabled) +OgreImageCodec& OgreRenderer::createOgreImageCodec() { - S_frameListener.setCEGUIRenderEnabled(enabled); + return *new OgreImageCodec(); } //----------------------------------------------------------------------------// -bool OgreRenderer::isRenderingEnabled() const +void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic) { - return S_frameListener.isCEGUIRenderEnabled(); + delete ⁣ } //----------------------------------------------------------------------------// -RenderTarget& OgreRenderer::getDefaultRenderTarget() +//! Conversion function from Ogre to glm +glm::mat4 OgreRenderer::ogreToGlmMatrix(const Ogre::Matrix4& matrix) { - return *d_pimpl->d_defaultTarget; + return glm::mat4(matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], + matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], + matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], + matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]); } //----------------------------------------------------------------------------// -GeometryBuffer& OgreRenderer::createGeometryBuffer() +//! Conversion function from glm to Ogre +Ogre::Matrix4 OgreRenderer::glmToOgreMatrix(const glm::mat4& matrix) { - OgreGeometryBuffer* gb = - CEGUI_NEW_AO OgreGeometryBuffer(*this, *d_pimpl->d_renderSystem); - - d_pimpl->d_geometryBuffers.push_back(gb); - return *gb; + return Ogre::Matrix4(matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], + matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], + matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], + matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]); } //----------------------------------------------------------------------------// -void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) +void OgreRenderer::setRenderingEnabled(const bool enabled) { - GeometryBufferList::iterator i = std::find(d_pimpl->d_geometryBuffers.begin(), - d_pimpl->d_geometryBuffers.end(), - &buffer); +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + d_pimpl->d_frameListener->setCEGUIRenderEnabled(enabled); + d_pimpl->d_workspace->setEnabled(false); +#else + S_frameListener.setCEGUIRenderEnabled(enabled); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 +} - if (d_pimpl->d_geometryBuffers.end() != i) - { - d_pimpl->d_geometryBuffers.erase(i); - CEGUI_DELETE_AO &buffer; - } +//----------------------------------------------------------------------------// +bool OgreRenderer::isRenderingEnabled() const +{ +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + return d_pimpl->d_frameListener->isCEGUIRenderEnabled(); +#else + return S_frameListener.isCEGUIRenderEnabled(); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 } //----------------------------------------------------------------------------// -void OgreRenderer::destroyAllGeometryBuffers() +RenderTarget& OgreRenderer::getDefaultRenderTarget() { - while (!d_pimpl->d_geometryBuffers.empty()) - destroyGeometryBuffer(**d_pimpl->d_geometryBuffers.begin()); + return *d_pimpl->d_defaultTarget; } //----------------------------------------------------------------------------// TextureTarget* OgreRenderer::createTextureTarget() { - TextureTarget* tt = CEGUI_NEW_AO OgreTextureTarget(*this, *d_pimpl->d_renderSystem); + TextureTarget* tt = new OgreTextureTarget(*this, *d_pimpl->d_renderSystem); d_pimpl->d_textureTargets.push_back(tt); return tt; } @@ -403,7 +469,7 @@ void OgreRenderer::destroyTextureTarget(TextureTarget* target) if (d_pimpl->d_textureTargets.end() != i) { d_pimpl->d_textureTargets.erase(i); - CEGUI_DELETE_AO target; + delete target; } } @@ -419,7 +485,7 @@ Texture& OgreRenderer::createTexture(const String& name) { throwIfNameExists(name); - OgreTexture* t = CEGUI_NEW_AO OgreTexture(name); + OgreTexture* t = new OgreTexture(name); d_pimpl->d_textures[name] = t; logTextureCreation(name); @@ -433,7 +499,7 @@ Texture& OgreRenderer::createTexture(const String& name, const String& filename, { throwIfNameExists(name); - OgreTexture* t = CEGUI_NEW_AO OgreTexture(name, filename, resourceGroup); + OgreTexture* t = new OgreTexture(name, filename, resourceGroup); d_pimpl->d_textures[name] = t; logTextureCreation(name); @@ -446,7 +512,7 @@ Texture& OgreRenderer::createTexture(const String& name, const Sizef& size) { throwIfNameExists(name); - OgreTexture* t = CEGUI_NEW_AO OgreTexture(name, size); + OgreTexture* t = new OgreTexture(name, size); d_pimpl->d_textures[name] = t; logTextureCreation(name); @@ -460,7 +526,7 @@ Texture& OgreRenderer::createTexture(const String& name, Ogre::TexturePtr& tex, { throwIfNameExists(name); - OgreTexture* t = CEGUI_NEW_AO OgreTexture(name, tex, take_ownership); + OgreTexture* t = new OgreTexture(name, tex, take_ownership); d_pimpl->d_textures[name] = t; logTextureCreation(name); @@ -498,7 +564,7 @@ void OgreRenderer::destroyTexture(const String& name) if (d_pimpl->d_textures.end() != i) { logTextureDestruction(name); - CEGUI_DELETE_AO i->second; + delete i->second; d_pimpl->d_textures.erase(i); } } @@ -538,16 +604,19 @@ bool OgreRenderer::isTextureDefined(const String& name) const //----------------------------------------------------------------------------// void OgreRenderer::beginRendering() { - if ( !d_pimpl->d_previousVP ) +#if !defined(CEGUI_USE_OGRE_COMPOSITOR2) + if ( !d_pimpl->d_previousVP ) { d_pimpl->d_previousVP = d_pimpl->d_renderSystem->_getViewport(); if ( d_pimpl->d_previousVP && d_pimpl->d_previousVP->getCamera() ) d_pimpl->d_previousProjMatrix = - d_pimpl->d_previousVP->getCamera()->getProjectionMatrixRS(); + d_pimpl->d_previousVP->getCamera()->getProjectionMatrixRS(); } //FIXME: ??? System::getSingleton().getDefaultGUIContext().getRenderTarget().activate(); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 + initialiseRenderStateSettings(); if (d_pimpl->d_makeFrameControlCalls) @@ -560,13 +629,14 @@ void OgreRenderer::endRendering() if (d_pimpl->d_makeFrameControlCalls) d_pimpl->d_renderSystem->_endFrame(); +#if !defined(CEGUI_USE_OGRE_COMPOSITOR2) //FIXME: ??? System::getSingleton().getDefaultGUIContext().getRenderTarget().deactivate(); - if ( d_pimpl->d_previousVP ) + if ( d_pimpl->d_previousVP ) { d_pimpl->d_renderSystem->_setViewport(d_pimpl->d_previousVP); - + if ( d_pimpl->d_previousVP->getCamera() ) { d_pimpl->d_renderSystem->_setProjectionMatrix( @@ -577,6 +647,7 @@ void OgreRenderer::endRendering() d_pimpl->d_previousVP = 0; d_pimpl->d_previousProjMatrix = Ogre::Matrix4::IDENTITY; } +#endif // CEGUI_USE_OGRE_COMPOSITOR2 } //----------------------------------------------------------------------------// @@ -586,7 +657,7 @@ const Sizef& OgreRenderer::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& OgreRenderer::getDisplayDPI() const +const glm::vec2& OgreRenderer::getDisplayDPI() const { return d_pimpl->d_displayDPI; } @@ -605,7 +676,7 @@ const String& OgreRenderer::getIdentifierString() const //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer() : - d_pimpl(CEGUI_NEW_AO OgreRenderer_impl()) + d_pimpl(new OgreRenderer_impl()) { checkOgreInitialised(); @@ -622,7 +693,7 @@ OgreRenderer::OgreRenderer() : //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) : - d_pimpl(CEGUI_NEW_AO OgreRenderer_impl()) + d_pimpl(new OgreRenderer_impl()) { checkOgreInitialised(); @@ -632,16 +703,38 @@ OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) : //----------------------------------------------------------------------------// OgreRenderer::~OgreRenderer() { +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + // Remove the listener and then delete the scene + d_pimpl->d_workspace->setListener(0); + + d_pimpl->d_ogreRoot->destroySceneManager(d_pimpl->d_dummyScene); + + d_pimpl->d_dummyScene = 0; + d_pimpl->d_dummyCamera = 0; + + // Remove the workspace so the contents aren't rendered anymore + d_pimpl->d_ogreRoot->getCompositorManager2()->removeWorkspace( + d_pimpl->d_workspace); + + d_pimpl->d_workspace = 0; + +#else d_pimpl->d_ogreRoot->removeFrameListener(&S_frameListener); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 cleanupShaders(); +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + delete d_pimpl->d_frameListener; +#endif + destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); + clearVertexBufferPool(); - CEGUI_DELETE_AO d_pimpl->d_defaultTarget; - CEGUI_DELETE_AO d_pimpl; + delete d_pimpl->d_defaultTarget; + delete d_pimpl; } //----------------------------------------------------------------------------// @@ -661,165 +754,246 @@ void OgreRenderer::constructor_impl(Ogre::RenderTarget& target) { d_pimpl->d_renderSystem = d_pimpl->d_ogreRoot->getRenderSystem(); - d_pimpl->d_displaySize.d_width = target.getWidth(); - d_pimpl->d_displaySize.d_height = target.getHeight(); + d_pimpl->d_displaySize.d_width = static_cast(target.getWidth()); + d_pimpl->d_displaySize.d_height = static_cast(target.getHeight()); - d_pimpl->d_useGLSLCore = ( d_pimpl->d_renderSystem->getName().compare(0, 8, "OpenGL 3") == 0 ) ; + //! Checking if OpenGL > 3.2 supported + if (d_pimpl->d_renderSystem->getName().find("OpenGL 3+") != Ogre::String::npos) + { + d_pimpl->d_useGLSLCore = true; + } // create default target & rendering root (surface) that uses it d_pimpl->d_defaultTarget = - CEGUI_NEW_AO OgreWindowTarget(*this, *d_pimpl->d_renderSystem, target); + new OgreWindowTarget(*this, *d_pimpl->d_renderSystem, target); #if OGRE_VERSION >= 0x10800 - // Check if built with RT Shader System and if it is: Check if fixed function pipeline is enabled - #if defined RTSHADER_SYSTEM_BUILD_CORE_SHADERS - bool isFixedFunctionEnabled = d_pimpl->d_renderSystem->getFixedPipelineEnabled(); - #else - bool isFixedFunctionEnabled = true; - #endif - #ifndef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - if (d_pimpl->d_useGLSLCore) - CEGUI_THROW(RendererException("RT Shader System not available but trying to render using OpenGL 3.X+ Core." - "When GLSL shaders are necessary, the RT Shader System component of Ogre is required for rendering CEGUI.")); + CEGUI_THROW(RendererException("RT Shader System not available. However CEGUI relies on shaders for rendering. ")); #endif - - // Default to using shaders when that is the sane thing to do. - // We check for use of the OpenGL 3+ Renderer in which case we always wanna (because we have to) use shaders - if (!isFixedFunctionEnabled || d_pimpl->d_useGLSLCore) - setUsingShaders(true); #endif // hook into the rendering process +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + + // Some automatic bootstrapping + if (!OgreRenderer_impl::s_compositorResourcesInitialized) + { + createOgreCompositorResources(); + } + + // Create the dummy scene and camera + std::stringstream scene_name; + scene_name << "CEGUI_forWindow_" << + OgreRenderer_impl::s_createdSceneNumber++; + + d_pimpl->d_dummyScene = d_pimpl->d_ogreRoot->createSceneManager( + Ogre::ST_INTERIOR, 1, Ogre::INSTANCING_CULLING_SINGLETHREAD, + scene_name.str()); + + // Unused camera for the scene + d_pimpl->d_dummyCamera = d_pimpl->d_dummyScene->createCamera( + "CEGUI_dummy_camera"); + + + // We will get notified when the workspace is drawn + d_pimpl->d_frameListener = new OgreGUIRenderQueueListener(this); + + // Create the workspace for rendering + Ogre::CompositorManager2* manager = d_pimpl->d_ogreRoot-> + getCompositorManager2(); + + // The -1 should guarantee this to be rendered last on top of everything + d_pimpl->d_workspace = manager->addWorkspace(d_pimpl->d_dummyScene, + &target, d_pimpl->d_dummyCamera, "CEGUI_workspace", true, -1); + + d_pimpl->d_workspace->setListener(d_pimpl->d_frameListener); + +#else d_pimpl->d_ogreRoot->addFrameListener(&S_frameListener); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 + + initialiseShaders(); } //----------------------------------------------------------------------------// void OgreRenderer::initialiseShaders() { + Ogre::HighLevelGpuProgramPtr texture_vs; + Ogre::HighLevelGpuProgramPtr texture_ps; + + Ogre::HighLevelGpuProgramPtr colour_vs; + Ogre::HighLevelGpuProgramPtr colour_ps; + d_pimpl->d_useGLSL = Ogre::HighLevelGpuProgramManager::getSingleton(). isLanguageSupported("glsl"); + d_pimpl->d_useGLSLES = Ogre::HighLevelGpuProgramManager::getSingleton(). + isLanguageSupported("glsles"); + d_pimpl->d_useHLSL = Ogre::HighLevelGpuProgramManager::getSingleton(). + isLanguageSupported("hlsl"); Ogre::String shaderLanguage; - if(d_pimpl->d_useGLSL) + + if (d_pimpl->d_useGLSL) { - if(d_pimpl->d_useGLSLCore) - shaderLanguage = "glsl"; - else - shaderLanguage = "glsl"; + shaderLanguage = "glsl"; } - else + else if (d_pimpl->d_useGLSLES) + { + shaderLanguage = "glsles"; + } + else if (d_pimpl->d_useHLSL) + { shaderLanguage = "hlsl"; + } + else { + CEGUI_THROW(RendererException("Underlying Ogre render system does not support available " + "shader languages which should be one of glsl, glsles or hlsl " + "which are required for supporting custom shaders in this CEGUI version")); + } - // Create vertex shader - d_pimpl->d_vertexShader = Ogre::HighLevelGpuProgramManager::getSingleton(). - createProgram("__cegui_internal_vs__", + // Create vertex shaders + texture_vs = Ogre::HighLevelGpuProgramManager::getSingleton(). + createProgram("__cegui_internal_texture_vs__", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, shaderLanguage, Ogre::GPT_VERTEX_PROGRAM); + + colour_vs = Ogre::HighLevelGpuProgramManager::getSingleton(). + createProgram("__cegui_internal_colour_vs__", + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, + shaderLanguage, Ogre::GPT_VERTEX_PROGRAM); + + // Create pixel shaders + texture_ps = Ogre::HighLevelGpuProgramManager::getSingleton(). + createProgram("__cegui_internal_texture_ps__", + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, + shaderLanguage, Ogre::GPT_FRAGMENT_PROGRAM); + + colour_ps = Ogre::HighLevelGpuProgramManager::getSingleton(). + createProgram("__cegui_internal_colour_ps__", + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, + shaderLanguage, Ogre::GPT_FRAGMENT_PROGRAM); + // We always enter through the main function - d_pimpl->d_vertexShader->setParameter("entry_point", "main"); + texture_vs->setParameter("entry_point", "main"); + texture_ps->setParameter("entry_point", "main"); + colour_vs->setParameter("entry_point", "main"); + colour_ps->setParameter("entry_point", "main"); // If we use GLSL if (d_pimpl->d_useGLSL) { // We check if we want to use a GLSL core shader, which is required for the Ogre OpenGL 3+ Renderer - if(d_pimpl->d_useGLSLCore) + if (d_pimpl->d_useGLSLCore) { - d_pimpl->d_vertexShader->setParameter("target", "glsl"); - d_pimpl->d_vertexShader->setSource(S_glsl_core_vs_source); + texture_vs->setParameter("target", "glsl"); + texture_vs->setSource(VertexShaderTextured_GLSL); + + colour_vs->setParameter("target", "glsl"); + colour_vs->setSource(VertexShaderColoured_GLSL); + + texture_ps->setParameter("target", "glsl"); + texture_ps->setSource(PixelShaderTextured_GLSL); + + colour_ps->setParameter("target", "glsl"); + colour_ps->setSource(PixelShaderColoured_GLSL); } else // else we use regular GLSL shader, as in the normal Ogre OpenGL Renderer { - d_pimpl->d_vertexShader->setParameter("target", "arbvp1"); - d_pimpl->d_vertexShader->setSource(S_glsl_compat_vs_source); + texture_vs->setParameter("target", "arbvp1"); + texture_vs->setSource(VertexShaderTextured_GLSL_Compat); + + colour_vs->setParameter("target", "arbvp1"); + colour_vs->setSource(VertexShaderColoured_GLSL_Compat); + + texture_ps->setParameter("target", "arbfp1"); + texture_ps->setSource(PixelShaderTextured_GLSL_Compat); + + colour_ps->setParameter("target", "arbfp1"); + colour_ps->setSource(PixelShaderColoured_GLSL_Compat); } + } + else if (d_pimpl->d_useGLSLES) + { + texture_vs->setParameter("target", "glsles"); + texture_vs->setSource(VertexShaderTextured_GLSLES1); + + colour_vs->setParameter("target", "glsles"); + colour_vs->setSource(VertexShaderColoured_GLSLES1); + texture_ps->setParameter("target", "glsles"); + texture_ps->setSource(PixelShaderTextured_GLSLES1); + + colour_ps->setParameter("target", "glsles"); + colour_ps->setSource(PixelShaderColoured_GLSLES1); } else // else we use a hlsl shader with an available syntax code { - if (Ogre::GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0")) + if (Ogre::GpuProgramManager::getSingleton().isSyntaxSupported("vs_5_0")) { - d_pimpl->d_vertexShader->setParameter("target", "vs_4_0"); - d_pimpl->d_vertexShader->setSource(S_hlsl_vs_source); + texture_vs->setParameter("target", "vs_5_0"); + texture_vs->setSource(VertexShaderTextured_HLSL); + + colour_vs->setParameter("target", "vs_5_0"); + colour_vs->setSource(VertexShaderColoured_HLSL); } else if (Ogre::GpuProgramManager::getSingleton().isSyntaxSupported("vs_2_0")) { - d_pimpl->d_vertexShader->setParameter("target", "vs_2_0"); - d_pimpl->d_vertexShader->setSource(S_hlsl_vs_source); + texture_vs->setParameter("target", "vs_2_0"); + texture_vs->setSource(VertexShaderTextured_HLSL); + + colour_vs->setParameter("target", "vs_2_0"); + colour_vs->setSource(VertexShaderColoured_HLSL); } else// If no shader was compatible { - d_pimpl->d_vertexShader.setNull(); CEGUI_THROW(RendererException( "OgreRenderer::initialiseShaders: No supported syntax - " - "unable to compile '__cegui_internal_vs__'")); + "unable to compile for vs_5_0 or vs_2_0")); } - } - - d_pimpl->d_vertexShader->load(); - - // Create pixel shader - d_pimpl->d_pixelShader = Ogre::HighLevelGpuProgramManager::getSingleton(). - createProgram("__cegui_internal_ps__", - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - shaderLanguage, Ogre::GPT_FRAGMENT_PROGRAM); - // We always enter through the main function - d_pimpl->d_pixelShader->setParameter("entry_point", "main"); - if (d_pimpl->d_useGLSL) - { - // We check if we want to use a GLSL core shader, which is required for the Ogre OpenGL 3+ Renderer - if(d_pimpl->d_useGLSLCore) + if (Ogre::GpuProgramManager::getSingleton().isSyntaxSupported("ps_5_0")) { - d_pimpl->d_pixelShader->setParameter("target", "glsl"); - d_pimpl->d_pixelShader->setSource(S_glsl_core_ps_source); - } - else // else we use regular GLSL shader, as in the normal Ogre OpenGL Renderer - { - d_pimpl->d_pixelShader->setParameter("target", "arbfp1"); - d_pimpl->d_pixelShader->setSource(S_glsl_compat_ps_source); - } - } - else - { - // D3D shaders - if (Ogre::GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0")) - { - d_pimpl->d_pixelShader->setParameter("target", "ps_4_0"); - d_pimpl->d_pixelShader->setSource(S_hlsl_ps_source); + texture_ps->setParameter("target", "ps_5_0"); + texture_ps->setSource(PixelShaderTextured_HLSL); + + colour_ps->setParameter("target", "ps_5_0"); + colour_ps->setSource(PixelShaderColoured_HLSL); } else if (Ogre::GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_0")) { - d_pimpl->d_pixelShader->setParameter("target", "ps_2_0"); - d_pimpl->d_pixelShader->setSource(S_hlsl_ps_source); + texture_ps->setParameter("target", "ps_2_0"); + texture_ps->setSource(PixelShaderTextured_HLSL); + + colour_ps->setParameter("target", "ps_2_0"); + colour_ps->setSource(PixelShaderColoured_HLSL); } else { - d_pimpl->d_vertexShader.setNull(); - d_pimpl->d_pixelShader.setNull(); - CEGUI_THROW(RendererException( "OgreRenderer::initialiseShaders: No supported syntax - " - "unable to compile '__cegui_internal_ps__'")); + "unable to compile for ps_5_0 or ps_2_0")); } + } - d_pimpl->d_pixelShader->load(); + // Load all the shaders after setting the source code + texture_vs->load(); + texture_ps->load(); + colour_vs->load(); + colour_ps->load(); - d_pimpl->d_vertexShaderParameters = - d_pimpl->d_vertexShader->createParameters(); + d_pimpl->d_texturedShaderWrapper = new OgreShaderWrapper(*this, + *d_pimpl->d_renderSystem, texture_vs, texture_ps); - d_pimpl->d_pixelShaderParameters = - d_pimpl->d_pixelShader->createParameters(); + d_pimpl->d_colouredShaderWrapper = new OgreShaderWrapper(*this, + *d_pimpl->d_renderSystem, colour_vs, colour_ps); } -//----------------------------------------------------------------------------// void OgreRenderer::cleanupShaders() { - d_pimpl->d_pixelShaderParameters.setNull(); - d_pimpl->d_vertexShaderParameters.setNull(); - d_pimpl->d_pixelShader.setNull(); - d_pimpl->d_vertexShader.setNull(); + delete d_pimpl->d_texturedShaderWrapper; + delete d_pimpl->d_colouredShaderWrapper; } //----------------------------------------------------------------------------// @@ -860,7 +1034,6 @@ void OgreRenderer::setupRenderingBlendMode(const BlendMode mode, SBF_ONE); } - //----------------------------------------------------------------------------// void OgreRenderer::setFrameControlExecutionEnabled(const bool enabled) { @@ -878,6 +1051,38 @@ bool OgreRenderer::isFrameControlExecutionEnabled() const return d_pimpl->d_makeFrameControlCalls; } +//----------------------------------------------------------------------------// +static const Ogre::LayerBlendModeEx S_colourBlendMode = +{ + Ogre::LBT_COLOUR, + Ogre::LBX_MODULATE, + Ogre::LBS_TEXTURE, + Ogre::LBS_DIFFUSE, + Ogre::ColourValue(0, 0, 0, 0), + Ogre::ColourValue(0, 0, 0, 0), + 0, 0, 0 +}; + +//----------------------------------------------------------------------------// +static const Ogre::LayerBlendModeEx S_alphaBlendMode = +{ + Ogre::LBT_ALPHA, + Ogre::LBX_MODULATE, + Ogre::LBS_TEXTURE, + Ogre::LBS_DIFFUSE, + Ogre::ColourValue(0, 0, 0, 0), + Ogre::ColourValue(0, 0, 0, 0), + 0, 0, 0 +}; + +//----------------------------------------------------------------------------// +static const Ogre::TextureUnitState::UVWAddressingMode S_textureAddressMode = +{ + Ogre::TextureUnitState::TAM_CLAMP, + Ogre::TextureUnitState::TAM_CLAMP, + Ogre::TextureUnitState::TAM_CLAMP +}; + //----------------------------------------------------------------------------// void OgreRenderer::initialiseRenderStateSettings() { @@ -892,8 +1097,7 @@ void OgreRenderer::initialiseRenderStateSettings() d_pimpl->d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true); d_pimpl->d_renderSystem->setShadingType(SO_GOURAUD); d_pimpl->d_renderSystem->_setPolygonMode(PM_SOLID); - - bindShaders(); + d_pimpl->d_renderSystem->setScissorTest(false); // set alpha blending to known state setupRenderingBlendMode(BM_NORMAL, true); @@ -905,154 +1109,283 @@ void OgreRenderer::setDefaultRootRenderTarget(Ogre::RenderTarget& target) d_pimpl->d_defaultTarget->setOgreRenderTarget(target); } +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +void OgreRenderer::updateWorkspaceRenderTarget(Ogre::RenderTarget& target) +{ + // There seems to be no way to change the target, so we need to recreate it + Ogre::CompositorManager2* manager = d_pimpl->d_ogreRoot-> + getCompositorManager2(); + + d_pimpl->d_ogreRoot->getCompositorManager2()->removeWorkspace( + d_pimpl->d_workspace); + + // The -1 should guarantee this to be rendered last on top of everything + d_pimpl->d_workspace = manager->addWorkspace(d_pimpl->d_dummyScene, + &target, d_pimpl->d_dummyCamera, "CEGUI_workspace", true, -1); +} +#endif // CEGUI_USE_OGRE_COMPOSITOR2 + //----------------------------------------------------------------------------// -void OgreRenderer::bindShaders() +void OgreRenderer::setViewProjectionMatrix(const glm::mat4& viewProjMatrix) { - if (isUsingShaders()) + d_pimpl->d_renderSystem->_setProjectionMatrix( OgreRenderer::glmToOgreMatrix(viewProjMatrix) ); + + d_viewProjectionMatrix = viewProjMatrix; + + if (d_pimpl->d_renderSystem->_getViewport()->getTarget()->requiresTextureFlipping()) { - if (Ogre::GpuProgram* prog = d_pimpl->d_vertexShader->_getBindingDelegate()) - d_pimpl->d_renderSystem->bindGpuProgram(prog); + d_viewProjectionMatrix[0][1] = -d_viewProjectionMatrix[0][1]; + d_viewProjectionMatrix[1][1] = -d_viewProjectionMatrix[1][1]; + d_viewProjectionMatrix[2][1] = -d_viewProjectionMatrix[2][1]; + d_viewProjectionMatrix[3][1] = -d_viewProjectionMatrix[3][1]; + } +} - if (Ogre::GpuProgram* prog = d_pimpl->d_pixelShader->_getBindingDelegate()) - d_pimpl->d_renderSystem->bindGpuProgram(prog); +//----------------------------------------------------------------------------// +void OgreRenderer::bindBlendMode(BlendMode blend) +{ + setupRenderingBlendMode(blend, false); +} + +//----------------------------------------------------------------------------// +RefCounted OgreRenderer::createRenderMaterial( + const DefaultShaderType shaderType) const +{ + if (shaderType == DS_TEXTURED) + { + RefCounted render_material(new + RenderMaterial(d_pimpl->d_texturedShaderWrapper)); + + return render_material; + } + else if (shaderType == DS_SOLID) + { + RefCounted render_material(new + RenderMaterial(d_pimpl->d_colouredShaderWrapper)); + + return render_material; } else { - d_pimpl->d_renderSystem->unbindGpuProgram(Ogre::GPT_VERTEX_PROGRAM); - d_pimpl->d_renderSystem->unbindGpuProgram(Ogre::GPT_FRAGMENT_PROGRAM); + CEGUI_THROW(RendererException("A default shader of this type does not exist.")); + + return RefCounted(); } } //----------------------------------------------------------------------------// -bool OgreRenderer::isUsingShaders() const +GeometryBuffer& OgreRenderer::createGeometryBufferColoured( + CEGUI::RefCounted renderMaterial) { - return d_pimpl->d_useShaders; + OgreGeometryBuffer* geom_buffer = new OgreGeometryBuffer(*this, + *d_pimpl->d_renderSystem, renderMaterial); + + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->finaliseVertexAttributes( + OgreGeometryBuffer::MT_COLOURED); + + addGeometryBuffer(*geom_buffer); + return *geom_buffer; } //----------------------------------------------------------------------------// -void OgreRenderer::setUsingShaders(const bool use_shaders) +GeometryBuffer& OgreRenderer::createGeometryBufferTextured( + CEGUI::RefCounted renderMaterial) { - if (d_pimpl->d_useShaders == use_shaders) - return; + OgreGeometryBuffer* geom_buffer = new OgreGeometryBuffer(*this, + *d_pimpl->d_renderSystem, renderMaterial); + + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->addVertexAttribute(VAT_TEXCOORD0); + geom_buffer->finaliseVertexAttributes( + OgreGeometryBuffer::MT_TEXTURED); - if (use_shaders) - initialiseShaders(); - else - cleanupShaders(); + addGeometryBuffer(*geom_buffer); + return *geom_buffer; +} - d_pimpl->d_useShaders = use_shaders; +//----------------------------------------------------------------------------// +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +Ogre::SceneManager& OgreRenderer::getDummyScene() const{ + return *d_pimpl->d_dummyScene; } +#endif //----------------------------------------------------------------------------// -void OgreRenderer::updateShaderParams() const +Ogre::HardwareVertexBufferSharedPtr OgreRenderer::getVertexBuffer(size_t + min_size) { - if (!isUsingShaders()) - return; + Ogre::HardwareVertexBufferSharedPtr result(0); - if (d_pimpl->d_useGLSL) + if (d_pimpl->d_vbPool.empty()) + return result; + + size_t best_found = -1; + size_t best_over = -1; + + // The vector is searched in reverse to find exact matches from the end + // which will allow popping the last element which is faster then removing + // the first one + + for (size_t i = d_pimpl->d_vbPool.size(); --i > 0;) { - if(d_pimpl->d_useGLSLCore) + // It seems that there can be nullptrs in the pool + Ogre::HardwareVertexBufferSharedPtr current = d_pimpl->d_vbPool[i]; + + if (!current.get()){ + + d_pimpl->d_vbPool.erase(d_pimpl->d_vbPool.begin()+i); + continue; + } + + size_t current_over = current->getNumVertices()-min_size; + + // Perfect match stops searching instantly + if (current_over == 0) { - d_pimpl->d_vertexShaderParameters-> - setNamedConstant("modelViewPerspMatrix", getWorldViewProjMatrix()); - d_pimpl->d_renderSystem-> - bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, - d_pimpl->d_vertexShaderParameters, - Ogre::GPV_ALL); + best_found = i; + best_over = 0; + break; } - d_pimpl->d_pixelShaderParameters-> - setNamedConstant("texture0", 0); + if (current_over <= best_over) + { - d_pimpl->d_renderSystem-> - bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, - d_pimpl->d_pixelShaderParameters, - Ogre::GPV_ALL); + best_over = current_over; + best_found = i; + } } - else + + // If the smallest buffer is too large then none is found + // This will also be true if all buffers are too small + if (best_over > min_size*1.5f || best_found >= d_pimpl->d_vbPool.size()) { - d_pimpl->d_vertexShaderParameters-> - setNamedConstant("worldViewProjMatrix", getWorldViewProjMatrix()); + // Clear if there are too many buffers + int over_size = d_pimpl->d_vbPool.size()- + VERTEXBUFFER_POOL_SIZE_STARTCLEAR; - d_pimpl->d_renderSystem-> - bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, - d_pimpl->d_vertexShaderParameters, - Ogre::GPV_ALL); + if (over_size > 2) + cleanLargestVertexBufferPool(over_size); + + } else { + + result = d_pimpl->d_vbPool[best_found]; + + d_pimpl->d_vbPool.erase(d_pimpl->d_vbPool.begin()+best_found); + + // We want to avoid using too much memory + // even if matches are always found + int over_size = d_pimpl->d_vbPool.size()- + (VERTEXBUFFER_POOL_SIZE_STARTCLEAR*5); + + if (over_size > 5) + cleanLargestVertexBufferPool(over_size/2); } + + return result; } -//----------------------------------------------------------------------------// -const Ogre::Matrix4& OgreRenderer::getWorldViewProjMatrix() const +void OgreRenderer::returnVertexBuffer(Ogre::HardwareVertexBufferSharedPtr + buffer) { - if (!d_pimpl->d_combinedMatrixValid) - { - Ogre::Matrix4 final_prj(d_pimpl->d_projectionMatrix); + d_pimpl->d_vbPool.push_back(buffer); +} - if (d_pimpl->d_renderSystem->_getViewport()->getTarget()-> - requiresTextureFlipping()) - { - final_prj[1][0] = -final_prj[1][0]; - final_prj[1][1] = -final_prj[1][1]; - final_prj[1][2] = -final_prj[1][2]; - final_prj[1][3] = -final_prj[1][3]; - } +void OgreRenderer::clearVertexBufferPool() +{ + d_pimpl->d_vbPool.clear(); +} - d_pimpl->d_worldViewProjMatrix = - final_prj * d_pimpl->d_viewMatrix * d_pimpl->d_worldMatrix; +bool hardwareBufferSizeLess(const Ogre::HardwareVertexBufferSharedPtr &first, + const Ogre::HardwareVertexBufferSharedPtr &second) +{ + return first->getNumVertices() < second->getNumVertices(); +} + +void OgreRenderer::cleanLargestVertexBufferPool(size_t count) +{ + // The easiest way might be to sort the vector and delete the last count + // elements + std::sort(d_pimpl->d_vbPool.begin(), d_pimpl->d_vbPool.end(), + &hardwareBufferSizeLess); - d_pimpl->d_combinedMatrixValid = true; + // Adjust the count if there aren't enough elements to delete to avoid + // asserting + if (count >= d_pimpl->d_vbPool.size()) + { + + d_pimpl->d_vbPool.clear(); } - return d_pimpl->d_worldViewProjMatrix; + for (size_t i = 0; i < count; i++) + { + + d_pimpl->d_vbPool.pop_back(); + } } //----------------------------------------------------------------------------// -const Ogre::Matrix4& OgreRenderer::getWorldMatrix() const +void OgreRenderer::initialiseTextureStates() { - return d_pimpl->d_worldMatrix; + d_pimpl->d_renderSystem->_setTextureCoordCalculation(0, Ogre::TEXCALC_NONE); + d_pimpl->d_renderSystem->_setTextureCoordSet(0, 0); + d_pimpl->d_renderSystem->_setTextureAddressingMode(0, S_textureAddressMode); + d_pimpl->d_renderSystem->_setTextureMatrix(0, Ogre::Matrix4::IDENTITY); + d_pimpl->d_renderSystem->_setTextureUnitFiltering(0, Ogre::FO_LINEAR, Ogre::FO_LINEAR, Ogre::FO_NONE); + d_pimpl->d_renderSystem->_setAlphaRejectSettings(Ogre::CMPF_ALWAYS_PASS, 0, false); + d_pimpl->d_renderSystem->_setTextureBlendMode(0, S_colourBlendMode); + d_pimpl->d_renderSystem->_setTextureBlendMode(0, S_alphaBlendMode); + d_pimpl->d_renderSystem->_disableTextureUnitsFrom(1); } //----------------------------------------------------------------------------// -const Ogre::Matrix4& OgreRenderer::getViewMatrix() const +bool OgreRenderer::usesOpenGL() { - return d_pimpl->d_viewMatrix; + return d_pimpl->d_renderSystem->getName().find("OpenGL") != Ogre::String::npos; } //----------------------------------------------------------------------------// -const Ogre::Matrix4& OgreRenderer::getProjectionMatrix() const +bool OgreRenderer::usesDirect3D() { - return d_pimpl->d_projectionMatrix; + return d_pimpl->d_renderSystem->getName().find("Direct3D") != Ogre::String::npos; } //----------------------------------------------------------------------------// -void OgreRenderer::setWorldMatrix(const Ogre::Matrix4& m) +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +OgreGUIRenderQueueListener::OgreGUIRenderQueueListener(OgreRenderer* owner) : + d_enabled(true), d_owner(owner) { - d_pimpl->d_renderSystem->_setWorldMatrix(m); - d_pimpl->d_worldMatrix = m; - d_pimpl->d_combinedMatrixValid = false; } //----------------------------------------------------------------------------// -void OgreRenderer::setViewMatrix(const Ogre::Matrix4& m) +void OgreGUIRenderQueueListener::setCEGUIRenderEnabled(bool enabled) { - d_pimpl->d_renderSystem->_setViewMatrix(m); - - d_pimpl->d_viewMatrix = m; - d_pimpl->d_combinedMatrixValid = false; + d_enabled = enabled; } //----------------------------------------------------------------------------// -void OgreRenderer::setProjectionMatrix(const Ogre::Matrix4& m) +bool OgreGUIRenderQueueListener::isCEGUIRenderEnabled() const { - d_pimpl->d_renderSystem->_setProjectionMatrix(m); + return d_enabled; +} - d_pimpl->d_projectionMatrix = m; - d_pimpl->d_combinedMatrixValid = false; +void OgreGUIRenderQueueListener::passPreExecute(Ogre::CompositorPass *pass) +{ + + if (d_enabled && pass->getType() == Ogre::PASS_SCENE) + { + // We should only render contexts that are on this render target + System::getSingleton().renderAllGUIContextsOnTarget(d_owner); + } } //----------------------------------------------------------------------------// + +#else OgreGUIFrameListener::OgreGUIFrameListener() : d_enabled(true) { @@ -1078,5 +1411,6 @@ bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&) return true; } +#endif // CEGUI_USE_OGRE_COMPOSITOR2 } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/Ogre/ShaderWrapper.cpp b/cegui/src/RendererModules/Ogre/ShaderWrapper.cpp new file mode 100644 index 000000000..3ea40d6a5 --- /dev/null +++ b/cegui/src/RendererModules/Ogre/ShaderWrapper.cpp @@ -0,0 +1,199 @@ +/*********************************************************************** + created: Fri, 4th July 2014 + author: Henri I Hyyryläinen +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "CEGUI/RendererModules/Ogre/ShaderWrapper.h" +#include "CEGUI/RendererModules/Ogre/Texture.h" +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/Exceptions.h" + +#include +#include "OgreRenderSystem.h" +#include "CEGUI/Logger.h" + +// Start of CEGUI namespace section +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +OgreShaderWrapper::OgreShaderWrapper(OgreRenderer& owner, + Ogre::RenderSystem& rs, + Ogre::HighLevelGpuProgramPtr vs, Ogre::HighLevelGpuProgramPtr ps) + : d_vertexShader(vs), + d_pixelShader(ps), + d_owner(owner), + d_renderSystem(rs), + d_lastMatrix(), + d_previousAlpha(-1.f) +{ + d_vertexParameters = d_vertexShader->createParameters(); + d_pixelParameters = d_pixelShader->createParameters(); + + const Ogre::GpuConstantDefinitionMap& vertex_map = + d_vertexShader->getConstantDefinitions().map; + + Ogre::GpuConstantDefinitionMap::const_iterator target = + vertex_map.find("modelViewProjMatrix"); + + const Ogre::GpuConstantDefinitionMap& pixel_map = + d_pixelShader->getConstantDefinitions().map; + + Ogre::GpuConstantDefinitionMap::const_iterator target2 = + pixel_map.find("alphaPercentage"); + + // We will throw an error if shaders/parameter names are invalid + if (target == vertex_map.end() || target2 == pixel_map.end()) + { + CEGUI_THROW(RendererException("Ogre renderer couldn't find an index for" + " the shader data.")); + + return; + } + + d_paramTypeToIndex[SPT_MATRIX_4X4] = target->second.physicalIndex; + d_paramTypeToIndex[SPT_FLOAT] = target2->second.physicalIndex; + d_paramTypeToIndex[SPT_TEXTURE] = 0; +} + +//----------------------------------------------------------------------------// +OgreShaderWrapper::~OgreShaderWrapper() +{ + d_pixelParameters.setNull(); + d_vertexParameters.setNull(); + d_vertexShader.setNull(); + d_pixelShader.setNull(); +} + +//----------------------------------------------------------------------------// +Ogre::GpuProgramParametersSharedPtr OgreShaderWrapper::getVertexParameters() const +{ + return d_vertexParameters; +} + +//----------------------------------------------------------------------------// +void OgreShaderWrapper::prepareForRendering(const ShaderParameterBindings* + shaderParameterBindings) +{ + Ogre::GpuProgram* vs = d_vertexShader->_getBindingDelegate(); + d_renderSystem.bindGpuProgram(vs); + + Ogre::GpuProgram* ps = d_pixelShader->_getBindingDelegate(); + d_renderSystem.bindGpuProgram(ps); + + const ShaderParameterBindings::ShaderParameterBindingsMap& + shader_parameter_bindings = shaderParameterBindings-> + getShaderParameterBindings(); + + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = + shader_parameter_bindings.begin(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = + shader_parameter_bindings.end(); + + for (; iter != end; ++iter) + { + const CEGUI::ShaderParameter* parameter = iter->second; + const ShaderParamType parameterType = parameter->getType(); + + std::map::const_iterator find_iter = d_paramTypeToIndex. + find(parameterType); + + if (find_iter == d_paramTypeToIndex.end()) + { + std::string errorMessage = std::string("Unknown variable name: \"")+ + iter->first + "\""; + CEGUI_THROW(RendererException(errorMessage)); + } + + size_t target_index = find_iter->second; + + switch (parameterType) + { + case SPT_TEXTURE: + { + const CEGUI::ShaderParameterTexture* parameterTexture = + static_cast(parameter); + + const CEGUI::OgreTexture* texture = static_cast(parameterTexture->d_parameterValue); + + Ogre::TexturePtr actual_texture = texture->getOgreTexture(); + + if (actual_texture.isNull()) + { + CEGUI_THROW(RendererException("Ogre texture ptr is empty")); + } + + d_renderSystem._setTexture(0, true, actual_texture); + d_owner.initialiseTextureStates(); + + break; + } + case SPT_MATRIX_4X4: + { + // This is the "modelViewProjMatrix" + const CEGUI::ShaderParameterMatrix* mat = static_cast(parameter); + + if (d_lastMatrix != mat->d_parameterValue) + { + d_vertexParameters->_writeRawConstants(target_index, + glm::value_ptr(mat->d_parameterValue), + 16); + d_lastMatrix = mat->d_parameterValue; + } + break; + } + case SPT_FLOAT: + { + // This is the alpha value + const CEGUI::ShaderParameterFloat* new_alpha = static_cast(parameter); + + if (d_previousAlpha != new_alpha->d_parameterValue) + { + d_previousAlpha = new_alpha->d_parameterValue; + + d_pixelParameters->_writeRawConstants(target_index, + &d_previousAlpha, 1); + } + + break; + } + default: + CEGUI_THROW(RendererException("Invalid parameter type")); + } + } + + // Pass the finalized parameters to Ogre + d_renderSystem.bindGpuProgramParameters(Ogre::GPT_VERTEX_PROGRAM, + d_vertexParameters, Ogre::GPV_ALL); + d_renderSystem.bindGpuProgramParameters(Ogre::GPT_FRAGMENT_PROGRAM, + d_pixelParameters, Ogre::GPV_ALL); +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/RendererModules/Ogre/Shaders.inl b/cegui/src/RendererModules/Ogre/Shaders.inl new file mode 100644 index 000000000..6a229ebb0 --- /dev/null +++ b/cegui/src/RendererModules/Ogre/Shaders.inl @@ -0,0 +1,328 @@ +/*********************************************************************** + created: Fri, 4th July 2014 + author: Henri I Hyyryläinen +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +namespace CEGUI +{ +// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders + +//! A string containing an HLSL vertex shader for solid colouring of a polygon +static Ogre::String VertexShaderColoured_HLSL("" +"float4x4 modelViewProjMatrix;\n" +"\n" +"struct VertOut\n" +"{\n" +" float4 pos : SV_Position;\n" +" float4 colour : COLOR;\n" +"};\n" +"\n" +"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n" +"{\n" +" VertOut output;\n" +"\n" +" output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n" +" output.colour = inColour;\n" +"\n" +" return output;\n" +"}\n" +); + +//! A string containing an HLSL fragment shader for solid colouring of a polygon +static Ogre::String PixelShaderColoured_HLSL("" +"uniform float alphaPercentage;\n" +"\n" +"struct VS_OUT\n" +"{\n" +" float4 position : POSITION;\n" +" float4 colour : COLOR;\n" +"};\n" +"\n" +"float4 main(VS_OUT input) : COLOR\n" +"{\n" +" float4 colour = input.colour;\n" +" colour.a *= alphaPercentage;\n" +" return colour;\n" +"}\n" +"\n" +); + +/*! +A string containing an HLSL vertex shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +static Ogre::String VertexShaderTextured_HLSL("" +"float4x4 modelViewProjMatrix;\n" +"\n" +"struct VertOut\n" +"{\n" +" float4 pos : SV_Position;\n" +" float4 colour : COLOR;\n" +" float2 texcoord0 : TEXCOORD;\n" +"};\n" +"\n" +"// Vertex shader\n" +"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n" +"{\n" +" VertOut output;\n" +"\n" +" output.pos = mul(modelViewProjMatrix, inPos);\n" +" output.texcoord0 = inTexCoord0;\n" +" output.colour = inColour;\n" +"\n" +" return output;\n" +"}\n" +); + +/*! +A string containing an HLSL fragment shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +static Ogre::String PixelShaderTextured_HLSL("" +"uniform float alphaPercentage;\n" +"struct VS_OUT\n" +"{\n" +" float4 position : POSITION;\n" +" float4 colour : COLOR;\n" +" float2 uv : TEXCOORD0;\n" +"};\n" +"\n" +"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, " +" uniform sampler2D texture0 : TEXUNIT0) : COLOR\n" +"{\n" +" colour = tex2D(texture0, uv) * colour;\n" +" colour.a *= alphaPercentage;\n" +" return colour;\n" +"}\n" +"\n" +); + +//! Shader for older OpenGL versions < 3 +static Ogre::String VertexShaderTextured_GLSL_Compat("" + "uniform mat4 modelViewProjMatrix;\n" + "void main(void)" + "{" + " gl_TexCoord[0] = gl_MultiTexCoord0;" + " gl_FrontColor = gl_Color;" + " gl_Position = modelViewProjMatrix * gl_Vertex;" + "}" +); + +//! Shader for older OpenGL versions < 3 +static Ogre::String PixelShaderTextured_GLSL_Compat("" + "uniform sampler2D texture0;" + "uniform float alphaPercentage;\n" + "void main(void)" + "{" + " gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;" + " gl_FragColor.a *= alphaPercentage;\n" + "}" +); + +//! Shader for older OpenGL versions < 3 +static Ogre::String VertexShaderColoured_GLSL_Compat("" + "uniform mat4 modelViewProjMatrix;\n" + "void main(void)" + "{" + " gl_FrontColor = gl_Color;" + " gl_Position = modelViewProjMatrix * gl_Vertex;" + "}" +); + +//! Shader for older OpenGL versions < 3 +static Ogre::String PixelShaderColoured_GLSL_Compat("" + "uniform float alphaPercentage;\n" + "void main(void)\n" + "{" + " gl_FragColor = gl_Color;" + " gl_FragColor.a *= alphaPercentage;\n" + "}" +); + +//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon +static Ogre::String VertexShaderColoured_GLSL("" + "#version 150 core\n" + + "uniform mat4 modelViewProjMatrix;\n" + + "in vec4 vertex;\n" + "in vec4 colour;\n" + + "out vec4 exColour;" + + "void main(void)\n" + "{\n" + " exColour = colour;\n" + + " gl_Position = modelViewProjMatrix * vertex;\n" + "}" +); + +//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon +static Ogre::String PixelShaderColoured_GLSL("" + "#version 150 core\n" + + "in vec4 exColour;\n" + + "out vec4 fragColour;\n" + + "uniform float alphaPercentage;\n" + + "void main(void)\n" + "{\n" + " fragColour = exColour;\n" + " fragColour.a *= alphaPercentage;\n" + "}" +); + +/*! +A string containing an OpenGL3 vertex shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +static Ogre::String VertexShaderTextured_GLSL("" + "#version 150 core\n" + + "uniform mat4 modelViewProjMatrix;\n" + + "in vec4 vertex;\n" + "in vec4 colour;\n" + "in vec2 uv0;\n" + + "out vec2 exTexCoord;\n" + "out vec4 exColour;\n" + + "void main()\n" + "{\n" + " exTexCoord = uv0;\n" + " exColour = colour;\n" + + " gl_Position = modelViewProjMatrix * vertex;\n" + "}" +); + +/*! +A string containing an OpenGL3 fragment shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +static Ogre::String PixelShaderTextured_GLSL("" + "#version 150 core\n" + + "uniform sampler2D texture0;\n" + "uniform float alphaPercentage;\n" + + + "in vec2 exTexCoord;\n" + "in vec4 exColour;\n" + + "out vec4 fragColour;\n" + + "void main(void)\n" + "{\n" + " fragColour = texture(texture0, exTexCoord) * exColour;\n" + " fragColour.a *= alphaPercentage;\n" + "}" +); + +//! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon +static Ogre::String VertexShaderColoured_GLSLES1("" + "#version 100\n" + "precision mediump int;\n" + "precision mediump float;\n" + "uniform mat4 modelViewProjMatrix;\n" + "attribute vec4 vertex;\n" + "attribute vec4 colour;\n" + "varying vec4 exColour;\n" + "void main(void)\n" + "{\n" + " exColour = colour;\n" + " gl_Position = modelViewProjMatrix * vertex;\n" + "}" +); + +//! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon +static Ogre::String PixelShaderColoured_GLSLES1("" + "#version 100\n" + "precision mediump int;\n" + "precision mediump float;\n" + "varying vec4 exColour;\n" + "uniform float alphaPercentage;\n" + "void main(void)\n" + "{\n" + " gl_FragColor = exColour;\n" + " gl_FragColor.a *= alphaPercentage;\n" + "}" +); + +/*! +A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +static Ogre::String VertexShaderTextured_GLSLES1("" + "#version 100\n" + "precision mediump int;\n" + "precision mediump float;\n" + "uniform mat4 modelViewProjMatrix;\n" + "attribute vec4 vertex;\n" + "attribute vec4 colour;\n" + "attribute vec2 uv0;\n" + "varying vec2 exTexCoord;\n" + "varying vec4 exColour;\n" + "void main()\n" + "{\n" + " exTexCoord = uv0;\n" + " exColour = colour;" + " gl_Position = modelViewProjMatrix * vertex;\n" + "}" +); + +/*! +A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +static Ogre::String PixelShaderTextured_GLSLES1("" + "#version 100\n" + "precision mediump int;\n" + "precision mediump float;\n" + "precision lowp sampler2D;\n" + "uniform sampler2D texture0;\n" + "uniform float alphaPercentage;\n" + "varying vec2 exTexCoord;\n" + "varying vec4 exColour;\n" + "void main(void)\n" + "{\n" + " gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n" + " gl_FragColor.a *= alphaPercentage;\n" + "}" +); + + +} + diff --git a/cegui/src/RendererModules/Ogre/Texture.cpp b/cegui/src/RendererModules/Ogre/Texture.cpp index e9ecf7049..9a048e57e 100644 --- a/cegui/src/RendererModules/Ogre/Texture.cpp +++ b/cegui/src/RendererModules/Ogre/Texture.cpp @@ -41,14 +41,14 @@ static size_t calculateDataSize(const Sizef size, Texture::PixelFormat fmt) switch (fmt) { case Texture::PF_RGBA: - return size.d_width * size.d_height * 4; + return static_cast(size.d_width * size.d_height * 4); case Texture::PF_RGB: - return size.d_width * size.d_height * 3; + return static_cast(size.d_width * size.d_height * 3); case Texture::PF_RGB_565: case Texture::PF_RGBA_4444: - return size.d_width * size.d_height * 2; + return static_cast(size.d_width * size.d_height * 2); case Texture::PF_PVRTC2: return (static_cast(size.d_width * size.d_height) * 2 + 7) / 8; @@ -57,11 +57,11 @@ static size_t calculateDataSize(const Sizef size, Texture::PixelFormat fmt) return (static_cast(size.d_width * size.d_height) * 4 + 7) / 8; case Texture::PF_RGBA_DXT1: - return std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 8; + return static_cast( std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 8 ); case Texture::PF_RGBA_DXT3: case Texture::PF_RGBA_DXT5: - return std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 16; + return static_cast( std::ceil(size.d_width / 4) * std::ceil(size.d_height / 4) * 16 ); default: return 0; @@ -110,8 +110,8 @@ OgreTexture::OgreTexture(const String& name, const Sizef& sz) : CEGUI_THROW(RendererException( "Failed to create Texture object with spcecified size.")); - d_size.d_width = d_texture->getWidth(); - d_size.d_height = d_texture->getHeight(); + d_size.d_width = static_cast(d_texture->getWidth()); + d_size.d_height = static_cast(d_texture->getHeight()); d_dataSize = sz; updateCachedScaleValues(); } @@ -153,7 +153,7 @@ const Sizef& OgreTexture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& OgreTexture::getTexelScaling() const +const glm::vec2& OgreTexture::getTexelScaling() const { return d_texelScaling; } @@ -212,11 +212,11 @@ void OgreTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, char* bufferCopy = new char[byte_size]; memcpy(bufferCopy, buffer, byte_size); - const Ogre::PixelBox* pixelBox = new Ogre::PixelBox(buffer_size.d_width, buffer_size.d_height, + const Ogre::PixelBox* pixelBox = new Ogre::PixelBox(static_cast(buffer_size.d_width), static_cast(buffer_size.d_height), 1, toOgrePixelFormat(pixel_format), bufferCopy); d_texture->freeInternalResources(); - d_texture->setWidth(buffer_size.d_width); - d_texture->setHeight(buffer_size.d_height); + d_texture->setWidth(static_cast(buffer_size.d_width)); + d_texture->setHeight(static_cast(buffer_size.d_height)); d_texture->setDepth(1); d_texture->createInternalResources(); d_texture->getBuffer(0,0).get()->blitFromMemory(*pixelBox); @@ -226,8 +226,8 @@ void OgreTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, CEGUI_THROW(RendererException( "Failed to blit to Texture from memory.")); - d_size.d_width = d_texture->getWidth(); - d_size.d_height = d_texture->getHeight(); + d_size.d_width = static_cast(d_texture->getWidth()); + d_size.d_height = static_cast(d_texture->getHeight()); d_dataSize = buffer_size; updateCachedScaleValues(); } @@ -241,9 +241,15 @@ void OgreTexture::blitFromMemory(const void* sourceData, const Rectf& area) // NOTE: const_cast because Ogre takes pointer to non-const here. Rather // than allow that to dictate poor choices in our own APIs, we choose to // address the issue as close to the source of the problem as possible. - Ogre::PixelBox pb(area.getWidth(), area.getHeight(), - 1, Ogre::PF_A8R8G8B8, const_cast(sourceData)); - Ogre::Image::Box box(area.left(), area.top(), area.right(), area.bottom()); + Ogre::PixelBox pb(static_cast(area.getWidth()), + static_cast(area.getHeight()), + 1, + Ogre::PF_A8R8G8B8, const_cast(sourceData)); + + Ogre::Image::Box box(static_cast(area.left()), + static_cast(area.top()), + static_cast(area.right()), + static_cast(area.bottom()) ); d_texture->getBuffer()->blitFromMemory(pb, box); } @@ -253,7 +259,7 @@ void OgreTexture::blitToMemory(void* targetData) if (d_texture.isNull()) // TODO: exception? return; - Ogre::PixelBox pb(d_size.d_width, d_size.d_height, + Ogre::PixelBox pb(static_cast(d_size.d_width), static_cast(d_size.d_height), 1, Ogre::PF_A8R8G8B8, targetData); d_texture->getBuffer()->blitToMemory(pb); } @@ -297,7 +303,7 @@ void OgreTexture::updateCachedScaleValues() // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. - d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); + d_texelScaling.x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale @@ -309,7 +315,7 @@ void OgreTexture::updateCachedScaleValues() // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. - d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); + d_texelScaling.y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// @@ -322,8 +328,8 @@ void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership) if (!d_texture.isNull()) { - d_size.d_width = d_texture->getWidth(); - d_size.d_height= d_texture->getHeight(); + d_size.d_width = static_cast(d_texture->getWidth()); + d_size.d_height= static_cast(d_texture->getHeight()); d_dataSize = d_size; } else diff --git a/cegui/src/RendererModules/Ogre/TextureTarget.cpp b/cegui/src/RendererModules/Ogre/TextureTarget.cpp index 0387baaa4..c23506ee6 100644 --- a/cegui/src/RendererModules/Ogre/TextureTarget.cpp +++ b/cegui/src/RendererModules/Ogre/TextureTarget.cpp @@ -77,7 +77,7 @@ void OgreTextureTarget::clear() d_renderSystem._setViewport(d_viewport); d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR, - Ogre::ColourValue(0, 0, 0, 0)); + Ogre::ColourValue(0, 0, 0, 0)); #if OGRE_VERSION < 0x10800 if (saved_vp) @@ -100,17 +100,24 @@ void OgreTextureTarget::declareRenderSize(const Sizef& sz) if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height)) return; - Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual( - OgreTexture::getUniqueName(), - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8, - Ogre::TU_RENDERTARGET); + Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual(OgreTexture::getUniqueName(), + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, + Ogre::TEX_TYPE_2D, + static_cast(sz.d_width), + static_cast(sz.d_height), + 1, + 0, + Ogre::PF_A8R8G8B8, + Ogre::TU_RENDERTARGET); d_renderTarget = rttTex->getBuffer()->getRenderTarget(); - Rectf init_area( - Vector2f(0, 0), - Sizef(d_renderTarget->getWidth(), d_renderTarget->getHeight()) + const Rectf init_area( + glm::vec2(0.0f, 0.0f), + Sizef( + static_cast(d_renderTarget->getWidth()), + static_cast(d_renderTarget->getHeight()) + ) ); setArea(init_area); diff --git a/cegui/src/RendererModules/Ogre/WindowTarget.cpp b/cegui/src/RendererModules/Ogre/WindowTarget.cpp index d2aaa375f..5886da5ed 100644 --- a/cegui/src/RendererModules/Ogre/WindowTarget.cpp +++ b/cegui/src/RendererModules/Ogre/WindowTarget.cpp @@ -68,10 +68,9 @@ void OgreWindowTarget::initRenderTarget(Ogre::RenderTarget& target) { d_renderTarget = ⌖ - Rectf init_area( - Vector2f(0, 0), - Sizef(d_renderTarget->getWidth(), d_renderTarget->getHeight()) - ); + Rectf init_area(glm::vec2(0.0f, 0.0f), + Sizef(static_cast(d_renderTarget->getWidth()), + static_cast(d_renderTarget->getHeight())) ); setArea(init_area); } diff --git a/cegui/src/RendererModules/OpenGL/CMakeLists.txt b/cegui/src/RendererModules/OpenGL/CMakeLists.txt index 7440caf0a..b4edee85f 100644 --- a/cegui/src/RendererModules/OpenGL/CMakeLists.txt +++ b/cegui/src/RendererModules/OpenGL/CMakeLists.txt @@ -20,33 +20,77 @@ endif() if (NOT CEGUI_BUILD_RENDERER_OPENGL) list (REMOVE_ITEM CORE_SOURCE_FILES GLRenderer.cpp GLGeometryBuffer.cpp - GLFBOTextureTarget.cpp) + GLFBOTextureTarget.cpp + GLShaderWrapper.cpp) list (REMOVE_ITEM CORE_HEADER_FILES ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLRenderer.h ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLFBOTextureTarget.h) + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLFBOTextureTarget.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLShaderWrapper.h) endif() +if (NOT CEGUI_BUILD_RENDERER_OPENGL3 AND NOT CEGUI_BUILD_RENDERER_OPENGLES2) + list (REMOVE_ITEM CORE_SOURCE_FILES Shader.cpp + ShaderManager.cpp + StateChangeWrapper.cpp + GLBaseShaderWrapper.cpp) + list (REMOVE_ITEM CORE_HEADER_FILES ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/Shader.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/ShaderManager.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/StateChangeWrapper.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderFrag.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderVert.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h) +endif() + + if (NOT CEGUI_BUILD_RENDERER_OPENGL3) list (REMOVE_ITEM CORE_SOURCE_FILES GL3Renderer.cpp + GL3Texture.cpp GL3GeometryBuffer.cpp GL3FBOTextureTarget.cpp - Shader.cpp - ShaderManager.cpp - StateChangeWrapper.cpp) + GL3Shader.cpp + GL3StateChangeWrapper.cpp) list (REMOVE_ITEM CORE_HEADER_FILES ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3Renderer.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3Texture.h ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/Shader.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/ShaderManager.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/StateChangeWrapper.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderFrag.h - ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderVert.h) + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3Shader.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3StateShaderWrapper.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h) +endif() + +#GL and GL3 both use GLTexture via inheritance +if (NOT CEGUI_BUILD_RENDERER_OPENGL3 AND NOT CEGUI_BUILD_RENDERER_OPENGL) + list (REMOVE_ITEM CORE_SOURCE_FILES GLTexture.cpp) + list (REMOVE_ITEM CORE_HEADER_FILES ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLTexture.h) +endif() + +if (NOT CEGUI_BUILD_RENDERER_OPENGLES2) + list (REMOVE_ITEM CORE_SOURCE_FILES GLES2Renderer.cpp + GLES2Texture.cpp + GLES2GeometryBuffer.cpp + GLES2FBOTextureTarget.cpp + GLES2StateChangeWrapper.cpp) + list (REMOVE_ITEM CORE_HEADER_FILES ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Renderer.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLES2Texture.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h + ${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/RendererModules/OpenGL/GLES2StateShaderWrapper.h) + endif() cegui_add_library(${CEGUI_TARGET_NAME} CORE_SOURCE_FILES CORE_HEADER_FILES) -cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGL) cegui_add_dependency(${CEGUI_TARGET_NAME} GLM) -cegui_add_dependency(${CEGUI_TARGET_NAME} GLEW) +if (CEGUI_BUILD_RENDERER_OPENGLES2) + if (CEGUI_BUILD_RENDERER_OPENGLES2_WITH_GLES3_SUPPORT) + add_definitions ( -DCEGUI_GLES3_SUPPORT ) + cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGLES3) + else() + cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGLES2) + endif() +endif() +if (CEGUI_BUILD_RENDERER_OPENGL OR CEGUI_BUILD_RENDERER_OPENGL3) + cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGL) + cegui_add_dependency(${CEGUI_TARGET_NAME} GLEW) +endif() cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME}) diff --git a/cegui/src/RendererModules/OpenGL/GL3FBOTextureTarget.cpp b/cegui/src/RendererModules/OpenGL/GL3FBOTextureTarget.cpp index 9bbf05b8e..628ac487a 100644 --- a/cegui/src/RendererModules/OpenGL/GL3FBOTextureTarget.cpp +++ b/cegui/src/RendererModules/OpenGL/GL3FBOTextureTarget.cpp @@ -24,8 +24,6 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - #include "CEGUI/RendererModules/OpenGL/GL3FBOTextureTarget.h" #include "CEGUI/Exceptions.h" #include "CEGUI/RenderQueue.h" @@ -33,6 +31,7 @@ #include "CEGUI/RendererModules/OpenGL/GL3Renderer.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" #include "CEGUI/Logger.h" @@ -47,7 +46,8 @@ const float OpenGL3FBOTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// OpenGL3FBOTextureTarget::OpenGL3FBOTextureTarget(OpenGL3Renderer& owner) : - OpenGLTextureTarget(owner) + OpenGLTextureTarget(owner), + d_glStateChanger(owner.getOpenGLStateChanger()) { // no need to initialise d_previousFrameBuffer here, it will be // initialised in activate() @@ -62,6 +62,8 @@ OpenGL3FBOTextureTarget::OpenGL3FBOTextureTarget(OpenGL3Renderer& owner) : OpenGL3FBOTextureTarget::~OpenGL3FBOTextureTarget() { glDeleteFramebuffers(1, &d_frameBuffer); + + glDeleteRenderbuffers(1, &d_stencilBufferRBO); } //----------------------------------------------------------------------------// @@ -115,8 +117,14 @@ void OpenGL3FBOTextureTarget::clear() // switch to our FBO glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); // Clear it. + d_glStateChanger->disable(GL_SCISSOR_TEST); glClearColor(0,0,0,0); - glClear(GL_COLOR_BUFFER_BIT); + + if(!d_usesStencil) + glClear(GL_COLOR_BUFFER_BIT); + else + glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + // switch back to rendering to the previously bound FBO glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); @@ -143,7 +151,7 @@ void OpenGL3FBOTextureTarget::initialiseRenderTexture() // set up the texture the FBO will draw to glGenTextures(1, &d_texture); - glBindTexture(GL_TEXTURE_2D, d_texture); + d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, @@ -153,6 +161,16 @@ void OpenGL3FBOTextureTarget::initialiseRenderTexture() glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, d_texture, 0); + // Set up the stencil buffer for the FBO + glGenRenderbuffers(1, &d_stencilBufferRBO); + glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); + glRenderbufferStorage(GL_RENDERBUFFER, + GL_STENCIL_INDEX8, + static_cast(DEFAULT_SIZE), + static_cast(DEFAULT_SIZE)); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, d_stencilBufferRBO); + //Check for framebuffer completeness checkFramebufferStatus(); @@ -163,7 +181,7 @@ void OpenGL3FBOTextureTarget::initialiseRenderTexture() d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize()); // restore previous texture binding. - glBindTexture(GL_TEXTURE_2D, old_tex); + d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// @@ -185,18 +203,25 @@ void OpenGL3FBOTextureTarget::resizeRenderTexture() } // set the texture to the required size - glBindTexture(GL_TEXTURE_2D, d_texture); + d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast(sz.d_width), static_cast(sz.d_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); + + glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); + glRenderbufferStorage(GL_RENDERBUFFER, + GL_STENCIL_INDEX8, + static_cast(sz.d_width), + static_cast(sz.d_height)); + clear(); // ensure the CEGUI::Texture is wrapping the gl texture and has correct size d_CEGUITexture->setOpenGLTexture(d_texture, sz); // restore previous texture binding. - glBindTexture(GL_TEXTURE_2D, old_tex); + d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); } //----------------------------------------------------------------------------// @@ -234,16 +259,16 @@ void OpenGL3FBOTextureTarget::checkFramebufferStatus() stringStream << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"; break; case GL_FRAMEBUFFER_UNDEFINED: - stringStream << "GL_FRAMEBUFFER_UNDEFINED \n"; + stringStream << "GL_FRAMEBUFFER_UNDEFINED\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER : - stringStream << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER \n"; + stringStream << "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"; + stringStream << "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n"; diff --git a/cegui/src/RendererModules/OpenGL/GL3GeometryBuffer.cpp b/cegui/src/RendererModules/OpenGL/GL3GeometryBuffer.cpp index 5688d877b..f7794812c 100644 --- a/cegui/src/RendererModules/OpenGL/GL3GeometryBuffer.cpp +++ b/cegui/src/RendererModules/OpenGL/GL3GeometryBuffer.cpp @@ -24,21 +24,19 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - -#include "glm/glm.hpp" -#include "glm/gtc/quaternion.hpp" -#include "glm/gtc/type_ptr.hpp" -#include "glm/gtc/matrix_transform.hpp" #include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h" #include "CEGUI/RendererModules/OpenGL/GL3Renderer.h" #include "CEGUI/RenderEffect.h" -#include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/Vertex.h" +#include "CEGUI/ShaderParameterBindings.h" #include "CEGUI/RendererModules/OpenGL/ShaderManager.h" #include "CEGUI/RendererModules/OpenGL/Shader.h" #include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" -#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" +#include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" + +#include +#include +#include #define BUFFER_OFFSET(i) ((char *)NULL + (i)) @@ -46,17 +44,12 @@ namespace CEGUI { //----------------------------------------------------------------------------// -OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner) : - OpenGLGeometryBufferBase(owner), - d_shader(owner.getShaderStandard()), - d_shaderPosLoc(owner.getShaderStandardPositionLoc()), - d_shaderTexCoordLoc(owner.getShaderStandardTexCoordLoc()), - d_shaderColourLoc(owner.getShaderStandardColourLoc()), - d_shaderStandardMatrixLoc(owner.getShaderStandardMatrixUniformLoc()), +OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner, CEGUI::RefCounted renderMaterial) : + OpenGLGeometryBufferBase(owner, renderMaterial), d_glStateChanger(owner.getOpenGLStateChanger()), d_bufferSize(0) { - initialiseOpenGLBuffers(); + initialiseVertexBuffers(); } //----------------------------------------------------------------------------// @@ -68,68 +61,56 @@ OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer() //----------------------------------------------------------------------------// void OpenGL3GeometryBuffer::draw() const { - CEGUI::Rectf viewPort = d_owner->getActiveViewPort(); + if(d_vertexData.empty()) + return; + + CEGUI::Rectf viewPort = d_owner.getActiveViewPort(); + + if (d_clippingActive) + { + d_glStateChanger->scissor(static_cast(d_clipRect.left()), + static_cast(viewPort.getHeight() - d_clipRect.bottom()), + static_cast(d_clipRect.getWidth()), + static_cast(d_clipRect.getHeight())); + + d_glStateChanger->enable(GL_SCISSOR_TEST); + } + else + d_glStateChanger->disable(GL_SCISSOR_TEST); - d_glStateChanger->scissor(static_cast(d_clipRect.left()), - static_cast(viewPort.getHeight() - d_clipRect.bottom()), - static_cast(d_clipRect.getWidth()), - static_cast(d_clipRect.getHeight())); + // Update the model view projection matrix + updateMatrix(); - // apply the transformations we need to use. - if (!d_matrixValid) - updateMatrix(); + CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings(); - // Send ModelViewProjection matrix to shader - glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix; - glUniformMatrix4fv(d_shaderStandardMatrixLoc, 1, GL_FALSE, glm::value_ptr(modelViewProjectionMatrix)); + // Set the uniform variables for this GeometryBuffer in the Shader + shaderParameterBindings->setParameter("modelViewProjMatrix", d_matrix); + shaderParameterBindings->setParameter("alphaPercentage", d_alpha); // activate desired blending mode - d_owner->setupRenderingBlendMode(d_blendMode); + d_owner.setupRenderingBlendMode(d_blendMode); // Bind our vao d_glStateChanger->bindVertexArray(d_verticesVAO); const int pass_count = d_effect ? d_effect->getPassCount() : 1; - size_t pos = 0; for (int pass = 0; pass < pass_count; ++pass) { // set up RenderEffect if (d_effect) d_effect->performPreRenderFunctions(pass); - // draw the batches - - BatchList::const_iterator i = d_batches.begin(); - for ( ; i != d_batches.end(); ++i) - { - const BatchInfo& currentBatch = *i; - - if (currentBatch.clip) - glEnable(GL_SCISSOR_TEST); - else - glDisable(GL_SCISSOR_TEST); - - glBindTexture(GL_TEXTURE_2D, currentBatch.texture); - - // draw the geometry - const unsigned int numVertices = currentBatch.vertexCount; - glDrawArrays(GL_TRIANGLES, pos, numVertices); + d_renderMaterial->prepareForRendering(); - pos += numVertices; - } + // draw the geometry + drawDependingOnFillRule(); } // clean up RenderEffect if (d_effect) d_effect->performPostRenderFunctions(); -} -//----------------------------------------------------------------------------// -void OpenGL3GeometryBuffer::appendGeometry(const Vertex* const vbuff, - uint vertex_count) -{ - OpenGLGeometryBufferBase::appendGeometry(vbuff, vertex_count); - updateOpenGLBuffers(); + updateRenderTargetData(d_owner.getActiveRenderTarget()); } //----------------------------------------------------------------------------// @@ -140,39 +121,74 @@ void OpenGL3GeometryBuffer::reset() } //----------------------------------------------------------------------------// -void OpenGL3GeometryBuffer::initialiseOpenGLBuffers() +void OpenGL3GeometryBuffer::initialiseVertexBuffers() { glGenVertexArrays(1, &d_verticesVAO); - glBindVertexArray(d_verticesVAO); + d_glStateChanger->bindVertexArray(d_verticesVAO); // Generate and bind position vbo glGenBuffers(1, &d_verticesVBO); - glBindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); - glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_STATIC_DRAW); - d_shader->bind(); - - GLsizei stride = 9 * sizeof(GL_FLOAT); + // Unbind Vertex Attribute Array (VAO) + d_glStateChanger->bindVertexArray(0); - glVertexAttribPointer(d_shaderTexCoordLoc, 2, GL_FLOAT, GL_FALSE, stride, 0); - glEnableVertexAttribArray(d_shaderTexCoordLoc); + // Unbind array and element array buffers + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, 0); +} - glVertexAttribPointer(d_shaderColourLoc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(2 * sizeof(GL_FLOAT))); - glEnableVertexAttribArray(d_shaderColourLoc); - glVertexAttribPointer(d_shaderPosLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(6 * sizeof(GL_FLOAT))); - glEnableVertexAttribArray(d_shaderPosLoc); +//----------------------------------------------------------------------------// +void OpenGL3GeometryBuffer::finaliseVertexAttributes() +{ + //We need to bind both of the following calls + d_glStateChanger->bindVertexArray(d_verticesVAO); + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); - d_shader->unbind(); + GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT); - // Unbind Vertex Attribute Array (VAO) - glBindVertexArray(0); + const CEGUI::OpenGLBaseShaderWrapper* gl3_shader_wrapper = static_cast(d_renderMaterial->getShaderWrapper()); - // Unbind array and element array buffers - glBindBuffer(GL_ARRAY_BUFFER, 0); + //Update the vertex attrib pointers of the vertex array object depending on the saved attributes + int dataOffset = 0; + const size_t attribute_count = d_vertexAttributes.size(); + for (size_t i = 0; i < attribute_count; ++i) + { + switch(d_vertexAttributes.at(i)) + { + case VAT_POSITION0: + { + GLint shader_pos_loc = gl3_shader_wrapper->getAttributeLocation("inPosition"); + glVertexAttribPointer(shader_pos_loc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT))); + glEnableVertexAttribArray(shader_pos_loc); + dataOffset += 3; + } + break; + case VAT_COLOUR0: + { + GLint shader_colour_loc = gl3_shader_wrapper->getAttributeLocation("inColour"); + glVertexAttribPointer(shader_colour_loc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT))); + glEnableVertexAttribArray(shader_colour_loc); + dataOffset += 4; + } + break; + case VAT_TEXCOORD0: + { + GLint texture_coord_loc = gl3_shader_wrapper->getAttributeLocation("inTexCoord"); + glVertexAttribPointer(texture_coord_loc, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT))); + glEnableVertexAttribArray(texture_coord_loc); + dataOffset += 2; + } + break; + default: + break; + } + } } + //----------------------------------------------------------------------------// void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers() { @@ -184,7 +200,7 @@ void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers() void OpenGL3GeometryBuffer::updateOpenGLBuffers() { bool needNewBuffer = false; - unsigned int vertexCount = d_vertices.size(); + size_t vertexCount = d_vertexData.size(); if(d_bufferSize < vertexCount) { @@ -194,24 +210,106 @@ void OpenGL3GeometryBuffer::updateOpenGLBuffers() d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); - GLsizei dataSize = vertexCount * sizeof(GLVertex); - - GLVertex* data; - if(d_vertices.empty()) - data = 0; + float* vertexData; + if(d_vertexData.empty()) + vertexData = 0; else - data = &d_vertices[0]; + vertexData = &d_vertexData[0]; + + GLsizei dataSize = vertexCount * sizeof(float); if(needNewBuffer) { - glBufferData(GL_ARRAY_BUFFER, dataSize, data, GL_DYNAMIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, dataSize, vertexData, GL_STATIC_DRAW); } else { - glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, data); + glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, vertexData); } } +//----------------------------------------------------------------------------// +void OpenGL3GeometryBuffer::appendGeometry(const float* vertex_data, std::size_t array_size) +{ + OpenGLGeometryBufferBase::appendGeometry(vertex_data, array_size); + + updateOpenGLBuffers(); +} + +//----------------------------------------------------------------------------// +void OpenGL3GeometryBuffer::drawDependingOnFillRule() const +{ + if(d_polygonFillRule == PFR_NONE) + { + d_glStateChanger->disable(GL_CULL_FACE); + d_glStateChanger->disable(GL_STENCIL_TEST); + + glDrawArrays(GL_TRIANGLES, 0, d_vertexCount); + } + else if(d_polygonFillRule == PFR_EVEN_ODD) + { + //We use a stencil buffer to determine the insideness + //of a fragment. Every draw inverts the precious value + //according to the even-odd rule. + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + + d_glStateChanger->disable(GL_CULL_FACE); + d_glStateChanger->enable(GL_STENCIL_TEST); + glStencilMask(0xFF); + glClear(GL_STENCIL_BUFFER_BIT); + glStencilFunc(GL_ALWAYS, 0x00, 0xFF); + glStencilOp(GL_INVERT, GL_KEEP, GL_INVERT); + glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - d_postStencilVertexCount); + + unsigned int postStencilStart = d_vertexCount - d_postStencilVertexCount; + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glStencilMask(0x00); + glStencilFunc(GL_EQUAL, 0xFF, 0xFF); + glDrawArrays(GL_TRIANGLES, postStencilStart, d_postStencilVertexCount); + } + else if(d_polygonFillRule == PFR_NON_ZERO) + { + //We use a stencil buffer to determine the insideness + //of a fragment. We draw the front sides while increasing + //stencil values and then draw backside while decreasing them. + //A resulting 0 value means we are outside. + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + + unsigned int solid_fill_count = d_vertexCount - d_postStencilVertexCount; + unsigned int vertex_pos = 0; + + //Performing the back/front faces stencil incr and decr stencil op + d_glStateChanger->enable(GL_CULL_FACE); + d_glStateChanger->enable(GL_STENCIL_TEST); + glStencilMask(0xFF); + glClear(GL_STENCIL_BUFFER_BIT); + glStencilFunc(GL_ALWAYS, 0x00, 0xFF); + + glCullFace(GL_FRONT); + glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP); + glDrawArrays(GL_TRIANGLES, vertex_pos, solid_fill_count); + + glCullFace(GL_BACK); + glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP); + glDrawArrays(GL_TRIANGLES, vertex_pos, solid_fill_count); + + vertex_pos += solid_fill_count; + + //Only needing culling for the back/front face stencil calculations + d_glStateChanger->disable(GL_CULL_FACE); + + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glStencilMask(0x00); + + if(d_postStencilVertexCount != 0) + { + glStencilFunc(GL_NOTEQUAL, 0x00, 0xFF); + glDrawArrays(GL_TRIANGLES, d_vertexCount - d_postStencilVertexCount, d_postStencilVertexCount); + } + } +} + + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/OpenGL/GL3Renderer.cpp b/cegui/src/RendererModules/OpenGL/GL3Renderer.cpp index 8197518ba..187fbbdf7 100644 --- a/cegui/src/RendererModules/OpenGL/GL3Renderer.cpp +++ b/cegui/src/RendererModules/OpenGL/GL3Renderer.cpp @@ -24,11 +24,9 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - #include "CEGUI/RendererModules/OpenGL/ShaderManager.h" #include "CEGUI/RendererModules/OpenGL/GL3Renderer.h" -#include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/RendererModules/OpenGL/GL3Texture.h" #include "CEGUI/RendererModules/OpenGL/Shader.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" @@ -40,7 +38,9 @@ #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/Logger.h" -#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "CEGUI/RendererModules/OpenGL/GL3StateChangeWrapper.h" +#include "CEGUI/RenderMaterial.h" +#include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" #include #include @@ -69,7 +69,7 @@ template class OGLTemplateTargetFactory : public OGLTextureTargetFactory { TextureTarget* create(OpenGLRendererBase& r) const - { return CEGUI_NEW_AO T(static_cast(r)); } + { return new T(static_cast(r)); } }; //----------------------------------------------------------------------------// @@ -82,7 +82,7 @@ OpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const int abi) "CEGUI::System object is already initialised.")); OpenGL3Renderer& renderer(create()); - DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider(); + DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; @@ -99,7 +99,7 @@ OpenGL3Renderer& OpenGL3Renderer::bootstrapSystem(const Sizef& display_size, "CEGUI::System object is already initialised.")); OpenGL3Renderer& renderer(create(display_size)); - DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider(); + DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; @@ -118,7 +118,7 @@ void OpenGL3Renderer::destroySystem() static_cast(sys->getResourceProvider()); System::destroy(); - CEGUI_DELETE_AO rp; + delete rp; destroy(*renderer); } @@ -127,7 +127,7 @@ OpenGL3Renderer& OpenGL3Renderer::create(const int abi) { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO OpenGL3Renderer(); + return *new OpenGL3Renderer(); } //----------------------------------------------------------------------------// @@ -136,63 +136,64 @@ OpenGL3Renderer& OpenGL3Renderer::create(const Sizef& display_size, { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO OpenGL3Renderer(display_size); + return *new OpenGL3Renderer(display_size); } //----------------------------------------------------------------------------// void OpenGL3Renderer::destroy(OpenGL3Renderer& renderer) { - CEGUI_DELETE_AO &renderer; + delete &renderer; } //----------------------------------------------------------------------------// OpenGL3Renderer::OpenGL3Renderer() : - d_shaderStandard(0), + d_shaderWrapperTextured(0), d_openGLStateChanger(0), d_shaderManager(0) { initialiseRendererIDString(); initialiseGLExtensions(); + d_openGLStateChanger = new OpenGL3StateChangeWrapper(); initialiseTextureTargetFactory(); initialiseOpenGLShaders(); - - d_openGLStateChanger = CEGUI_NEW_AO OpenGL3StateChangeWrapper(*this); } //----------------------------------------------------------------------------// OpenGL3Renderer::OpenGL3Renderer(const Sizef& display_size) : OpenGLRendererBase(display_size), - d_shaderStandard(0), + d_shaderWrapperTextured(0), d_openGLStateChanger(0), d_shaderManager(0) { initialiseRendererIDString(); initialiseGLExtensions(); + d_openGLStateChanger = new OpenGL3StateChangeWrapper(); initialiseTextureTargetFactory(); initialiseOpenGLShaders(); - - d_openGLStateChanger = CEGUI_NEW_AO OpenGL3StateChangeWrapper(*this); } //----------------------------------------------------------------------------// OpenGL3Renderer::~OpenGL3Renderer() { - CEGUI_DELETE_AO d_textureTargetFactory; - CEGUI_DELETE_AO d_openGLStateChanger; - CEGUI_DELETE_AO d_shaderManager; + delete d_textureTargetFactory; + delete d_openGLStateChanger; + delete d_shaderManager; + + delete d_shaderWrapperTextured; + delete d_shaderWrapperSolid; } //----------------------------------------------------------------------------// void OpenGL3Renderer::initialiseRendererIDString() { - d_rendererID = + d_rendererID = "CEGUI::OpenGL3Renderer - Official OpenGL 3.2 core based " "renderer module."; } //----------------------------------------------------------------------------// -OpenGLGeometryBufferBase* OpenGL3Renderer::createGeometryBuffer_impl() +OpenGLGeometryBufferBase* OpenGL3Renderer::createGeometryBuffer_impl(CEGUI::RefCounted renderMaterial) { - return CEGUI_NEW_AO OpenGL3GeometryBuffer(*this); + return new OpenGL3GeometryBuffer(*this, renderMaterial); } //----------------------------------------------------------------------------// @@ -204,26 +205,22 @@ TextureTarget* OpenGL3Renderer::createTextureTarget_impl() //----------------------------------------------------------------------------// void OpenGL3Renderer::beginRendering() { - // do required set-up. yes, it really is this minimal ;) - glEnable(GL_SCISSOR_TEST); - glEnable(GL_BLEND); - - // force set blending ops to get to a known state. - setupRenderingBlendMode(BM_NORMAL, true); - // if enabled, restores a subset of the GL state back to default values. if (d_initExtraStates) setupExtraStates(); - d_shaderStandard->bind(); - d_openGLStateChanger->reset(); + + // Setup initial states + d_openGLStateChanger->enable(GL_BLEND); + + // force set blending ops to get to a known state. + setupRenderingBlendMode(BM_NORMAL, true); } //----------------------------------------------------------------------------// void OpenGL3Renderer::endRendering() { - d_shaderStandard->unbind(); } //----------------------------------------------------------------------------// @@ -246,12 +243,12 @@ void OpenGL3Renderer::initialiseTextureTargetFactory() { //Use OGL core implementation for FBOs d_rendererID += " TextureTarget support enabled via FBO OGL 3.2 core implementation."; - d_textureTargetFactory = CEGUI_NEW_AO OGLTemplateTargetFactory; + d_textureTargetFactory = new OGLTemplateTargetFactory; } //----------------------------------------------------------------------------// void OpenGL3Renderer::setupRenderingBlendMode(const BlendMode mode, - const bool force) + const bool force) { // exit if mode is already set up (and update not forced) if ((d_activeBlendMode == mode) && !force) @@ -261,52 +258,22 @@ void OpenGL3Renderer::setupRenderingBlendMode(const BlendMode mode, if (d_activeBlendMode == BM_RTT_PREMULTIPLIED) { - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + d_openGLStateChanger->blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); + d_openGLStateChanger->blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); } } //----------------------------------------------------------------------------// -Sizef OpenGL3Renderer::getAdjustedTextureSize(const Sizef& sz) const +Sizef OpenGL3Renderer::getAdjustedTextureSize(const Sizef& sz) { return Sizef(sz); } //----------------------------------------------------------------------------// -OpenGL3Shader*& OpenGL3Renderer::getShaderStandard() -{ - return d_shaderStandard; -} - -//----------------------------------------------------------------------------// -GLint OpenGL3Renderer::getShaderStandardPositionLoc() -{ - return d_shaderStandardPosLoc; -} - -//----------------------------------------------------------------------------// -GLint OpenGL3Renderer::getShaderStandardTexCoordLoc() -{ - return d_shaderStandardTexCoordLoc; -} - -//----------------------------------------------------------------------------// -GLint OpenGL3Renderer::getShaderStandardColourLoc() -{ - return d_shaderStandardColourLoc; -} - -//----------------------------------------------------------------------------// -GLint OpenGL3Renderer::getShaderStandardMatrixUniformLoc() -{ - return d_shaderStandardMatrixLoc; -} - -//----------------------------------------------------------------------------// -OpenGL3StateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger() +OpenGLBaseStateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger() { return d_openGLStateChanger; } @@ -315,19 +282,11 @@ OpenGL3StateChangeWrapper* OpenGL3Renderer::getOpenGLStateChanger() void OpenGL3Renderer::initialiseOpenGLShaders() { checkGLErrors(); - d_shaderManager = CEGUI_NEW_AO OpenGL3ShaderManager(); + d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSL); d_shaderManager->initialiseShaders(); - d_shaderStandard = d_shaderManager->getShader(SHADER_ID_STANDARDSHADER); - GLuint texLoc = d_shaderStandard->getUniformLocation("texture0"); - d_shaderStandard->bind(); - glUniform1i(texLoc, 0); - d_shaderStandard->unbind(); - - d_shaderStandardPosLoc = d_shaderStandard->getAttribLocation("inPosition"); - d_shaderStandardTexCoordLoc = d_shaderStandard->getAttribLocation("inTexCoord"); - d_shaderStandardColourLoc = d_shaderStandard->getAttribLocation("inColour"); - d_shaderStandardMatrixLoc = d_shaderStandard->getUniformLocation("modelViewPerspMatrix"); + initialiseStandardTexturedShaderWrapper(); + initialiseStandardColouredShaderWrapper(); } //----------------------------------------------------------------------------// @@ -370,6 +329,65 @@ bool OpenGL3Renderer::isS3TCSupported() const return d_s3tcSupported; } +//----------------------------------------------------------------------------// +RefCounted OpenGL3Renderer::createRenderMaterial(const DefaultShaderType shaderType) const +{ + if(shaderType == DS_TEXTURED) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperTextured)); + + return render_material; + } + else if(shaderType == DS_SOLID) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperSolid)); + + return render_material; + } + else + { + CEGUI_THROW(RendererException( + "A default shader of this type does not exist.")); + + return RefCounted(); + } +} + +//----------------------------------------------------------------------------// +void OpenGL3Renderer::initialiseStandardTexturedShaderWrapper() +{ + OpenGLBaseShader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED); + d_shaderWrapperTextured = new OpenGLBaseShaderWrapper(*shader_standard_textured, d_openGLStateChanger); + + d_shaderWrapperTextured->addTextureUniformVariable("texture0", 0); + + d_shaderWrapperTextured->addUniformVariable("modelViewProjMatrix"); + d_shaderWrapperTextured->addUniformVariable("alphaPercentage"); + + d_shaderWrapperTextured->addAttributeVariable("inPosition"); + d_shaderWrapperTextured->addAttributeVariable("inTexCoord"); + d_shaderWrapperTextured->addAttributeVariable("inColour"); +} + +//----------------------------------------------------------------------------// +void OpenGL3Renderer::initialiseStandardColouredShaderWrapper() +{ + OpenGLBaseShader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID); + d_shaderWrapperSolid = new OpenGLBaseShaderWrapper(*shader_standard_solid, d_openGLStateChanger); + + d_shaderWrapperSolid->addUniformVariable("modelViewProjMatrix"); + d_shaderWrapperSolid->addUniformVariable("alphaPercentage"); + + d_shaderWrapperSolid->addAttributeVariable("inPosition"); + d_shaderWrapperSolid->addAttributeVariable("inColour"); +} + +//----------------------------------------------------------------------------// +OpenGLTexture* OpenGL3Renderer::createTexture_impl(const String& name) +{ + return new OpenGL3Texture(*this, name); +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/samples_framework/src/DeviceReset_Direct3D9.cpp b/cegui/src/RendererModules/OpenGL/GL3Shader.cpp similarity index 50% rename from samples_framework/src/DeviceReset_Direct3D9.cpp rename to cegui/src/RendererModules/OpenGL/GL3Shader.cpp index 3ccf81c09..ce3e2fc44 100644 --- a/samples_framework/src/DeviceReset_Direct3D9.cpp +++ b/cegui/src/RendererModules/OpenGL/GL3Shader.cpp @@ -1,9 +1,9 @@ /*********************************************************************** - created: 25/5/2008 - author: Paul D Turner + created: Wed, 8th Feb 2012 + author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,53 +24,51 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "CEGUISamplesConfig.h" +#include "CEGUI/RendererModules/OpenGL/GL3Shader.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "CEGUI/Logger.h" +#include "CEGUI/Exceptions.h" -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE -#include "CEGUI/CEGUI.h" -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" +#include +#include +namespace CEGUI +{ //----------------------------------------------------------------------------// -// The following function is basically a nasty hack; we just needed to do the -// preD3DReset call, the actual device reset, and then the postD3DReset call - -// the issue is that much of the information is not readily available here to us -// so we jump through a couple of hoops to obtain that information (and in the -// case of the D3DPRESENT_PARAMETERS recreate it from scratch). -// -// The reason this is in it's own file is that we need to be able to handle -// multiple different versions of this function for the D3D versions that the -// sample framework supports, though we can only include one main d3d header -// at a time, so these funcs live in their own files. -//----------------------------------------------------------------------------// +OpenGL3Shader::OpenGL3Shader(const std::string& vertex_shader_source, + const std::string& fragment_shader_source, + OpenGLBaseStateChangeWrapper* glStateChanger) : + OpenGLBaseShader(vertex_shader_source,fragment_shader_source, glStateChanger) +{ +} //----------------------------------------------------------------------------// -void DeviceReset_Direct3D9(HWND window, CEGUI::Renderer* renderer) +void OpenGL3Shader::bindFragDataLocation(const std::string &name) { - CEGUI::Direct3D9Renderer* d3d_renderer = - static_cast(renderer); - - LPDIRECT3DDEVICE9 d3d_device = d3d_renderer->getDevice(); - - LPDIRECT3D9 d3d; - d3d_device->GetDirect3D(&d3d); - - D3DDISPLAYMODE d3ddm; - d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm); + if(d_program > 0) + { + glBindFragDataLocation(d_program, 0, name.c_str() ); + link(); + } +} - D3DPRESENT_PARAMETERS ppars; - ZeroMemory(&ppars, sizeof(ppars)); - ppars.BackBufferFormat = d3ddm.Format; - ppars.hDeviceWindow = window; - ppars.SwapEffect = D3DSWAPEFFECT_DISCARD; - ppars.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - ppars.Windowed = true; +//----------------------------------------------------------------------------// +void OpenGL3Shader::link() +{ + OpenGLBaseShader::link(); - d3d_renderer->preD3DReset(); - d3d_device->Reset(&ppars); - d3d_renderer->postD3DReset(); + glBindFragDataLocation(d_program, 0, "out0"); // GL_COLOR_ATTACHMENT0 + glBindFragDataLocation(d_program, 1, "out1"); // GL_COLOR_ATTACHMENT1 + glBindFragDataLocation(d_program, 2, "out2"); // ... + glBindFragDataLocation(d_program, 3, "out3"); + glBindFragDataLocation(d_program, 4, "out4"); + glBindFragDataLocation(d_program, 5, "out5"); + glBindFragDataLocation(d_program, 6, "out6"); + glBindFragDataLocation(d_program, 7, "out7"); + checkGLErrors(); } //----------------------------------------------------------------------------// +} -#endif diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderVert.h b/cegui/src/RendererModules/OpenGL/GL3StateChangeWrapper.cpp similarity index 67% rename from cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderVert.h rename to cegui/src/RendererModules/OpenGL/GL3StateChangeWrapper.cpp index 1916d0d4b..103908eab 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderVert.h +++ b/cegui/src/RendererModules/OpenGL/GL3StateChangeWrapper.cpp @@ -25,31 +25,31 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _CEGUIOpenGL3StandardShaderVert_h_ -#define _CEGUIOpenGL3StandardShaderVert_h_ +#include "CEGUI/RendererModules/OpenGL/GL3StateChangeWrapper.h" namespace CEGUI { - const char StandardShaderVert[] = - "#version 150 core\n" - "uniform mat4 modelViewPerspMatrix;\n" - - "in vec3 inPosition;\n" - "in vec2 inTexCoord;\n" - "in vec4 inColour;\n" - - "out vec2 exTexCoord;\n" - "out vec4 exColour;\n" +//----------------------------------------------------------------------------// +OpenGL3StateChangeWrapper::OpenGL3StateChangeWrapper() + : OpenGLBaseStateChangeWrapper() +{ +} - "void main(void)\n" - "{\n" - " exTexCoord = inTexCoord;\n" - " exColour = inColour;\n" +//----------------------------------------------------------------------------// +OpenGL3StateChangeWrapper::~OpenGL3StateChangeWrapper() +{ +} - "gl_Position = modelViewPerspMatrix * vec4(inPosition, 1.0);\n" - "}" - ; +//----------------------------------------------------------------------------// +void OpenGL3StateChangeWrapper::bindVertexArray(GLuint vertexArray) +{ + if (vertexArray != d_vertexArrayObject) + { + glBindVertexArray(vertexArray); + d_vertexArrayObject = vertexArray; + } } -#endif \ No newline at end of file +//----------------------------------------------------------------------------// +} diff --git a/cegui/src/RendererModules/OpenGL/GL3Texture.cpp b/cegui/src/RendererModules/OpenGL/GL3Texture.cpp new file mode 100644 index 000000000..de114496d --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GL3Texture.cpp @@ -0,0 +1,58 @@ +/*********************************************************************** + created: Sun Jan 11 2009 + author: Paul D Turner +*************************************************************************/ +/*************************************************************************** + Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GL3Texture.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/System.h" +#include "CEGUI/ImageCodec.h" + +#include "CEGUI/RendererModules/OpenGL/GL.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +OpenGL3Texture::OpenGL3Texture(OpenGLRendererBase& owner, const String& name) + : OpenGL1Texture(owner, name) +{ +} + +//----------------------------------------------------------------------------// +OpenGL3Texture::~OpenGL3Texture() +{ +} + +//----------------------------------------------------------------------------// +void OpenGL3Texture::setTextureEnvironment() +{ +} + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section + diff --git a/cegui/src/RendererModules/OpenGL/GLBaseShaderWrapper.cpp b/cegui/src/RendererModules/OpenGL/GLBaseShaderWrapper.cpp new file mode 100644 index 000000000..5c0ea310e --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLBaseShaderWrapper.cpp @@ -0,0 +1,198 @@ +/*********************************************************************** + created: 18th July 2013 + author: Lukas Meindl + edited: David Reepmeyer (GLES2/3 support) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" +#include "CEGUI/RendererModules/OpenGL/Shader.h" +#include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/Exceptions.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +OpenGLBaseShaderWrapper::OpenGLBaseShaderWrapper(OpenGLBaseShader& shader, OpenGLBaseStateChangeWrapper* stateChangeWrapper) + : d_shader(shader) + , d_glStateChangeWrapper(stateChangeWrapper) +{ +} + +//----------------------------------------------------------------------------// +OpenGLBaseShaderWrapper::~OpenGLBaseShaderWrapper() +{ +} + +//----------------------------------------------------------------------------// +void OpenGLBaseShaderWrapper::addUniformVariable(const std::string& uniformName) +{ + GLint variable_location = d_shader.getUniformLocation(uniformName); + + if(variable_location == -1) + CEGUI_THROW(RendererException("OpenGLBaseShaderWrapper::addUniformVariable - A uniform variable with " + "the name \"" + uniformName + "\" was not found in the OpenGL shader.")); + + d_uniformVariables.insert(std::pair(uniformName, variable_location)); +} + +//----------------------------------------------------------------------------// +void OpenGLBaseShaderWrapper::addTextureUniformVariable(const std::string& uniformName, GLint textureUnitIndex) +{ + GLint variable_location = d_shader.getUniformLocation(uniformName); + + if(variable_location == -1) + CEGUI_THROW(RendererException("OpenGLBaseShaderWrapper::addTextureUniformVariable - A texture uniform variable with " + "the name \"" + uniformName + "\" was not found in the OpenGL shader.")); + + d_uniformVariables.insert(std::pair(uniformName, textureUnitIndex)); + + d_shader.bind(); + glUniform1i(variable_location, textureUnitIndex); +} + +//----------------------------------------------------------------------------// +void OpenGLBaseShaderWrapper::addAttributeVariable(const std::string& attributeName) +{ + GLint variable_location = d_shader.getAttribLocation(attributeName); + + if(variable_location == -1) + CEGUI_THROW(RendererException("OpenGLBaseShaderWrapper::addAttributeVariable- An attribute with the name \"" + + attributeName + "\" was not found in the OpenGL shader.")); + + d_attributeVariables.insert(std::pair(attributeName, variable_location)); +} + +//----------------------------------------------------------------------------// +void OpenGLBaseShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) +{ + d_shader.bind(); + + const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings->getShaderParameterBindings(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); + + while(iter != end) + { + const CEGUI::ShaderParameter* parameter = iter->second; + + if(parameter->getType() != SPT_TEXTURE) + { + std::map::iterator found_iterator = d_shaderParameterStates.find(iter->first); + if(found_iterator != d_shaderParameterStates.end()) + { + ShaderParameter* last_shader_parameter = found_iterator->second; + if(parameter->equal(last_shader_parameter)) + { + ++iter; + continue; + } + else + { + if(parameter->getType() == last_shader_parameter->getType()) + last_shader_parameter->takeOverParameterValue(parameter); + else + { + delete found_iterator->second; + found_iterator->second = parameter->clone(); + } + } + } + else + { + d_shaderParameterStates[iter->first] = parameter->clone(); + } + } + + const GLint& location = d_uniformVariables.find(iter->first)->second; + + + CEGUI::ShaderParamType parameter_type = parameter->getType(); + + switch(parameter_type) + { + case SPT_INT: + { + const CEGUI::ShaderParameterInt* parameterInt = static_cast(parameter); + glUniform1i(location, parameterInt->d_parameterValue); + } + break; + case SPT_FLOAT: + { + const CEGUI::ShaderParameterFloat* parameterFloat = static_cast(parameter); + glUniform1f(location, parameterFloat->d_parameterValue); + } + break; + case SPT_MATRIX_4X4: + { + const CEGUI::ShaderParameterMatrix* parameterMatrix = static_cast(parameter); + glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(parameterMatrix->d_parameterValue)); + } + break; + case SPT_TEXTURE: + { + const CEGUI::ShaderParameterTexture* parameterTexture = static_cast(parameter); + const CEGUI::OpenGLTexture* openglTexture = static_cast(parameterTexture->d_parameterValue); + + d_glStateChangeWrapper->activeTexture(location); + d_glStateChangeWrapper->bindTexture(GL_TEXTURE_2D, openglTexture->getOpenGLTexture()); + } + break; + default: + break; + } + + ++iter; + } +} + +//----------------------------------------------------------------------------// +GLint OpenGLBaseShaderWrapper::getAttributeLocation(const std::string& attributeName) const +{ + std::map::const_iterator iter = d_attributeVariables.find(attributeName); + if(iter != d_attributeVariables.end()) + return iter->second; + + CEGUI_THROW(RendererException("OpenGLBaseShaderWrapper::getAttributeLocation: An attribute variable with the name \"" + attributeName + "\" has not been added to the ShaderWrapper.")); +} + +//----------------------------------------------------------------------------// +GLint OpenGLBaseShaderWrapper::getUniformLocation(const std::string& uniformName) const +{ + std::map::const_iterator iter = d_uniformVariables.find(uniformName); + if(iter != d_uniformVariables.end()) + return iter->second; + + CEGUI_THROW(RendererException("OpenGLBaseShaderWrapper::getUniformLocation: An uniform variable with the name \"" + uniformName + "\" has not been added to the ShaderWrapper.")); +} + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section + diff --git a/cegui/src/RendererModules/OpenGL/GLES2FBOTextureTarget.cpp b/cegui/src/RendererModules/OpenGL/GLES2FBOTextureTarget.cpp new file mode 100644 index 000000000..ad083cd24 --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLES2FBOTextureTarget.cpp @@ -0,0 +1,306 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl (based on code by Paul D Turner) + David Reepmeyer (added GLES2/GLES3) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/RenderQueue.h" +#include "CEGUI/GeometryBuffer.h" + +#include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" +#include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" + +#include "CEGUI/Logger.h" + +#include +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +const float GLES2FBOTextureTarget::DEFAULT_SIZE = 128.0f; + +//----------------------------------------------------------------------------// +GLES2FBOTextureTarget::GLES2FBOTextureTarget(GLES2Renderer& owner) : + OpenGLTextureTarget(owner), + d_glStateChanger(owner.getOpenGLStateChanger()) +{ + // no need to initialise d_previousFrameBuffer here, it will be + // initialised in activate() + + initialiseRenderTexture(); + + // setup area and cause the initial texture to be generated. + declareRenderSize(Sizef(DEFAULT_SIZE, DEFAULT_SIZE)); +} + +//----------------------------------------------------------------------------// +GLES2FBOTextureTarget::~GLES2FBOTextureTarget() +{ + glDeleteFramebuffers(1, &d_frameBuffer); + + glDeleteRenderbuffers(1, &d_stencilBufferRBO); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::declareRenderSize(const Sizef& sz) +{ + setArea(Rectf(d_area.getPosition(), d_owner.getAdjustedTextureSize(sz))); + resizeRenderTexture(); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::activate() +{ + // remember previously bound FBO to make sure we set it back + // when deactivating + glGetIntegerv(GL_FRAMEBUFFER_BINDING, + reinterpret_cast(&d_previousFrameBuffer)); + + // switch to rendering to the texture + glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); + + OpenGLTextureTarget::activate(); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::deactivate() +{ + OpenGLTextureTarget::deactivate(); + + // switch back to rendering to the previously bound framebuffer + glBindFramebuffer(GL_FRAMEBUFFER, d_previousFrameBuffer); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::clear() +{ + const Sizef sz(d_area.getSize()); + // Some drivers crash when clearing a 0x0 RTT. This is a workaround for + // those cases. + if (sz.d_width < 1.0f || sz.d_height < 1.0f) + return; + + // save old clear colour + GLfloat old_col[4]; + glGetFloatv(GL_COLOR_CLEAR_VALUE, old_col); + + // remember previously bound FBO to make sure we set it back + GLuint previousFBO = 0; + glGetIntegerv(GL_FRAMEBUFFER_BINDING, + reinterpret_cast(&previousFBO)); + + // switch to our FBO + glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); + // Clear it. + d_glStateChanger->disable(GL_SCISSOR_TEST); + glClearColor(0,0,0,0); + + if(!d_usesStencil) + glClear(GL_COLOR_BUFFER_BIT); + else + glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + // switch back to rendering to the previously bound FBO + glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); + + // restore previous clear colour + glClearColor(old_col[0], old_col[1], old_col[2], old_col[3]); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::initialiseRenderTexture() +{ + // save old texture binding + GLuint old_tex; + glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); + + // create FBO + glGenFramebuffers(1, &d_frameBuffer); + + // remember previously bound FBO to make sure we set it back + GLuint previousFBO = 0; + //glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, + glGetIntegerv(GL_FRAMEBUFFER_BINDING, + reinterpret_cast(&previousFBO)); + glBindFramebuffer(GL_FRAMEBUFFER, d_frameBuffer); + + // set up the texture the FBO will draw to + glGenTextures(1, &d_texture); + d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +#ifdef CEGUI_GLES3_SUPPORT + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, +#else + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, +#endif + static_cast(DEFAULT_SIZE), + static_cast(DEFAULT_SIZE), + 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_TEXTURE_2D, d_texture, 0); + + // Set up the stencil buffer for the FBO + glGenRenderbuffers(1, &d_stencilBufferRBO); + glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); + glRenderbufferStorage(GL_RENDERBUFFER, + GL_STENCIL_INDEX8, + static_cast(DEFAULT_SIZE), + static_cast(DEFAULT_SIZE)); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, d_stencilBufferRBO); + + //Check for framebuffer completeness + checkFramebufferStatus(); + + // switch from our frame buffer back to the previously bound buffer. + glBindFramebuffer(GL_FRAMEBUFFER, previousFBO); + + // ensure the CEGUI::Texture is wrapping the gl texture and has correct size + d_CEGUITexture->setOpenGLTexture(d_texture, d_area.getSize()); + + // restore previous texture binding. + d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::resizeRenderTexture() +{ + // save old texture binding + GLuint old_tex; + glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); + + // Some drivers (hint: Intel) segfault when glTexImage2D is called with + // any of the dimensions being 0. The downside of this workaround is very + // small. We waste a tiny bit of VRAM on cards with sane drivers and + // prevent insane drivers from crashing CEGUI. + Sizef sz(d_area.getSize()); + if (sz.d_width < 1.0f || sz.d_height < 1.0f) + { + sz.d_width = 1.0f; + sz.d_height = 1.0f; + } + + // set the texture to the required size + d_glStateChanger->bindTexture(GL_TEXTURE_2D, d_texture); +#ifdef CEGUI_GLES3_SUPPORT + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, +#else + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, +#endif + static_cast(sz.d_width), + static_cast(sz.d_height), + 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); + + glBindRenderbuffer(GL_RENDERBUFFER, d_stencilBufferRBO); + glRenderbufferStorage(GL_RENDERBUFFER, + GL_STENCIL_INDEX8, + static_cast(sz.d_width), + static_cast(sz.d_height)); + + clear(); + + // ensure the CEGUI::Texture is wrapping the gl texture and has correct size + d_CEGUITexture->setOpenGLTexture(d_texture, sz); + + // restore previous texture binding. + d_glStateChanger->bindTexture(GL_TEXTURE_2D, old_tex); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::grabTexture() +{ + glDeleteFramebuffers(1, &d_frameBuffer); + d_frameBuffer = 0; + + OpenGLTextureTarget::grabTexture(); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::restoreTexture() +{ + OpenGLTextureTarget::restoreTexture(); + + initialiseRenderTexture(); + resizeRenderTexture(); +} + +//----------------------------------------------------------------------------// +void GLES2FBOTextureTarget::checkFramebufferStatus() +{ + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + + // Check for completeness + if(status != GL_FRAMEBUFFER_COMPLETE) + { + std::stringstream stringStream; + stringStream << "GLES2Renderer: Error Framebuffer is not complete\n"; + + switch(status) + { +#ifdef CEGUI_GLES3_SUPPORT + case GL_FRAMEBUFFER_UNDEFINED: + stringStream << "GL_FRAMEBUFFER_UNDEFINED\n"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n"; + break; +#else //GLES2 ONLY +# ifdef __ANDROID__ //LINUX DOES NOT SEEM TO SUPPORT TYPE + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + stringStream << "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS\n"; + break; +# endif +#endif + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + stringStream << "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n"; + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + stringStream << "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n"; + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + stringStream << "GL_FRAMEBUFFER_UNSUPPORTED\n"; + break; + default: + stringStream << "Undefined Framebuffer error\n"; + break; + } + + if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr()) + logger->logEvent(stringStream.str().c_str()); + else + std::cerr << stringStream.str() << std::endl; + } +} + +//----------------------------------------------------------------------------// + + + +} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/OpenGL/GLES2GeometryBuffer.cpp b/cegui/src/RendererModules/OpenGL/GLES2GeometryBuffer.cpp new file mode 100644 index 000000000..1dd5f873a --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLES2GeometryBuffer.cpp @@ -0,0 +1,338 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl (based on code by Paul D Turner) + David Reepmeyer (added GLES2/GLES3) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h" +#include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" +#include "CEGUI/RenderEffect.h" +#include "CEGUI/Vertex.h" +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/RendererModules/OpenGL/ShaderManager.h" +#include "CEGUI/RendererModules/OpenGL/Shader.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" + +#include +#include +#include + +#define BUFFER_OFFSET(i) ((char *)NULL + (i)) + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +GLES2GeometryBuffer::GLES2GeometryBuffer(GLES2Renderer& owner, CEGUI::RefCounted renderMaterial) : + OpenGLGeometryBufferBase(owner, renderMaterial), + d_glStateChanger(owner.getOpenGLStateChanger()), + d_bufferSize(0) +{ + initialiseVertexBuffers(); +} + +//----------------------------------------------------------------------------// +GLES2GeometryBuffer::~GLES2GeometryBuffer() +{ + deinitialiseOpenGLBuffers(); +} + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::draw() const +{ + if(d_vertexData.empty()) + return; + + CEGUI::Rectf viewPort = d_owner.getActiveViewPort(); + + if (d_clippingActive) + { + d_glStateChanger->scissor(static_cast(d_clipRect.left()), + static_cast(viewPort.getHeight() - d_clipRect.bottom()), + static_cast(d_clipRect.getWidth()), + static_cast(d_clipRect.getHeight())); + + d_glStateChanger->enable(GL_SCISSOR_TEST); + } + else + d_glStateChanger->disable(GL_SCISSOR_TEST); + + // Update the model view projection matrix + updateMatrix(); + + CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings(); + + // Set the uniform variables for this GeometryBuffer in the Shader + shaderParameterBindings->setParameter("modelViewProjMatrix", d_matrix); + shaderParameterBindings->setParameter("alphaPercentage", d_alpha); + + // activate desired blending mode + d_owner.setupRenderingBlendMode(d_blendMode); + +#if CEGUI_GLES3_SUPPORT + // Bind our vao + d_glStateChanger->bindVertexArray(d_verticesVAO); +#else + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); + bindVertexAttributes(); +#endif + + const int pass_count = d_effect ? d_effect->getPassCount() : 1; + for (int pass = 0; pass < pass_count; ++pass) + { + // set up RenderEffect + if (d_effect) + d_effect->performPreRenderFunctions(pass); + + d_renderMaterial->prepareForRendering(); + + // draw the geometry + drawDependingOnFillRule(); + } + + // clean up RenderEffect + if (d_effect) + d_effect->performPostRenderFunctions(); + updateRenderTargetData(d_owner.getActiveRenderTarget()); +} + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::reset() +{ + OpenGLGeometryBufferBase::reset(); + updateOpenGLBuffers(); +} + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::initialiseVertexBuffers() +{ +#if CEGUI_GLES3_SUPPORT + glGenVertexArrays(1, &d_verticesVAO); + d_glStateChanger->bindVertexArray(d_verticesVAO); +#endif + + // Generate and bind position vbo + glGenBuffers(1, &d_verticesVBO); + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); + + glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_STATIC_DRAW); + +#if CEGUI_GLES3_SUPPORT + // Unbind Vertex Attribute Array (VAO) + d_glStateChanger->bindVertexArray(0); +#endif + + // Unbind array and element array buffers + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, 0); +} + + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::finaliseVertexAttributes() +{ + const CEGUI::OpenGLBaseShaderWrapper* gl3_shader_wrapper = static_cast(d_renderMaterial->getShaderWrapper()); + d_posAttrib = gl3_shader_wrapper->getAttributeLocation("inPosition"); + d_colAttrib = gl3_shader_wrapper->getAttributeLocation("inColour"); + d_texAttrib = gl3_shader_wrapper->getAttributeLocation("inTexCoord"); +#ifdef CEGUI_GLES3_SUPPORT + //We need to bind both of the following calls + d_glStateChanger->bindVertexArray(d_verticesVAO); + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); + bindVertexAttributes(); +#else + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); +#endif +} + + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::bindVertexAttributes() const { + + GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT); + + const CEGUI::OpenGLBaseShaderWrapper* gl3_shader_wrapper = static_cast(d_renderMaterial->getShaderWrapper()); + + //Update the vertex attrib pointers of the vertex array object depending on the saved attributes + int dataOffset = 0; + const size_t attribute_count = d_vertexAttributes.size(); + for (size_t i = 0; i < attribute_count; ++i) + { + switch(d_vertexAttributes.at(i)) + { + case VAT_POSITION0: + { + glVertexAttribPointer(d_posAttrib, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT))); + glEnableVertexAttribArray(d_posAttrib); + dataOffset += 3; + } + break; + case VAT_COLOUR0: + { + glVertexAttribPointer(d_colAttrib, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT))); + glEnableVertexAttribArray(d_colAttrib); + dataOffset += 4; + } + break; + case VAT_TEXCOORD0: + { + glVertexAttribPointer(d_texAttrib, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT))); + glEnableVertexAttribArray(d_texAttrib); + dataOffset += 2; + } + break; + default: + break; + } + } +} + + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::deinitialiseOpenGLBuffers() +{ +#if CEGUI_GLES3_SUPPORT + glDeleteVertexArrays(1, &d_verticesVAO); +#endif + glDeleteBuffers(1, &d_verticesVBO); +} + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::updateOpenGLBuffers() +{ + bool needNewBuffer = false; + size_t vertexCount = d_vertexData.size(); + + if(d_bufferSize < vertexCount) + { + needNewBuffer = true; + d_bufferSize = vertexCount; + } + + d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO); + + float* vertexData; + if(d_vertexData.empty()) + vertexData = 0; + else + vertexData = &d_vertexData[0]; + + GLsizei dataSize = vertexCount * sizeof(float); + + if(needNewBuffer) + { + glBufferData(GL_ARRAY_BUFFER, dataSize, vertexData, GL_STATIC_DRAW); + } + else + { + glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, vertexData); + } +} + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::appendGeometry(const float* vertex_data, std::size_t array_size) +{ + OpenGLGeometryBufferBase::appendGeometry(vertex_data, array_size); + + updateOpenGLBuffers(); +} + +//----------------------------------------------------------------------------// +void GLES2GeometryBuffer::drawDependingOnFillRule() const +{ + if(d_polygonFillRule == PFR_NONE) + { + d_glStateChanger->disable(GL_CULL_FACE); + d_glStateChanger->disable(GL_STENCIL_TEST); + + glDrawArrays(GL_TRIANGLES, 0, d_vertexCount); + } + else if(d_polygonFillRule == PFR_EVEN_ODD) + { + //We use a stencil buffer to determine the insideness + //of a fragment. Every draw inverts the precious value + //according to the even-odd rule. + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + + d_glStateChanger->disable(GL_CULL_FACE); + d_glStateChanger->enable(GL_STENCIL_TEST); + glStencilMask(0xFF); + glClear(GL_STENCIL_BUFFER_BIT); + glStencilFunc(GL_ALWAYS, 0x00, 0xFF); + glStencilOp(GL_INVERT, GL_KEEP, GL_INVERT); + glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - d_postStencilVertexCount); + + unsigned int postStencilStart = d_vertexCount - d_postStencilVertexCount; + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glStencilMask(0x00); + glStencilFunc(GL_EQUAL, 0xFF, 0xFF); + glDrawArrays(GL_TRIANGLES, postStencilStart, d_postStencilVertexCount); + } + else if(d_polygonFillRule == PFR_NON_ZERO) + { + //We use a stencil buffer to determine the insideness + //of a fragment. We draw the front sides while increasing + //stencil values and then draw backside while decreasing them. + //A resulting 0 value means we are outside. + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + + unsigned int solid_fill_count = d_vertexCount - d_postStencilVertexCount; + unsigned int vertex_pos = 0; + + //Performing the back/front faces stencil incr and decr stencil op + d_glStateChanger->enable(GL_CULL_FACE); + d_glStateChanger->enable(GL_STENCIL_TEST); + glStencilMask(0xFF); + glClear(GL_STENCIL_BUFFER_BIT); + glStencilFunc(GL_ALWAYS, 0x00, 0xFF); + + glCullFace(GL_FRONT); + glStencilOp(GL_KEEP, GL_KEEP, GL_INCR_WRAP); + glDrawArrays(GL_TRIANGLES, vertex_pos, solid_fill_count); + + glCullFace(GL_BACK); + glStencilOp(GL_KEEP, GL_KEEP, GL_DECR_WRAP); + glDrawArrays(GL_TRIANGLES, vertex_pos, solid_fill_count); + + vertex_pos += solid_fill_count; + + //Only needing culling for the back/front face stencil calculations + d_glStateChanger->disable(GL_CULL_FACE); + + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glStencilMask(0x00); + + if(d_postStencilVertexCount != 0) + { + glStencilFunc(GL_NOTEQUAL, 0x00, 0xFF); + glDrawArrays(GL_TRIANGLES, d_vertexCount - d_postStencilVertexCount, d_postStencilVertexCount); + } + } +} + + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section + diff --git a/cegui/src/RendererModules/OpenGL/GLES2Renderer.cpp b/cegui/src/RendererModules/OpenGL/GLES2Renderer.cpp new file mode 100644 index 000000000..db8f55643 --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLES2Renderer.cpp @@ -0,0 +1,392 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl (based on code by Paul D Turner) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/ShaderManager.h" +#include "CEGUI/RendererModules/OpenGL/GLES2Renderer.h" +#include "CEGUI/RendererModules/OpenGL/GLES2Texture.h" +#include "CEGUI/RendererModules/OpenGL/Shader.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/ImageCodec.h" +#include "CEGUI/DynamicModule.h" +#include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" +#include "CEGUI/RendererModules/OpenGL/GLES2GeometryBuffer.h" +#include "CEGUI/GUIContext.h" +#include "CEGUI/RendererModules/OpenGL/GLES2FBOTextureTarget.h" +#include "CEGUI/System.h" +#include "CEGUI/DefaultResourceProvider.h" +#include "CEGUI/Logger.h" +#include "CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h" +#include "CEGUI/RenderMaterial.h" +#include "CEGUI/RendererModules/OpenGL/GLBaseShaderWrapper.h" + +#include +#include +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +// The following are some GL extension / version dependant related items. +// This is all done totally internally here; no need for external interface +// to show any of this. +//----------------------------------------------------------------------------// +// we only really need this with MSVC / Windows(?) and by now it should already +// be defined on that platform, so we just define it as empty macro so the +// compile does not break on other systems. +#ifndef APIENTRY +# define APIENTRY +#endif +//! Dummy function for if real ones are not present (saves testing each render) +static void APIENTRY activeTextureDummy(GLenum) {} + +//----------------------------------------------------------------------------// +// template specialised class that does the real work for us +template +class OGLTemplateTargetFactory : public OGLTextureTargetFactory +{ + TextureTarget* create(OpenGLRendererBase& r) const + { return new T(static_cast(r)); } +}; + +//----------------------------------------------------------------------------// +GLES2Renderer& GLES2Renderer::bootstrapSystem(const int abi) +{ + System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); + + if (System::getSingletonPtr()) + CEGUI_THROW(InvalidRequestException( + "CEGUI::System object is already initialised.")); + + GLES2Renderer& renderer(create()); + DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); + System::create(renderer, rp); + + return renderer; +} + +//----------------------------------------------------------------------------// +GLES2Renderer& GLES2Renderer::bootstrapSystem(const Sizef& display_size, + const int abi) +{ + System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); + + if (System::getSingletonPtr()) + CEGUI_THROW(InvalidRequestException( + "CEGUI::System object is already initialised.")); + + GLES2Renderer& renderer(create(display_size)); + DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); + System::create(renderer, rp); + + return renderer; +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::destroySystem() +{ + System* sys; + if (!(sys = System::getSingletonPtr())) + CEGUI_THROW(InvalidRequestException( + "CEGUI::System object is not created or was already destroyed.")); + + GLES2Renderer* renderer = static_cast(sys->getRenderer()); + DefaultResourceProvider* rp = + static_cast(sys->getResourceProvider()); + + System::destroy(); + delete rp; + destroy(*renderer); +} + +//----------------------------------------------------------------------------// +GLES2Renderer& GLES2Renderer::create(const int abi) +{ + System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); + + return *new GLES2Renderer(); +} + +//----------------------------------------------------------------------------// +GLES2Renderer& GLES2Renderer::create(const Sizef& display_size, + const int abi) +{ + System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); + + return *new GLES2Renderer(display_size); +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::destroy(GLES2Renderer& renderer) +{ + delete &renderer; +} + +//----------------------------------------------------------------------------// +GLES2Renderer::GLES2Renderer() : + d_shaderWrapperTextured(0), + d_openGLStateChanger(0), + d_shaderManager(0) +{ + initialiseRendererIDString(); + initialiseGLExtensions(); + d_openGLStateChanger = new GLES2StateChangeWrapper(); + initialiseTextureTargetFactory(); + initialiseOpenGLShaders(); +} + +//----------------------------------------------------------------------------// +GLES2Renderer::GLES2Renderer(const Sizef& display_size) : + OpenGLRendererBase(display_size), + d_shaderWrapperTextured(0), + d_openGLStateChanger(0), + d_shaderManager(0) +{ + initialiseRendererIDString(); + initialiseGLExtensions(); + d_openGLStateChanger = new GLES2StateChangeWrapper(); + initialiseTextureTargetFactory(); + initialiseOpenGLShaders(); +} + +//----------------------------------------------------------------------------// +GLES2Renderer::~GLES2Renderer() +{ + delete d_textureTargetFactory; + delete d_openGLStateChanger; + delete d_shaderManager; + + delete d_shaderWrapperTextured; + delete d_shaderWrapperSolid; +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::initialiseRendererIDString() +{ + d_rendererID = +#ifdef CEGUI_GLES3_SUPPORT + "CEGUI::GLES2Renderer - OpenGL ES 3.0 Renderer" +#else + "CEGUI::GLES2Renderer - OpenGL ES 2.0 Renderer" +#endif + "renderer module."; +} +//----------------------------------------------------------------------------// +OpenGLGeometryBufferBase* GLES2Renderer::createGeometryBuffer_impl(CEGUI::RefCounted renderMaterial) +{ + return new GLES2GeometryBuffer(*this, renderMaterial); +} + +//----------------------------------------------------------------------------// +TextureTarget* GLES2Renderer::createTextureTarget_impl() +{ + return d_textureTargetFactory->create(*this); +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::beginRendering() +{ + // if enabled, restores a subset of the GL state back to default values. + if (d_initExtraStates) + setupExtraStates(); + + d_openGLStateChanger->reset(); + + // Setup initial states + d_openGLStateChanger->enable(GL_BLEND); + + // force set blending ops to get to a known state. + setupRenderingBlendMode(BM_NORMAL, true); +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::endRendering() +{ +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::setupExtraStates() +{ + glActiveTexture(GL_TEXTURE0); + + //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + + glUseProgram(0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::initialiseTextureTargetFactory() +{ + //Use OGL core implementation for FBOs + d_rendererID += " TextureTarget support enabled via FBO OGL 3.2 core implementation."; + d_textureTargetFactory = new OGLTemplateTargetFactory; +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::setupRenderingBlendMode(const BlendMode mode, + const bool force) +{ + // exit if mode is already set up (and update not forced) + if ((d_activeBlendMode == mode) && !force) + return; + + d_activeBlendMode = mode; + + if (d_activeBlendMode == BM_RTT_PREMULTIPLIED) + { + d_openGLStateChanger->blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + else + { + d_openGLStateChanger->blendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); + } +} + +//----------------------------------------------------------------------------// +Sizef GLES2Renderer::getAdjustedTextureSize(const Sizef& sz) +{ + Sizef out(sz); + + const GLubyte* pcExt = glGetString(GL_EXTENSIONS); + String extensions = String((const char*)pcExt); + + // if we can't support non power of two sizes, get appropriate POT values. + if (!extensions.find("GL_OES_texture_npot")) + { + out.d_width = getNextPOTSize(out.d_width); + out.d_height = getNextPOTSize(out.d_height); + } + + return out; + +} + +//----------------------------------------------------------------------------// +OpenGLBaseStateChangeWrapper* GLES2Renderer::getOpenGLStateChanger() +{ + return d_openGLStateChanger; +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::initialiseOpenGLShaders() +{ + checkGLErrors(); +#ifdef CEGUI_GLES3_SUPPORT + d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSLES3); +#else + d_shaderManager = new OpenGLBaseShaderManager(d_openGLStateChanger, SHADER_GLSLES1); +#endif + d_shaderManager->initialiseShaders(); + + initialiseStandardTexturedShaderWrapper(); + initialiseStandardColouredShaderWrapper(); +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::initialiseGLExtensions() +{ + const GLubyte* pcExt = glGetString(GL_EXTENSIONS); + String extensions = String((const char*)pcExt); + + if (extensions.find("GL_EXT_texture_compression_s3tc")) + { + d_s3tcSupported = true; + } +} + +//----------------------------------------------------------------------------// +bool GLES2Renderer::isS3TCSupported() const +{ + return d_s3tcSupported; +} + +//----------------------------------------------------------------------------// +RefCounted GLES2Renderer::createRenderMaterial(const DefaultShaderType shaderType) const +{ + if(shaderType == DS_TEXTURED) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperTextured)); + + return render_material; + } + else if(shaderType == DS_SOLID) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperSolid)); + + return render_material; + } + else + { + CEGUI_THROW(RendererException( + "A default shader of this type does not exist.")); + + return RefCounted(); + } +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::initialiseStandardTexturedShaderWrapper() +{ + OpenGLBaseShader* shader_standard_textured = d_shaderManager->getShader(SHADER_ID_STANDARD_TEXTURED); + d_shaderWrapperTextured = new OpenGLBaseShaderWrapper(*shader_standard_textured, d_openGLStateChanger); + + d_shaderWrapperTextured->addTextureUniformVariable("texture0", 0); + + d_shaderWrapperTextured->addUniformVariable("modelViewProjMatrix"); + d_shaderWrapperTextured->addUniformVariable("alphaPercentage"); + + d_shaderWrapperTextured->addAttributeVariable("inPosition"); + d_shaderWrapperTextured->addAttributeVariable("inTexCoord"); + d_shaderWrapperTextured->addAttributeVariable("inColour"); +} + +//----------------------------------------------------------------------------// +void GLES2Renderer::initialiseStandardColouredShaderWrapper() +{ + OpenGLBaseShader* shader_standard_solid = d_shaderManager->getShader(SHADER_ID_STANDARD_SOLID); + d_shaderWrapperSolid = new OpenGLBaseShaderWrapper(*shader_standard_solid, d_openGLStateChanger); + + d_shaderWrapperSolid->addUniformVariable("modelViewProjMatrix"); + d_shaderWrapperSolid->addUniformVariable("alphaPercentage"); + + d_shaderWrapperSolid->addAttributeVariable("inPosition"); + d_shaderWrapperSolid->addAttributeVariable("inColour"); +} + +//----------------------------------------------------------------------------// +OpenGLTexture* GLES2Renderer::createTexture_impl(const String& name) +{ + return new GLES2Texture(*this, name); +} + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/OpenGL/GLES2StateChangeWrapper.cpp b/cegui/src/RendererModules/OpenGL/GLES2StateChangeWrapper.cpp new file mode 100644 index 000000000..c2f2b1cab --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLES2StateChangeWrapper.cpp @@ -0,0 +1,57 @@ +/*********************************************************************** + created: Wed, 8th Feb 2012 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "CEGUI/RendererModules/OpenGL/GLES2StateChangeWrapper.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +GLES2StateChangeWrapper::GLES2StateChangeWrapper() + : OpenGLBaseStateChangeWrapper() +{ +} + +//----------------------------------------------------------------------------// +GLES2StateChangeWrapper::~GLES2StateChangeWrapper() +{ +} + +//----------------------------------------------------------------------------// +void GLES2StateChangeWrapper::bindVertexArray(GLuint vertexArray) +{ +#if CEGUI_GLES3_SUPPORT + if (vertexArray != d_vertexArrayObject) + { + glBindVertexArray(vertexArray); + d_vertexArrayObject = vertexArray; + } +#endif +} + +//----------------------------------------------------------------------------// +} diff --git a/cegui/src/RendererModules/OpenGL/GLES2Texture.cpp b/cegui/src/RendererModules/OpenGL/GLES2Texture.cpp new file mode 100644 index 000000000..82cd40133 --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLES2Texture.cpp @@ -0,0 +1,151 @@ +/*********************************************************************** + created: Sun Jan 11 2009 + author: Paul D Turner +*************************************************************************/ +/*************************************************************************** + Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GLES2Texture.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/System.h" +#include "CEGUI/ImageCodec.h" + +#include "CEGUI/RendererModules/OpenGL/GL.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +GLES2Texture::GLES2Texture(OpenGLRendererBase& owner, const String& name) + : OpenGLTexture(owner, name) +{ +} + +//----------------------------------------------------------------------------// +GLES2Texture::~GLES2Texture() +{ +} + +//----------------------------------------------------------------------------// +void GLES2Texture::initInternalPixelFormatFields(const PixelFormat fmt) +{ + d_isCompressed = false; + + switch(fmt) + { + case PF_RGBA: + d_format = GL_RGBA; + d_subpixelFormat = GL_UNSIGNED_BYTE; + break; + + case PF_RGB: + d_format = GL_RGB; + d_subpixelFormat = GL_UNSIGNED_BYTE; + break; + + case PF_RGB_565: + d_format = GL_RGB; + d_subpixelFormat = GL_UNSIGNED_SHORT_5_6_5; + break; + + case PF_RGBA_4444: + d_format = GL_RGBA; + d_subpixelFormat = GL_UNSIGNED_SHORT_4_4_4_4; + break; + + default: + CEGUI_THROW(RendererException( + "invalid or unsupported CEGUI::PixelFormat.")); + } +} + + + +//----------------------------------------------------------------------------// +GLsizei GLES2Texture::getCompressedTextureSize(const Sizef& pixel_size) const +{ + GLsizei blocksize = 16; + return ( + static_cast( + std::ceil(pixel_size.d_width / 4) * + std::ceil(pixel_size.d_height / 4) * + blocksize)); +} + +//----------------------------------------------------------------------------// +void GLES2Texture::setTextureSize_impl(const Sizef& sz) +{ + const Sizef size(d_owner.getAdjustedTextureSize(sz)); + d_size = size; + + // make sure size is within boundaries + GLfloat maxSize; + glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize); + + if((size.d_width > maxSize) || (size.d_height > maxSize)) + CEGUI_THROW(RendererException("size too big")); + + // save old texture binding + GLuint old_tex; + glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); + + // set texture to required size + glBindTexture(GL_TEXTURE_2D, d_ogltexture); + + if(d_isCompressed) + { + const GLsizei image_size = getCompressedTextureSize(size); + glCompressedTexImage2D(GL_TEXTURE_2D, 0, d_format, + static_cast(size.d_width), + static_cast(size.d_height), + 0, image_size, 0); + } + else + { +#ifndef CEGUI_GLES3_SUPPORT + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, +#else + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, +#endif + static_cast(size.d_width), + static_cast(size.d_height), + 0, GL_RGBA , GL_UNSIGNED_BYTE, 0); + } + + // restore previous texture binding. + glBindTexture(GL_TEXTURE_2D, old_tex); +} + +//----------------------------------------------------------------------------// +void GLES2Texture::blitToMemory(void* targetData) +{ + // TODO: + CEGUI_THROW(RendererException("GLES2Texture blitToMemory unimplemented!")); +} + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section + + diff --git a/cegui/src/RendererModules/OpenGL/GLFBOTextureTarget.cpp b/cegui/src/RendererModules/OpenGL/GLFBOTextureTarget.cpp index df6d530bd..035f79437 100644 --- a/cegui/src/RendererModules/OpenGL/GLFBOTextureTarget.cpp +++ b/cegui/src/RendererModules/OpenGL/GLFBOTextureTarget.cpp @@ -24,7 +24,6 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include #include "CEGUI/RendererModules/OpenGL/GLFBOTextureTarget.h" #include "CEGUI/Exceptions.h" #include "CEGUI/RenderQueue.h" diff --git a/cegui/src/RendererModules/OpenGL/GLGeometryBuffer.cpp b/cegui/src/RendererModules/OpenGL/GLGeometryBuffer.cpp index 5bb32284c..002bea4d8 100644 --- a/cegui/src/RendererModules/OpenGL/GLGeometryBuffer.cpp +++ b/cegui/src/RendererModules/OpenGL/GLGeometryBuffer.cpp @@ -25,44 +25,50 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include #include "CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h" #include "CEGUI/RendererModules/OpenGL/GLRenderer.h" #include "CEGUI/RenderEffect.h" -#include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/Vertex.h" -#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" -#include "glm/gtc/type_ptr.hpp" + +#include // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// -OpenGLGeometryBuffer::OpenGLGeometryBuffer(OpenGLRenderer& owner) : - OpenGLGeometryBufferBase(owner) +OpenGLGeometryBuffer::OpenGLGeometryBuffer(OpenGLRenderer& owner, CEGUI::RefCounted renderMaterial) : + OpenGLGeometryBufferBase(owner, renderMaterial) { } //----------------------------------------------------------------------------// void OpenGLGeometryBuffer::draw() const { - CEGUI::Rectf viewPort = d_owner->getActiveViewPort(); + if(d_vertexData.empty()) + return; + + CEGUI::Rectf viewPort = d_owner.getActiveViewPort(); + + if (d_clippingActive) + { + glScissor(static_cast(d_clipRect.left()), + static_cast(viewPort.getHeight() - d_clipRect.bottom()), + static_cast(d_clipRect.getWidth()), + static_cast(d_clipRect.getHeight())); - // setup clip region - glScissor(static_cast(d_clipRect.left()), - static_cast(viewPort.getHeight() - d_clipRect.bottom()), - static_cast(d_clipRect.getWidth()), - static_cast(d_clipRect.getHeight())); + glEnable(GL_SCISSOR_TEST); + } + else + glDisable(GL_SCISSOR_TEST); - // apply the transformations we need to use. - if (!d_matrixValid) - updateMatrix(); + // Update the model view projection matrix + updateMatrix(); glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(glm::value_ptr(d_matrix->d_matrix)); + glLoadMatrixf(glm::value_ptr(d_matrix)); // activate desired blending mode - d_owner->setupRenderingBlendMode(d_blendMode); + d_owner.setupRenderingBlendMode(d_blendMode); const int pass_count = d_effect ? d_effect->getPassCount() : 1; for (int pass = 0; pass < pass_count; ++pass) @@ -71,33 +77,62 @@ void OpenGLGeometryBuffer::draw() const if (d_effect) d_effect->performPreRenderFunctions(pass); - // draw the batches - size_t pos = 0; - BatchList::const_iterator i = d_batches.begin(); - for ( ; i != d_batches.end(); ++i) - { - if (i->clip) - glEnable(GL_SCISSOR_TEST); - else - glDisable(GL_SCISSOR_TEST); - - glBindTexture(GL_TEXTURE_2D, i->texture); - // set up pointers to the vertex element arrays - glTexCoordPointer(2, GL_FLOAT, sizeof(GLVertex), - &d_vertices[pos]); - glColorPointer(4, GL_FLOAT, sizeof(GLVertex), - &d_vertices[pos].colour[0]); - glVertexPointer(3, GL_FLOAT, sizeof(GLVertex), - &d_vertices[pos].position[0]); - // draw the geometry - glDrawArrays(GL_TRIANGLES, 0, i->vertexCount); - pos += i->vertexCount; - } + d_renderMaterial->prepareForRendering(); + + setupVertexDataPointers(); + + // draw the geometry + glDrawArrays(GL_TRIANGLES, 0, d_vertexCount); } // clean up RenderEffect if (d_effect) d_effect->performPostRenderFunctions(); + + updateRenderTargetData(d_owner.getActiveRenderTarget()); +} + +//----------------------------------------------------------------------------// +void OpenGLGeometryBuffer::finaliseVertexAttributes() +{ +} + +//----------------------------------------------------------------------------// +void OpenGLGeometryBuffer::setupVertexDataPointers() const +{ + int dataOffset = 0; + GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT); + + const size_t attribute_count = d_vertexAttributes.size(); + for (size_t i = 0; i < attribute_count; ++i) + { + switch(d_vertexAttributes.at(i)) + { + case VAT_POSITION0: + { + glVertexPointer(3, GL_FLOAT, stride, + &d_vertexData[dataOffset]); + dataOffset += 3; + } + break; + case VAT_COLOUR0: + { + glColorPointer(4, GL_FLOAT, stride, + &d_vertexData[dataOffset]); + dataOffset += 4; + } + break; + case VAT_TEXCOORD0: + { + glTexCoordPointer(2, GL_FLOAT, stride, + &d_vertexData[dataOffset]); + dataOffset += 2; + } + break; + default: + break; + } + } } //----------------------------------------------------------------------------// diff --git a/cegui/src/RendererModules/OpenGL/GLRenderer.cpp b/cegui/src/RendererModules/OpenGL/GLRenderer.cpp index aa488f83d..19663b6b4 100644 --- a/cegui/src/RendererModules/OpenGL/GLRenderer.cpp +++ b/cegui/src/RendererModules/OpenGL/GLRenderer.cpp @@ -25,23 +25,20 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - -#include "CEGUI/RendererModules/OpenGL/GLRenderer.h" -#include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGL/GLGeometryBuffer.h" - #include "CEGUI/RendererModules/OpenGL/GLFBOTextureTarget.h" +#include "CEGUI/RendererModules/OpenGL/GLRenderer.h" +#include "CEGUI/RendererModules/OpenGL/GLTexture.h" +#include "CEGUI/RendererModules/OpenGL/GLShaderWrapper.h" #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/Logger.h" -#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" #include "glm/gtc/type_ptr.hpp" #include @@ -82,7 +79,7 @@ template class OGLTemplateTargetFactory : public OGLTextureTargetFactory { virtual TextureTarget* create(OpenGLRendererBase& r) const - { return CEGUI_NEW_AO T(r); } + { return new T(r); } }; //----------------------------------------------------------------------------// @@ -96,7 +93,7 @@ OpenGLRenderer& OpenGLRenderer::bootstrapSystem(const TextureTargetType tt_type, "CEGUI::System object is already initialised.")); OpenGLRenderer& renderer(create(tt_type)); - DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider(); + DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; @@ -114,7 +111,7 @@ OpenGLRenderer& OpenGLRenderer::bootstrapSystem(const Sizef& display_size, "CEGUI::System object is already initialised.")); OpenGLRenderer& renderer(create(display_size, tt_type)); - DefaultResourceProvider* rp = CEGUI_NEW_AO CEGUI::DefaultResourceProvider(); + DefaultResourceProvider* rp = new CEGUI::DefaultResourceProvider(); System::create(renderer, rp); return renderer; @@ -133,7 +130,7 @@ void OpenGLRenderer::destroySystem() static_cast(sys->getResourceProvider()); System::destroy(); - CEGUI_DELETE_AO rp; + delete rp; destroy(*renderer); } @@ -143,7 +140,7 @@ OpenGLRenderer& OpenGLRenderer::create(const TextureTargetType tt_type, { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO OpenGLRenderer(tt_type); + return *new OpenGLRenderer(tt_type); } //----------------------------------------------------------------------------// @@ -153,13 +150,13 @@ OpenGLRenderer& OpenGLRenderer::create(const Sizef& display_size, { System::performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO OpenGLRenderer(display_size, tt_type); + return *new OpenGLRenderer(display_size, tt_type); } //----------------------------------------------------------------------------// void OpenGLRenderer::destroy(OpenGLRenderer& renderer) { - CEGUI_DELETE_AO &renderer; + delete &renderer; } //----------------------------------------------------------------------------// @@ -168,6 +165,7 @@ OpenGLRenderer::OpenGLRenderer(const TextureTargetType tt_type) initialiseRendererIDString(); initialiseGLExtensions(); initialiseTextureTargetFactory(tt_type); + initialiseShaderWrappers(); // we _really_ need separate rgb/alpha blend modes, if this support is not // available, add a note to the renderer ID string so that this fact is @@ -195,7 +193,7 @@ OpenGLRenderer::OpenGLRenderer(const Sizef& display_size, //----------------------------------------------------------------------------// OpenGLRenderer::~OpenGLRenderer() { - CEGUI_DELETE_AO d_textureTargetFactory; + delete d_textureTargetFactory; } //----------------------------------------------------------------------------// @@ -207,9 +205,9 @@ void OpenGLRenderer::initialiseRendererIDString() } //----------------------------------------------------------------------------// -OpenGLGeometryBufferBase* OpenGLRenderer::createGeometryBuffer_impl() +OpenGLGeometryBufferBase* OpenGLRenderer::createGeometryBuffer_impl(CEGUI::RefCounted renderMaterial) { - return CEGUI_NEW_AO OpenGLGeometryBuffer(*this); + return new OpenGLGeometryBuffer(*this, renderMaterial); } //----------------------------------------------------------------------------// @@ -225,9 +223,6 @@ void OpenGLRenderer::beginRendering() glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); glPushAttrib(GL_ALL_ATTRIB_BITS); - // save current matrices - glMatrixMode(GL_PROJECTION); - glPushMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); @@ -262,8 +257,6 @@ void OpenGLRenderer::endRendering() // restore former matrices // FIXME: If the push ops failed, the following could mess things up! - glMatrixMode(GL_PROJECTION); - glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); @@ -316,7 +309,7 @@ void OpenGLRenderer::initialiseTextureTargetFactory( { d_rendererID += " TextureTarget support enabled via FBO extension."; d_textureTargetFactory = - CEGUI_NEW_AO OGLTemplateTargetFactory; + new OGLTemplateTargetFactory; } #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) @@ -326,7 +319,7 @@ void OpenGLRenderer::initialiseTextureTargetFactory( { d_rendererID += " TextureTarget support enabled via GLX pbuffers."; d_textureTargetFactory = - CEGUI_NEW_AO OGLTemplateTargetFactory; + new OGLTemplateTargetFactory; } #elif defined(_WIN32) || defined(__WIN32__) // on Windows, we can try for WGL based pbuffer support @@ -335,7 +328,7 @@ void OpenGLRenderer::initialiseTextureTargetFactory( { d_rendererID += " TextureTarget support enabled via WGL_ARB_pbuffer."; d_textureTargetFactory = - CEGUI_NEW_AO OGLTemplateTargetFactory; + new OGLTemplateTargetFactory; } #elif defined(__APPLE__) // on Apple Mac, we can try for Apple's pbuffer support @@ -345,14 +338,14 @@ void OpenGLRenderer::initialiseTextureTargetFactory( d_rendererID += " TextureTarget support enabled via " "GL_APPLE_pixel_buffer."; d_textureTargetFactory = - CEGUI_NEW_AO OGLTemplateTargetFactory; + new OGLTemplateTargetFactory; } #endif // Nothing suitable available, try to carry on without TextureTargets else { d_rendererID += " TextureTarget support is not available :("; - d_textureTargetFactory = CEGUI_NEW_AO OGLTextureTargetFactory; + d_textureTargetFactory = new OGLTextureTargetFactory; } } @@ -424,14 +417,58 @@ bool OpenGLRenderer::isS3TCSupported() const } //----------------------------------------------------------------------------// -void OpenGLRenderer::setViewProjectionMatrix(const mat4Pimpl* viewProjectionMatrix) +RefCounted OpenGLRenderer::createRenderMaterial(const DefaultShaderType shaderType) const { - OpenGLRendererBase::setViewProjectionMatrix(viewProjectionMatrix); + if(shaderType == DS_TEXTURED) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperTextured)); + + return render_material; + } + else if(shaderType == DS_SOLID) + { + RefCounted render_material(new RenderMaterial(d_shaderWrapperSolid)); + + return render_material; + } + else + { + CEGUI_THROW(RendererException( + "A default shader of this type does not exist.")); - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(glm::value_ptr(d_viewProjectionMatrix->d_matrix)); + return RefCounted(); + } } +//----------------------------------------------------------------------------// +void OpenGLRenderer::initialiseShaderWrappers() +{ + d_shaderWrapperTextured = new OpenGLShaderWrapper(); + + d_shaderWrapperSolid = new OpenGLShaderWrapper(); +} + +//----------------------------------------------------------------------------// +Sizef OpenGLRenderer::getAdjustedTextureSize(const Sizef& sz) +{ + Sizef out(sz); + + // if we can't support non power of two sizes, get appropriate POT values. + if (!GLEW_ARB_texture_non_power_of_two) + { + out.d_width = getNextPOTSize(out.d_width); + out.d_height = getNextPOTSize(out.d_height); + } + + return out; +} + +//----------------------------------------------------------------------------// +OpenGLTexture* OpenGLRenderer::createTexture_impl(const String& name) +{ + return new OpenGL1Texture(*this, name); +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/OpenGL/GLShaderWrapper.cpp b/cegui/src/RendererModules/OpenGL/GLShaderWrapper.cpp new file mode 100644 index 000000000..0bd228ae0 --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLShaderWrapper.cpp @@ -0,0 +1,96 @@ +/*********************************************************************** + created: 23rd September 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GLShaderWrapper.h" +#include "CEGUI/RendererModules/OpenGL/GLRenderer.h" +#include "CEGUI/RendererModules/OpenGL/Texture.h" +#include "CEGUI/ShaderParameterBindings.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +OpenGLShaderWrapper::OpenGLShaderWrapper() +{ +} + +//----------------------------------------------------------------------------// +OpenGLShaderWrapper::~OpenGLShaderWrapper() +{ +} + +//----------------------------------------------------------------------------// +void OpenGLShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings) +{ + const ShaderParameterBindings::ShaderParameterBindingsMap& shader_parameter_bindings = shaderParameterBindings->getShaderParameterBindings(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator iter = shader_parameter_bindings.begin(); + ShaderParameterBindings::ShaderParameterBindingsMap::const_iterator end = shader_parameter_bindings.end(); + + bool is_textured = false; + + while(iter != end) + { + const CEGUI::ShaderParameter* parameter = iter->second; + + CEGUI::ShaderParamType parameter_type = parameter->getType(); + + switch(parameter_type) + { + case SPT_TEXTURE: + { + const CEGUI::ShaderParameterTexture* parameterTexture = static_cast(parameter); + const CEGUI::OpenGLTexture* openglTexture = static_cast(parameterTexture->d_parameterValue); + + glActiveTexture(GL_TEXTURE0); + glClientActiveTexture(GL_TEXTURE0); + + glBindTexture(GL_TEXTURE_2D, openglTexture->getOpenGLTexture()); + + is_textured = true; + } + break; + default: + break; + } + + ++iter; + } + + if(is_textured) + { + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnable(GL_TEXTURE_2D); + } + else + { + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisable(GL_TEXTURE_2D); + } +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/RendererModules/OpenGL/GLTexture.cpp b/cegui/src/RendererModules/OpenGL/GLTexture.cpp new file mode 100644 index 000000000..5a8060039 --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/GLTexture.cpp @@ -0,0 +1,201 @@ +/*********************************************************************** + created: Sun Jan 11 2009 + author: Paul D Turner +*************************************************************************/ +/*************************************************************************** + Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/RendererModules/OpenGL/GLTexture.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/System.h" +#include "CEGUI/ImageCodec.h" + +#include "CEGUI/RendererModules/OpenGL/GL.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +OpenGL1Texture::OpenGL1Texture(OpenGLRendererBase& owner, const String& name) + : OpenGLTexture(owner, name) +{ +} + +//----------------------------------------------------------------------------// +void OpenGL1Texture::initInternalPixelFormatFields(const PixelFormat fmt) +{ + d_isCompressed = false; + + switch(fmt) + { + case PF_RGBA: + d_format = GL_RGBA; + d_subpixelFormat = GL_UNSIGNED_BYTE; + break; + + case PF_RGB: + d_format = GL_RGB; + d_subpixelFormat = GL_UNSIGNED_BYTE; + break; + + case PF_RGB_565: + d_format = GL_RGB; + d_subpixelFormat = GL_UNSIGNED_SHORT_5_6_5; + break; + + case PF_RGBA_4444: + d_format = GL_RGBA; + d_subpixelFormat = GL_UNSIGNED_SHORT_4_4_4_4; + break; + + case PF_RGB_DXT1: + d_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; + d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. + d_isCompressed = true; + break; + + case PF_RGBA_DXT1: + d_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; + d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. + d_isCompressed = true; + break; + + case PF_RGBA_DXT3: + d_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; + d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. + d_isCompressed = true; + break; + + case PF_RGBA_DXT5: + d_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. + d_isCompressed = true; + break; + + default: + CEGUI_THROW(RendererException( + "invalid or unsupported CEGUI::PixelFormat.")); + } +} + +//----------------------------------------------------------------------------// +OpenGL1Texture::~OpenGL1Texture() +{ +} + +//----------------------------------------------------------------------------// +GLsizei OpenGL1Texture::getCompressedTextureSize(const Sizef& pixel_size) const +{ + GLsizei blocksize = 16; + + if(d_format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT || + d_format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) + { + blocksize = 8; + } + + return ( + static_cast( + std::ceil(pixel_size.d_width / 4) * + std::ceil(pixel_size.d_height / 4) * + blocksize)); +} + +//----------------------------------------------------------------------------// +void OpenGL1Texture::setTextureSize_impl(const Sizef& sz) +{ + const Sizef size(d_owner.getAdjustedTextureSize(sz)); + d_size = size; + + // make sure size is within boundaries + GLfloat maxSize; + glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize); + + if((size.d_width > maxSize) || (size.d_height > maxSize)) + CEGUI_THROW(RendererException("size too big")); + + // save old texture binding + GLuint old_tex; + glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); + + // set texture to required size + glBindTexture(GL_TEXTURE_2D, d_ogltexture); + + if(d_isCompressed) + { + const GLsizei image_size = getCompressedTextureSize(size); + glCompressedTexImage2D(GL_TEXTURE_2D, 0, d_format, + static_cast(size.d_width), + static_cast(size.d_height), + 0, image_size, 0); + } + else + { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, + static_cast(size.d_width), + static_cast(size.d_height), + 0, GL_RGBA , GL_UNSIGNED_BYTE, 0); + } + + // restore previous texture binding. + glBindTexture(GL_TEXTURE_2D, old_tex); +} + +//----------------------------------------------------------------------------// +void OpenGL1Texture::blitToMemory(void* targetData) +{ + // save existing config + GLuint old_tex; + glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); + + glBindTexture(GL_TEXTURE_2D, d_ogltexture); + + if(d_isCompressed) + { + glGetCompressedTexImage(GL_TEXTURE_2D, 0, targetData); + } + else + { + GLint old_pack; + glGetIntegerv(GL_PACK_ALIGNMENT, &old_pack); + + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glGetTexImage(GL_TEXTURE_2D, 0, d_format, d_subpixelFormat, targetData); + + glPixelStorei(GL_PACK_ALIGNMENT, old_pack); + } + + // restore previous config. + glBindTexture(GL_TEXTURE_2D, old_tex); +} + +//----------------------------------------------------------------------------// +void OpenGL1Texture::setTextureEnvironment() +{ + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); +} +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section + diff --git a/cegui/src/RendererModules/OpenGL/GeometryBufferBase.cpp b/cegui/src/RendererModules/OpenGL/GeometryBufferBase.cpp index 1fafc98cb..d061866a0 100644 --- a/cegui/src/RendererModules/OpenGL/GeometryBufferBase.cpp +++ b/cegui/src/RendererModules/OpenGL/GeometryBufferBase.cpp @@ -25,66 +25,30 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - -#include "glm/glm.hpp" -#include "glm/gtc/quaternion.hpp" -#include "glm/gtc/type_ptr.hpp" -#include "glm/gtc/matrix_transform.hpp" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include "CEGUI/RenderEffect.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/Vertex.h" -#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" + +#include +#include +#include +#include namespace CEGUI { //----------------------------------------------------------------------------// -OpenGLGeometryBufferBase::OpenGLGeometryBufferBase(OpenGLRendererBase& owner) : - d_owner(&owner), - d_activeTexture(0), - d_clipRect(0, 0, 0, 0), - d_clippingActive(true), - d_translation(0, 0, 0), - d_rotation(Quaternion::IDENTITY), - d_pivot(0, 0, 0), - d_effect(0), - d_matrix(new mat4Pimpl()), - d_matrixValid(false) +OpenGLGeometryBufferBase::OpenGLGeometryBufferBase(OpenGLRendererBase& owner, CEGUI::RefCounted renderMaterial) + : GeometryBuffer(renderMaterial) + , d_owner(owner) + , d_clipRect(0, 0, 0, 0) + , d_matrix(1.0) { } //----------------------------------------------------------------------------// OpenGLGeometryBufferBase::~OpenGLGeometryBufferBase() { - delete d_matrix; -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::appendVertex(const Vertex& vertex) -{ - appendGeometry(&vertex, 1); -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::setTranslation(const Vector3f& v) -{ - d_translation = v; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::setRotation(const Quaternion& r) -{ - d_rotation = r; - d_matrixValid = false; -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::setPivot(const Vector3f& p) -{ - d_pivot = Vector3f(p.d_x, p.d_y, p.d_z); - d_matrixValid = false; } //----------------------------------------------------------------------------// @@ -97,141 +61,19 @@ void OpenGLGeometryBufferBase::setClippingRegion(const Rectf& region) } //----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::appendGeometry(const Vertex* const vbuff, - uint vertex_count) +void OpenGLGeometryBufferBase::updateMatrix() const { - performBatchManagement(); - - // update size of current batch - d_batches.back().vertexCount += vertex_count; - - // buffer these vertices - GLVertex vd; - const Vertex* vs = vbuff; - for (uint i = 0; i < vertex_count; ++i, ++vs) + if ( !d_matrixValid || !isRenderTargetDataValid(d_owner.getActiveRenderTarget()) ) { - // copy vertex info the buffer, converting from CEGUI::Vertex to - // something directly usable by OpenGL as needed. - vd.tex[0] = vs->tex_coords.d_x; - vd.tex[1] = vs->tex_coords.d_y; - vd.colour[0] = vs->colour_val.getRed(); - vd.colour[1] = vs->colour_val.getGreen(); - vd.colour[2] = vs->colour_val.getBlue(); - vd.colour[3] = vs->colour_val.getAlpha(); - vd.position[0] = vs->position.d_x; - vd.position[1] = vs->position.d_y; - vd.position[2] = vs->position.d_z; - d_vertices.push_back(vd); - } -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::setActiveTexture(Texture* texture) -{ - d_activeTexture = static_cast(texture); -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::reset() -{ - d_batches.clear(); - d_vertices.clear(); - d_activeTexture = 0; -} - -//----------------------------------------------------------------------------// -Texture* OpenGLGeometryBufferBase::getActiveTexture() const -{ - return d_activeTexture; -} + // Apply the view projection matrix to the model matrix and save the result as cached matrix + d_matrix = d_owner.getViewProjectionMatrix() * getModelMatrix(); -//----------------------------------------------------------------------------// -uint OpenGLGeometryBufferBase::getVertexCount() const -{ - return d_vertices.size(); -} - -//----------------------------------------------------------------------------// -uint OpenGLGeometryBufferBase::getBatchCount() const -{ - return d_batches.size(); -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::performBatchManagement() -{ - const GLuint gltex = d_activeTexture ? - d_activeTexture->getOpenGLTexture() : 0; - - // create a new batch if there are no batches yet, or if the active texture - // differs from that used by the current batch. - if (d_batches.empty() || - gltex != d_batches.back().texture || - d_clippingActive != d_batches.back().clip) - { - const BatchInfo batch = {gltex, 0, d_clippingActive}; - d_batches.push_back(batch); + d_matrixValid = true; } } -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::setRenderEffect(RenderEffect* effect) -{ - d_effect = effect; -} - -//----------------------------------------------------------------------------// -RenderEffect* OpenGLGeometryBufferBase::getRenderEffect() -{ - return d_effect; -} - -//----------------------------------------------------------------------------// -const mat4Pimpl* OpenGLGeometryBufferBase::getMatrix() const -{ - if (!d_matrixValid) - updateMatrix(); - return d_matrix; -} //----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::updateMatrix() const -{ - glm::mat4& modelMatrix = d_matrix->d_matrix; - modelMatrix = glm::mat4(1.f); - - const glm::vec3 final_trans(d_translation.d_x + d_pivot.d_x, - d_translation.d_y + d_pivot.d_y, - d_translation.d_z + d_pivot.d_z); - - modelMatrix = glm::translate(modelMatrix, final_trans); - - glm::quat rotationQuat = glm::quat(d_rotation.d_w, d_rotation.d_x, d_rotation.d_y, d_rotation.d_z); - glm::mat4 rotation_matrix = glm::mat4_cast(rotationQuat); - - modelMatrix = modelMatrix * rotation_matrix; - - glm::vec3 transl = glm::vec3(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z); - glm::mat4 translMatrix = glm::translate(glm::mat4(1.f), transl); - modelMatrix = modelMatrix * translMatrix; - - d_matrixValid = true; -} - -//----------------------------------------------------------------------------// -void OpenGLGeometryBufferBase::setClippingActive(const bool active) -{ - d_clippingActive = active; -} - -//----------------------------------------------------------------------------// -bool OpenGLGeometryBufferBase::isClippingActive() const -{ - return d_clippingActive; -} - -//----------------------------------------------------------------------------// - -} +} \ No newline at end of file diff --git a/cegui/src/RendererModules/OpenGL/RenderTarget.inl b/cegui/src/RendererModules/OpenGL/RenderTarget.inl index d49c954e6..0778dadf8 100644 --- a/cegui/src/RendererModules/OpenGL/RenderTarget.inl +++ b/cegui/src/RendererModules/OpenGL/RenderTarget.inl @@ -25,129 +25,79 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/RendererModules/OpenGL/RenderTarget.h" -#include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" -#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" -#include +#include +#include -#include "glm/glm.hpp" -#include "glm/gtc/matrix_transform.hpp" +#include // Start of CEGUI namespace section namespace CEGUI { -//----------------------------------------------------------------------------// -template -const double OpenGLRenderTarget::d_yfov_tan = 0.267949192431123; - //----------------------------------------------------------------------------// template OpenGLRenderTarget::OpenGLRenderTarget(OpenGLRendererBase& owner) : - d_owner(owner), - d_area(0, 0, 0, 0), - d_matrix(0), - d_matrixValid(false), - d_viewDistance(0) + d_owner(owner) { - d_matrix = new mat4Pimpl(); } //----------------------------------------------------------------------------// template OpenGLRenderTarget::~OpenGLRenderTarget() { - delete d_matrix; -} - -//----------------------------------------------------------------------------// -template -void OpenGLRenderTarget::draw(const GeometryBuffer& buffer) -{ - buffer.draw(); -} - -//----------------------------------------------------------------------------// -template -void OpenGLRenderTarget::draw(const RenderQueue& queue) -{ - queue.draw(); -} - -//----------------------------------------------------------------------------// -template -void OpenGLRenderTarget::setArea(const Rectf& area) -{ - d_area = area; - d_matrixValid = false; - - RenderTargetEventArgs args(this); - T::fireEvent(RenderTarget::EventAreaChanged, args); -} - -//----------------------------------------------------------------------------// -template -const Rectf& OpenGLRenderTarget::getArea() const -{ - return d_area; } //----------------------------------------------------------------------------// template void OpenGLRenderTarget::activate() { - glViewport(static_cast(d_area.left()), - static_cast(d_area.top()), - static_cast(d_area.getWidth()), - static_cast(d_area.getHeight())); + glViewport(static_cast(RenderTarget::d_area.left()), + static_cast(RenderTarget::d_area.top()), + static_cast(RenderTarget::d_area.getWidth()), + static_cast(RenderTarget::d_area.getHeight())); - if (!d_matrixValid) + if (!RenderTarget::d_matrixValid) updateMatrix(); - d_owner.setViewProjectionMatrix(d_matrix); + d_owner.setViewProjectionMatrix(RenderTarget::d_matrix); - d_owner.setActiveRenderTarget(this); -} - -//----------------------------------------------------------------------------// -template -void OpenGLRenderTarget::deactivate() -{ + RenderTarget::activate(); } //----------------------------------------------------------------------------// template void OpenGLRenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const + const glm::vec2& p_in, glm::vec2& p_out) const { - if (!d_matrixValid) + if (!RenderTarget::d_matrixValid) updateMatrix(); const OpenGLGeometryBufferBase& gb = static_cast(buff); const GLint vp[4] = { - static_cast(d_area.left()), - static_cast(d_area.top()), - static_cast(d_area.getWidth()), - static_cast(d_area.getHeight()) + static_cast(RenderTarget::d_area.left()), + static_cast(RenderTarget::d_area.top()), + static_cast(RenderTarget::d_area.getWidth()), + static_cast(RenderTarget::d_area.getHeight()) }; - GLdouble in_x, in_y, in_z = 0.0; + GLfloat in_x, in_y, in_z; glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); - const glm::mat4& projMatrix = d_matrix->d_matrix; - const glm::mat4& modelMatrix = gb.getMatrix()->d_matrix; + const glm::mat4& projMatrix = RenderTarget::d_matrix; + const glm::mat4& modelMatrix = gb.getModelMatrix(); // unproject the ends of the ray glm::vec3 unprojected1; glm::vec3 unprojected2; in_x = vp[2] * 0.5; in_y = vp[3] * 0.5; - in_z = -d_viewDistance; + in_z = -RenderTarget::d_viewDistance; unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); - in_x = p_in.d_x; - in_y = vp[3] - p_in.d_y; + in_x = p_in.x; + in_y = vp[3] - p_in.y; in_z = 0.0; unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort); @@ -182,42 +132,26 @@ void OpenGLRenderTarget::unprojectPoint(const GeometryBuffer& buff, const double is_x = unprojected1.x - rv.x * tmp1; const double is_y = unprojected1.y - rv.y * tmp1; - p_out.d_x = static_cast(is_x); - p_out.d_y = static_cast(is_y); - - p_out = p_in; // CrazyEddie wanted this + p_out.x = static_cast(is_x); + p_out.y = static_cast(is_y); } //----------------------------------------------------------------------------// template void OpenGLRenderTarget::updateMatrix() const { - const float w = d_area.getWidth(); - const float h = d_area.getHeight(); - - // We need to check if width or height are zero and act accordingly to prevent running into issues - // with divisions by zero which would lead to undefined values, as well as faulty clipping planes - // This is mostly important for avoiding asserts - const bool widthAndHeightNotZero = ( w != 0.0f ) && ( h != 0.0f); - - const float aspect = widthAndHeightNotZero ? w / h : 1.0f; - const float midx = widthAndHeightNotZero ? w * 0.5f : 0.5f; - const float midy = widthAndHeightNotZero ? h * 0.5f : 0.5f; - d_viewDistance = midx / (aspect * d_yfov_tan); - - glm::vec3 eye = glm::vec3(midx, midy, float(-d_viewDistance)); - glm::vec3 center = glm::vec3(midx, midy, 1); - glm::vec3 up = glm::vec3(0, -1, 0); - - glm::mat4 projectionMatrix = glm::perspective(30.f, aspect, float(d_viewDistance * 0.5), float(d_viewDistance * 2.0)); - // Projection matrix abuse! - glm::mat4 viewMatrix = glm::lookAt(eye, center, up); - - d_matrix->d_matrix = projectionMatrix * viewMatrix; - - d_matrixValid = true; + RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() ); } + +//----------------------------------------------------------------------------// +template +OpenGLRendererBase& OpenGLRenderTarget::getOwner() +{ + return d_owner; +} + + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/RendererModules/OpenGL/RendererBase.cpp b/cegui/src/RendererModules/OpenGL/RendererBase.cpp index fe51abc0f..940b994fa 100644 --- a/cegui/src/RendererModules/OpenGL/RendererBase.cpp +++ b/cegui/src/RendererModules/OpenGL/RendererBase.cpp @@ -25,14 +25,11 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - #include "CEGUI/RendererModules/OpenGL/RendererBase.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/RendererModules/OpenGL/TextureTarget.h" #include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" -#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" @@ -51,14 +48,12 @@ String OpenGLRendererBase::d_rendererID("--- subclass did not set ID: Fix this!" OpenGLRendererBase::OpenGLRendererBase() : d_displayDPI(96, 96), d_initExtraStates(false), - d_activeBlendMode(BM_INVALID), - d_viewProjectionMatrix(new mat4Pimpl()), - d_activeRenderTarget(0) + d_activeBlendMode(BM_INVALID) { initialiseMaxTextureSize(); initialiseDisplaySizeWithViewportSize(); - d_defaultTarget = CEGUI_NEW_AO OpenGLViewportTarget(*this); + d_defaultTarget = new OpenGLViewportTarget(*this); } //----------------------------------------------------------------------------// @@ -66,13 +61,11 @@ OpenGLRendererBase::OpenGLRendererBase(const Sizef& display_size) : d_displaySize(display_size), d_displayDPI(96, 96), d_initExtraStates(false), - d_activeBlendMode(BM_INVALID), - d_viewProjectionMatrix(new mat4Pimpl()), - d_activeRenderTarget(0) + d_activeBlendMode(BM_INVALID) { initialiseMaxTextureSize(); - d_defaultTarget = CEGUI_NEW_AO OpenGLViewportTarget(*this); + d_defaultTarget = new OpenGLViewportTarget(*this); } //----------------------------------------------------------------------------// @@ -82,8 +75,7 @@ OpenGLRendererBase::~OpenGLRendererBase() destroyAllTextureTargets(); destroyAllTextures(); - CEGUI_DELETE_AO d_defaultTarget; - delete d_viewProjectionMatrix; + delete d_defaultTarget; } //----------------------------------------------------------------------------// @@ -110,34 +102,33 @@ RenderTarget& OpenGLRendererBase::getDefaultRenderTarget() } //----------------------------------------------------------------------------// -GeometryBuffer& OpenGLRendererBase::createGeometryBuffer() +GeometryBuffer& OpenGLRendererBase::createGeometryBufferTextured(CEGUI::RefCounted renderMaterial) { - OpenGLGeometryBufferBase* b = createGeometryBuffer_impl(); - d_geometryBuffers.push_back(b); - return *b; -} + OpenGLGeometryBufferBase* geom_buffer = createGeometryBuffer_impl(renderMaterial); -//----------------------------------------------------------------------------// -void OpenGLRendererBase::destroyGeometryBuffer(const GeometryBuffer& buffer) -{ - GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), - d_geometryBuffers.end(), - &buffer); + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->addVertexAttribute(VAT_TEXCOORD0); + geom_buffer->finaliseVertexAttributes(); - if (d_geometryBuffers.end() != i) - { - d_geometryBuffers.erase(i); - CEGUI_DELETE_AO &buffer; - } + addGeometryBuffer(*geom_buffer); + return *geom_buffer; } //----------------------------------------------------------------------------// -void OpenGLRendererBase::destroyAllGeometryBuffers() +GeometryBuffer& OpenGLRendererBase::createGeometryBufferColoured(CEGUI::RefCounted renderMaterial) { - while (!d_geometryBuffers.empty()) - destroyGeometryBuffer(**d_geometryBuffers.begin()); + OpenGLGeometryBufferBase* geom_buffer = createGeometryBuffer_impl(renderMaterial); + + geom_buffer->addVertexAttribute(VAT_POSITION0); + geom_buffer->addVertexAttribute(VAT_COLOUR0); + geom_buffer->finaliseVertexAttributes(); + + addGeometryBuffer(*geom_buffer); + return *geom_buffer; } + //----------------------------------------------------------------------------// TextureTarget* OpenGLRendererBase::createTextureTarget() { @@ -159,7 +150,7 @@ void OpenGLRendererBase::destroyTextureTarget(TextureTarget* target) if (d_textureTargets.end() != i) { d_textureTargets.erase(i); - CEGUI_DELETE_AO target; + delete target; } } @@ -177,7 +168,8 @@ Texture& OpenGLRendererBase::createTexture(const String& name) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); - OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name); + OpenGLTexture* tex = createTexture_impl(name); + tex->initialise(); d_textures[name] = tex; logTextureCreation(name); @@ -194,7 +186,8 @@ Texture& OpenGLRendererBase::createTexture(const String& name, CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); - OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name, filename, resourceGroup); + OpenGLTexture* tex = createTexture_impl(name); + tex->initialise(filename, resourceGroup); d_textures[name] = tex; logTextureCreation(name); @@ -209,7 +202,8 @@ Texture& OpenGLRendererBase::createTexture(const String& name, const Sizef& size CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); - OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name, size); + OpenGLTexture* tex = createTexture_impl(name); + tex->initialise(size); d_textures[name] = tex; logTextureCreation(name); @@ -239,7 +233,7 @@ void OpenGLRendererBase::destroyTexture(const String& name) if (d_textures.end() != i) { logTextureDestruction(name); - CEGUI_DELETE_AO i->second; + delete i->second; d_textures.erase(i); } } @@ -284,7 +278,7 @@ const Sizef& OpenGLRendererBase::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& OpenGLRendererBase::getDisplayDPI() const +const glm::vec2& OpenGLRendererBase::getDisplayDPI() const { return d_displayDPI; } @@ -309,7 +303,8 @@ Texture& OpenGLRendererBase::createTexture(const String& name, GLuint tex, CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); - OpenGLTexture* t = CEGUI_NEW_AO OpenGLTexture(*this, name, tex, sz); + OpenGLTexture* t = createTexture_impl(name); + t->initialise(tex, sz); d_textures[name] = t; logTextureCreation(name); @@ -365,21 +360,6 @@ void OpenGLRendererBase::restoreTextures() static_cast(*target_iterator)->restoreTexture(); } -//----------------------------------------------------------------------------// -Sizef OpenGLRendererBase::getAdjustedTextureSize(const Sizef& sz) const -{ - Sizef out(sz); - - // if we can't support non power of two sizes, get appropriate POT values. - if (!GLEW_ARB_texture_non_power_of_two) - { - out.d_width = getNextPOTSize(out.d_width); - out.d_height = getNextPOTSize(out.d_height); - } - - return out; -} - //----------------------------------------------------------------------------// float OpenGLRendererBase::getNextPOTSize(const float f) { @@ -401,36 +381,12 @@ float OpenGLRendererBase::getNextPOTSize(const float f) return static_cast(size); } -//----------------------------------------------------------------------------// -const mat4Pimpl* OpenGLRendererBase::getViewProjectionMatrix() -{ - return d_viewProjectionMatrix; -} - -//----------------------------------------------------------------------------// -void OpenGLRendererBase::setViewProjectionMatrix(const mat4Pimpl* viewProjectionMatrix) -{ - *d_viewProjectionMatrix = *viewProjectionMatrix; -} - //----------------------------------------------------------------------------// const CEGUI::Rectf& OpenGLRendererBase::getActiveViewPort() { return d_activeRenderTarget->getArea(); } -//----------------------------------------------------------------------------// -void OpenGLRendererBase::setActiveRenderTarget(RenderTarget* renderTarget) -{ - d_activeRenderTarget = renderTarget; -} - -//----------------------------------------------------------------------------// -RenderTarget* OpenGLRendererBase::getActiveRenderTarget() -{ - return d_activeRenderTarget; -} - //----------------------------------------------------------------------------// } diff --git a/cegui/src/RendererModules/OpenGL/Shader.cpp b/cegui/src/RendererModules/OpenGL/Shader.cpp index 39db1d2dc..fa98d3f12 100644 --- a/cegui/src/RendererModules/OpenGL/Shader.cpp +++ b/cegui/src/RendererModules/OpenGL/Shader.cpp @@ -24,9 +24,8 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - #include "CEGUI/RendererModules/OpenGL/Shader.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" #include "CEGUI/Logger.h" #include "CEGUI/Exceptions.h" @@ -40,9 +39,11 @@ namespace CEGUI static const size_t LOG_BUFFER_SIZE = 8096; //----------------------------------------------------------------------------// -OpenGL3Shader::OpenGL3Shader(const std::string& vertex_shader_source, - const std::string& fragment_shader_source) : - d_createdSucessfully(false), +OpenGLBaseShader::OpenGLBaseShader(const std::string& vertex_shader_source, + const std::string& fragment_shader_source, + OpenGLBaseStateChangeWrapper* glStateChanger) : + d_glStateChanger(glStateChanger), + d_createdSuccessfully(false), d_vertexShader(0), d_fragmentShader(0), d_geometryShader(0), @@ -70,7 +71,7 @@ OpenGL3Shader::OpenGL3Shader(const std::string& vertex_shader_source, } //----------------------------------------------------------------------------// -OpenGL3Shader::~OpenGL3Shader() +OpenGLBaseShader::~OpenGLBaseShader() { if(d_program != 0) glDeleteProgram(d_program); @@ -83,47 +84,40 @@ OpenGL3Shader::~OpenGL3Shader() } //----------------------------------------------------------------------------// -void OpenGL3Shader::bind() const -{ - glUseProgram(d_program); -} - -//----------------------------------------------------------------------------// -void OpenGL3Shader::unbind() const +void OpenGLBaseShader::bind() const { - glUseProgram(0); + d_glStateChanger->useProgram(d_program); } //----------------------------------------------------------------------------// -GLuint OpenGL3Shader::getAttribLocation(const std::string &name) const +GLint OpenGLBaseShader::getAttribLocation(const std::string &name) const { return glGetAttribLocation(d_program, name.c_str()); } //----------------------------------------------------------------------------// -GLuint OpenGL3Shader::getUniformLocation(const std::string &name) const +GLint OpenGLBaseShader::getUniformLocation(const std::string &name) const { return glGetUniformLocation(d_program, name.c_str()); } //----------------------------------------------------------------------------// -void OpenGL3Shader::bindFragDataLocation(const std::string &name) +void OpenGLBaseShader::bindFragDataLocation(const std::string &name) { if(d_program > 0) { - glBindFragDataLocation(d_program, 0, name.c_str() ); link(); } } //----------------------------------------------------------------------------// -bool OpenGL3Shader::isCreatedSuccessfully() +bool OpenGLBaseShader::isCreatedSuccessfully() { - return d_createdSucessfully; + return d_createdSuccessfully; } //----------------------------------------------------------------------------// -GLuint OpenGL3Shader::compile(GLuint type, const std::string &source) +GLuint OpenGLBaseShader::compile(GLuint type, const std::string &source) { // Create shader object checkGLErrors(); @@ -164,7 +158,7 @@ GLuint OpenGL3Shader::compile(GLuint type, const std::string &source) } //----------------------------------------------------------------------------// -void OpenGL3Shader::link() +void OpenGLBaseShader::link() { // Attach shaders and link @@ -196,23 +190,12 @@ void OpenGL3Shader::link() if (d_program == 0) return; - d_createdSucessfully = true; - checkGLErrors(); - - - glBindFragDataLocation(d_program, 0, "out0"); // GL_COLOR_ATTACHMENT0 - glBindFragDataLocation(d_program, 1, "out1"); // GL_COLOR_ATTACHMENT1 - glBindFragDataLocation(d_program, 2, "out2"); // ... - glBindFragDataLocation(d_program, 3, "out3"); - glBindFragDataLocation(d_program, 4, "out4"); - glBindFragDataLocation(d_program, 5, "out5"); - glBindFragDataLocation(d_program, 6, "out6"); - glBindFragDataLocation(d_program, 7, "out7"); + d_createdSuccessfully = true; checkGLErrors(); } //----------------------------------------------------------------------------// -void OpenGL3Shader::outputProgramLog(GLuint program) +void OpenGLBaseShader::outputProgramLog(GLuint program) { char logBuffer[LOG_BUFFER_SIZE]; GLsizei length; @@ -223,13 +206,13 @@ void OpenGL3Shader::outputProgramLog(GLuint program) if (length > 0) { std::stringstream sstream; - sstream << "OpenGL3Shader linking has failed.\n" << logBuffer; + sstream << "OpenGLBaseShader linking has failed.\n" << logBuffer; CEGUI_THROW(RendererException(sstream.str().c_str())); } }; //----------------------------------------------------------------------------// -void OpenGL3Shader::outputShaderLog(GLuint shader) +void OpenGLBaseShader::outputShaderLog(GLuint shader) { char logBuffer[LOG_BUFFER_SIZE]; GLsizei length; @@ -240,7 +223,7 @@ void OpenGL3Shader::outputShaderLog(GLuint shader) if (length > 0) { std::stringstream ss; - ss << "OpenGL3Shader compilation has failed.\n" << logBuffer; + ss << "OpenGLBaseShader compilation has failed.\n" << logBuffer; CEGUI_THROW(RendererException(ss.str().c_str())); } }; @@ -253,7 +236,7 @@ void getGLErrors(const char *location) if (error != GL_NO_ERROR) { std::stringstream stringStream; - stringStream << "OpenGL3Renderer: Notification - OpenGL error at " << location << ": " << std::endl; + stringStream << "OpenGLBaseRenderer: Notification - OpenGL error at " << location << ": " << std::endl; switch (error) { diff --git a/cegui/src/RendererModules/OpenGL/ShaderManager.cpp b/cegui/src/RendererModules/OpenGL/ShaderManager.cpp index 2b3e0e1fa..ce2aa6ec1 100644 --- a/cegui/src/RendererModules/OpenGL/ShaderManager.cpp +++ b/cegui/src/RendererModules/OpenGL/ShaderManager.cpp @@ -29,8 +29,7 @@ #include "CEGUI/RendererModules/OpenGL/Shader.h" -#include "CEGUI/RendererModules/OpenGL/StandardShaderVert.h" -#include "CEGUI/RendererModules/OpenGL/StandardShaderFrag.h" +#include "Shaders.inl" #include "CEGUI/Logger.h" #include "CEGUI/Exceptions.h" @@ -39,64 +38,83 @@ namespace CEGUI { - OpenGL3ShaderManager::OpenGL3ShaderManager() - { - d_shadersInitialised = false; - } - OpenGL3ShaderManager::~OpenGL3ShaderManager() - { - deinitialiseShaders(); - d_shadersInitialised = false; - } +OpenGLBaseShaderManager::OpenGLBaseShaderManager(OpenGLBaseStateChangeWrapper* glStateChanger, + ShaderVersion shaderVersion) + : d_glStateChanger(glStateChanger), d_shaderVersion(shaderVersion) +{ + d_shadersInitialised = false; +} + +OpenGLBaseShaderManager::~OpenGLBaseShaderManager() +{ + deinitialiseShaders(); + d_shadersInitialised = false; +} - OpenGL3Shader* OpenGL3ShaderManager::getShader(GLuint id) +OpenGLBaseShader* OpenGLBaseShaderManager::getShader(GLuint id) +{ + if(d_shaders.find(id) != d_shaders.end()) + return d_shaders[id]; + else + return 0; +} + +void OpenGLBaseShaderManager::loadShader(GLuint id, std::string vertexShader, std::string fragmentShader) +{ + if(d_shaders.find(id) == d_shaders.end()) { - if(d_shaders.find(id) != d_shaders.end()) - return d_shaders[id]; - else - return 0; + d_shaders[id] = new OpenGLBaseShader(vertexShader, fragmentShader, d_glStateChanger); + d_shaders[id]->link(); } +} - void OpenGL3ShaderManager::loadShader(GLuint id, std::string vertexShader, std::string fragmentShader) +void OpenGLBaseShaderManager::initialiseShaders() +{ + if(!d_shadersInitialised) { - if(d_shaders.find(id) == d_shaders.end()) + + if (d_shaderVersion == SHADER_GLSL) { - d_shaders[id] = CEGUI_NEW_AO OpenGL3Shader(vertexShader, fragmentShader); - d_shaders[id]->link(); + loadShader(SHADER_ID_STANDARD_TEXTURED, StandardShaderTexturedVert, StandardShaderTexturedFrag); + loadShader(SHADER_ID_STANDARD_SOLID, StandardShaderSolidVert, StandardShaderSolidFrag); } - } - - void OpenGL3ShaderManager::initialiseShaders() - { - if(!d_shadersInitialised) + else if (d_shaderVersion == SHADER_GLSLES1) { - loadShader(SHADER_ID_STANDARDSHADER, StandardShaderVert, StandardShaderFrag); - - - if(!getShader(SHADER_ID_STANDARDSHADER)->isCreatedSuccessfully()) - { - const CEGUI::String errorString("Critical Error - One or multiple shader programs weren't created successfully"); - CEGUI_THROW(RendererException(errorString)); - - return; - } - - const CEGUI::String notify("OpenGL3Renderer: Notification - Successfully initialised OpenGL3Renderer shader programs."); - if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr()) - logger->logEvent(notify); + loadShader(SHADER_ID_STANDARD_TEXTURED, StandardShaderTexturedVertGLSLES1, + StandardShaderTexturedFragGLSLES1); + loadShader(SHADER_ID_STANDARD_SOLID, StandardShaderSolidVertGLSLES1, StandardShaderSolidFragGLSLES1); + } + else if (d_shaderVersion == SHADER_GLSLES3) + { + loadShader(SHADER_ID_STANDARD_TEXTURED, StandardShaderTexturedVertGLSLES3, + StandardShaderTexturedFragGLSLES3); + loadShader(SHADER_ID_STANDARD_SOLID, StandardShaderSolidVertGLSLES3, StandardShaderSolidFragGLSLES3); + } + if(!getShader(SHADER_ID_STANDARD_TEXTURED)->isCreatedSuccessfully() || + !getShader(SHADER_ID_STANDARD_SOLID)->isCreatedSuccessfully() ) + { + const CEGUI::String errorString("Critical Error - One or multiple shader programs weren't created successfully"); + CEGUI_THROW(RendererException(errorString)); return; } + + const CEGUI::String notify("OpenGLBaseRenderer: Notification - Successfully initialised OpenGLBaseRenderer shader programs."); + if (CEGUI::Logger* logger = CEGUI::Logger::getSingletonPtr()) + logger->logEvent(notify); + + return; } +} - void OpenGL3ShaderManager::deinitialiseShaders() +void OpenGLBaseShaderManager::deinitialiseShaders() +{ + for(shaderContainerType::iterator iter = d_shaders.begin(); iter != d_shaders.end(); ++iter) { - for(shaderContainerType::iterator iter = d_shaders.begin(); iter != d_shaders.end(); ++iter) - { - CEGUI_DELETE_AO iter->second; - } - d_shaders.clear(); + delete iter->second; } + d_shaders.clear(); +} } diff --git a/cegui/src/RendererModules/OpenGL/Shaders.inl b/cegui/src/RendererModules/OpenGL/Shaders.inl new file mode 100644 index 000000000..f1afaac3a --- /dev/null +++ b/cegui/src/RendererModules/OpenGL/Shaders.inl @@ -0,0 +1,278 @@ +/*********************************************************************** + created: Thu, 26th June 2014 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +namespace CEGUI +{ + +//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon +const char StandardShaderSolidVert[] = +"#version 150 core\n" + +"uniform mat4 modelViewProjMatrix;\n" + +"in vec3 inPosition;\n" +"in vec4 inColour;\n" + +"out vec4 exColour;\n" + +"void main(void)\n" +"{\n" + "exColour = inColour;\n" + + "gl_Position = modelViewProjMatrix * vec4(inPosition, 1.0);\n" +"}" +; + +//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon +const char StandardShaderSolidFrag[] = +"#version 150 core\n" + +"in vec4 exColour;\n" + +"out vec4 out0;\n" + +"uniform float alphaPercentage;\n" + +"void main(void)\n" +"{\n" + "out0 = exColour;\n" + "out0.a *= alphaPercentage;\n" +"}" +; + +/*! +A string containing an OpenGL3 vertex shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +const char StandardShaderTexturedVert[] = +"#version 150 core\n" + +"uniform mat4 modelViewProjMatrix;\n" + +"in vec3 inPosition;\n" +"in vec2 inTexCoord;\n" +"in vec4 inColour;\n" + +"out vec2 exTexCoord;\n" +"out vec4 exColour;\n" + +"void main(void)\n" +"{\n" + "exTexCoord = inTexCoord;\n" + "exColour = inColour;\n" + + "gl_Position = modelViewProjMatrix * vec4(inPosition, 1.0);\n" +"}" +; + +/*! +A string containing an OpenGL3 fragment shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +const char StandardShaderTexturedFrag[] = +"#version 150 core\n" + +"uniform sampler2D texture0;\n" + +"in vec2 exTexCoord;\n" +"in vec4 exColour;\n" + +"out vec4 out0;\n" + +"uniform float alphaPercentage;\n" + +"void main(void)\n" +"{\n" + "out0 = texture(texture0, exTexCoord) * exColour;\n" + "out0.a *= alphaPercentage;\n" +"}" +; + +//! A string containing an GLSLES 3.0 vertex shader for solid colouring of a polygon +const char StandardShaderSolidVertGLSLES3[] = +"#version 300 es\n" + +"uniform mat4 modelViewProjMatrix;\n" + +"in vec3 inPosition;\n" +"in vec4 inColour;\n" + +"out vec4 exColour;\n" + +"void main(void)\n" +"{\n" + "exColour = inColour;\n" + + "gl_Position = modelViewProjMatrix * vec4(inPosition, 1.0);\n" +"}" +; + +//! A string containing an GLSLES 3.0 fragment shader for solid colouring of a polygon +const char StandardShaderSolidFragGLSLES3[] = +"#version 300 es\n" + +"in vec4 exColour;\n" + +"out vec4 out0;\n" + +"uniform float alphaPercentage;\n" + +"void main(void)\n" +"{\n" + "out0 = exColour;\n" + "out0.a *= alphaPercentage;\n" +"}" +; + +/*! +A string containing an GLSLES 3.0 vertex shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +const char StandardShaderTexturedVertGLSLES3[] = +"#version 300 es\n" + +"uniform mat4 modelViewProjMatrix;\n" + +"in vec3 inPosition;\n" +"in vec2 inTexCoord;\n" +"in vec4 inColour;\n" + +"out vec2 exTexCoord;\n" +"out vec4 exColour;\n" + +"void main(void)\n" +"{\n" + "exTexCoord = inTexCoord;\n" + "exColour = inColour;\n" + + "gl_Position = modelViewProjMatrix * vec4(inPosition, 1.0);\n" +"}" +; + +/*! +A string containing an GLSLES 3.0 fragment shader for polygons that should be coloured +based on a texture. The fetched texture colour will be multiplied by a colour +supplied to the shader, resulting in the final colour. +*/ +const char StandardShaderTexturedFragGLSLES3[] = +"#version 300 es\n" + +"uniform sampler2D texture0;\n" + +"in vec2 exTexCoord;\n" +"in vec4 exColour;\n" + +"out vec4 out0;\n" + +"uniform float alphaPercentage;\n" + +"void main(void)\n" +"{\n" + "out0 = texture(texture0, exTexCoord) * exColour;\n" + "out0.a *= alphaPercentage;\n" +"}" +; + +/*! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid + */ +const char StandardShaderSolidVertGLSLES1[] = +"#version 100\n" +"precision mediump int;\n" +"precision mediump float;\n" +"uniform mat4 modelViewProjMatrix;\n" +"attribute vec3 inPosition;\n" +"attribute vec4 inColour;\n" +"varying vec4 exColour;\n" +"void main(void)\n" +"{\n" +" exColour = inColour;\n" +" gl_Position = modelViewProjMatrix * vec4(inPosition, 1.0);\n" +"}" +; + +/*! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid + */ +const char StandardShaderSolidFragGLSLES1[] = +"#version 100\n" +"precision mediump int;\n" +"precision mediump float;\n" +"varying vec4 exColour;\n" +"uniform float alphaPercentage;\n" +"void main(void)\n" +"{\n" +" gl_FragColor = exColour;\n" +" gl_FragColor.a *= alphaPercentage;\n" +"}" +; + +/*! +A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured +based on a texture. +*/ +const char StandardShaderTexturedVertGLSLES1[] = +"#version 100\n" +"precision mediump int;\n" +"precision mediump float;\n" +"uniform mat4 modelViewProjMatrix;\n" +"attribute vec3 inPosition;\n" +"attribute vec2 inTexCoord;\n" +"attribute vec4 inColour;\n" +"varying vec2 exTexCoord;\n" +"varying vec4 exColour;\n" +"void main()\n" +"{\n" +" exTexCoord = inTexCoord;\n" +" exColour = inColour;" +" gl_Position = modelViewProjMatrix * vec4(inPosition, 1.0);\n" +"}" +; + +/*! +A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured +based on a texture. +*/ +const char StandardShaderTexturedFragGLSLES1[] = +"#version 100\n" +"precision mediump int;\n" +"precision mediump float;\n" +"precision lowp sampler2D;\n" +"uniform sampler2D texture0;\n" +"varying vec2 exTexCoord;\n" +"varying vec4 exColour;\n" +"uniform float alphaPercentage;\n" +"void main(void)\n" +"{\n" +" gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n" +" gl_FragColor.a *= alphaPercentage;\n" +"}" +; + +} + diff --git a/cegui/src/RendererModules/OpenGL/StateChangeWrapper.cpp b/cegui/src/RendererModules/OpenGL/StateChangeWrapper.cpp index e2048292a..6c7f34c07 100644 --- a/cegui/src/RendererModules/OpenGL/StateChangeWrapper.cpp +++ b/cegui/src/RendererModules/OpenGL/StateChangeWrapper.cpp @@ -25,175 +25,281 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include - -#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" +#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h" namespace CEGUI { - OpenGL3StateChangeWrapper::BlendFuncParams::BlendFuncParams() - { - reset(); - } +OpenGLBaseStateChangeWrapper::BlendFuncSeperateParams::BlendFuncSeperateParams() +{ + reset(); +} - void OpenGL3StateChangeWrapper::BlendFuncParams::reset() - { - d_dFactor = -1; - d_sFactor = -1; - } +void OpenGLBaseStateChangeWrapper::BlendFuncSeperateParams::reset() +{ + d_sfactorRGB = -1; + d_dfactorRGB = -1; + d_sfactorAlpha = -1; + d_dfactorAlpha = -1; +} - bool OpenGL3StateChangeWrapper::BlendFuncParams::equal(GLenum sFactor, GLenum dFactor) - { - bool equal = (d_sFactor == sFactor) && (d_dFactor == dFactor); - if(!equal) - { - d_sFactor = sFactor; - d_dFactor = dFactor; - } - return equal; - } +bool OpenGLBaseStateChangeWrapper::BlendFuncSeperateParams::equal(GLenum sFactor, GLenum dFactor) +{ + return equal(sFactor, dFactor, sFactor, dFactor); +} - OpenGL3StateChangeWrapper::BlendFuncSeperateParams::BlendFuncSeperateParams() +bool OpenGLBaseStateChangeWrapper::BlendFuncSeperateParams::equal(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) +{ + bool equal = (d_sfactorRGB == sfactorRGB) && (d_dfactorRGB == dfactorRGB) && (d_sfactorAlpha == sfactorAlpha) && (d_dfactorAlpha == dfactorAlpha); + if (!equal) { - reset(); + d_sfactorRGB = sfactorRGB; + d_dfactorRGB = dfactorRGB; + d_sfactorAlpha = sfactorAlpha; + d_dfactorAlpha = dfactorAlpha; } + return equal; +} - void OpenGL3StateChangeWrapper::BlendFuncSeperateParams::reset() - { - d_sfactorRGB = -1; - d_dfactorRGB = -1; - d_sfactorAlpha = -1; - d_dfactorAlpha = -1; - } +OpenGLBaseStateChangeWrapper::PortParams::PortParams() +{ + reset(); +} +void OpenGLBaseStateChangeWrapper::PortParams::reset() +{ + d_x = -1; + d_y = -1; + d_width = -1; + d_height = -1; +} - bool OpenGL3StateChangeWrapper::BlendFuncSeperateParams::equal(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) +bool OpenGLBaseStateChangeWrapper::PortParams::equal(GLint x, GLint y, GLsizei width, GLsizei height) +{ + bool equal = (d_x == x) && (d_y == y) && (d_width == width) && (d_height == height); + if (!equal) { - bool equal = (d_sfactorRGB == sfactorRGB) && (d_dfactorRGB == dfactorRGB) && (d_sfactorAlpha == sfactorAlpha) && (d_dfactorAlpha == dfactorAlpha); - if(!equal) - { - d_sfactorRGB = sfactorRGB; - d_dfactorRGB = dfactorRGB; - d_sfactorAlpha = sfactorAlpha; - d_dfactorAlpha = dfactorAlpha; - } - return equal; + d_x = x; + d_y = y; + d_width = width; + d_height = height; } + return equal; +} - OpenGL3StateChangeWrapper::PortParams::PortParams() - { - reset(); - } - void OpenGL3StateChangeWrapper::PortParams::reset() - { - d_x = -1; - d_y = -1; - d_width = -1; - d_height = -1; - } +OpenGLBaseStateChangeWrapper::BindBufferParams::BindBufferParams() +{ + reset(); +} +void OpenGLBaseStateChangeWrapper::BindBufferParams::reset() +{ + d_target = -1; + d_buffer = -1; +} - bool OpenGL3StateChangeWrapper::PortParams::equal(GLint x, GLint y, GLsizei width, GLsizei height) +bool OpenGLBaseStateChangeWrapper::BindBufferParams::equal(GLenum target, GLuint buffer) +{ + bool equal = (d_target == target) && (d_buffer == buffer); + if (!equal) { - bool equal = (d_x == x) && (d_y == y) && (d_width == width) && (d_height == height); - if(!equal) - { - d_x = x; - d_y = y; - d_width = width; - d_height = height; - } - return equal; + d_target = target; + d_buffer = buffer; } + return equal; +} - OpenGL3StateChangeWrapper::BindBufferParams::BindBufferParams() - { - reset(); - } - void OpenGL3StateChangeWrapper::BindBufferParams::reset() - { - d_target = -1; - d_buffer = -1; - } +OpenGLBaseStateChangeWrapper::BoundTexture::BoundTexture() +{ + d_target = -1; + d_texture = -1; +} - bool OpenGL3StateChangeWrapper::BindBufferParams::equal(GLenum target, GLuint buffer) - { - bool equal = (d_target == target) && (d_buffer == buffer); - if(!equal) - { - d_target = target; - d_buffer = buffer; - } - return equal; - } +void OpenGLBaseStateChangeWrapper::BoundTexture::bindTexture(GLenum target, GLuint texture) +{ + d_target = target; + d_texture = texture; +} //! constructor. -OpenGL3StateChangeWrapper::OpenGL3StateChangeWrapper(OpenGL3Renderer& owner) +OpenGLBaseStateChangeWrapper::OpenGLBaseStateChangeWrapper() { reset(); } //! destructor -OpenGL3StateChangeWrapper::~OpenGL3StateChangeWrapper() +OpenGLBaseStateChangeWrapper::~OpenGLBaseStateChangeWrapper() { } -void OpenGL3StateChangeWrapper::reset() +void OpenGLBaseStateChangeWrapper::reset() { d_vertexArrayObject = -1; - d_blendFuncParams.reset(); + d_shaderProgram = -1; d_blendFuncSeperateParams.reset(); d_viewPortParams.reset(); d_scissorParams.reset(); d_bindBufferParams.reset(); + d_activeTexturePosition = -1; + d_boundTextures.clear(); + d_enabledOpenGLStates.clear(); } -void OpenGL3StateChangeWrapper::bindVertexArray(GLuint vertexArray) +GLuint OpenGLBaseStateChangeWrapper::getBoundVertexArray() const { - if(vertexArray != d_vertexArrayObject) + return d_vertexArrayObject; +} + +void OpenGLBaseStateChangeWrapper::useProgram(GLuint program) +{ + if (program != d_shaderProgram) { - glBindVertexArray(vertexArray); - d_vertexArrayObject = vertexArray; + glUseProgram(program); + d_shaderProgram = program; } +} +GLuint OpenGLBaseStateChangeWrapper::getUsedProgram() const +{ + return d_shaderProgram; } -void OpenGL3StateChangeWrapper::blendFunc(GLenum sfactor, GLenum dfactor) + +void OpenGLBaseStateChangeWrapper::blendFunc(GLenum sfactor, GLenum dfactor) { - bool callIsRedundant = d_blendFuncParams.equal(sfactor, dfactor); - if(!callIsRedundant) - { + bool callIsRedundant = d_blendFuncSeperateParams.equal(sfactor, dfactor); + if (!callIsRedundant) glBlendFunc(sfactor, dfactor); - } } -void OpenGL3StateChangeWrapper::blendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) +OpenGLBaseStateChangeWrapper::BlendFuncSeperateParams OpenGLBaseStateChangeWrapper::getBlendFuncParams() const +{ + return d_blendFuncSeperateParams; +} + +void OpenGLBaseStateChangeWrapper::blendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) { bool callIsRedundant = d_blendFuncSeperateParams.equal(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); - if(!callIsRedundant) + if (!callIsRedundant) glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); } -void OpenGL3StateChangeWrapper::viewport(GLint x, GLint y, GLsizei width, GLsizei height) +void OpenGLBaseStateChangeWrapper::viewport(GLint x, GLint y, GLsizei width, GLsizei height) { bool callIsRedundant = d_viewPortParams.equal(x, y, width, height); if(!callIsRedundant) glViewport(x, y, width, height); } -void OpenGL3StateChangeWrapper::scissor(GLint x, GLint y, GLsizei width, GLsizei height) +OpenGLBaseStateChangeWrapper::PortParams OpenGLBaseStateChangeWrapper::getViewportParams() const +{ + return d_viewPortParams; +} + +void OpenGLBaseStateChangeWrapper::scissor(GLint x, GLint y, GLsizei width, GLsizei height) { bool callIsRedundant = d_scissorParams.equal(x, y, width, height); - if(!callIsRedundant) + if (!callIsRedundant) glScissor(x, y, width, height); } -void OpenGL3StateChangeWrapper::bindBuffer(GLenum target, GLuint buffer) + +OpenGLBaseStateChangeWrapper::PortParams OpenGLBaseStateChangeWrapper::getScissorParams() const +{ + return d_scissorParams; +} + +void OpenGLBaseStateChangeWrapper::bindBuffer(GLenum target, GLuint buffer) { bool callIsRedundant = d_bindBufferParams.equal(target, buffer); - if(!callIsRedundant) + if (!callIsRedundant) glBindBuffer(target, buffer); } +OpenGLBaseStateChangeWrapper::BindBufferParams OpenGLBaseStateChangeWrapper::getBoundBuffer() const +{ + return d_bindBufferParams; +} + +void OpenGLBaseStateChangeWrapper::activeTexture(unsigned int texture_position) +{ + if (d_activeTexturePosition != texture_position) + { + while (texture_position >= d_boundTextures.size()) + d_boundTextures.push_back(BoundTexture()); + + glActiveTexture(GL_TEXTURE0 + texture_position); + d_activeTexturePosition = texture_position; + } +} + +unsigned int OpenGLBaseStateChangeWrapper::getActiveTexture() const +{ + return GL_TEXTURE0 + d_activeTexturePosition; +} + +void OpenGLBaseStateChangeWrapper::bindTexture(GLenum target, GLuint texture) +{ + if (d_activeTexturePosition == -1) + return; + + BoundTexture& boundTexture = d_boundTextures[d_activeTexturePosition]; + if (boundTexture.d_target != target || boundTexture.d_texture != texture) + { + glBindTexture(target, texture); + boundTexture.bindTexture(target, texture); + } +} + +void OpenGLBaseStateChangeWrapper::enable(GLenum capability) +{ + std::map::iterator found_iterator = d_enabledOpenGLStates.find(capability); + if(found_iterator != d_enabledOpenGLStates.end()) + { + if(found_iterator->second != true) + { + glEnable(capability); + found_iterator->second = true; + } + } + else + { + d_enabledOpenGLStates[capability] = true; + glEnable(capability); + } +} + +void OpenGLBaseStateChangeWrapper::disable(GLenum capability) +{ + std::map::iterator found_iterator = d_enabledOpenGLStates.find(capability); + if(found_iterator != d_enabledOpenGLStates.end()) + { + if(found_iterator->second != false) + { + glDisable(capability); + found_iterator->second = false; + } + } + else + { + d_enabledOpenGLStates[capability] = false; + glDisable(capability); + } +} + +int OpenGLBaseStateChangeWrapper::isStateEnabled(GLenum capability) const +{ + std::map::const_iterator found_iterator = d_enabledOpenGLStates.find(capability); + if(found_iterator != d_enabledOpenGLStates.end()) + { + bool isEnabled = found_iterator->second; + if(isEnabled) + return 1; + else + return 0; + } + else + return -1; +} + } diff --git a/cegui/src/RendererModules/OpenGL/Texture.cpp b/cegui/src/RendererModules/OpenGL/Texture.cpp index dbe97a4e2..c337e2e38 100644 --- a/cegui/src/RendererModules/OpenGL/Texture.cpp +++ b/cegui/src/RendererModules/OpenGL/Texture.cpp @@ -24,11 +24,13 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/ImageCodec.h" + +#include "CEGUI/RendererModules/OpenGL/GL.h" + #include // Start of CEGUI namespace section @@ -43,114 +45,45 @@ OpenGLTexture::OpenGLTexture(OpenGLRendererBase& owner, const String& name) : d_owner(owner), d_name(name) { - initInternalPixelFormatFields(PF_RGBA); - generateOpenGLTexture(); } //----------------------------------------------------------------------------// -OpenGLTexture::OpenGLTexture(OpenGLRendererBase& owner, const String& name, - const String& filename, - const String& resourceGroup) : - d_size(0, 0), - d_grabBuffer(0), - d_dataSize(0, 0), - d_owner(owner), - d_name(name) +OpenGLTexture::~OpenGLTexture() { - initInternalPixelFormatFields(PF_RGBA); - generateOpenGLTexture(); - loadFromFile(filename, resourceGroup); + cleanupOpenGLTexture(); } //----------------------------------------------------------------------------// -OpenGLTexture::OpenGLTexture(OpenGLRendererBase& owner, const String& name, - const Sizef& size) : - d_size(0, 0), - d_grabBuffer(0), - d_dataSize(0, 0), - d_owner(owner), - d_name(name) +void OpenGLTexture::initialise() { initInternalPixelFormatFields(PF_RGBA); generateOpenGLTexture(); - setTextureSize(size); } //----------------------------------------------------------------------------// -OpenGLTexture::OpenGLTexture(OpenGLRendererBase& owner, const String& name, - GLuint tex, const Sizef& size) : - d_ogltexture(tex), - d_size(size), - d_grabBuffer(0), - d_dataSize(size), - d_owner(owner), - d_name(name) +void OpenGLTexture::initialise(const String& filename, const String& resourceGroup) { initInternalPixelFormatFields(PF_RGBA); - updateCachedScaleValues(); + generateOpenGLTexture(); + loadFromFile(filename, resourceGroup); } - + //----------------------------------------------------------------------------// -void OpenGLTexture::initInternalPixelFormatFields(const PixelFormat fmt) +void OpenGLTexture::initialise(const Sizef& size) { - d_isCompressed = false; - - switch (fmt) - { - case PF_RGBA: - d_format = GL_RGBA; - d_subpixelFormat = GL_UNSIGNED_BYTE; - break; - - case PF_RGB: - d_format = GL_RGB; - d_subpixelFormat = GL_UNSIGNED_BYTE; - break; - - case PF_RGB_565: - d_format = GL_RGB; - d_subpixelFormat = GL_UNSIGNED_SHORT_5_6_5; - break; - - case PF_RGBA_4444: - d_format = GL_RGBA; - d_subpixelFormat = GL_UNSIGNED_SHORT_4_4_4_4; - break; - - case PF_RGB_DXT1: - d_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; - d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. - d_isCompressed = true; - break; - - case PF_RGBA_DXT1: - d_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; - d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. - d_isCompressed = true; - break; - - case PF_RGBA_DXT3: - d_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; - d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. - d_isCompressed = true; - break; - - case PF_RGBA_DXT5: - d_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - d_subpixelFormat = GL_UNSIGNED_BYTE; // not used. - d_isCompressed = true; - break; - - default: - CEGUI_THROW(RendererException( - "invalid or unsupported CEGUI::PixelFormat.")); - } + initInternalPixelFormatFields(PF_RGBA); + generateOpenGLTexture(); + setTextureSize(size); } //----------------------------------------------------------------------------// -OpenGLTexture::~OpenGLTexture() +void OpenGLTexture::initialise(GLuint tex, const Sizef& size) { - cleanupOpenGLTexture(); + d_ogltexture = tex; + d_size = size; + d_dataSize = size; + initInternalPixelFormatFields(PF_RGBA); + updateCachedScaleValues(); } //----------------------------------------------------------------------------// @@ -172,7 +105,7 @@ const Sizef& OpenGLTexture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& OpenGLTexture::getTexelScaling() const +const glm::vec2& OpenGLTexture::getTexelScaling() const { return d_texelScaling; } @@ -189,17 +122,12 @@ void OpenGLTexture::loadFromFile(const String& filename, // load file to memory via resource provider RawDataContainer texFile; - System::getSingleton().getResourceProvider()-> - loadRawDataContainer(filename, texFile, resourceGroup); + CEGUI::System& system = System::getSingleton(); - // get and check existence of CEGUI::System (needed to access ImageCodec) - System* sys = System::getSingletonPtr(); - if (!sys) - CEGUI_THROW(RendererException( - "CEGUI::System object has not been created: " - "unable to access ImageCodec.")); + system.getResourceProvider()-> + loadRawDataContainer(filename, texFile, resourceGroup); - Texture* res = sys->getImageCodec().load(texFile, this); + Texture* res = system.getImageCodec().load(texFile, this); // unload file data buffer System::getSingleton().getResourceProvider()-> @@ -208,7 +136,7 @@ void OpenGLTexture::loadFromFile(const String& filename, if (!res) // It's an error CEGUI_THROW(RendererException( - sys->getImageCodec().getIdentifierString() + + system.getImageCodec().getIdentifierString() + " failed to load image '" + filename + "'.")); } @@ -227,7 +155,7 @@ void OpenGLTexture::loadFromMemory(const void* buffer, const Sizef& buffer_size, d_dataSize = buffer_size; updateCachedScaleValues(); - blitFromMemory(buffer, Rectf(Vector2f(0, 0), buffer_size)); + blitFromMemory(buffer, Rectf(glm::vec2(0, 0), buffer_size)); } //----------------------------------------------------------------------------// @@ -267,12 +195,6 @@ void OpenGLTexture::loadCompressedTextureBuffer(const Rectf& dest_area, GLsizei OpenGLTexture::getCompressedTextureSize(const Sizef& pixel_size) const { GLsizei blocksize = 16; - if (d_format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT || - d_format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) - { - blocksize = 8; - } - return ( static_cast( std::ceil(pixel_size.d_width / 4) * @@ -291,45 +213,6 @@ void OpenGLTexture::setTextureSize(const Sizef& sz) updateCachedScaleValues(); } -//----------------------------------------------------------------------------// -void OpenGLTexture::setTextureSize_impl(const Sizef& sz) -{ - const Sizef size(d_owner.getAdjustedTextureSize(sz)); - d_size = size; - - // make sure size is within boundaries - GLfloat maxSize; - glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize); - if ((size.d_width > maxSize) || (size.d_height > maxSize)) - CEGUI_THROW(RendererException("size too big")); - - // save old texture binding - GLuint old_tex; - glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); - - // set texture to required size - glBindTexture(GL_TEXTURE_2D, d_ogltexture); - - if (d_isCompressed) - { - const GLsizei image_size = getCompressedTextureSize(size); - glCompressedTexImage2D(GL_TEXTURE_2D, 0, d_format, - static_cast(size.d_width), - static_cast(size.d_height), - 0, image_size, 0); - } - else - { - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, - static_cast(size.d_width), - static_cast(size.d_height), - 0, GL_RGBA , GL_UNSIGNED_BYTE, 0); - } - - // restore previous texture binding. - glBindTexture(GL_TEXTURE_2D, old_tex); -} - //----------------------------------------------------------------------------// void OpenGLTexture::grabTexture() { @@ -353,10 +236,10 @@ void OpenGLTexture::restoreTexture() generateOpenGLTexture(); setTextureSize_impl(d_size); - blitFromMemory(d_grabBuffer, Rectf(Vector2f(0, 0), d_size)); + blitFromMemory(d_grabBuffer, Rectf(glm::vec2(0, 0), d_size)); // free the grabbuffer - delete [] d_grabBuffer; + delete[] d_grabBuffer; d_grabBuffer = 0; } @@ -379,66 +262,12 @@ void OpenGLTexture::blitFromMemory(const void* sourceData, const Rectf& area) glBindTexture(GL_TEXTURE_2D, old_tex); } -//----------------------------------------------------------------------------// -void OpenGLTexture::blitToMemory(void* targetData) -{ - // save existing config - GLuint old_tex; - glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast(&old_tex)); - - glBindTexture(GL_TEXTURE_2D, d_ogltexture); - - if (d_isCompressed) - { - glGetCompressedTexImage(GL_TEXTURE_2D, 0, targetData); - } - else - { - GLint old_pack; - glGetIntegerv(GL_PACK_ALIGNMENT, &old_pack); - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glGetTexImage(GL_TEXTURE_2D, 0, d_format, d_subpixelFormat, targetData); - - glPixelStorei(GL_PACK_ALIGNMENT, old_pack); - } - - // restore previous config. - glBindTexture(GL_TEXTURE_2D, old_tex); -} - //----------------------------------------------------------------------------// void OpenGLTexture::updateCachedScaleValues() { - // - // calculate what to use for x scale - // - const float orgW = d_dataSize.d_width; - const float texW = d_size.d_width; - - // if texture and original data width are the same, scale is based - // on the original size. - // if texture is wider (and source data was not stretched), scale - // is based on the size of the resulting texture. - if(orgW == texW && orgW == 0.0f) - d_texelScaling.d_x = 0.0f; - else - d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); - - // - // calculate what to use for y scale - // - const float orgH = d_dataSize.d_height; - const float texH = d_size.d_height; - - // if texture and original data height are the same, scale is based - // on the original size. - // if texture is taller (and source data was not stretched), scale - // is based on the size of the resulting texture. - if(orgH == texH && orgH == 0.0f) - d_texelScaling.d_x = 0.0f; - else - d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); + // Update the scale of a texel based on the absolute size + d_texelScaling.x = (d_size.d_width != 0.0f) ? (1.0f / d_size.d_width) : 0.0f; + d_texelScaling.y = (d_size.d_height != 0.0f) ? (1.0f / d_size.d_height) : 0.0f; } //----------------------------------------------------------------------------// @@ -454,17 +283,18 @@ void OpenGLTexture::generateOpenGLTexture() glBindTexture(GL_TEXTURE_2D, d_ogltexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); // GL_CLAMP_TO_EDGE - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); // GL_CLAMP_TO_EDGE + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - // FIXME: This hack was needed to fix #980 in a way that maintains binary - // compatibility in v0-8 branch. - if (d_owner.getIdentifierString().find("CEGUI::OpenGLRenderer -") == 0) - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + setTextureEnvironment(); // restore previous texture binding. glBindTexture(GL_TEXTURE_2D, old_tex); } +//----------------------------------------------------------------------------// +void OpenGLTexture::setTextureEnvironment() +{ +} //----------------------------------------------------------------------------// void OpenGLTexture::cleanupOpenGLTexture() diff --git a/cegui/src/RendererModules/OpenGL/ViewportTarget.cpp b/cegui/src/RendererModules/OpenGL/ViewportTarget.cpp index 4179e5f82..be166d0e8 100644 --- a/cegui/src/RendererModules/OpenGL/ViewportTarget.cpp +++ b/cegui/src/RendererModules/OpenGL/ViewportTarget.cpp @@ -41,8 +41,10 @@ OpenGLViewportTarget::OpenGLViewportTarget(OpenGLRendererBase& owner) : GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); - Rectf init_area(Vector2f(static_cast(vp[0]), static_cast(vp[1])), - Sizef(static_cast(vp[2]), static_cast(vp[3]))); + const Rectf init_area( + glm::vec2(static_cast(vp[0]), static_cast(vp[1])), + Sizef(static_cast(vp[2]), static_cast(vp[3])) + ); setArea(init_area); } diff --git a/cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp b/cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp index 534052473..53ef68da5 100644 --- a/cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp +++ b/cegui/src/RendererModules/OpenGLES/GeometryBuffer.cpp @@ -104,23 +104,23 @@ void OpenGLESGeometryBuffer::draw() const } //----------------------------------------------------------------------------// -void OpenGLESGeometryBuffer::setTranslation(const Vector3f& v) +void OpenGLESGeometryBuffer::setTranslation(const glm::vec3& v) { d_translation = v; d_matrixValid = false; } //----------------------------------------------------------------------------// -void OpenGLESGeometryBuffer::setRotation(const Quaternion& r) +void OpenGLESGeometryBuffer::setRotation(const glm::quat& r) { d_rotation = r; d_matrixValid = false; } //----------------------------------------------------------------------------// -void OpenGLESGeometryBuffer::setPivot(const Vector3f& p) +void OpenGLESGeometryBuffer::setPivot(const glm::vec3& p) { - d_pivot = Vector3f(p.d_x, p.d_y, p.d_z); + d_pivot = p; d_matrixValid = false; } @@ -230,12 +230,10 @@ void OpenGLESGeometryBuffer::updateMatrix() const glMatrixMode(GL_MODELVIEW); glPushMatrix(); - const Vector3f final_trans(d_translation.d_x + d_pivot.d_x, - d_translation.d_y + d_pivot.d_y, - d_translation.d_z + d_pivot.d_z); + const Vector3f final_trans = d_translation + d_pivot; glLoadIdentity(); - glTranslatef(final_trans.d_x, final_trans.d_y, final_trans.d_z); + glTranslatef(final_trans.x, final_trans.y, final_trans.z); float rotation_matrix[16]; rotation_matrix[ 0] = 1.0f - 2.0f * (d_rotation.d_y * d_rotation.d_y + d_rotation.d_z * d_rotation.d_z); @@ -260,7 +258,7 @@ void OpenGLESGeometryBuffer::updateMatrix() const glMultMatrixf(rotation_matrix); - glTranslatef(-d_pivot.d_x, -d_pivot.d_y, -d_pivot.d_z); + glTranslatef(-d_pivot.x, -d_pivot.y, -d_pivot.z); glGetFloatv(GL_MODELVIEW_MATRIX, d_matrix); glPopMatrix(); diff --git a/cegui/src/RendererModules/OpenGLES/RenderTarget.inl b/cegui/src/RendererModules/OpenGLES/RenderTarget.inl index 750cc0aab..597c79c11 100644 --- a/cegui/src/RendererModules/OpenGLES/RenderTarget.inl +++ b/cegui/src/RendererModules/OpenGLES/RenderTarget.inl @@ -128,7 +128,7 @@ gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar); //----------------------------------------------------------------------------// template void OpenGLESRenderTarget::unprojectPoint(const GeometryBuffer& buff, - const Vector2f& p_in, Vector2f& p_out) const + const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); diff --git a/cegui/src/RendererModules/OpenGLES/Renderer.cpp b/cegui/src/RendererModules/OpenGLES/Renderer.cpp index 87dc9e0bf..c40a986ce 100644 --- a/cegui/src/RendererModules/OpenGLES/Renderer.cpp +++ b/cegui/src/RendererModules/OpenGLES/Renderer.cpp @@ -477,7 +477,7 @@ const Sizef& OpenGLESRenderer::getDisplaySize() const } //----------------------------------------------------------------------------// -const Vector2f& OpenGLESRenderer::getDisplayDPI() const +const glm::vec2& OpenGLESRenderer::getDisplayDPI() const { return d_displayDPI; } diff --git a/cegui/src/RendererModules/OpenGLES/Texture.cpp b/cegui/src/RendererModules/OpenGLES/Texture.cpp index 460bfbd5a..3801fd0e7 100644 --- a/cegui/src/RendererModules/OpenGLES/Texture.cpp +++ b/cegui/src/RendererModules/OpenGLES/Texture.cpp @@ -113,7 +113,7 @@ const Sizef& OpenGLESTexture::getOriginalDataSize() const } //----------------------------------------------------------------------------// -const Vector2f& OpenGLESTexture::getTexelScaling() const +const glm::vec2& OpenGLESTexture::getTexelScaling() const { return d_texelScaling; } @@ -169,7 +169,7 @@ void OpenGLESTexture::loadFromMemory(const void* buffer, d_dataSize = buffer_size; updateCachedScaleValues(); - blitFromMemory(buffer, Rectf(Vector2f(0, 0), buffer_size)); + blitFromMemory(buffer, Rectf(glm::vec2(0, 0), buffer_size)); } //----------------------------------------------------------------------------// diff --git a/cegui/src/RendererModules/OpenGLES/ViewportTarget.cpp b/cegui/src/RendererModules/OpenGLES/ViewportTarget.cpp index ed36c39cb..4353d1961 100644 --- a/cegui/src/RendererModules/OpenGLES/ViewportTarget.cpp +++ b/cegui/src/RendererModules/OpenGLES/ViewportTarget.cpp @@ -41,8 +41,10 @@ OpenGLESViewportTarget::OpenGLESViewportTarget(OpenGLESRenderer& owner) : GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); - Rectf init_area(Vector2f(static_cast(vp[0]), static_cast(vp[1])), - Sizef(static_cast(vp[2]), static_cast(vp[3]))); + const Rectf init_area( + glm::vec2(static_cast(vp[0]), static_cast(vp[1])), + Sizef(static_cast(vp[2]), static_cast(vp[3])) + ); setArea(init_area); } diff --git a/cegui/src/RenderingSurface.cpp b/cegui/src/RenderingSurface.cpp index 1e964e5f0..b18026f21 100644 --- a/cegui/src/RenderingSurface.cpp +++ b/cegui/src/RenderingSurface.cpp @@ -62,21 +62,28 @@ RenderingSurface::~RenderingSurface() // destroy all the RenderingWindow objects attached to this surface const size_t count = d_windows.size(); for (size_t i = 0; i < count; ++i) - CEGUI_DELETE_AO d_windows[i]; + delete d_windows[i]; +} + +//----------------------------------------------------------------------------// +void RenderingSurface::addGeometryBuffers(const RenderQueueID queue, + const std::vector& geometry_buffers) +{ + d_queues[queue].addGeometryBuffers(geometry_buffers); } //----------------------------------------------------------------------------// void RenderingSurface::addGeometryBuffer(const RenderQueueID queue, - const GeometryBuffer& buffer) + const GeometryBuffer& geometry_buffer) { - d_queues[queue].addGeometryBuffer(buffer); + d_queues[queue].addGeometryBuffer(geometry_buffer); } //----------------------------------------------------------------------------// void RenderingSurface::removeGeometryBuffer(const RenderQueueID queue, - const GeometryBuffer& buffer) + const GeometryBuffer& geometry_buffer) { - d_queues[queue].removeGeometryBuffer(buffer); + d_queues[queue].removeGeometryBuffer(geometry_buffer); } //----------------------------------------------------------------------------// @@ -152,7 +159,7 @@ bool RenderingSurface::isRenderingWindow() const //----------------------------------------------------------------------------// RenderingWindow& RenderingSurface::createRenderingWindow(TextureTarget& target) { - RenderingWindow* w = CEGUI_NEW_AO RenderingWindow(target, *this); + RenderingWindow* w = new RenderingWindow(target, *this); attachWindow(*w); return *w; @@ -164,7 +171,7 @@ void RenderingSurface::destroyRenderingWindow(RenderingWindow& window) if (&window.getOwner() == this) { detatchWindow(window); - CEGUI_DELETE_AO &window; + delete &window; } } diff --git a/cegui/src/RenderingWindow.cpp b/cegui/src/RenderingWindow.cpp index ca80a3832..cf5cd81fc 100644 --- a/cegui/src/RenderingWindow.cpp +++ b/cegui/src/RenderingWindow.cpp @@ -42,19 +42,19 @@ RenderingWindow::RenderingWindow(TextureTarget& target, RenderingSurface& owner) d_renderer(*System::getSingleton().getRenderer()), d_textarget(target), d_owner(&owner), - d_geometry(&d_renderer.createGeometryBuffer()), d_geometryValid(false), d_position(0, 0), d_size(0, 0), - d_rotation(Quaternion::IDENTITY) + d_rotation(1, 0, 0, 0), // <-- IDENTITY + d_geometryBuffer(d_renderer.createGeometryBufferTextured()) { - d_geometry->setBlendMode(BM_RTT_PREMULTIPLIED); + d_geometryBuffer.setBlendMode(BM_RTT_PREMULTIPLIED); } //----------------------------------------------------------------------------// RenderingWindow::~RenderingWindow() { - d_renderer.destroyGeometryBuffer(*d_geometry); + d_renderer.destroyGeometryBuffer(d_geometryBuffer); } //----------------------------------------------------------------------------// @@ -66,29 +66,26 @@ void RenderingWindow::setClippingRegion(const Rectf& region) // that is a RenderingWindow. if (d_owner->isRenderingWindow()) { - final_region.offset( - Vector2f(-static_cast(d_owner)->d_position.d_x, - -static_cast(d_owner)->d_position.d_y)); + final_region.offset(-static_cast(d_owner)->d_position); } - d_geometry->setClippingRegion(final_region); + d_geometryBuffer.setClippingRegion(final_region); } //----------------------------------------------------------------------------// -void RenderingWindow::setPosition(const Vector2f& position) +void RenderingWindow::setPosition(const glm::vec2& position) { d_position = position; - Vector3f trans(d_position.d_x, d_position.d_y, 0.0f); + glm::vec3 trans(d_position, 0.0f); // geometry position must be offset according to our owner position, if // that is a RenderingWindow. if (d_owner->isRenderingWindow()) { - trans.d_x -= static_cast(d_owner)->d_position.d_x; - trans.d_y -= static_cast(d_owner)->d_position.d_y; + trans -= glm::vec3(static_cast(d_owner)->d_position, 0); } - d_geometry->setTranslation(trans); + d_geometryBuffer.setTranslation(trans); } //----------------------------------------------------------------------------// @@ -104,21 +101,21 @@ void RenderingWindow::setSize(const Sizef& size) } //----------------------------------------------------------------------------// -void RenderingWindow::setRotation(const Quaternion& rotation) +void RenderingWindow::setRotation(const glm::quat& rotation) { d_rotation = rotation; - d_geometry->setRotation(d_rotation); + d_geometryBuffer.setRotation(d_rotation); } //----------------------------------------------------------------------------// -void RenderingWindow::setPivot(const Vector3f& pivot) +void RenderingWindow::setPivot(const glm::vec3& pivot) { d_pivot = pivot; - d_geometry->setPivot(d_pivot); + d_geometryBuffer.setPivot(d_pivot); } //----------------------------------------------------------------------------// -const Vector2f& RenderingWindow::getPosition() const +const glm::vec2& RenderingWindow::getPosition() const { return d_position; } @@ -130,13 +127,13 @@ const Sizef& RenderingWindow::getSize() const } //----------------------------------------------------------------------------// -const Quaternion& RenderingWindow::getRotation() const +const glm::quat& RenderingWindow::getRotation() const { return d_rotation; } //----------------------------------------------------------------------------// -const Vector3f& RenderingWindow::getPivot() const +const glm::vec3& RenderingWindow::getPivot() const { return d_pivot; } @@ -157,7 +154,7 @@ TextureTarget& RenderingWindow::getTextureTarget() //----------------------------------------------------------------------------// void RenderingWindow::update(const float elapsed) { - RenderEffect* effect = d_geometry->getRenderEffect(); + RenderEffect* effect = d_geometryBuffer.getRenderEffect(); if (effect) d_geometryValid &= effect->update(elapsed, *this); @@ -166,13 +163,13 @@ void RenderingWindow::update(const float elapsed) //----------------------------------------------------------------------------// void RenderingWindow::setRenderEffect(RenderEffect* effect) { - d_geometry->setRenderEffect(effect); + d_geometryBuffer.setRenderEffect(effect); } //----------------------------------------------------------------------------// RenderEffect* RenderingWindow::getRenderEffect() { - return d_geometry->getRenderEffect(); + return d_geometryBuffer.getRenderEffect(); } //----------------------------------------------------------------------------// @@ -210,7 +207,7 @@ void RenderingWindow::draw() } // add our geometry to our owner for rendering - d_owner->addGeometryBuffer(RQ_BASE, *d_geometry); + d_owner->addGeometryBuffer(RQ_BASE, d_geometryBuffer); } //----------------------------------------------------------------------------// @@ -240,11 +237,11 @@ void RenderingWindow::realiseGeometry() if (d_geometryValid) return; - d_geometry->reset(); + d_geometryBuffer.reset(); - RenderEffect* effect = d_geometry->getRenderEffect(); + RenderEffect* effect = d_geometryBuffer.getRenderEffect(); - if (!effect || effect->realiseGeometry(*this, *d_geometry)) + if (!effect || effect->realiseGeometry(*this, d_geometryBuffer)) realiseGeometry_impl(); d_geometryValid = true; @@ -253,71 +250,70 @@ void RenderingWindow::realiseGeometry() //----------------------------------------------------------------------------// void RenderingWindow::realiseGeometry_impl() { - Texture& tex = d_textarget.getTexture(); + Texture& tex = d_textarget.getTexture(); - const float tu = d_size.d_width * tex.getTexelScaling().d_x; - const float tv = d_size.d_height * tex.getTexelScaling().d_y; + const float tu = d_size.d_width * tex.getTexelScaling().x; + const float tv = d_size.d_height * tex.getTexelScaling().y; const Rectf tex_rect(d_textarget.isRenderingInverted() ? Rectf(0, 1, tu, 1 - tv) : Rectf(0, 0, tu, tv)); const Rectf area(0, 0, d_size.d_width, d_size.d_height); - const Colour c(1, 1, 1, 1); - Vertex vbuffer[6]; + const glm::vec4 colour(1.0, 1.0, 1.0, 1.0); + TexturedColouredVertex vbuffer[6]; // vertex 0 - vbuffer[0].position = Vector3f(area.d_min.d_x, area.d_min.d_y, 0.0f); - vbuffer[0].colour_val = c; - vbuffer[0].tex_coords = Vector2f(tex_rect.d_min.d_x, tex_rect.d_min.d_y); + vbuffer[0].d_position = glm::vec3(area.d_min.d_x, area.d_min.d_y, 0.0f); + vbuffer[0].d_colour = colour; + vbuffer[0].d_texCoords = glm::vec2(tex_rect.d_min.d_x, tex_rect.d_min.d_y); // vertex 1 - vbuffer[1].position = Vector3f(area.d_min.d_x, area.d_max.d_y, 0.0f); - vbuffer[1].colour_val = c; - vbuffer[1].tex_coords = Vector2f(tex_rect.d_min.d_x, tex_rect.d_max.d_y); + vbuffer[1].d_position = glm::vec3(area.d_min.d_x, area.d_max.d_y, 0.0f); + vbuffer[1].d_colour = colour; + vbuffer[1].d_texCoords = glm::vec2(tex_rect.d_min.d_x, tex_rect.d_max.d_y); // vertex 2 - vbuffer[2].position = Vector3f(area.d_max.d_x, area.d_max.d_y, 0.0f); - vbuffer[2].colour_val = c; - vbuffer[2].tex_coords = Vector2f(tex_rect.d_max.d_x, tex_rect.d_max.d_y); + vbuffer[2].d_position = glm::vec3(area.d_max.d_x, area.d_max.d_y, 0.0f); + vbuffer[2].d_colour = colour; + vbuffer[2].d_texCoords = glm::vec2(tex_rect.d_max.d_x, tex_rect.d_max.d_y); // vertex 3 - vbuffer[3].position = Vector3f(area.d_max.d_x, area.d_min.d_y, 0.0f); - vbuffer[3].colour_val = c; - vbuffer[3].tex_coords = Vector2f(tex_rect.d_max.d_x, tex_rect.d_min.d_y); + vbuffer[3].d_position = glm::vec3(area.d_max.d_x, area.d_min.d_y, 0.0f); + vbuffer[3].d_colour = colour; + vbuffer[3].d_texCoords = glm::vec2(tex_rect.d_max.d_x, tex_rect.d_min.d_y); // vertex 4 - vbuffer[4].position = Vector3f(area.d_min.d_x, area.d_min.d_y, 0.0f); - vbuffer[4].colour_val = c; - vbuffer[4].tex_coords = Vector2f(tex_rect.d_min.d_x, tex_rect.d_min.d_y); + vbuffer[4].d_position = glm::vec3(area.d_min.d_x, area.d_min.d_y, 0.0f); + vbuffer[4].d_colour = colour; + vbuffer[4].d_texCoords = glm::vec2(tex_rect.d_min.d_x, tex_rect.d_min.d_y); // vertex 5 - vbuffer[5].position = Vector3f(area.d_max.d_x, area.d_max.d_y, 0.0f); - vbuffer[5].colour_val = c; - vbuffer[5].tex_coords = Vector2f(tex_rect.d_max.d_x, tex_rect.d_max.d_y); + vbuffer[5].d_position = glm::vec3(area.d_max.d_x, area.d_max.d_y, 0.0f); + vbuffer[5].d_colour = colour; + vbuffer[5].d_texCoords = glm::vec2(tex_rect.d_max.d_x, tex_rect.d_max.d_y); - d_geometry->setActiveTexture(&tex); - d_geometry->appendGeometry(vbuffer, 6); + d_geometryBuffer.setTexture("texture0", &tex); + d_geometryBuffer.appendGeometry(vbuffer, 6); } //----------------------------------------------------------------------------// -void RenderingWindow::unprojectPoint(const Vector2f& p_in, Vector2f& p_out) +void RenderingWindow::unprojectPoint(const glm::vec2& p_in, glm::vec2& p_out) { // quick test for rotations to save us a lot of work in the unrotated case - if ((d_rotation == Quaternion::IDENTITY)) + if (d_rotation == glm::quat(1, 0, 0, 0)) { p_out = p_in; return; } - Vector2f in(p_in); + glm::vec2 in(p_in); // localise point for cases where owner is also a RenderingWindow if (d_owner->isRenderingWindow()) in -= static_cast(d_owner)->getPosition(); - d_owner->getRenderTarget().unprojectPoint(*d_geometry, in, p_out); - p_out.d_x += d_position.d_x; - p_out.d_y += d_position.d_y; + d_owner->getRenderTarget().unprojectPoint(d_geometryBuffer, in, p_out); + p_out += d_position; } //----------------------------------------------------------------------------// diff --git a/cegui/src/RightAlignedRenderedString.cpp b/cegui/src/RightAlignedRenderedString.cpp index 65205d0aa..866b73728 100644 --- a/cegui/src/RightAlignedRenderedString.cpp +++ b/cegui/src/RightAlignedRenderedString.cpp @@ -51,19 +51,19 @@ void RightAlignedRenderedString::format(const Window* ref_wnd, //----------------------------------------------------------------------------// void RightAlignedRenderedString::draw(const Window* ref_wnd, - GeometryBuffer& buffer, - const Vector2f& position, + std::vector& geometry_buffers, + const glm::vec2& position, const ColourRect* mod_colours, const Rectf* clip_rect) const { - Vector2f draw_pos; - draw_pos.d_y = position.d_y; + glm::vec2 draw_pos; + draw_pos.y = position.y; for (size_t i = 0; i < d_renderedString->getLineCount(); ++i) { - draw_pos.d_x = position.d_x + d_offsets[i]; - d_renderedString->draw(ref_wnd, i, buffer, draw_pos, mod_colours, clip_rect, 0.0f); - draw_pos.d_y += d_renderedString->getPixelSize(ref_wnd, i).d_height; + draw_pos.x = position.x + d_offsets[i]; + d_renderedString->draw(ref_wnd, i, geometry_buffers, draw_pos, mod_colours, clip_rect, 0.0f); + draw_pos.y += d_renderedString->getPixelSize(ref_wnd, i).d_height; } } diff --git a/cegui/src/Scheme.cpp b/cegui/src/Scheme.cpp index 1ebf434a4..637776ab1 100644 --- a/cegui/src/Scheme.cpp +++ b/cegui/src/Scheme.cpp @@ -186,7 +186,7 @@ void Scheme::loadImageFileImagesets() // see if image is present, and create it if not. if (!imgr.isDefined((*pos).name)) - imgr.addFromImageFile((*pos).name, (*pos).filename, (*pos).resourceGroup); + imgr.addBitmapImageFromFile((*pos).name, (*pos).filename, (*pos).resourceGroup); } } @@ -259,7 +259,7 @@ void Scheme::loadWindowFactories() #if !defined(CEGUI_STATIC) // load dynamic module as required if (!(*cmod).dynamicModule) - (*cmod).dynamicModule = CEGUI_NEW_AO DynamicModule((*cmod).name); + (*cmod).dynamicModule = new DynamicModule((*cmod).name); FactoryModule& (*getWindowFactoryModuleFunc)() = reinterpret_cast( @@ -313,7 +313,7 @@ void Scheme::loadWindowRendererFactories() #if !defined(CEGUI_STATIC) // load dynamic module as required if (!(*cmod).dynamicModule) - (*cmod).dynamicModule = CEGUI_NEW_AO DynamicModule((*cmod).name); + (*cmod).dynamicModule = new DynamicModule((*cmod).name); FactoryModule& (*getWRFactoryModuleFunc)() = reinterpret_cast((*cmod).dynamicModule-> @@ -516,7 +516,7 @@ void Scheme::unloadWindowFactories() // unload dynamic module as required if ((*cmod).dynamicModule) { - CEGUI_DELETE_AO (*cmod).dynamicModule; + delete (*cmod).dynamicModule; (*cmod).dynamicModule = 0; } @@ -554,7 +554,7 @@ void Scheme::unloadWindowRendererFactories() // unload dynamic module as required if ((*cmod).dynamicModule) { - CEGUI_DELETE_AO (*cmod).dynamicModule; + delete (*cmod).dynamicModule; (*cmod).dynamicModule = 0; } diff --git a/cegui/src/Scheme_xmlHandler.cpp b/cegui/src/Scheme_xmlHandler.cpp index 7237a77f4..f230da050 100644 --- a/cegui/src/Scheme_xmlHandler.cpp +++ b/cegui/src/Scheme_xmlHandler.cpp @@ -81,7 +81,7 @@ Scheme_xmlHandler::Scheme_xmlHandler(): Scheme_xmlHandler::~Scheme_xmlHandler() { if (!d_objectRead) - CEGUI_DELETE_AO d_scheme; + delete d_scheme; } //----------------------------------------------------------------------------// @@ -167,7 +167,7 @@ void Scheme_xmlHandler::elementGUISchemeStart(const XMLAttributes& attributes) validateSchemeFileVersion(attributes); // create empty scheme with desired name - d_scheme = CEGUI_NEW_AO Scheme(name); + d_scheme = new Scheme(name); } //----------------------------------------------------------------------------// diff --git a/cegui/src/ScriptModules/Lua/package/Window.pkg b/cegui/src/ScriptModules/Lua/package/Window.pkg index bedccd85f..a5768c713 100644 --- a/cegui/src/ScriptModules/Lua/package/Window.pkg +++ b/cegui/src/ScriptModules/Lua/package/Window.pkg @@ -125,7 +125,6 @@ class Window : public NamedElement bool isInFront(const Window& wnd) const; bool isBehind(const Window& wnd) const; - bool wantsMultiClickEvents(void) const; void setWantsMultiClickEvents(bool setting); bool isMouseAutoRepeatEnabled(void) const; diff --git a/cegui/src/ScriptModules/Python/bindings/generators/include/python_CEGUI.h b/cegui/src/ScriptModules/Python/bindings/generators/include/python_CEGUI.h index 1c6ce4856..725ba09f7 100644 --- a/cegui/src/ScriptModules/Python/bindings/generators/include/python_CEGUI.h +++ b/cegui/src/ScriptModules/Python/bindings/generators/include/python_CEGUI.h @@ -377,21 +377,19 @@ namespace pyplusplus typedef ::CEGUI::Rect URect; typedef ::CEGUI::Size USize; - typedef std::vector ListBoxItemPtrVector; + typedef std::vector ListBoxItemPtrVector; // typedef std::vector AliasMappingVector; - typedef std::vector PropertyInitialiserVector; + typedef std::vector PropertyInitialiserVector; // typedef std::vector FalagardMappingVector; // typedef std::vector LoadableUIElementVector; // typedef std::vector UIElementFactoryVector; // typedef std::vector UIModuleVector; - typedef std::vector TextComponentVector; - typedef std::vector ImageryComponentVector; - typedef std::vector FrameComponentVector; - typedef std::vector LayerSpecificationVector; - typedef std::vector SectionSpecificationVector; + typedef std::vector TextComponentVector; + typedef std::vector ImageryComponentVector; + typedef std::vector FrameComponentVector; + typedef std::vector LayerSpecificationVector; + typedef std::vector SectionSpecificationVector; typedef ::CEGUI::Event::Connection Connection; typedef ::CEGUI::Event::Subscriber Subscriber; @@ -412,10 +410,8 @@ namespace pyplusplus typedef std::pair StdPairCEGUIStringString; typedef std::pair StdPairCEGUIImageImageFactory; - typedef std::map StringMap; - typedef std::vector StringVector; + typedef std::map StringMap; + typedef std::vector StringVector; typedef CEGUI::Singleton SingletonAnimationManager; typedef CEGUI::Singleton SingletonLogger; @@ -432,57 +428,35 @@ namespace pyplusplus typedef CEGUI::Singleton SingletonWindowRendererManager; typedef unsigned int Group; - typedef std::map ResourceGroupMap; + typedef std::map ResourceGroupMap; typedef CEGUI::RefCounted Connection; typedef CEGUI::SubscriberSlot Subscriber; - typedef std::multimap SlotContainer; - typedef std::map EventMap; - typedef std::map FontRegistry; + typedef std::multimap SlotContainer; + typedef std::map EventMap; + typedef std::map FontRegistry; typedef std::pair WindowStackEntry; - typedef std::vector WindowStack; - typedef std::map PropertyRegistry; - typedef std::map UserStringMap; + typedef std::vector WindowStack; + typedef std::map PropertyRegistry; + typedef std::map UserStringMap; typedef std::set StringSet; - typedef std::vector TargetTypeStack; //!< Type used to implement stack of target type names. - typedef std::map WindowRegistry; //!< Type used to implement registry of Window objects - typedef std::vector WindowVector; //!< Type to use for a collection of Window pointers. - typedef std::vector PropertyList; - typedef std::map WR_Registry; - typedef std::map AttributeMap; - - - typedef std::map EventLinkDefinitionMap; - typedef std::map ImagerySectionMap; - typedef std::map NamedAreaMap; - typedef std::map PropertyDefinitionBaseMap; - typedef std::map PropertyInitialiserMap; - typedef std::map StateImageryMap; - typedef std::map WidgetComponentMap; - typedef std::map WidgetLookFeelMap; - - typedef CEGUI::ConstVectorIterator > PropertyInitialiserVectorIterator; + typedef std::vector TargetTypeStack; //!< Type used to implement stack of target type names. + typedef std::map WindowRegistry; //!< Type used to implement registry of Window objects + typedef std::vector WindowVector; //!< Type to use for a collection of Window pointers. + typedef std::vector PropertyList; + typedef std::map WR_Registry; + typedef std::map AttributeMap; + + + typedef std::map EventLinkDefinitionMap; + typedef std::map ImagerySectionMap; + typedef std::map NamedAreaMap; + typedef std::map PropertyDefinitionBaseMap; + typedef std::map PropertyInitialiserMap; + typedef std::map StateImageryMap; + typedef std::map WidgetComponentMap; + typedef std::map WidgetLookFeelMap; + + typedef CEGUI::ConstVectorIterator > PropertyInitialiserVectorIterator; typedef CEGUI::TypedProperty TypedPropertyFloat; typedef CEGUI::FalagardPropertyBase FalagardPropertyBaseFloat; @@ -621,31 +595,31 @@ namespace python_CEGUI sizeof( ::std::pair ); // seems that doing an sizeof ( ::CEGUI::EventSet::Iterator ); doesn't expose the class :( - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - //sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstVectorIterator >); - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstVectorIterator CEGUI_VECTOR_ALLOC(CEGUI::LayerSpecification) > > ); - sizeof( CEGUI::ConstVectorIterator > ); - sizeof( CEGUI::ConstVectorIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + //sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstVectorIterator); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstVectorIterator > > ); + sizeof( CEGUI::ConstVectorIterator > ); + sizeof( CEGUI::ConstVectorIterator > ); sizeof( CEGUI::ConstVectorIterator > > ); - sizeof( CEGUI::ConstVectorIterator > ); + sizeof( CEGUI::ConstVectorIterator > ); sizeof( CEGUI::ConstVectorIterator > ); sizeof( CEGUI::ConstVectorIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - //sizeof( CEGUI::ConstVectorIterator > ); - sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + //sizeof( CEGUI::ConstVectorIterator ); + sizeof( CEGUI::ConstMapIterator > ); sizeof( CEGUI::ConstVectorIterator > ); - sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstMapIterator > ); sizeof( CEGUI::ConstVectorIterator > ); - sizeof( CEGUI::ConstMapIterator > ); - sizeof( CEGUI::ConstVectorIterator > ); - sizeof( CEGUI::ConstVectorIterator > ); + sizeof( CEGUI::ConstMapIterator > ); + sizeof( CEGUI::ConstVectorIterator > ); + sizeof( CEGUI::ConstVectorIterator > ); sizeof( CEGUI::TypedProperty ); sizeof( CEGUI::FalagardPropertyBase ); diff --git a/cegui/src/ScriptModules/Python/bindings/output/CEGUI/Window.pypp.cpp b/cegui/src/ScriptModules/Python/bindings/output/CEGUI/Window.pypp.cpp index 70d878b85..5e482dd35 100644 --- a/cegui/src/ScriptModules/Python/bindings/output/CEGUI/Window.pypp.cpp +++ b/cegui/src/ScriptModules/Python/bindings/output/CEGUI/Window.pypp.cpp @@ -5936,29 +5936,6 @@ void register_Window_class(){ Nothing\n\ *\n" ); - } - { //::CEGUI::Window::setWantsMultiClickEvents - - typedef void ( ::CEGUI::Window::*setWantsMultiClickEvents_function_type )( bool ) ; - - Window_exposer.def( - "setWantsMultiClickEvents" - , setWantsMultiClickEvents_function_type( &::CEGUI::Window::setWantsMultiClickEvents ) - , ( bp::arg("setting") ) - , "*!\n\ - \n\ - Set whether this window will receive multi-click events or multiple\n\ - 'down' events instead.\n\ - \n\ - @param setting\n\ - - true if the Window will receive double-click and triple-click events.\n\ - - false if the Window will receive multiple mouse button down events\n\ - instead of doubletriple click events.\n\ - \n\ - @return\n\ - Nothing.\n\ - *\n" ); - } { //::CEGUI::Window::setWindowRenderer @@ -6163,25 +6140,6 @@ void register_Window_class(){ False if not.\n\ *\n" ); - } - { //::CEGUI::Window::wantsMultiClickEvents - - typedef bool ( ::CEGUI::Window::*wantsMultiClickEvents_function_type )( ) const; - - Window_exposer.def( - "wantsMultiClickEvents" - , wantsMultiClickEvents_function_type( &::CEGUI::Window::wantsMultiClickEvents ) - , "*!\n\ - \n\ - Return whether this window will receive multi-click events or multiple\n\ - 'down' events instead.\n\ - \n\ - @return\n\ - - true if the Window will receive double-click and triple-click events.\n\ - - false if the Window will receive multiple mouse button down events\n\ - instead of doubletriple click events.\n\ - *\n" ); - } { //::CEGUI::Window::writeAutoChildWindowXML diff --git a/cegui/src/ShaderParameterBindings.cpp b/cegui/src/ShaderParameterBindings.cpp new file mode 100644 index 000000000..fddb0abac --- /dev/null +++ b/cegui/src/ShaderParameterBindings.cpp @@ -0,0 +1,197 @@ +/*********************************************************************** + created: 18th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "CEGUI/ShaderParameterBindings.h" +#include "CEGUI/System.h" + +#include "glm/glm.hpp" + +namespace CEGUI +{ +//----------------------------------------------------------------------------// +bool ShaderParameterFloat::equal(const ShaderParameter* other_parameter) const +{ + if (this->getType() == other_parameter->getType()) + return (d_parameterValue == static_cast(other_parameter)->d_parameterValue); + else + return false; +} + +//----------------------------------------------------------------------------// +void ShaderParameterFloat::takeOverParameterValue(const ShaderParameter* other_parameter) +{ + if (getType() == other_parameter->getType()) + d_parameterValue = static_cast(other_parameter)->d_parameterValue; +} + +//----------------------------------------------------------------------------// +bool ShaderParameterInt::equal(const ShaderParameter* other_parameter) const +{ + if (this->getType() == other_parameter->getType()) + return (d_parameterValue == static_cast(other_parameter)->d_parameterValue); + else + return false; +} + +//----------------------------------------------------------------------------// +void ShaderParameterInt::takeOverParameterValue(const ShaderParameter* other_parameter) +{ + if (getType() == other_parameter->getType()) + d_parameterValue = static_cast(other_parameter)->d_parameterValue; +} + +//----------------------------------------------------------------------------// +bool ShaderParameterTexture::equal(const ShaderParameter* other_parameter) const +{ + if (this->getType() == other_parameter->getType()) + return (d_parameterValue == static_cast(other_parameter)->d_parameterValue); + else + return false; +} + +//----------------------------------------------------------------------------// +void ShaderParameterTexture::takeOverParameterValue(const ShaderParameter* other_parameter) +{ + if (getType() == other_parameter->getType()) + d_parameterValue = static_cast(other_parameter)->d_parameterValue; +} + +//----------------------------------------------------------------------------// +bool ShaderParameterMatrix::equal(const ShaderParameter* other_parameter) const +{ + if (this->getType() == other_parameter->getType()) + return (d_parameterValue == static_cast(other_parameter)->d_parameterValue); + else + return false; +} + +//----------------------------------------------------------------------------// +void ShaderParameterMatrix::takeOverParameterValue(const ShaderParameter* other_parameter) +{ + if (getType() == other_parameter->getType()) + d_parameterValue = static_cast(other_parameter)->d_parameterValue; +} + +//----------------------------------------------------------------------------// +ShaderParameterBindings::ShaderParameterBindings() +{ +} + +//----------------------------------------------------------------------------// +ShaderParameterBindings::~ShaderParameterBindings() +{ + ShaderParameterBindings::ShaderParameterBindingsMap::iterator iter = d_shaderParameterBindings.begin(); + ShaderParameterBindings::ShaderParameterBindingsMap::iterator end = d_shaderParameterBindings.end(); + + while (iter != end) + { + delete iter->second; + ++iter; + } + + d_shaderParameterBindings.clear(); +} + +//----------------------------------------------------------------------------// +void ShaderParameterBindings::removeParameter(const std::string& parameter_name) +{ + ShaderParameterBindingsMap::iterator found_iterator = d_shaderParameterBindings.find(parameter_name); + if (found_iterator != d_shaderParameterBindings.end()) + { + delete found_iterator->second; + d_shaderParameterBindings.erase(found_iterator); + } +} + +//----------------------------------------------------------------------------// +void ShaderParameterBindings::setNewParameter(const std::string& parameter_name, ShaderParameter* shader_parameter) +{ + std::map::iterator found_iterator = d_shaderParameterBindings.find(parameter_name); + if (found_iterator != d_shaderParameterBindings.end()) + { + delete found_iterator->second; + found_iterator->second = shader_parameter; + } + else + { + std::pair shader_params_pair(parameter_name, shader_parameter); + d_shaderParameterBindings.insert(shader_params_pair); + } +} + +//----------------------------------------------------------------------------// +void ShaderParameterBindings::setParameter(const std::string& parameter_name, + const glm::mat4& matrix) +{ + ShaderParameter* shader_param = getParameter(parameter_name); + if (shader_param && ( shader_param->getType() == SPT_MATRIX_4X4 ) ) + static_cast(shader_param)->d_parameterValue = matrix; + else + setNewParameter(parameter_name, new ShaderParameterMatrix(matrix)); +} + +//----------------------------------------------------------------------------// +void ShaderParameterBindings::setParameter(const std::string& parameter_name, const CEGUI::Texture* texture) +{ + ShaderParameter* shader_param = getParameter(parameter_name); + if (shader_param && ( shader_param->getType() == SPT_TEXTURE ) ) + static_cast(shader_param)->d_parameterValue = texture; + else + setNewParameter(parameter_name, new ShaderParameterTexture(texture)); +} + +//----------------------------------------------------------------------------// +void ShaderParameterBindings::setParameter(const std::string& parameter_name, + const float fvalue) +{ + ShaderParameter* shader_param = getParameter(parameter_name); + if (shader_param && (shader_param->getType() == SPT_FLOAT)) + static_cast(shader_param)->d_parameterValue = + fvalue; + else + setNewParameter(parameter_name, new ShaderParameterFloat(fvalue)); +} + +//----------------------------------------------------------------------------// +ShaderParameter* ShaderParameterBindings::getParameter(const std::string& parameter_name) +{ + std::map::iterator found_iterator = d_shaderParameterBindings.find(parameter_name); + if (found_iterator != d_shaderParameterBindings.end()) + return found_iterator->second; + else + return 0; +} + + +//----------------------------------------------------------------------------// +const ShaderParameterBindings::ShaderParameterBindingsMap& ShaderParameterBindings::getShaderParameterBindings() const +{ + return d_shaderParameterBindings; +} + +//----------------------------------------------------------------------------// +} diff --git a/cegui/src/String.cpp b/cegui/src/String.cpp index 4995b7251..bdf211618 100644 --- a/cegui/src/String.cpp +++ b/cegui/src/String.cpp @@ -67,12 +67,12 @@ bool String::grow(size_type new_size) if (new_size > d_reserve) { - utf32* temp = CEGUI_NEW_ARRAY_PT(utf32, new_size, String); + utf32* temp = new utf32[new_size]; if (d_reserve > CEGUI_STR_QUICKBUFF_SIZE) { memcpy(temp, d_buffer, (d_cplength + 1) * sizeof(utf32)); - CEGUI_DELETE_ARRAY_PT(d_buffer, utf32, d_reserve, String); + delete[] d_buffer; } else { @@ -100,15 +100,15 @@ void String::trim(void) if (min_size <= CEGUI_STR_QUICKBUFF_SIZE) { memcpy(d_quickbuff, d_buffer, min_size * sizeof(utf32)); - CEGUI_DELETE_ARRAY_PT(d_buffer, utf32, d_reserve, String); + delete[] d_buffer; d_reserve = CEGUI_STR_QUICKBUFF_SIZE; } // re-allocate buffer else { - utf32* temp = CEGUI_NEW_ARRAY_PT(utf32, min_size, String); + utf32* temp = new utf32[min_size]; memcpy(temp, d_buffer, min_size * sizeof(utf32)); - CEGUI_DELETE_ARRAY_PT(d_buffer, utf32, d_reserve, String); + delete[] d_buffer; d_buffer = temp; d_reserve = min_size; } @@ -126,10 +126,10 @@ utf8* String::build_utf8_buff(void) const if (d_encodedbufflen > 0) { - CEGUI_DELETE_ARRAY_PT(d_encodedbuff, utf8, d_encodedbufflen, String); + delete[] d_encodedbuff; } - d_encodedbuff = CEGUI_NEW_ARRAY_PT(utf8, buffsize, String); + d_encodedbuff = new utf8[buffsize]; d_encodedbufflen = buffsize; } diff --git a/cegui/src/SubscriberSlot.cpp b/cegui/src/SubscriberSlot.cpp index be7cfd1ce..e096ca197 100644 --- a/cegui/src/SubscriberSlot.cpp +++ b/cegui/src/SubscriberSlot.cpp @@ -31,7 +31,7 @@ namespace CEGUI { SubscriberSlot::SubscriberSlot(FreeFunctionSlot::SlotFunction* func) : - d_functor_impl(CEGUI_NEW_AO FreeFunctionSlot(func)) + d_functor_impl(new FreeFunctionSlot(func)) { } @@ -48,7 +48,7 @@ SubscriberSlot::~SubscriberSlot() void SubscriberSlot::cleanup() { - CEGUI_DELETE_AO d_functor_impl; + delete d_functor_impl; d_functor_impl = 0; } diff --git a/cegui/src/System.cpp b/cegui/src/System.cpp index ee962c706..272c43f69 100644 --- a/cegui/src/System.cpp +++ b/cegui/src/System.cpp @@ -36,7 +36,7 @@ #include "CEGUI/SchemeManager.h" #include "CEGUI/RenderEffectManager.h" #include "CEGUI/AnimationManager.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/Window.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ScriptModule.h" @@ -54,11 +54,16 @@ #include "CEGUI/RenderingContext.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/ImageCodec.h" +#include "CEGUI/views/All.h" #include "CEGUI/widgets/All.h" #include "CEGUI/RegexMatcher.h" +#include "CEGUI/svg/SVGDataManager.h" #ifdef CEGUI_HAS_PCRE_REGEX # include "CEGUI/PCRERegexMatcher.h" #endif +#if defined(__WIN32__) || defined(_WIN32) +# include "CEGUI/Win32ClipboardProvider.h" +#endif #include #include @@ -120,7 +125,8 @@ System::System(Renderer& renderer, : d_renderer(&renderer), d_resourceProvider(resourceProvider), d_ourResourceProvider(false), - d_clipboard(CEGUI_NEW_AO Clipboard()), + d_clipboard(new Clipboard()), + d_nativeClipboardProvider(0), d_scriptModule(scriptModule), d_xmlParser(xmlParser), d_ourXmlParser(false), @@ -144,7 +150,13 @@ System::System(Renderer& renderer, // seeing its configuration overwritten by this. #ifdef CEGUI_HAS_DEFAULT_LOGGER if (d_ourLogger) - CEGUI_NEW_AO DefaultLogger(); + new DefaultLogger(); +#endif + +#if defined(__WIN32__) || defined(_WIN32) + d_nativeClipboardProvider = new Win32ClipboardProvider; + // set the default win 32 clipboard provider + d_clipboard->setNativeProvider(d_nativeClipboardProvider); #endif Logger& logger(Logger::getSingleton()); @@ -152,7 +164,7 @@ System::System(Renderer& renderer, // create default resource provider, unless one was already provided if (!d_resourceProvider) { - d_resourceProvider = CEGUI_NEW_AO DefaultResourceProvider(); + d_resourceProvider = new DefaultResourceProvider(); d_ourResourceProvider = true; } @@ -173,7 +185,7 @@ System::System(Renderer& renderer, { // cleanup XML stuff d_xmlParser->cleanup(); - CEGUI_DELETE_AO d_xmlParser; + delete d_xmlParser; CEGUI_RETHROW; } } @@ -224,7 +236,7 @@ System::System(Renderer& renderer, // set up defaults config.initialiseDefaultFont(); - config.initialiseDefaultMouseCursor(); + config.initialiseDefaultCursor(); config.initialiseDefaulTooltip(); // scripting available? @@ -255,6 +267,9 @@ System::~System(void) } + if (d_nativeClipboardProvider != 0) + delete d_nativeClipboardProvider; + cleanupImageCodec(); // cleanup XML stuff @@ -286,12 +301,12 @@ System::~System(void) i != d_guiContexts.end(); ++i) { - CEGUI_DELETE_AO *i; + delete *i; } // cleanup resource provider if we own it if (d_ourResourceProvider) - CEGUI_DELETE_AO d_resourceProvider; + delete d_resourceProvider; char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast(this)); @@ -302,10 +317,10 @@ System::~System(void) #ifdef CEGUI_HAS_DEFAULT_LOGGER // delete the Logger object only if we created it. if (d_ourLogger) - CEGUI_DELETE_AO Logger::getSingletonPtr(); + delete Logger::getSingletonPtr(); #endif - - CEGUI_DELETE_AO d_clipboard; + + delete d_clipboard; } //---------------------------------------------------------------------------// @@ -421,6 +436,24 @@ void System::renderAllGUIContexts() WindowManager::getSingleton().cleanDeadPool(); } +void System::renderAllGUIContextsOnTarget(Renderer* contained_in) +{ + d_renderer->beginRendering(); + + for (GUIContextCollection::iterator i = d_guiContexts.begin(); + i != d_guiContexts.end(); + ++i) + { + // Add a check here to see if the renderer of context matches + // contained_in + (*i)->draw(); + } + + d_renderer->endRendering(); + + // do final destruction on dead-pool windows + WindowManager::getSingleton().cleanDeadPool(); +} /************************************************************************* Return a pointer to the ScriptModule being used for scripting within @@ -630,7 +663,6 @@ void System::addStandardWindowFactories() WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); - WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); @@ -638,9 +670,9 @@ void System::addStandardWindowFactories() WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); - WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); + WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); @@ -657,42 +689,46 @@ void System::addStandardWindowFactories() WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); - WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); - WindowFactoryManager::addWindowType(); - WindowFactoryManager::addWindowType(); + WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); WindowFactoryManager::addWindowType(); + + // views + WindowFactoryManager::addWindowType(); + WindowFactoryManager::addWindowType(); } void System::createSingletons() { // cause creation of other singleton objects - CEGUI_NEW_AO ImageManager(); - CEGUI_NEW_AO FontManager(); - CEGUI_NEW_AO WindowFactoryManager(); - CEGUI_NEW_AO WindowManager(); - CEGUI_NEW_AO SchemeManager(); - CEGUI_NEW_AO GlobalEventSet(); - CEGUI_NEW_AO AnimationManager(); - CEGUI_NEW_AO WidgetLookManager(); - CEGUI_NEW_AO WindowRendererManager(); - CEGUI_NEW_AO RenderEffectManager(); + new ImageManager(); + new FontManager(); + new WindowFactoryManager(); + new WindowManager(); + new SchemeManager(); + new GlobalEventSet(); + new AnimationManager(); + new WidgetLookManager(); + new WindowRendererManager(); + new RenderEffectManager(); + new SVGDataManager(); } void System::destroySingletons() { - CEGUI_DELETE_AO SchemeManager::getSingletonPtr(); - CEGUI_DELETE_AO WindowManager::getSingletonPtr(); - CEGUI_DELETE_AO WindowFactoryManager::getSingletonPtr(); - CEGUI_DELETE_AO WidgetLookManager::getSingletonPtr(); - CEGUI_DELETE_AO WindowRendererManager::getSingletonPtr(); - CEGUI_DELETE_AO AnimationManager::getSingletonPtr(); - CEGUI_DELETE_AO RenderEffectManager::getSingletonPtr(); - CEGUI_DELETE_AO FontManager::getSingletonPtr(); - CEGUI_DELETE_AO ImageManager::getSingletonPtr(); - CEGUI_DELETE_AO GlobalEventSet::getSingletonPtr(); + delete SchemeManager::getSingletonPtr(); + delete WindowManager::getSingletonPtr(); + delete WindowFactoryManager::getSingletonPtr(); + delete WidgetLookManager::getSingletonPtr(); + delete WindowRendererManager::getSingletonPtr(); + delete AnimationManager::getSingletonPtr(); + delete RenderEffectManager::getSingletonPtr(); + delete FontManager::getSingletonPtr(); + delete ImageManager::getSingletonPtr(); + delete GlobalEventSet::getSingletonPtr(); + delete SVGDataManager::getSingletonPtr(); } //----------------------------------------------------------------------------// @@ -740,7 +776,7 @@ void System::cleanupXMLParser() deleteFunc(d_xmlParser); // delete the dynamic module for the xml parser - CEGUI_DELETE_AO d_parserModule; + delete d_parserModule; d_parserModule = 0; } #ifdef CEGUI_STATIC @@ -758,7 +794,7 @@ void System::setXMLParser(const String& parserName) #ifndef CEGUI_STATIC cleanupXMLParser(); // load dynamic module - d_parserModule = CEGUI_NEW_AO DynamicModule(String("CEGUI") + parserName); + d_parserModule = new DynamicModule(String("CEGUI") + parserName); // get pointer to parser creation function XMLParser* (*createFunc)(void) = (XMLParser* (*)(void))d_parserModule->getSymbolAddress("createParser"); @@ -828,8 +864,8 @@ void System::setupImageCodec(const String& codecName) # else // load the appropriate image codec module d_imageCodecModule = codecName.empty() ? - CEGUI_NEW_AO DynamicModule(String("CEGUI") + d_defaultImageCodecName) : - CEGUI_NEW_AO DynamicModule(String("CEGUI") + codecName); + new DynamicModule(String("CEGUI") + d_defaultImageCodecName) : + new DynamicModule(String("CEGUI") + codecName); // use function from module to create the codec object. d_imageCodec = ((ImageCodec*(*)(void))d_imageCodecModule-> @@ -852,7 +888,7 @@ void System::cleanupImageCodec() ((void(*)(ImageCodec*))d_imageCodecModule-> getSymbolAddress("destroyImageCodec"))(d_imageCodec); - CEGUI_DELETE_AO d_imageCodecModule; + delete d_imageCodecModule; d_imageCodecModule = 0; } #if defined(CEGUI_STATIC) @@ -883,7 +919,7 @@ System& System::create(Renderer& renderer, ResourceProvider* resourceProvider, { performVersionTest(CEGUI_VERSION_ABI, abi, CEGUI_FUNCTION_NAME); - return *CEGUI_NEW_AO System(renderer, resourceProvider, xmlParser, imageCodec, + return *new System(renderer, resourceProvider, xmlParser, imageCodec, scriptModule, configFile, logFile); } @@ -905,7 +941,7 @@ void System::performVersionTest(const int expected, const int received, //----------------------------------------------------------------------------// void System::destroy() { - CEGUI_DELETE_AO System::getSingletonPtr(); + delete System::getSingletonPtr(); } //----------------------------------------------------------------------------// @@ -920,7 +956,7 @@ void System::setDefaultCustomRenderedStringParser(RenderedStringParser* parser) if (parser != d_customRenderedStringParser) { d_customRenderedStringParser = parser; - + // fire event EventArgs args; fireEvent(EventRenderedStringParserChanged, args, EventNamespace); @@ -931,7 +967,6 @@ void System::setDefaultCustomRenderedStringParser(RenderedStringParser* parser) void System::invalidateAllCachedRendering() { invalidateAllWindows(); - //MouseCursor::getSingleton().invalidate(); } //----------------------------------------------------------------------------// @@ -956,7 +991,7 @@ void System::invalidateAllWindows() RegexMatcher* System::createRegexMatcher() const { #ifdef CEGUI_HAS_PCRE_REGEX - return CEGUI_NEW_AO PCRERegexMatcher(); + return new PCRERegexMatcher(); #else return 0; #endif @@ -965,7 +1000,7 @@ RegexMatcher* System::createRegexMatcher() const //----------------------------------------------------------------------------// void System::destroyRegexMatcher(RegexMatcher* rm) const { - CEGUI_DELETE_AO rm; + delete rm; } //----------------------------------------------------------------------------// @@ -977,7 +1012,7 @@ GUIContext& System::getDefaultGUIContext() const //----------------------------------------------------------------------------// GUIContext& System::createGUIContext(RenderTarget& rt) { - GUIContext* c = CEGUI_NEW_AO GUIContext(rt); + GUIContext* c = new GUIContext(rt); d_guiContexts.push_back(c); return *c; @@ -992,7 +1027,7 @@ void System::destroyGUIContext(GUIContext& context) { if (*i == &context) { - CEGUI_DELETE_AO *i; + delete *i; d_guiContexts.erase(i); return; } diff --git a/cegui/src/SystemKeys.cpp b/cegui/src/SystemKeys.cpp deleted file mode 100644 index 2459b0fb5..000000000 --- a/cegui/src/SystemKeys.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/*********************************************************************** - created: Fri Feb 17 2012 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/SystemKeys.h" - -namespace CEGUI -{ -//----------------------------------------------------------------------------// -SystemKeys::SystemKeys() : - d_current(0), - d_leftShift(false), - d_rightShift(false), - d_leftCtrl(false), - d_rightCtrl(false), - d_leftAlt(false), - d_rightAlt(false) -{ -} - -//----------------------------------------------------------------------------// -void SystemKeys::reset() -{ - *this = SystemKeys(); -} - -//----------------------------------------------------------------------------// -uint SystemKeys::get() const -{ - return d_current; -} - -//----------------------------------------------------------------------------// -bool SystemKeys::isPressed(SystemKey key) const -{ - return (d_current & key) || (!key && !d_current); -} - -//----------------------------------------------------------------------------// -void SystemKeys::keyPressed(Key::Scan key) -{ - updatePressedStateForKey(key, true); - updateSystemKeyState(keyCodeToSystemKey(key)); -} - -//----------------------------------------------------------------------------// -void SystemKeys::keyReleased(Key::Scan key) -{ - updatePressedStateForKey(key, false); - updateSystemKeyState(keyCodeToSystemKey(key)); -} - -//----------------------------------------------------------------------------// -SystemKeys::SystemKey SystemKeys::keyCodeToSystemKey(Key::Scan key) -{ - switch (key) - { - case Key::RightShift: - case Key::LeftShift: - return Shift; - - case Key::LeftControl: - case Key::RightControl: - return Control; - - case Key::LeftAlt: - case Key::RightAlt: - return Alt; - - default: - return None; - } -} - -//----------------------------------------------------------------------------// -void SystemKeys::updateSystemKeyState(SystemKey syskey) -{ - switch (syskey) - { - case Shift: - (d_leftShift || d_rightShift) ? d_current |= Shift : d_current &= ~Shift; - break; - - case Control: - (d_leftCtrl || d_rightCtrl) ? d_current |= Control : d_current &= ~Control; - break; - - case Alt: - (d_leftAlt || d_rightAlt) ? d_current |= Alt : d_current &= ~Alt; - break; - - default: - break; - } -} - -//----------------------------------------------------------------------------// -void SystemKeys::updatePressedStateForKey(Key::Scan key, bool state) -{ - switch (key) - { - case Key::LeftShift: - d_leftShift = state; - break; - - case Key::RightShift: - d_rightShift = state; - break; - - case Key::LeftControl: - d_leftCtrl = state; - break; - - case Key::RightControl: - d_rightCtrl = state; - - case Key::LeftAlt: - d_leftAlt = state; - break; - - case Key::RightAlt: - d_rightAlt = state; - break; - - default: - break; - } -} - -//----------------------------------------------------------------------------// -void SystemKeys::mouseButtonPressed(MouseButton button) -{ - d_current |= mouseButtonToSystemKey(button); -} - -//----------------------------------------------------------------------------// -void SystemKeys::mouseButtonReleased(MouseButton button) -{ - d_current &= ~mouseButtonToSystemKey(button); -} - -//----------------------------------------------------------------------------// -SystemKeys::SystemKey SystemKeys::mouseButtonToSystemKey(MouseButton button) -{ - switch (button) - { - case LeftButton: - return LeftMouse; - - case RightButton: - return RightMouse; - - case MiddleButton: - return MiddleMouse; - - case X1Button: - return X1Mouse; - - case X2Button: - return X2Mouse; - - default: - return None; - } -} -//----------------------------------------------------------------------------// -} - diff --git a/cegui/src/UndoHandler.cpp b/cegui/src/UndoHandler.cpp new file mode 100644 index 000000000..fae4c7b84 --- /dev/null +++ b/cegui/src/UndoHandler.cpp @@ -0,0 +1,184 @@ +/*********************************************************************** + created: 15/07/2013 + author: Erihel + +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/UndoHandler.h" + +// Start of CEGUI namespace section +namespace CEGUI +{ + +////////////////////////////////////////////////////////////////////////// +// Constructor +////////////////////////////////////////////////////////////////////////// +UndoHandler::UndoHandler(Window *window) : + d_undoLimit(10), + d_undoPosition(-1), + d_lastUndo(true) +{ + d_attachedWindow = window; +} + +/************************************************************************* + Undo/Redo +*************************************************************************/ +bool UndoHandler::undo(size_t &cursor) +{ + if (!d_attachedWindow) + return false; + + if (canUndo()) + { + if (static_cast(d_undoPosition) < d_undoList.size()) + { + UndoAction &action = d_undoList[d_undoPosition--]; + + String newText = d_attachedWindow->getText(); + if (action.d_type == UAT_INSERT) + { + newText.erase(action.d_startIdx, action.d_text.length()); + cursor = action.d_startIdx; + } + else + { + newText.insert(action.d_startIdx, action.d_text); + cursor = action.d_startIdx + action.d_text.length(); + } + d_attachedWindow->setText(newText); + d_lastUndo = true; + return true; + } + } + return false; +} + +//----------------------------------------------------------------------------// +bool UndoHandler::redo(size_t &cursor) +{ + if (!d_attachedWindow) + return false; + + if (canRedo()) + { + UndoAction &action = d_undoList[++d_undoPosition]; + + String newText = d_attachedWindow->getText(); + if (action.d_type == UAT_INSERT) + { + newText.insert(action.d_startIdx, action.d_text); + cursor = action.d_startIdx + action.d_text.length(); + } + else + { + newText.erase(action.d_startIdx, action.d_text.length()); + cursor = action.d_startIdx; + } + d_attachedWindow->setText(newText); + d_lastUndo = false; + return true; + } + return false; +} + +//----------------------------------------------------------------------------// +void UndoHandler::setUndoLimit(int limit) +{ + if (limit < 0) + { + CEGUI_THROW(InvalidRequestException("Invalid undo limit. Limit cannot be less then zero.")); + } + + d_undoLimit = limit; + + while (d_undoList.size() > d_undoLimit) + d_undoList.pop_front(); + + d_undoPosition = d_undoList.size() - 1; +} + +//----------------------------------------------------------------------------// +void UndoHandler::addUndoHistory(UndoAction &action) +{ + // discard all actions that are after our current position in undo list + while (d_undoList.size() > 0 && d_undoPosition < static_cast(d_undoList.size()) - 1) + d_undoList.pop_back(); + + if (d_undoList.size() > d_undoLimit) + d_undoList.pop_front(); + + d_undoList.push_back(action); + d_undoPosition = d_undoList.size() - 1; +} + +//----------------------------------------------------------------------------// +void UndoHandler::clearUndoHistory() +{ + d_undoList.clear(); + d_undoPosition = -1; +} + +//----------------------------------------------------------------------------// +size_t UndoHandler::count() +{ + return d_undoList.size(); +} + +//----------------------------------------------------------------------------// +bool UndoHandler::canUndo() +{ + return (d_undoList.size() > 0 && d_undoPosition >= 0); +} + +//----------------------------------------------------------------------------// +bool UndoHandler::canRedo() +{ + return (d_undoList.size() > 0 && d_undoPosition < static_cast(d_undoList.size()) - 1); +} + +//----------------------------------------------------------------------------// +UndoHandler::UndoAction UndoHandler::getLastAction() +{ + UndoAction lastAction; + + if (d_lastUndo) + { + if (d_undoPosition == d_undoList.size() - 1) + lastAction = d_undoList[d_undoPosition]; + else + lastAction = d_undoList[d_undoPosition + 1]; + } + else + { + if (d_undoPosition <= 0) + lastAction = d_undoList[0]; + else + lastAction = d_undoList[d_undoPosition]; + } + return lastAction; +} + +} // End of CEGUI namespace section + diff --git a/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderFrag.h b/cegui/src/Vertex.cpp similarity index 75% rename from cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderFrag.h rename to cegui/src/Vertex.cpp index e1c9df11f..9f75a0a4e 100644 --- a/cegui/include/CEGUI/RendererModules/OpenGL/StandardShaderFrag.h +++ b/cegui/src/Vertex.cpp @@ -1,9 +1,9 @@ /*********************************************************************** - created: Wed, 8th Feb 2012 + created: Sunday, 21st August 2014 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,26 +24,21 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ +#include "CEGUI/Vertex.h" -#ifndef _CEGUIOpenGL3StandardShaderFrag_h_ -#define _CEGUIOpenGL3StandardShaderFrag_h_ +#include namespace CEGUI { -const char StandardShaderFrag[] = - "#version 150 core\n" - "uniform sampler2D texture0;\n" - - "in vec2 exTexCoord;\n" - "in vec4 exColour;\n" - - "out vec4 out0;\n" +void TexturedColouredVertex::setColour(const Colour& colour) +{ + d_colour = glm::vec4(colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha()); +} - "void main(void)\n" - "{\n" - "out0 = texture(texture0, exTexCoord) * exColour;\n" - "}" - ; +void ColouredVertex::setColour(const Colour& colour) +{ + d_colour = glm::vec4(colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha()); } -#endif \ No newline at end of file + +} \ No newline at end of file diff --git a/cegui/src/Win32ClipboardProvider.cpp b/cegui/src/Win32ClipboardProvider.cpp new file mode 100644 index 000000000..a83d619a1 --- /dev/null +++ b/cegui/src/Win32ClipboardProvider.cpp @@ -0,0 +1,119 @@ +/*********************************************************************** + created: 19/09/2013 + author: Alexander Gladis + + purpose: Implement a clipboard provider for Windows +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include +#include "CEGUI/CEGUI.h" +#include "CEGUI/Win32ClipboardProvider.h" + +namespace CEGUI +{ + +Win32ClipboardProvider::Win32ClipboardProvider() : + d_buffer(0), + d_bufferSize(0) +{ +} + +Win32ClipboardProvider::~Win32ClipboardProvider() +{ + deallocateBuffer(); +} + +void Win32ClipboardProvider::allocateBuffer(size_t size) +{ + if(d_buffer) + delete[] d_buffer; + + d_buffer = new char[size]; + d_bufferSize = size; +} + +void Win32ClipboardProvider::deallocateBuffer() +{ + delete[] d_buffer; + d_buffer = 0; + d_bufferSize = 0; +} + +void Win32ClipboardProvider::sendToClipboard(const String& mime_type, void* buffer, size_t size) +{ + if(mime_type == "text/plain") + { + if(OpenClipboard(0)) + { + // Transcode buffer to UTF-16 +#if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UNICODE + String str(static_cast(buffer), size); +#else + String str(static_cast(buffer), size); +#endif + uint16* str_utf16 = System::getSingleton().getStringTranscoder().stringToUTF16(str); + size_t size_in_bytes = (str.size() + 1) * sizeof(uint16); + + // Copy to clipboard + EmptyClipboard(); + HGLOBAL clipboard_data = GlobalAlloc(GMEM_DDESHARE,size_in_bytes); + LPWSTR clipboard = static_cast(GlobalLock(clipboard_data)); + if(clipboard) + memcpy(clipboard, str_utf16, size_in_bytes); + GlobalUnlock(clipboard_data); + SetClipboardData(CF_UNICODETEXT, clipboard_data); + CloseClipboard(); + + // Free temporary UTF-16 buffer + System::getSingleton().getStringTranscoder().deleteUTF16Buffer(str_utf16); + } + } +} + +void Win32ClipboardProvider::retrieveFromClipboard(String& mime_type, void*& buffer, size_t& size) +{ + if(OpenClipboard(0)) + { + // Open & read UTF-16 clipboard data + HGLOBAL clipboard_data = GetClipboardData(CF_UNICODETEXT); + const uint16* clipboard = static_cast(GlobalLock(clipboard_data)); + if(clipboard) + { + // Transcode UTF-16 to native format and copy to local buffer + String str = System::getSingleton().getStringTranscoder().stringFromUTF16(clipboard); + allocateBuffer(strlen(str.c_str())); // We need the actual byte count which can be different from str.size() when using UTF-8! + memcpy(d_buffer, str.c_str(), d_bufferSize); + + mime_type = "text/plain"; + buffer = d_buffer; + size = d_bufferSize; + } + + // Close clipboard + GlobalUnlock(clipboard_data); + CloseClipboard(); + } +} + +} diff --git a/cegui/src/Win32StringTranscoder.cpp b/cegui/src/Win32StringTranscoder.cpp index 8d45cb3c7..edbf51170 100644 --- a/cegui/src/Win32StringTranscoder.cpp +++ b/cegui/src/Win32StringTranscoder.cpp @@ -46,7 +46,7 @@ uint16* Win32StringTranscoder::stringToUTF16(const String& input) const CEGUI_THROW(CEGUI::InvalidRequestException( "MultiByteToWideChar failed")); - uint16* buff = CEGUI_NEW_ARRAY_PT(uint16, len, CEGUI::BufferAllocator); + uint16* buff = new uint16[len]; MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, reinterpret_cast(buff), len); @@ -76,15 +76,14 @@ static CEGUI::String stringFromUTF16(UINT codepage, const uint16* input) CEGUI_THROW(CEGUI::InvalidRequestException( "WideCharToMultiByte failed")); - T* buff = - CEGUI_NEW_ARRAY_PT(T, len, CEGUI::BufferAllocator); + T* buff = new T[len]; WideCharToMultiByte(codepage, 0, reinterpret_cast(input), -1, reinterpret_cast(buff), len, 0, 0); const CEGUI::String result(buff); - CEGUI_DELETE_ARRAY_PT(buff, T, len, CEGUI::BufferAllocator); + delete[] buff; return result; } @@ -111,7 +110,7 @@ void Win32StringTranscoder::deleteUTF16Buffer(uint16* input) const const uint16* b = input; while (*b++); - CEGUI_DELETE_ARRAY_PT(input, uint16, b - input, CEGUI::BufferAllocator); + delete[] input; } //----------------------------------------------------------------------------// diff --git a/cegui/src/Window.cpp b/cegui/src/Window.cpp index aa8a1d115..aae8b2ff6 100644 --- a/cegui/src/Window.cpp +++ b/cegui/src/Window.cpp @@ -32,7 +32,7 @@ #include "CEGUI/System.h" #include "CEGUI/FontManager.h" #include "CEGUI/ImageManager.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/CoordConverter.h" #include "CEGUI/WindowRendererManager.h" #include "CEGUI/WindowFactoryManager.h" @@ -97,20 +97,16 @@ const String Window::EventWindowRendererAttached("WindowRendererAttached"); const String Window::EventWindowRendererDetached("WindowRendererDetached"); const String Window::EventTextParsingChanged("TextParsingChanged"); const String Window::EventMarginChanged("MarginChanged"); -const String Window::EventMouseEntersArea("MouseEntersArea"); -const String Window::EventMouseLeavesArea("MouseLeavesArea"); -const String Window::EventMouseEntersSurface( "MouseEntersSurface" ); -const String Window::EventMouseLeavesSurface( "MouseLeavesSurface" ); -const String Window::EventMouseMove("MouseMove"); -const String Window::EventMouseWheel("MouseWheel"); -const String Window::EventMouseButtonDown("MouseButtonDown"); -const String Window::EventMouseButtonUp("MouseButtonUp"); -const String Window::EventMouseClick("MouseClick"); -const String Window::EventMouseDoubleClick("MouseDoubleClick"); -const String Window::EventMouseTripleClick("MouseTripleClick"); -const String Window::EventKeyDown("KeyDown"); -const String Window::EventKeyUp("KeyUp"); +const String Window::EventCursorEntersArea("CursorEntersArea"); +const String Window::EventCursorLeavesArea("CursorLeavesArea"); +const String Window::EventCursorEntersSurface("CursorEntersSurface"); +const String Window::EventCursorLeavesSurface("CursorLeavesSurface"); +const String Window::EventCursorMove("CursorMove"); +const String Window::EventCursorPressHold("CursorPressHold"); +const String Window::EventCursorActivate("CursorActivate"); const String Window::EventCharacterKey("CharacterKey"); +const String Window::EventScroll("Scroll"); +const String Window::EventSemanticEvent("SemanticEvent"); //----------------------------------------------------------------------------// // XML element and attribute names that relate to Window. @@ -196,17 +192,16 @@ Window::Window(const String& type, const String& name): // rendering components and options d_windowRenderer(0), - d_geometry(&System::getSingleton().getRenderer()->createGeometryBuffer()), d_surface(0), d_needsRedraw(true), d_autoRenderingWindow(false), - d_mouseCursor(0), + d_cursor(0), // alpha transparency set up d_alpha(1.0f), d_inheritsAlpha(true), - // mouse input capture set up + // cursor input capture set up d_oldCapture(0), d_restoreOldCapture(false), d_distCapturedInputs(false), @@ -216,9 +211,9 @@ Window::Window(const String& type, const String& name): #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), + d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), + d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif @@ -236,16 +231,14 @@ Window::Window(const String& type, const String& name): // z-order related options d_alwaysOnTop(false), - d_riseOnClick(true), + d_riseOnPointerActivation(true), d_zOrderingEnabled(true), - // mouse input options - d_wantsMultiClicks(true), - d_mousePassThroughEnabled(false), + d_cursorPassThroughEnabled(false), d_autoRepeat(false), d_repeatDelay(0.3f), d_repeatRate(0.06f), - d_repeatButton(NoButton), + d_repeatPointerSource(CIS_None), d_repeating(false), d_repeatElapsed(0.0f), @@ -273,13 +266,13 @@ Window::Window(const String& type, const String& name): // Initial update mode d_updateMode(WUM_VISIBLE), - // Don't propagate mouse inputs by default. - d_propagateMouseInputs(false), + // Don't propagate cursor inputs by default. + d_propagatePointerInputs(false), d_guiContext(0), - d_containsMouse(false), - + d_containsPointer(false), + d_isFocused(false), d_fontRenderSizeChangeConnection( GlobalEventSet::getSingleton().subscribeEvent( "Font/RenderSizeChanged", @@ -293,9 +286,9 @@ Window::Window(const String& type, const String& name): Window::~Window(void) { // most cleanup actually happened earlier in Window::destroy. + destroyGeometryBuffers(); - System::getSingleton().getRenderer()->destroyGeometryBuffer(*d_geometry); - CEGUI_DELETE_AO d_bidiVisualMapping; + delete d_bidiVisualMapping; } //----------------------------------------------------------------------------// @@ -435,7 +428,7 @@ const Window* Window::getActiveChild(void) const // don't need full backward scan for activeness as we already know // 'this' is active. NB: This uses the draw-ordered child list, as that // should be quicker in most cases. - + const Window* wnd = *it; if (wnd->d_active) return wnd->getActiveChild(); @@ -526,7 +519,7 @@ Rectf Window::getParentElementClipIntersection(const Rectf& unclipped_area) cons return unclipped_area.getIntersection( (d_parent && d_clippedByParent) ? getParent()->getClipRect(isNonClient()) : - Rectf(Vector2f(0, 0), getRootContainerSize())); + Rectf(glm::vec2(0, 0), getRootContainerSize())); } //----------------------------------------------------------------------------// @@ -569,12 +562,12 @@ Rectf Window::getHitTestRect_impl() const else { return getUnclippedOuterRect().get().getIntersection( - Rectf(Vector2f(0, 0), getRootContainerSize())); + Rectf(glm::vec2(0, 0), getRootContainerSize())); } } //----------------------------------------------------------------------------// -bool Window::isHit(const Vector2f& position, const bool allow_disabled) const +bool Window::isHit(const glm::vec2& position, const bool allow_disabled) const { // cannot be hit if we are disabled. if (!allow_disabled && isEffectiveDisabled()) @@ -589,17 +582,17 @@ bool Window::isHit(const Vector2f& position, const bool allow_disabled) const } //----------------------------------------------------------------------------// -Window* Window::getChildAtPosition(const Vector2f& position) const +Window* Window::getChildAtPosition(const glm::vec2& position) const { return getChildAtPosition(position, &Window::isHit); } //----------------------------------------------------------------------------// -Window* Window::getChildAtPosition(const Vector2f& position, - bool (Window::*hittestfunc)(const Vector2f&, bool) const, +Window* Window::getChildAtPosition(const glm::vec2& position, + bool (Window::*hittestfunc)(const glm::vec2&, bool) const, bool allow_disabled) const { - Vector2f p; + glm::vec2 p; // if the window has RenderingWindow backing if (d_surface && d_surface->isRenderingWindow()) static_cast(d_surface)->unprojectPoint(position, p); @@ -616,7 +609,7 @@ Window* Window::getChildAtPosition(const Vector2f& position, // recursively scan for hit on children of this child window... if (Window* const wnd = (*child)->getChildAtPosition(p, hittestfunc, allow_disabled)) return wnd; - // see if this child is hit and return it's pointer if it is + // see if this child is hit and return it's cursor if it is else if (((*child)->*hittestfunc)(p, allow_disabled)) return *child; } @@ -627,16 +620,16 @@ Window* Window::getChildAtPosition(const Vector2f& position, } //----------------------------------------------------------------------------// -Window* Window::getTargetChildAtPosition(const Vector2f& position, +Window* Window::getTargetChildAtPosition(const glm::vec2& position, const bool allow_disabled) const { return getChildAtPosition(position, &Window::isHitTargetWindow, allow_disabled); } //----------------------------------------------------------------------------// -bool Window::isHitTargetWindow(const Vector2f& position, bool allow_disabled) const +bool Window::isHitTargetWindow(const glm::vec2& position, bool allow_disabled) const { - return !isMousePassThroughEnabled() && isHit(position, allow_disabled); + return !isCursorPassThroughEnabled() && isHit(position, allow_disabled); } //----------------------------------------------------------------------------// @@ -688,7 +681,7 @@ void Window::setEnabled(bool setting) onDisabled(args); } - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); } //----------------------------------------------------------------------------// @@ -708,7 +701,7 @@ void Window::setVisible(bool setting) WindowEventArgs args(this); d_visible ? onShown(args) : onHidden(args); - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); } //----------------------------------------------------------------------------// @@ -873,7 +866,7 @@ bool Window::moveToFront_impl(bool wasClicked) // bring us to the front of our siblings if (d_zOrderingEnabled && - (!wasClicked || d_riseOnClick) && + (!wasClicked || d_riseOnPointerActivation) && !isTopOfZOrder()) { took_action = true; @@ -1026,12 +1019,6 @@ void Window::setInheritsAlpha(bool setting) } } -//----------------------------------------------------------------------------// -void Window::invalidate(void) -{ - invalidate(false); -} - //----------------------------------------------------------------------------// void Window::invalidate(const bool recursive) { @@ -1062,7 +1049,7 @@ void Window::render() // don't do anything if window is not visible if (!isEffectiveVisible()) return; - + // get rendering context RenderingContext ctx; getRenderingContext(ctx); @@ -1102,7 +1089,7 @@ void Window::bufferGeometry(const RenderingContext&) if (d_needsRedraw) { // dispose of already cached geometry. - d_geometry->reset(); + destroyGeometryBuffers(); // signal rendering started WindowEventArgs args(this); @@ -1117,6 +1104,10 @@ void Window::bufferGeometry(const RenderingContext&) else populateGeometryBuffer(); + updateGeometryBuffersTranslationAndClipping(); + + updateGeometryBuffersAlpha(); + // signal rendering ended args.handled = 0; onRenderingEnded(args); @@ -1130,7 +1121,7 @@ void Window::bufferGeometry(const RenderingContext&) void Window::queueGeometry(const RenderingContext& ctx) { // add geometry so that it gets drawn to the target surface. - ctx.surface->addGeometryBuffer(ctx.queue, *d_geometry); + ctx.surface->addGeometryBuffers(ctx.queue, d_geometryBuffers); } //----------------------------------------------------------------------------// @@ -1179,16 +1170,16 @@ void Window::cleanupChildren(void) void Window::addChild_impl(Element* element) { Window* wnd = dynamic_cast(element); - + if (!wnd) CEGUI_THROW(InvalidRequestException( "Window can only have Elements of type Window added as children " "(Window path: " + getNamePath() + ").")); - + // if the element is already a child of this Window, this is a NOOP if (isChild(element)) return; - + NamedElement::addChild_impl(wnd); addWindowToDrawList(*wnd); @@ -1212,7 +1203,7 @@ void Window::removeChild_impl(Element* element) removeWindowFromDrawList(*wnd); Element::removeChild_impl(wnd); - + // find this window in the child list const ChildList::iterator position = std::find(d_children.begin(), d_children.end(), wnd); @@ -1223,7 +1214,7 @@ void Window::removeChild_impl(Element* element) // unban properties window could write as a root window wnd->unbanPropertyFromXML("RestoreOldCapture"); } - + wnd->onZChange_impl(); } @@ -1247,32 +1238,32 @@ void Window::onZChange_impl(void) } - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); } //----------------------------------------------------------------------------// -const Image* Window::getMouseCursor(bool useDefault) const +const Image* Window::getCursor(bool useDefault) const { - if (d_mouseCursor) - return d_mouseCursor; + if (d_cursor) + return d_cursor; else - return useDefault ? getGUIContext().getMouseCursor().getDefaultImage() : 0; + return useDefault ? getGUIContext().getCursor().getDefaultImage() : 0; } //----------------------------------------------------------------------------// -void Window::setMouseCursor(const String& name) +void Window::setCursor(const String& name) { - setMouseCursor( + setCursor( &ImageManager::getSingleton().get(name)); } //----------------------------------------------------------------------------// -void Window::setMouseCursor(const Image* image) +void Window::setCursor(const Image* image) { - d_mouseCursor = image; + d_cursor = image; - if (getGUIContext().getWindowContainingMouse() == this) - getGUIContext().getMouseCursor().setImage(image); + if (getGUIContext().getWindowContainingCursor() == this) + getGUIContext().getCursor().setImage(image); } //----------------------------------------------------------------------------// @@ -1300,16 +1291,15 @@ void Window::setDestroyedByParent(bool setting) } //----------------------------------------------------------------------------// -void Window::generateAutoRepeatEvent(MouseButton button) +void Window::generateAutoRepeatEvent(CursorInputSource source) { - MouseEventArgs ma(this); - ma.position = getUnprojectedPosition( - getGUIContext().getMouseCursor().getPosition()); - ma.moveDelta = Vector2f(0.0f, 0.0f); - ma.button = button; - ma.sysKeys = getGUIContext().getSystemKeys().get(); - ma.wheelChange = 0; - onMouseButtonDown(ma); + CursorInputEventArgs ciea(this); + ciea.position = getUnprojectedPosition( + getGUIContext().getCursor().getPosition()); + ciea.moveDelta = glm::vec2(0, 0); + ciea.source = source; + ciea.scroll = 0; + onCursorPressHold(ciea); } //----------------------------------------------------------------------------// @@ -1358,8 +1348,8 @@ void Window::addWindowProperties(void) ); CEGUI_DEFINE_PROPERTY(Window, Image*, - "MouseCursorImage","Property to get/set the mouse cursor image for the Window. Value should be \"\".", - &Window::setMouseCursor, &Window::property_getMouseCursor, 0 + "CursorImage","Property to get/set the cursor image for the Window. Value should be \"\".", + &Window::setCursor, &Window::property_getCursor, 0 ); CEGUI_DEFINE_PROPERTY(Window, bool, @@ -1383,13 +1373,8 @@ void Window::addWindowProperties(void) ); CEGUI_DEFINE_PROPERTY(Window, bool, - "WantsMultiClickEvents", "Property to get/set whether the window will receive double-click and triple-click events. Value is either \"true\" or \"false\".", - &Window::setWantsMultiClickEvents, &Window::wantsMultiClickEvents, true - ); - - CEGUI_DEFINE_PROPERTY(Window, bool, - "MouseAutoRepeatEnabled", "Property to get/set whether the window will receive autorepeat mouse button down events. Value is either \"true\" or \"false\".", - &Window::setMouseAutoRepeatEnabled, &Window::isMouseAutoRepeatEnabled, false + "CursorAutoRepeatEnabled", "Property to get/set whether the window will receive autorepeat cursor press events. Value is either \"true\" or \"false\".", + &Window::setCursorAutoRepeatEnabled, &Window::isCursorAutoRepeatEnabled, false ); CEGUI_DEFINE_PROPERTY(Window, float, @@ -1424,14 +1409,14 @@ void Window::addWindowProperties(void) CEGUI_DEFINE_PROPERTY(Window, bool, "RiseOnClickEnabled", "Property to get/set whether the window will come to the top of the Z-order when clicked. Value is either \"true\" or \"false\".", - &Window::setRiseOnClickEnabled, &Window::isRiseOnClickEnabled, true + &Window::setRiseOnClickEnabled, &Window::isRiseOnPointerActivationEnabled, true ); CEGUI_DEFINE_PROPERTY(Window, bool, - "MousePassThroughEnabled", "Property to get/set whether the window ignores mouse events and pass them through to any windows behind it. Value is either \"true\" or \"false\".", - &Window::setMousePassThroughEnabled, &Window::isMousePassThroughEnabled, false + "CursorPassThroughEnabled", "Property to get/set whether the window ignores cursor events and pass them through to any windows behind it. Value is either \"true\" or \"false\".", + &Window::setCursorPassThroughEnabled, &Window::isCursorPassThroughEnabled, false ); - + addProperty(&d_windowRendererProperty); addProperty(&d_lookNFeelProperty); @@ -1449,19 +1434,19 @@ void Window::addWindowProperties(void) " Value is either \"true\" or \"false\".", &Window::setUsingAutoRenderingSurface, &Window::isUsingAutoRenderingSurface, false /* TODO: Inconsistency*/ ); - + CEGUI_DEFINE_PROPERTY(Window, bool, "TextParsingEnabled", "Property to get/set the text parsing setting for the Window. " "Value is either \"true\" or \"false\".", &Window::setTextParsingEnabled, &Window::isTextParsingEnabled, true ); - + CEGUI_DEFINE_PROPERTY(Window, UBox, "Margin", "Property to get/set margin for the Window. Value format:" "{top:{[tops],[topo]},left:{[lefts],[lefto]},bottom:{[bottoms],[bottomo]},right:{[rights],[righto]}}.", &Window::setMargin, &Window::getMargin, UBox(UDim(0, 0)) ); - + CEGUI_DEFINE_PROPERTY(Window, WindowUpdateMode, "UpdateMode", "Property to get/set the window update mode setting. " "Value is one of \"Always\", \"Never\" or \"Visible\".", @@ -1469,10 +1454,10 @@ void Window::addWindowProperties(void) ); CEGUI_DEFINE_PROPERTY(Window, bool, - "MouseInputPropagationEnabled", "Property to get/set whether unhandled mouse inputs should be " + "CursorInputPropagationEnabled", "Property to get/set whether unhandled cursor inputs should be " "propagated back to the Window's parent. " "Value is either \"true\" or \"false\".", - &Window::setMouseInputPropagationEnabled, &Window::isMouseInputPropagationEnabled, false + &Window::setCursorInputPropagationEnabled, &Window::isCursorInputPropagationEnabled, false ); CEGUI_DEFINE_PROPERTY(Window, bool, @@ -1497,19 +1482,7 @@ void Window::setZOrderingEnabled(bool setting) } //----------------------------------------------------------------------------// -bool Window::wantsMultiClickEvents(void) const -{ - return d_wantsMultiClicks; -} - -//----------------------------------------------------------------------------// -void Window::setWantsMultiClickEvents(bool setting) -{ - d_wantsMultiClicks = setting; -} - -//----------------------------------------------------------------------------// -bool Window::isMouseAutoRepeatEnabled(void) const +bool Window::isCursorAutoRepeatEnabled(void) const { return d_autoRepeat; } @@ -1527,16 +1500,16 @@ float Window::getAutoRepeatRate(void) const } //----------------------------------------------------------------------------// -void Window::setMouseAutoRepeatEnabled(bool setting) +void Window::setCursorAutoRepeatEnabled(bool setting) { if (d_autoRepeat == setting) return; d_autoRepeat = setting; - d_repeatButton = NoButton; + d_repeatPointerSource = CIS_None; // FIXME: There is a potential issue here if this setting is - // FIXME: changed _while_ the mouse is auto-repeating, and + // FIXME: changed _while_ the cursor is auto-repeating, and // FIXME: the 'captured' state of input could get messed up. // FIXME: The alternative is to always release here, but that // FIXME: has a load of side effects too - so for now nothing @@ -1560,7 +1533,7 @@ void Window::setAutoRepeatRate(float rate) //----------------------------------------------------------------------------// void Window::update(float elapsed) -{ +{ // perform update for 'this' Window updateSelf(elapsed); @@ -1587,8 +1560,8 @@ void Window::update(float elapsed) //----------------------------------------------------------------------------// void Window::updateSelf(float elapsed) { - // Mouse button autorepeat processing. - if (d_autoRepeat && d_repeatButton != NoButton) + // cursor autorepeat processing. + if (d_autoRepeat && d_repeatPointerSource != CIS_None) { d_repeatElapsed += elapsed; @@ -1598,7 +1571,7 @@ void Window::updateSelf(float elapsed) { d_repeatElapsed -= d_repeatRate; // trigger the repeated event - generateAutoRepeatEvent(d_repeatButton); + generateAutoRepeatEvent(d_repeatPointerSource); } } else @@ -1608,7 +1581,7 @@ void Window::updateSelf(float elapsed) d_repeatElapsed = 0; d_repeating = true; // trigger the repeated event - generateAutoRepeatEvent(d_repeatButton); + generateAutoRepeatEvent(d_repeatPointerSource); } } } @@ -1639,6 +1612,20 @@ bool Window::performPaste(Clipboard& /*clipboard*/) return false; } +//----------------------------------------------------------------------------// +bool Window::performUndo() +{ + // deny undo by default + return false; +} + +//----------------------------------------------------------------------------// +bool Window::performRedo() +{ + // deny redo by default + return false; +} + //----------------------------------------------------------------------------// bool Window::distributesCapturedInputs(void) const { @@ -1751,7 +1738,7 @@ bool Window::isUsingDefaultTooltip(void) const //----------------------------------------------------------------------------// Tooltip* Window::getTooltip(void) const { - return isUsingDefaultTooltip() ? + return isUsingDefaultTooltip() ? getGUIContext().getDefaultTooltipObject(): d_customTip; } @@ -1844,7 +1831,7 @@ void Window::setArea_impl(const UVector2& pos, const USize& size, //if (moved || sized) // FIXME: This is potentially wasteful - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); // update geometry position and clipping if nothing from above appears to // have done so already (NB: may be occasionally wasteful, but fixes bugs!) @@ -2217,7 +2204,7 @@ void Window::onSized(ElementEventArgs& e) void Window::onMoved(ElementEventArgs& e) { Element::onMoved(e); - + // handle invalidation of surfaces and trigger needed redraws if (d_parent) { @@ -2263,7 +2250,10 @@ void Window::onAlphaChanged(WindowEventArgs& e) } - invalidate(); + updateGeometryBuffersAlpha(); + invalidateRenderingSurface(); + getGUIContext().markAsDirty(); + fireEvent(EventAlphaChanged, e, EventNamespace); } @@ -2369,7 +2359,7 @@ void Window::onCaptureGained(WindowEventArgs& e) void Window::onCaptureLost(WindowEventArgs& e) { // reset auto-repeat state - d_repeatButton = NoButton; + d_repeatPointerSource = CIS_None; // handle restore of previous capture window as required. if (d_restoreOldCapture && (d_oldCapture != 0)) { @@ -2377,10 +2367,14 @@ void Window::onCaptureLost(WindowEventArgs& e) d_oldCapture = 0; } - // handle case where mouse is now in a different window - // (this is a bit of a hack that uses the mouse input injector to handle + // handle case where cursor is now in a different window + // (this is a bit of a hack that uses the injection of a semantic event to handle // this for us). - getGUIContext().injectMouseMove(0, 0); + SemanticInputEvent moveEvent(SV_CursorMove); + const glm::vec2 cursorPosition = getGUIContext().getCursor().getPosition(); + moveEvent.d_payload.array[0] = cursorPosition.x; + moveEvent.d_payload.array[1] = cursorPosition.y; + getGUIContext().injectInputEvent(moveEvent); fireEvent(EventInputCaptureLost, e, EventNamespace); } @@ -2466,7 +2460,7 @@ void Window::onChildAdded(ElementEventArgs& e) // we no longer want a total redraw here, instead we just get each window // to resubmit it's imagery to the Renderer. getGUIContext().markAsDirty(); - + Element::onChildAdded(e); } @@ -2478,217 +2472,157 @@ void Window::onChildRemoved(ElementEventArgs& e) getGUIContext().markAsDirty(); // Though we do need to invalidate the rendering surface! getTargetRenderingSurface().invalidate(); - + Element::onChildRemoved(e); } //----------------------------------------------------------------------------// -void Window::onMouseEntersArea(MouseEventArgs& e) +void Window::onCursorEntersArea(CursorInputEventArgs& e) { - d_containsMouse = true; - fireEvent(EventMouseEntersArea, e, EventNamespace); + d_containsPointer = true; + fireEvent(EventCursorEntersArea, e, EventNamespace); } //----------------------------------------------------------------------------// -void Window::onMouseLeavesArea(MouseEventArgs& e) +void Window::onCursorLeavesArea(CursorInputEventArgs& e) { - d_containsMouse = false; - fireEvent(EventMouseLeavesArea, e, EventNamespace); + d_containsPointer = false; + fireEvent(EventCursorLeavesArea, e, EventNamespace); } //----------------------------------------------------------------------------// -void Window::onMouseEnters(MouseEventArgs& e) +void Window::onCursorEnters(CursorInputEventArgs& e) { - // set the mouse cursor - getGUIContext(). - getMouseCursor().setImage(getMouseCursor()); + // set the cursor + getGUIContext().getCursor().setImage(getCursor()); // perform tooltip control Tooltip* const tip = getTooltip(); if (tip && !isAncestor(tip)) tip->setTargetWindow(this); - fireEvent(EventMouseEntersSurface, e, EventNamespace); + fireEvent(EventCursorEntersSurface, e, EventNamespace); } //----------------------------------------------------------------------------// -void Window::onMouseLeaves(MouseEventArgs& e) +void Window::onCursorLeaves(CursorInputEventArgs& e) { // perform tooltip control - const Window* const mw = getGUIContext().getWindowContainingMouse(); + const Window* const mw = getGUIContext().getWindowContainingCursor(); Tooltip* const tip = getTooltip(); if (tip && mw != tip && !(mw && mw->isAncestor(tip))) tip->setTargetWindow(0); - fireEvent(EventMouseLeavesSurface, e, EventNamespace); + fireEvent(EventCursorLeavesSurface, e, EventNamespace); } //----------------------------------------------------------------------------// -void Window::onMouseMove(MouseEventArgs& e) +void Window::onCursorMove(CursorInputEventArgs& e) { // perform tooltip control Tooltip* const tip = getTooltip(); if (tip) tip->resetTimer(); - fireEvent(EventMouseMove, e, EventNamespace); + fireEvent(EventCursorMove, e, EventNamespace); // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && + if (!e.handled && d_propagatePointerInputs && d_parent && this != getGUIContext().getModalWindow()) { e.window = getParent(); - getParent()->onMouseMove(e); + getParent()->onCursorMove(e); return; } - // by default we now mark mouse events as handled + // by default we now mark cursor events as handled // (derived classes may override, of course!) ++e.handled; } //----------------------------------------------------------------------------// -void Window::onMouseWheel(MouseEventArgs& e) +void Window::onScroll(CursorInputEventArgs& e) { - fireEvent(EventMouseWheel, e, EventNamespace); + fireEvent(EventScroll, e, EventNamespace); // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && + if (!e.handled && d_propagatePointerInputs && d_parent && this != getGUIContext().getModalWindow()) { e.window = getParent(); - getParent()->onMouseWheel(e); + getParent()->onScroll(e); return; } - // by default we now mark mouse events as handled + // by default we now mark cursor events as handled // (derived classes may override, of course!) ++e.handled; } //----------------------------------------------------------------------------// -void Window::onMouseButtonDown(MouseEventArgs& e) +void Window::onCursorPressHold(CursorInputEventArgs& e) { // perform tooltip control Tooltip* const tip = getTooltip(); if (tip) tip->setTargetWindow(0); - if ((e.button == LeftButton) && moveToFront_impl(true)) + if ((e.source == CIS_Left) && moveToFront_impl(true)) ++e.handled; // if auto repeat is enabled and we are not currently tracking - // the button that was just pushed (need this button check because + // the source that was just pushed (need this source check because // it could be us that generated this event via auto-repeat). if (d_autoRepeat) { - if (d_repeatButton == NoButton) + if (d_repeatPointerSource == CIS_None) captureInput(); - if ((d_repeatButton != e.button) && isCapturedByThis()) + if ((d_repeatPointerSource != e.source) && isCapturedByThis()) { - d_repeatButton = e.button; + d_repeatPointerSource = e.source; d_repeatElapsed = 0; d_repeating = false; } } - fireEvent(EventMouseButtonDown, e, EventNamespace); + fireEvent(EventCursorPressHold, e, EventNamespace); // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && + if (!e.handled && d_propagatePointerInputs && d_parent && this != getGUIContext().getModalWindow()) { e.window = getParent(); - getParent()->onMouseButtonDown(e); + getParent()->onCursorPressHold(e); return; } - // by default we now mark mouse events as handled + // by default we now mark cursor events as handled // (derived classes may override, of course!) ++e.handled; } //----------------------------------------------------------------------------// -void Window::onMouseButtonUp(MouseEventArgs& e) +void Window::onCursorActivate(CursorInputEventArgs& e) { // reset auto-repeat state - if (d_autoRepeat && d_repeatButton != NoButton) + if (d_autoRepeat && d_repeatPointerSource != CIS_None) { releaseInput(); - d_repeatButton = NoButton; - } - - fireEvent(EventMouseButtonUp, e, EventNamespace); - - // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && - d_parent && this != getGUIContext().getModalWindow()) - { - e.window = getParent(); - getParent()->onMouseButtonUp(e); - - return; - } - - // by default we now mark mouse events as handled - // (derived classes may override, of course!) - ++e.handled; -} - -//----------------------------------------------------------------------------// -void Window::onMouseClicked(MouseEventArgs& e) -{ - fireEvent(EventMouseClick, e, EventNamespace); - - // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && - d_parent && this != getGUIContext().getModalWindow()) - { - e.window = getParent(); - getParent()->onMouseClicked(e); - - return; - } - - // if event was directly injected, mark as handled to be consistent with - // other mouse button injectors - if (!getGUIContext().isMouseClickEventGenerationEnabled()) - ++e.handled; -} - -//----------------------------------------------------------------------------// -void Window::onMouseDoubleClicked(MouseEventArgs& e) -{ - fireEvent(EventMouseDoubleClick, e, EventNamespace); - - // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && - d_parent && this != getGUIContext().getModalWindow()) - { - e.window = getParent(); - getParent()->onMouseDoubleClicked(e); - - return; + d_repeatPointerSource = CIS_None; } - ++e.handled; -} - -//----------------------------------------------------------------------------// -void Window::onMouseTripleClicked(MouseEventArgs& e) -{ - fireEvent(EventMouseTripleClick, e, EventNamespace); + fireEvent(EventCursorActivate, e, EventNamespace); // optionally propagate to parent - if (!e.handled && d_propagateMouseInputs && + if (!e.handled && d_propagatePointerInputs && d_parent && this != getGUIContext().getModalWindow()) { e.window = getParent(); - getParent()->onMouseTripleClicked(e); + getParent()->onCursorActivate(e); return; } @@ -2697,50 +2631,33 @@ void Window::onMouseTripleClicked(MouseEventArgs& e) } //----------------------------------------------------------------------------// -void Window::onKeyDown(KeyEventArgs& e) +void Window::onCharacter(TextEventArgs& e) { - fireEvent(EventKeyDown, e, EventNamespace); + fireEvent(EventCharacterKey, e, EventNamespace); // As of 0.7.0 CEGUI::System no longer does input event propogation, so by // default we now do that here. Generally speaking key handling widgets - // may need to override this behaviour to halt further propogation. + // may need to override this behaviour to halt further propagation. if (!e.handled && d_parent && this != getGUIContext().getModalWindow()) { e.window = getParent(); - getParent()->onKeyDown(e); + getParent()->onCharacter(e); } } //----------------------------------------------------------------------------// -void Window::onKeyUp(KeyEventArgs& e) +void Window::onSemanticInputEvent(SemanticEventArgs& e) { - fireEvent(EventKeyUp, e, EventNamespace); + fireEvent(EventSemanticEvent, e, EventNamespace); - // As of 0.7.0 CEGUI::System no longer does input event propogation, so by - // default we now do that here. Generally speaking key handling widgets - // may need to override this behaviour to halt further propogation. - if (!e.handled && d_parent && - this != getGUIContext().getModalWindow()) + // optionally propagate to parent + if (!e.handled && d_parent && this != getGUIContext().getModalWindow()) { e.window = getParent(); - getParent()->onKeyUp(e); - } -} + getParent()->onSemanticInputEvent(e); -//----------------------------------------------------------------------------// -void Window::onCharacter(KeyEventArgs& e) -{ - fireEvent(EventCharacterKey, e, EventNamespace); - - // As of 0.7.0 CEGUI::System no longer does input event propogation, so by - // default we now do that here. Generally speaking key handling widgets - // may need to override this behaviour to halt further propogation. - if (!e.handled && d_parent && - this != getGUIContext().getModalWindow()) - { - e.window = getParent(); - getParent()->onCharacter(e); + return; } } @@ -2921,31 +2838,24 @@ bool Window::isPropertyAtDefault(const Property* property) const WidgetLookManager::getSingleton(). getWidgetLook(getParent()->getLookNFeel()); - // if this property is a target of a PropertyLink, we always report - // as being at default. NB: This check is only performed on the - // immediate parent. - const WidgetLookFeel::PropertyLinkDefinitionList& pldl(wlf.getPropertyLinkDefinitions()); - WidgetLookFeel::PropertyLinkDefinitionList::const_iterator i = pldl.begin(); - for (; i != pldl.end(); ++i) - { - if ((*i)->getPropertyName() == property->getName()) - return true; - } + // If this property is a target of a PropertyLink, we always report it as being at default. + WidgetLookFeel::StringSet propDefNames = wlf.getPropertyDefinitionNames(true); + if(propDefNames.find(property->getName()) != propDefNames.end()) + return true; // for an auto-window see if the property is is set via a Property // tag within the WidgetComponent that defines it. if (d_autoWindow) { - // find the widget component if possible - const WidgetComponent* const wc = wlf.findWidgetComponent(getName()); - if (wc) + // Check if a widget component with the name was added to the look + if(wlf.isWidgetComponentPresent(getName())) { - const PropertyInitialiser* const propinit = - wc->findPropertyInitialiser(property->getName()); + const WidgetComponent& widgetComp = wlf.getWidgetComponent(getName()); + + const PropertyInitialiser* const propInitialiser = widgetComp.findPropertyInitialiser(property->getName()); - if (propinit) - return (getProperty(property->getName()) == - propinit->getInitialiserValue()); + if (propInitialiser) + return (getProperty(property->getName()) == propInitialiser->getInitialiserValue()); } } } @@ -2997,22 +2907,30 @@ void Window::updateGeometryRenderSettings() if (ctx.owner == this && ctx.surface->isRenderingWindow()) { static_cast(ctx.surface)-> - setPosition(getUnclippedOuterRect().get().getPosition()); + setPosition(getUnclippedOuterRect().get().getPositionGLM()); static_cast(d_surface)->setPivot( - Vector3f(d_pixelSize.d_width / 2.0f, - d_pixelSize.d_height / 2.0f, - 0.0f)); - d_geometry->setTranslation(Vector3f(0.0f, 0.0f, 0.0f)); + glm::vec3( + d_pixelSize.d_width / 2.0f, + d_pixelSize.d_height / 2.0f, + 0.0f + ) + ); + + d_translation = glm::vec3(0, 0, 0); } // if we're not texture backed, update geometry position. else { // position is the offset of the window on the dest surface. const Rectf ucrect(getUnclippedOuterRect().get()); - d_geometry->setTranslation(Vector3f(ucrect.d_min.d_x - ctx.offset.d_x, - ucrect.d_min.d_y - ctx.offset.d_y, 0.0f)); + + d_translation = glm::vec3(ucrect.d_min.d_x - ctx.offset.x, + ucrect.d_min.d_y - ctx.offset.y, + 0.0f); } initialiseClippers(ctx); + + updateGeometryBuffersTranslationAndClipping(); } //----------------------------------------------------------------------------// @@ -3099,9 +3017,9 @@ void Window::appendText(const String& text) } //----------------------------------------------------------------------------// -GeometryBuffer& Window::getGeometryBuffer() +std::vector& Window::getGeometryBuffers() { - return *d_geometry; + return d_geometryBuffers; } //----------------------------------------------------------------------------// @@ -3120,7 +3038,7 @@ void Window::getRenderingContext_impl(RenderingContext& ctx) const { ctx.surface = d_surface; ctx.owner = this; - ctx.offset = getUnclippedOuterRect().get().getPosition(); + ctx.offset = getUnclippedOuterRect().get().getPositionGLM(); ctx.queue = RQ_BASE; } else if (d_parent) @@ -3131,7 +3049,7 @@ void Window::getRenderingContext_impl(RenderingContext& ctx) const { ctx.surface = &getGUIContext(); ctx.owner = 0; - ctx.offset = Vector2f(0, 0); + ctx.offset = glm::vec2(0, 0); ctx.queue = RQ_BASE; } } @@ -3250,7 +3168,7 @@ void Window::allocateRenderingWindow() // set size and position of RenderingWindow static_cast(d_surface)->setSize(getPixelSize()); static_cast(d_surface)-> - setPosition(getUnclippedOuterRect().get().getPosition()); + setPosition(getUnclippedOuterRect().get().getPositionGLM()); getGUIContext().markAsDirty(); } @@ -3307,18 +3225,18 @@ void Window::initialiseClippers(const RenderingContext& ctx) getParent()->getClipRect(d_nonClient)); else rendering_window->setClippingRegion( - Rectf(Vector2f(0, 0), getRootContainerSize())); + Rectf(glm::vec2(0, 0), getRootContainerSize())); - d_geometry->setClippingRegion(Rectf(Vector2f(0, 0), d_pixelSize)); + d_clippingRegion = Rectf(glm::vec2(0, 0), d_pixelSize); } else { Rectf geo_clip(getOuterRectClipper()); if (geo_clip.getWidth() != 0.0f && geo_clip.getHeight() != 0.0f) - geo_clip.offset(Vector2f(-ctx.offset.d_x, -ctx.offset.d_y)); + geo_clip.offset(-ctx.offset); - d_geometry->setClippingRegion(geo_clip); + d_clippingRegion = Rectf(geo_clip); } } @@ -3326,7 +3244,7 @@ void Window::initialiseClippers(const RenderingContext& ctx) void Window::onRotated(ElementEventArgs& e) { Element::onRotated(e); - + // if we have no surface set, enable the auto surface if (!d_surface) { @@ -3361,7 +3279,7 @@ void Window::onRotated(ElementEventArgs& e) // Checks / setup complete! Now we can finally set the rotation. static_cast(d_surface)->setRotation(d_rotation); static_cast(d_surface)->setPivot( - Vector3f(d_pixelSize.d_width / 2.0f, d_pixelSize.d_height / 2.0f, 0.0f)); + glm::vec3(d_pixelSize.d_width / 2.0f, d_pixelSize.d_height / 2.0f, 0.0f)); } //----------------------------------------------------------------------------// @@ -3369,9 +3287,8 @@ const RenderedString& Window::getRenderedString() const { if (!d_renderedStringValid) { - // FIXME: Evil const cast! d_renderedString = getRenderedStringParser().parse( - getTextVisual(), const_cast(getFont()), 0); + getTextVisual(), getFont(), 0); d_renderedStringValid = true; } @@ -3415,7 +3332,7 @@ RenderedStringParser& Window::getRenderedStringParser() const } //----------------------------------------------------------------------------// -Vector2f Window::getUnprojectedPosition(const Vector2f& pos) const +glm::vec2 Window::getUnprojectedPosition(const glm::vec2& pos) const { RenderingSurface* rs = &getTargetRenderingSurface(); @@ -3427,13 +3344,13 @@ Vector2f Window::getUnprojectedPosition(const Vector2f& pos) const RenderingWindow* rw = static_cast(rs); // setup for loop - Vector2f out_pos(pos); + glm::vec2 out_pos(pos); // while there are rendering windows while (rw) { // unproject the point for the current rw - const Vector2f in_pos(out_pos); + const glm::vec2 in_pos(out_pos); rw->unprojectPoint(in_pos, out_pos); // get next rendering window, if any @@ -3580,15 +3497,15 @@ WindowUpdateMode Window::getUpdateMode() const } //----------------------------------------------------------------------------// -void Window::setMouseInputPropagationEnabled(const bool enabled) +void Window::setCursorInputPropagationEnabled(const bool enabled) { - d_propagateMouseInputs = enabled; + d_propagatePointerInputs = enabled; } //----------------------------------------------------------------------------// -bool Window::isMouseInputPropagationEnabled() const +bool Window::isCursorInputPropagationEnabled() const { - return d_propagateMouseInputs; + return d_propagatePointerInputs; } //----------------------------------------------------------------------------// @@ -3612,7 +3529,7 @@ void Window::clonePropertiesTo(Window& target) const { for (PropertySet::PropertyIterator propertyIt = getPropertyIterator(); !propertyIt.isAtEnd(); - ++propertyIt) + ++propertyIt) { const String& propertyName = propertyIt.getCurrentKey(); const String propertyValue = getProperty(propertyName); @@ -3741,14 +3658,14 @@ const Font* Window::property_getFont() const // for this window but we don't return name of the default font when // no font is set. This is IMO more practical. User can always use // getFont() directly to get 0.7 behaviour. - + return getFont(false); } //----------------------------------------------------------------------------// -const Image* Window::property_getMouseCursor() const +const Image* Window::property_getCursor() const { - return getMouseCursor(); + return getCursor(); } //----------------------------------------------------------------------------// @@ -3817,9 +3734,80 @@ bool Window::handleFontRenderSizeChange(const EventArgs& args) } //----------------------------------------------------------------------------// -bool Window::isMouseContainedInArea() const +bool Window::isPointerContainedInArea() const { - return d_containsMouse; + return d_containsPointer; +} + +//----------------------------------------------------------------------------// +bool Window::isFocused() const +{ + return d_isFocused; +} + +//----------------------------------------------------------------------------// +void Window::focus() +{ + if (isDisabled()) + return; + + d_isFocused = true; + + ActivationEventArgs event_args(this); + onActivated(event_args); +} + +//----------------------------------------------------------------------------// +void Window::unfocus() +{ + d_isFocused = false; + + if (d_active) + { + ActivationEventArgs event_args(this); + onDeactivated(event_args); + } +} + +//----------------------------------------------------------------------------// +bool Window::canFocus() +{ + // by default all widgets can be focused if they are not disabled + return !isDisabled(); +} + +//----------------------------------------------------------------------------// +void Window::destroyGeometryBuffers() +{ + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + System::getSingleton().getRenderer()->destroyGeometryBuffer(*d_geometryBuffers.at(i)); + + d_geometryBuffers.clear(); +} + +//----------------------------------------------------------------------------// +void Window::updateGeometryBuffersTranslationAndClipping() +{ + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + { + CEGUI::GeometryBuffer*& currentBuffer = d_geometryBuffers[i]; + currentBuffer->setTranslation(d_translation); + currentBuffer->setClippingRegion(d_clippingRegion); + } +} + +void Window::updateGeometryBuffersAlpha() +{ + float final_alpha = getEffectiveAlpha(); + + const size_t geom_buffer_count = d_geometryBuffers.size(); + for (size_t i = 0; i < geom_buffer_count; ++i) + { + CEGUI::GeometryBuffer*& currentBuffer = d_geometryBuffers[i]; + currentBuffer->setAlpha(final_alpha); + } } //----------------------------------------------------------------------------// diff --git a/cegui/src/WindowFactoryManager.cpp b/cegui/src/WindowFactoryManager.cpp index d77eeb2b9..44d514961 100644 --- a/cegui/src/WindowFactoryManager.cpp +++ b/cegui/src/WindowFactoryManager.cpp @@ -123,7 +123,7 @@ void WindowFactoryManager::removeFactory(const String& name) (*j)->getTypeName() + "' windows."); - CEGUI_DELETE_AO (*j); + delete (*j); d_ownedFactories.erase(j); } } diff --git a/cegui/src/WindowNavigator.cpp b/cegui/src/WindowNavigator.cpp new file mode 100644 index 000000000..1c14c12ee --- /dev/null +++ b/cegui/src/WindowNavigator.cpp @@ -0,0 +1,69 @@ +/*************************************************************************** + * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/WindowNavigator.h" +#include "CEGUI/Window.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +WindowNavigator::WindowNavigator(SemanticMappingsMap mappings, + NavigationStrategy* strategy) : + d_mappings(mappings), + d_strategy(strategy), + d_currentFocusedWindow(0) +{ +} + +//----------------------------------------------------------------------------// +void WindowNavigator::handleSemanticEvent(const SemanticInputEvent& event) +{ + SemanticMappingsMap::const_iterator itor = d_mappings.find(event.d_value); + + if (itor != d_mappings.end()) + { + if (d_currentFocusedWindow != 0) + d_currentFocusedWindow->unfocus(); + + d_currentFocusedWindow = + d_strategy->getWindow(d_currentFocusedWindow, itor->second); + + if (d_currentFocusedWindow != 0) + d_currentFocusedWindow->focus(); + } +} + +//----------------------------------------------------------------------------// +void WindowNavigator::setCurrentFocusedWindow(Window* window) +{ + d_currentFocusedWindow = window; +} + +//----------------------------------------------------------------------------// +Window* WindowNavigator::getCurrentFocusedWindow() +{ + return d_currentFocusedWindow; +} + +//----------------------------------------------------------------------------// +} diff --git a/cegui/src/WindowRenderer.cpp b/cegui/src/WindowRenderer.cpp index c50ed3e79..0388c02b4 100644 --- a/cegui/src/WindowRenderer.cpp +++ b/cegui/src/WindowRenderer.cpp @@ -63,11 +63,10 @@ const WidgetLookFeel& WindowRenderer::getLookNFeel() const *************************************************************************/ Rectf WindowRenderer::getUnclippedInnerRect() const { - const WidgetLookFeel& lf(getLookNFeel()); + const WidgetLookFeel& wlf(getLookNFeel()); - if (lf.isNamedAreaDefined("inner_rect")) - return lf.getNamedArea("inner_rect").getArea(). - getPixelRect(*d_window, d_window->getUnclippedOuterRect().get()); + if(wlf.isNamedAreaPresent("inner_rect", true)) + return wlf.getNamedArea("inner_rect").getArea().getPixelRect(*d_window, d_window->getUnclippedOuterRect().get()); else return d_window->getUnclippedOuterRect().get(); } diff --git a/cegui/src/WindowRendererManager.cpp b/cegui/src/WindowRendererManager.cpp index c22145797..5f31aa0ee 100644 --- a/cegui/src/WindowRendererManager.cpp +++ b/cegui/src/WindowRendererManager.cpp @@ -156,7 +156,7 @@ void WindowRendererManager::removeFactory(const String& name) (*j)->getName() + "' WindowRenderers."); - CEGUI_DELETE_AO (*j); + delete (*j); d_ownedFactories.erase(j); } } diff --git a/cegui/src/WindowRendererSets/Core/Button.cpp b/cegui/src/WindowRendererSets/Core/Button.cpp index 80951b2f3..fd0e7f25e 100644 --- a/cegui/src/WindowRendererSets/Core/Button.cpp +++ b/cegui/src/WindowRendererSets/Core/Button.cpp @@ -58,6 +58,10 @@ namespace CEGUI { state = "Hover"; } + else if (w->isFocused()) + { + state = "Focused"; + } else { state = "Normal"; diff --git a/cegui/src/WindowRendererSets/Core/Editbox.cpp b/cegui/src/WindowRendererSets/Core/Editbox.cpp index 55e986ac7..5e4d5e048 100644 --- a/cegui/src/WindowRendererSets/Core/Editbox.cpp +++ b/cegui/src/WindowRendererSets/Core/Editbox.cpp @@ -116,8 +116,22 @@ void FalagardEditbox::renderBaseImagery(const WidgetLookFeel& wlf) const { Editbox* w = static_cast(d_window); - const StateImagery* imagery = &wlf.getStateImagery( - w->isEffectiveDisabled() ? "Disabled" : (w->isReadOnly() ? "ReadOnly" : "Enabled")); + String state; + + if (w->isEffectiveDisabled()) + state = "Disabled"; + else + { + if (w->isReadOnly()) + state = "ReadOnly"; + else + state = "Enabled"; + + if (w->isFocused()) + state += "Focused"; + } + + const StateImagery* imagery = &wlf.getStateImagery(state); imagery->render(*w); } @@ -233,7 +247,6 @@ void FalagardEditbox::renderTextNoBidi(const WidgetLookFeel& wlf, text_part_rect.d_min.d_y += (text_area.getHeight() - font->getFontHeight()) * 0.5f; ColourRect colours; - const float alpha_comp = d_window->getEffectiveAlpha(); // get unhighlighted text colour (saves accessing property twice) ColourRect unselectedColours; setColourRectToUnselectedTextColour(unselectedColours); @@ -263,25 +276,22 @@ void FalagardEditbox::renderTextNoBidi(const WidgetLookFeel& wlf, // draw pre-highlight text String sect = text.substr(0, w->getSelectionStartIndex()); colours = unselectedColours; - colours.modulateAlpha(alpha_comp); text_part_rect.d_min.d_x = - font->drawText(w->getGeometryBuffer(), sect, - text_part_rect.getPosition(), &text_area, colours); + font->drawText(w->getGeometryBuffers(), sect, text_part_rect.getPositionGLM(), + &text_area, true, colours); // draw highlight text sect = text.substr(w->getSelectionStartIndex(), w->getSelectionLength()); setColourRectToSelectedTextColour(colours); - colours.modulateAlpha(alpha_comp); text_part_rect.d_min.d_x = - font->drawText(w->getGeometryBuffer(), sect, - text_part_rect.getPosition(), &text_area, colours); + font->drawText(w->getGeometryBuffers(), sect, text_part_rect.getPositionGLM(), + &text_area, true, colours); // draw post-highlight text sect = text.substr(w->getSelectionEndIndex()); colours = unselectedColours; - colours.modulateAlpha(alpha_comp); - font->drawText(w->getGeometryBuffer(), sect, text_part_rect.getPosition(), - &text_area, colours); + font->drawText(w->getGeometryBuffers(), sect, text_part_rect.getPositionGLM(), + &text_area, true, colours); } //----------------------------------------------------------------------------// @@ -301,7 +311,6 @@ void FalagardEditbox::renderTextBidi(const WidgetLookFeel& wlf, text_part_rect.d_min.d_y += (text_area.getHeight() - font->getFontHeight()) * 0.5f; ColourRect colours; - const float alpha_comp = d_window->getEffectiveAlpha(); // get unhighlighted text colour (saves accessing property twice) ColourRect unselectedColour; setColourRectToUnselectedTextColour(unselectedColour); @@ -313,9 +322,8 @@ void FalagardEditbox::renderTextBidi(const WidgetLookFeel& wlf, { // no highlighted text - we can draw the whole thing colours = unselectedColour; - colours.modulateAlpha(alpha_comp); text_part_rect.d_min.d_x = - font->drawText(w->getGeometryBuffer(), text, + font->drawText(w->getGeometryBuffers(), text, text_part_rect.getPosition(), &text_area, colours); } else @@ -347,7 +355,6 @@ void FalagardEditbox::renderTextBidi(const WidgetLookFeel& wlf, if (highlighted) { setColourRectToSelectedTextColour(colours); - colours.modulateAlpha(alpha_comp); { @@ -366,9 +373,8 @@ void FalagardEditbox::renderTextBidi(const WidgetLookFeel& wlf, else { colours = unselectedColour; - colours.modulateAlpha(alpha_comp); } - font->drawText(w->getGeometryBuffer(), currChar, + font->drawText(w->getGeometryBuffers(), currChar, text_part_rect.getPosition(), &text_area, colours); // adjust rect for next section @@ -409,12 +415,12 @@ void FalagardEditbox::renderCaret(const ImagerySection& imagery, } //----------------------------------------------------------------------------// -size_t FalagardEditbox::getTextIndexFromPosition(const Vector2f& pt) const +size_t FalagardEditbox::getTextIndexFromPosition(const glm::vec2& pt) const { Editbox* w = static_cast(d_window); // calculate final window position to be checked - float wndx = CoordConverter::screenToWindowX(*w, pt.d_x); + float wndx = CoordConverter::screenToWindowX(*w, pt.x); wndx -= d_lastTextOffset; diff --git a/cegui/src/WindowRendererSets/Core/ItemListbox.cpp b/cegui/src/WindowRendererSets/Core/ItemListbox.cpp deleted file mode 100644 index af9b76212..000000000 --- a/cegui/src/WindowRendererSets/Core/ItemListbox.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/************************************************************************ - created: Mon Mar 20 2006 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/WindowRendererSets/Core/ItemListbox.h" -#include "CEGUI/falagard/WidgetLookManager.h" -#include "CEGUI/falagard/WidgetLookFeel.h" -#include "CEGUI/widgets/ItemListbox.h" -#include "CEGUI/CoordConverter.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ - const String FalagardItemListbox::TypeName("Core/ItemListbox"); - - FalagardItemListbox::FalagardItemListbox(const String& type) : - ItemListBaseWindowRenderer(type), - d_widgetLookAssigned(false) - { - } - - void FalagardItemListbox::render() - { - const StateImagery* imagery; - - // get WidgetLookFeel for the assigned look. - const WidgetLookFeel& wlf = getLookNFeel(); - // try and get imagery for our current state - imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : "Enabled"); - // peform the rendering operation. - imagery->render(*d_window); - } - - Rectf FalagardItemListbox::getItemRenderArea(void) const - { - ItemListbox* lb = static_cast(d_window); - return getItemRenderingArea(lb->getHorzScrollbar()->isVisible(), - lb->getVertScrollbar()->isVisible()); - } - - Rectf FalagardItemListbox::getItemRenderingArea(bool hscroll, - bool vscroll) const - { - const ItemListbox* const lb = static_cast(d_window); - const WidgetLookFeel& wlf = getLookNFeel(); - const String area_name("ItemRenderArea"); - const String alternate_name("ItemRenderingArea"); - const String scroll_suffix( - vscroll ? hscroll ? "HVScroll" : "VScroll" : hscroll ? "HScroll" : ""); - - if (wlf.isNamedAreaDefined(area_name + scroll_suffix)) - return wlf.getNamedArea(area_name + scroll_suffix).getArea().getPixelRect(*lb); - - if (wlf.isNamedAreaDefined(alternate_name + scroll_suffix)) - return wlf.getNamedArea(alternate_name + scroll_suffix).getArea().getPixelRect(*lb); - - // default to plain ItemRenderingArea - if (wlf.isNamedAreaDefined(area_name)) - return wlf.getNamedArea(area_name).getArea().getPixelRect(*lb); - else - return wlf.getNamedArea(alternate_name).getArea().getPixelRect(*lb); - } - - void FalagardItemListbox::onLookNFeelAssigned() - { - d_widgetLookAssigned = true; - } - - void FalagardItemListbox::onLookNFeelUnassigned() - { - d_widgetLookAssigned = false; - } - - Rectf FalagardItemListbox::getUnclippedInnerRect() const - { - if (!d_widgetLookAssigned) - return d_window->getUnclippedOuterRect().get(); - - Rectf lr(getItemRenderArea()); - lr.offset(d_window->getUnclippedOuterRect().get().d_min); - return lr; - } - -} // End of CEGUI namespace section diff --git a/cegui/src/WindowRendererSets/Core/ItemViewRenderer.cpp b/cegui/src/WindowRendererSets/Core/ItemViewRenderer.cpp new file mode 100644 index 000000000..a366af51d --- /dev/null +++ b/cegui/src/WindowRendererSets/Core/ItemViewRenderer.cpp @@ -0,0 +1,169 @@ +/*********************************************************************** + created: Mon Jun 02 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h" +#include "CEGUI/falagard/WidgetLookManager.h" +#include "CEGUI/CoordConverter.h" +#include "CEGUI/Font.h" + +namespace CEGUI +{ +//----------------------------------------------------------------------------// +ItemViewRenderer::~ItemViewRenderer() +{ +} + +//----------------------------------------------------------------------------// +Rectf ItemViewRenderer::getViewRenderArea(const ItemView* item_view) const +{ + return getViewRenderArea( + item_view, + item_view->getHorzScrollbar()->isVisible(), + item_view->getVertScrollbar()->isVisible()); +} + +//----------------------------------------------------------------------------// +Rectf ItemViewRenderer::getViewRenderArea(const ItemView* item_view, + bool hscroll, bool vscroll) const +{ + const WidgetLookFeel& wlf = + WidgetLookManager::getSingleton().getWidgetLook(item_view->getLookNFeel()); + String scroll_suffix; + + if (vscroll) + scroll_suffix += "V"; + + if (hscroll) + scroll_suffix += "H"; + + if(!scroll_suffix.empty()) + scroll_suffix += "Scroll"; + + const String area_names[] = { "ItemRenderingArea", "ItemRenderArea" }; + const String suffixes[] = { scroll_suffix, "" }; + + for (size_t suffix_id = 0; suffix_id < 2; suffix_id++) + { + const String& suffix = suffixes[suffix_id]; + + for (size_t area_id = 0; area_id < 2; ++area_id) + { + const String full_area_name(area_names[area_id] + suffix); + + if (wlf.isNamedAreaPresent(full_area_name)) + return wlf.getNamedArea(full_area_name).getArea(). + getPixelRect(*item_view); + } + } + + CEGUI_THROW(UnknownObjectException("There is no item rendering area defined!")); +} + +//----------------------------------------------------------------------------// +void ItemViewRenderer::renderString(ItemView* view, RenderedString& rendered_string, + Rectf draw_rect, const Font* font, const Rectf* item_clipper, bool is_selected) +{ + if (view->getSelectionBrushImage() != 0 && is_selected) + { + view->getSelectionBrushImage()->render( + view->getGeometryBuffers(), + draw_rect, + item_clipper, + true, + view->getSelectionColourRect()); + } + + glm::vec2 draw_pos(draw_rect.getPositionGLM()); + for (size_t i = 0; i < rendered_string.getLineCount(); ++i) + { + draw_pos.y += CoordConverter::alignToPixels( + (font->getLineSpacing() - font->getFontHeight()) * 0.5f); + + rendered_string.draw(view, i, view->getGeometryBuffers(), + draw_pos, 0, item_clipper, 0.0f); + + draw_pos.y += rendered_string.getPixelSize(view, i).d_height; + } +} + +//----------------------------------------------------------------------------// +glm::vec2 ItemViewRenderer::getItemRenderStartPosition(ItemView* view, + const Rectf& items_area) const +{ + return glm::vec2( + items_area.left() - view->getHorzScrollbar()->getScrollPosition(), + items_area.top() - view->getVertScrollbar()->getScrollPosition() + ); +} + +//----------------------------------------------------------------------------// +void ItemViewRenderer::resizeViewToContent(ItemView* view, bool fit_width, + bool fit_height) const +{ + const Rectf totalArea(view->getUnclippedOuterRect().get()); + const Rectf contentArea(getViewRenderArea(view, + fit_width ? false : view->getHorzScrollbar()->isVisible(), + fit_height ? false : view->getVertScrollbar()->isVisible())); + const Rectf withScrollContentArea(getViewRenderArea(view, true, true)); + + const Sizef frameSize(totalArea.getSize() - contentArea.getSize()); + const Sizef withScrollFrameSize(totalArea.getSize() - + withScrollContentArea.getSize()); + const Sizef contentSize(view->getRenderedMaxWidth(), + view->getRenderedTotalHeight()); + + const Sizef parentSize(view->getParentPixelSize()); + const Sizef maxSize( + parentSize.d_width - + CoordConverter::asAbsolute(view->getXPosition(), parentSize.d_width), + parentSize.d_height - + CoordConverter::asAbsolute(view->getYPosition(), parentSize.d_height)); + + Sizef requiredSize(frameSize + contentSize + Sizef(1, 1)); + + if (fit_height && requiredSize.d_height > maxSize.d_height) + { + requiredSize.d_height = maxSize.d_height; + requiredSize.d_width = ceguimin( + maxSize.d_width, + requiredSize.d_width - frameSize.d_width + withScrollFrameSize.d_width); + } + + if (fit_width && requiredSize.d_width > maxSize.d_width) + { + requiredSize.d_width = maxSize.d_width; + requiredSize.d_height = ceguimin( + maxSize.d_height, + requiredSize.d_height - frameSize.d_height + withScrollFrameSize.d_height); + } + + if (fit_height) + view->setHeight(UDim(0, requiredSize.d_height)); + + if (fit_width) + view->setWidth(UDim(0, requiredSize.d_width)); +} +} diff --git a/cegui/src/WindowRendererSets/Core/ListView.cpp b/cegui/src/WindowRendererSets/Core/ListView.cpp new file mode 100644 index 000000000..49a4de76e --- /dev/null +++ b/cegui/src/WindowRendererSets/Core/ListView.cpp @@ -0,0 +1,123 @@ +/*********************************************************************** + created: Mon May 26 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/WindowRendererSets/Core/ListView.h" +#include "CEGUI/falagard/WidgetLookManager.h" +#include "CEGUI/falagard/WidgetLookFeel.h" + +#include "CEGUI/Colour.h" +#include "CEGUI/CoordConverter.h" +#include "CEGUI/Font.h" +#include "CEGUI/ImageManager.h" +#include "CEGUI/Vector.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +const String FalagardListView::TypeName("Core/ListView"); +static ColourRect ICON_COLOUR_RECT(Colour(1, 1, 1, 1)); + +//----------------------------------------------------------------------------// +FalagardListView::FalagardListView(const String& type) : + ItemViewWindowRenderer(type) +{ +} + +//----------------------------------------------------------------------------// +void FalagardListView::render() +{ + const StateImagery* imagery; + const WidgetLookFeel& wlf = getLookNFeel(); + ListView* list_view = static_cast(d_window); + + list_view->prepareForRender(); + + bool has_focused_state = + list_view->isFocused() && wlf.isStateImageryPresent("EnabledFocused"); + imagery = &wlf.getStateImagery( + list_view->isEffectiveDisabled() ? "Disabled" : + (has_focused_state ? "EnabledFocused" : "Enabled")); + imagery->render(*list_view); + + render(list_view); +} + +//----------------------------------------------------------------------------// +void FalagardListView::render(ListView* list_view) +{ + Rectf items_area(getViewRenderArea()); + glm::vec2 item_pos(getItemRenderStartPosition(list_view, items_area)); + + for (size_t i = 0; i < list_view->getItems().size(); ++i) + { + ListViewItemRenderingState* item = list_view->getItems().at(i); + RenderedString& rendered_string = item->d_string; + Sizef size(item->d_size); + + size.d_width = ceguimax(items_area.getWidth(), size.d_width); + + Rectf item_rect; + item_rect.left(item_pos.x); + item_rect.top(item_pos.y); + item_rect.setSize(size); + + if (!item->d_icon.empty()) + { + Image& img = ImageManager::getSingleton().get(item->d_icon); + + Rectf icon_rect(item_rect); + icon_rect.setWidth(size.d_height); + icon_rect.setHeight(size.d_height); + + Rectf icon_clipper(icon_rect.getIntersection(items_area)); + img.render(list_view->getGeometryBuffers(), icon_rect, &icon_clipper, + true, ICON_COLOUR_RECT, 1.0f); + + item_rect.left(item_rect.left() + icon_rect.getWidth()); + } + + Rectf item_clipper(item_rect.getIntersection(items_area)); + + renderString(list_view, rendered_string, item_rect, + list_view->getFont(), &item_clipper, item->d_isSelected); + + item_pos.y += size.d_height; + } +} + +//----------------------------------------------------------------------------// +Rectf FalagardListView::getViewRenderArea(void) const +{ + return ItemViewRenderer::getViewRenderArea(getView()); +} + +//----------------------------------------------------------------------------// +void FalagardListView::resizeViewToContent(bool fit_width, bool fit_height) const +{ + ItemViewRenderer::resizeViewToContent(getView(), fit_width, fit_height); +} +} diff --git a/cegui/src/WindowRendererSets/Core/Listbox.cpp b/cegui/src/WindowRendererSets/Core/Listbox.cpp deleted file mode 100644 index e54aee6fa..000000000 --- a/cegui/src/WindowRendererSets/Core/Listbox.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/*********************************************************************** - created: Mon Jul 4 2005 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/WindowRendererSets/Core/Listbox.h" -#include "CEGUI/widgets/Scrollbar.h" -#include "CEGUI/widgets/ListboxItem.h" -#include "CEGUI/falagard/WidgetLookManager.h" -#include "CEGUI/falagard/WidgetLookFeel.h" -#include "CEGUI/CoordConverter.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ - const String FalagardListbox::TypeName("Core/Listbox"); - - - FalagardListbox::FalagardListbox(const String& type) : - ListboxWindowRenderer(type) - { - } - - Rectf FalagardListbox::getListRenderArea(void) const - { - Listbox* lb = (Listbox*)d_window; - - return getItemRenderingArea(lb->getHorzScrollbar()->isVisible(), - lb->getVertScrollbar()->isVisible()); - } - - Rectf FalagardListbox::getItemRenderingArea(bool hscroll, - bool vscroll) const - { - const Listbox* const lb = static_cast(d_window); - const WidgetLookFeel& wlf = getLookNFeel(); - const String area_name("ItemRenderingArea"); - const String alternate_name("ItemRenderArea"); - const String scroll_suffix( - vscroll ? hscroll ? "HVScroll" : "VScroll" : hscroll ? "HScroll" : ""); - - if (wlf.isNamedAreaDefined(area_name + scroll_suffix)) - return wlf.getNamedArea(area_name + scroll_suffix).getArea().getPixelRect(*lb); - - if (wlf.isNamedAreaDefined(alternate_name + scroll_suffix)) - return wlf.getNamedArea(alternate_name + scroll_suffix).getArea().getPixelRect(*lb); - - // default to plain ItemRenderingArea - if (wlf.isNamedAreaDefined(area_name)) - return wlf.getNamedArea(area_name).getArea().getPixelRect(*lb); - else - return wlf.getNamedArea(alternate_name).getArea().getPixelRect(*lb); - } - - void FalagardListbox::resizeListToContent(bool fit_width, - bool fit_height) const - { - Listbox* const lb = static_cast(d_window); - - const Rectf totalArea(lb->getUnclippedOuterRect().get()); - const Rectf contentArea(getItemRenderingArea( - fit_width ? false : lb->getHorzScrollbar()->isVisible(), - fit_height ? false : lb->getVertScrollbar()->isVisible())); - const Rectf withScrollContentArea(getItemRenderingArea(true, true)); - - const Sizef frameSize(totalArea.getSize() - contentArea.getSize()); - const Sizef withScrollFrameSize(totalArea.getSize() - - withScrollContentArea.getSize()); - const Sizef contentSize(lb->getWidestItemWidth(), - lb->getTotalItemsHeight()); - - const Sizef parentSize(lb->getParentPixelSize()); - const Sizef maxSize(parentSize.d_width - - CoordConverter::asAbsolute(lb->getXPosition(), - parentSize.d_width), - parentSize.d_height - - CoordConverter::asAbsolute(lb->getYPosition(), - parentSize.d_height)); - - Sizef requiredSize(frameSize + contentSize + Sizef(1, 1)); - - if (fit_height) - { - if (requiredSize.d_height > maxSize.d_height) - { - requiredSize.d_height = maxSize.d_height; - requiredSize.d_width = ceguimin( - maxSize.d_width, - requiredSize.d_width - frameSize.d_width + withScrollFrameSize.d_width); - } - } - - if (fit_width) - { - if (requiredSize.d_width > maxSize.d_width) - { - requiredSize.d_width = maxSize.d_width; - requiredSize.d_height = ceguimin( - maxSize.d_height, - requiredSize.d_height - frameSize.d_height + withScrollFrameSize.d_height); - } - } - - if (fit_height) - lb->setHeight(UDim(0, requiredSize.d_height)); - - if (fit_width) - lb->setWidth(UDim(0, requiredSize.d_width)); - } - - void FalagardListbox::render() - { - Listbox* lb = (Listbox*)d_window; - // render frame and stuff before we handle the items - cacheListboxBaseImagery(); - - // - // Render list items - // - Vector3f itemPos; - Sizef itemSize; - Rectf itemClipper, itemRect; - const float widest = lb->getWidestItemWidth(); - - // calculate position of area we have to render into - Rectf itemsArea(getListRenderArea()); - - // set up some initial positional details for items - itemPos.d_x = itemsArea.left() - lb->getHorzScrollbar()->getScrollPosition(); - itemPos.d_y = itemsArea.top() - lb->getVertScrollbar()->getScrollPosition(); - itemPos.d_z = 0.0f; - - const float alpha = lb->getEffectiveAlpha(); - - // loop through the items - size_t itemCount = lb->getItemCount(); - - for (size_t i = 0; i < itemCount; ++i) - { - ListboxItem* listItem = lb->getListboxItemFromIndex(i); - itemSize.d_height = listItem->getPixelSize().d_height; - - // allow item to have full width of box if this is wider than items - itemSize.d_width = ceguimax(itemsArea.getWidth(), widest); - - // calculate destination area for this item. - itemRect.left(itemPos.d_x); - itemRect.top(itemPos.d_y); - itemRect.setSize(itemSize); - itemClipper = itemRect.getIntersection(itemsArea); - - // skip this item if totally clipped - if (itemClipper.getWidth() == 0) - { - itemPos.d_y += itemSize.d_height; - continue; - } - - // draw this item - listItem->draw(lb->getGeometryBuffer(), itemRect, alpha, &itemClipper); - - // update position ready for next item - itemPos.d_y += itemSize.d_height; - } - - } - - void FalagardListbox::cacheListboxBaseImagery() - { - const StateImagery* imagery; - - // get WidgetLookFeel for the assigned look. - const WidgetLookFeel& wlf = getLookNFeel(); - // try and get imagery for our current state - imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : "Enabled"); - // peform the rendering operation. - imagery->render(*d_window); - } - - bool FalagardListbox::handleFontRenderSizeChange(const Font* const font) - { - bool res = ListboxWindowRenderer::handleFontRenderSizeChange(font); - - if (!res) - { - Listbox* const listbox = static_cast(d_window); - - for (size_t i = 0; i < listbox->getItemCount(); ++i) - res |= listbox->getListboxItemFromIndex(i)->handleFontRenderSizeChange(font); - - if (res) - listbox->invalidate(); - } - - return res; - } - -} // End of CEGUI namespace section diff --git a/cegui/src/WindowRendererSets/Core/MenuItem.cpp b/cegui/src/WindowRendererSets/Core/MenuItem.cpp index 2ebf2b7d9..77ad3b948 100644 --- a/cegui/src/WindowRendererSets/Core/MenuItem.cpp +++ b/cegui/src/WindowRendererSets/Core/MenuItem.cpp @@ -54,7 +54,7 @@ const NamedArea& FalagardMenuItem::getContentNamedArea() const const WidgetLookFeel& wlf(getLookNFeel()); if (static_cast(d_window)->getPopupMenu() && !parentIsMenubar() && - wlf.isNamedAreaDefined("HasPopupContentSize")) + wlf.isNamedAreaPresent("HasPopupContentSize")) { return wlf.getNamedArea("HasPopupContentSize"); } diff --git a/cegui/src/WindowRendererSets/Core/Module.cpp b/cegui/src/WindowRendererSets/Core/Module.cpp index a54914292..0fd172be8 100644 --- a/cegui/src/WindowRendererSets/Core/Module.cpp +++ b/cegui/src/WindowRendererSets/Core/Module.cpp @@ -35,7 +35,8 @@ #include "CEGUI/WindowRendererSets/Core/ItemEntry.h" #include "CEGUI/WindowRendererSets/Core/ListHeader.h" #include "CEGUI/WindowRendererSets/Core/ListHeaderSegment.h" -#include "CEGUI/WindowRendererSets/Core/Listbox.h" +#include "CEGUI/WindowRendererSets/Core/ListView.h" + #include "CEGUI/WindowRendererSets/Core/Menubar.h" #include "CEGUI/WindowRendererSets/Core/MenuItem.h" #include "CEGUI/WindowRendererSets/Core/MultiColumnList.h" @@ -53,8 +54,7 @@ #include "CEGUI/WindowRendererSets/Core/Titlebar.h" #include "CEGUI/WindowRendererSets/Core/ToggleButton.h" #include "CEGUI/WindowRendererSets/Core/Tooltip.h" -#include "CEGUI/WindowRendererSets/Core/ItemListbox.h" -#include "CEGUI/WindowRendererSets/Core/Tree.h" +#include "CEGUI/WindowRendererSets/Core/TreeView.h" //----------------------------------------------------------------------------// extern "C" @@ -69,33 +69,32 @@ namespace CEGUI //----------------------------------------------------------------------------// CoreWindowRendererModule::CoreWindowRendererModule() { - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); - d_registry.push_back(CEGUI_NEW_AO TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); + d_registry.push_back(new TplWRFactoryRegisterer()); } //----------------------------------------------------------------------------// @@ -103,7 +102,7 @@ CoreWindowRendererModule::~CoreWindowRendererModule() { FactoryRegistry::iterator i = d_registry.begin(); for ( ; i != d_registry.end(); ++i) - CEGUI_DELETE_AO (*i); + delete (*i); } //----------------------------------------------------------------------------// diff --git a/cegui/src/WindowRendererSets/Core/MultiColumnList.cpp b/cegui/src/WindowRendererSets/Core/MultiColumnList.cpp index c148ab8a2..846c1db8f 100644 --- a/cegui/src/WindowRendererSets/Core/MultiColumnList.cpp +++ b/cegui/src/WindowRendererSets/Core/MultiColumnList.cpp @@ -67,7 +67,7 @@ namespace CEGUI } area_name += "Scroll"; - if (wlf.isNamedAreaDefined(area_name)) + if (wlf.isNamedAreaPresent(area_name)) { return wlf.getNamedArea(area_name).getArea().getPixelRect(*w); } @@ -90,7 +90,7 @@ namespace CEGUI // // Render list items // - Vector3f itemPos; + glm::vec3 itemPos; Sizef itemSize; Rectf itemClipper, itemRect; @@ -98,8 +98,8 @@ namespace CEGUI Rectf itemsArea(getListRenderArea()); // set up initial positional details for items - itemPos.d_y = itemsArea.top() - vertScrollbar->getScrollPosition(); - itemPos.d_z = 0.0f; + itemPos.y = itemsArea.top() - vertScrollbar->getScrollPosition(); + itemPos.z = 0.0f; const float alpha = w->getEffectiveAlpha(); @@ -107,7 +107,7 @@ namespace CEGUI for (uint i = 0; i < w->getRowCount(); ++i) { // set initial x position for this row. - itemPos.d_x = itemsArea.left() - horzScrollbar->getScrollPosition(); + itemPos.x = itemsArea.left() - horzScrollbar->getScrollPosition(); // calculate height for this row. itemSize.d_height = w->getHighestRowItemHeight(i); @@ -124,28 +124,28 @@ namespace CEGUI if (item) { // calculate destination area for this item. - itemRect.left(itemPos.d_x); - itemRect.top(itemPos.d_y); + itemRect.left(itemPos.x); + itemRect.top(itemPos.y); itemRect.setSize(itemSize); itemClipper = itemRect.getIntersection(itemsArea); // skip this item if totally clipped if (itemClipper.getWidth() == 0) { - itemPos.d_x += itemSize.d_width; + itemPos.x += itemSize.d_width; continue; } // draw this item - item->draw(w->getGeometryBuffer(), itemRect, alpha, &itemClipper); + item->draw(w->getGeometryBuffers(), itemRect, alpha, &itemClipper); } // update position for next column. - itemPos.d_x += itemSize.d_width; + itemPos.x += itemSize.d_width; } // update position ready for next row - itemPos.d_y += itemSize.d_height; + itemPos.y += itemSize.d_height; } } @@ -156,8 +156,9 @@ namespace CEGUI // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); // try and get imagery for our current state - imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : "Enabled"); - // peform the rendering operation. + imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" + : (d_window->isFocused() ? "EnabledFocused" : "Enabled")); + // perform the rendering operation. imagery->render(*d_window); } diff --git a/cegui/src/WindowRendererSets/Core/MultiLineEditbox.cpp b/cegui/src/WindowRendererSets/Core/MultiLineEditbox.cpp index 8da219bd7..e0023f84f 100644 --- a/cegui/src/WindowRendererSets/Core/MultiLineEditbox.cpp +++ b/cegui/src/WindowRendererSets/Core/MultiLineEditbox.cpp @@ -87,7 +87,7 @@ Rectf FalagardMultiLineEditbox::getTextRenderArea(void) const } area_name += "Scroll"; - if (wlf.isNamedAreaDefined(area_name)) + if (wlf.isNamedAreaPresent(area_name)) { return wlf.getNamedArea(area_name).getArea().getPixelRect(*w); } @@ -104,9 +104,25 @@ void FalagardMultiLineEditbox::cacheEditboxBaseImagery() // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); + + String state; + + if (w->isEffectiveDisabled()) + state = "Disabled"; + else + { + if (w->isReadOnly()) + state = "ReadOnly"; + else + state = "Enabled"; + + if (w->isFocused()) + state += "Focused"; + } + // try and get imagery for our current state - imagery = &wlf.getStateImagery(w->isEffectiveDisabled() ? "Disabled" : (w->isReadOnly() ? "ReadOnly" : "Enabled")); - // peform the rendering operation. + imagery = &wlf.getStateImagery(state); + // perform the rendering operation. imagery->render(*w); } @@ -146,7 +162,7 @@ void FalagardMultiLineEditbox::cacheCaretImagery(const Rectf& textArea) caretArea.top(textArea.top() + ypos); caretArea.setWidth(caretImagery.getBoundingRect(*w).getSize().d_width); caretArea.setHeight(fnt->getLineSpacing()); - caretArea.offset(Vector2f(-w->getHorzScrollbar()->getScrollPosition(), -w->getVertScrollbar()->getScrollPosition())); + caretArea.offset(-glm::vec2(w->getHorzScrollbar()->getScrollPosition(), w->getVertScrollbar()->getScrollPosition())); // cache the caret image for rendering. caretImagery.render(*w, caretArea, 0, &textArea); @@ -176,7 +192,7 @@ void FalagardMultiLineEditbox::cacheTextLines(const Rectf& dest_area) // text is already formatted, we just grab the lines and render them with the required alignment. Rectf drawArea(dest_area); float vertScrollPos = w->getVertScrollbar()->getScrollPosition(); - drawArea.offset(Vector2f(-w->getHorzScrollbar()->getScrollPosition(), -vertScrollPos)); + drawArea.offset(-glm::vec2(w->getHorzScrollbar()->getScrollPosition(), vertScrollPos)); const Font* fnt = w->getFont(); @@ -184,17 +200,13 @@ void FalagardMultiLineEditbox::cacheTextLines(const Rectf& dest_area) { // calculate final colours to use. ColourRect colours; - const float alpha = w->getEffectiveAlpha(); ColourRect normalTextCol; setColourRectToUnselectedTextColour(normalTextCol); - normalTextCol.modulateAlpha(alpha); ColourRect selectTextCol; setColourRectToSelectedTextColour(selectTextCol); - selectTextCol.modulateAlpha(alpha); ColourRect selectBrushCol; w->hasInputFocus() ? setColourRectToActiveSelectionColour(selectBrushCol) : setColourRectToInactiveSelectionColour(selectBrushCol); - selectBrushCol.modulateAlpha(alpha); const MultiLineEditbox::LineList& d_lines = w->getFormattedLines(); const size_t numLines = d_lines.size(); @@ -224,8 +236,8 @@ void FalagardMultiLineEditbox::cacheTextLines(const Rectf& dest_area) { colours = normalTextCol; // render the complete line. - fnt->drawText(w->getGeometryBuffer(), lineText, - lineRect.getPosition(), &dest_area, colours); + fnt->drawText(w->getGeometryBuffers(), lineText, + lineRect.getPositionGLM(), &dest_area, true, colours); } // we have at least some selection highlighting to do else @@ -250,8 +262,8 @@ void FalagardMultiLineEditbox::cacheTextLines(const Rectf& dest_area) // draw this portion of the text colours = normalTextCol; - fnt->drawText(w->getGeometryBuffer(), sect, - lineRect.getPosition(), &dest_area, colours); + fnt->drawText(w->getGeometryBuffers(), sect, + lineRect.getPositionGLM(), &dest_area, true, colours); // set position ready for next portion of text lineRect.d_min.d_x += selStartOffset; @@ -277,12 +289,12 @@ void FalagardMultiLineEditbox::cacheTextLines(const Rectf& dest_area) // render the selection area brush for this line colours = selectBrushCol; - w->getSelectionBrushImage()->render(w->getGeometryBuffer(), lineRect, &dest_area, colours); + w->getSelectionBrushImage()->render(w->getGeometryBuffers(), lineRect, &dest_area, true, colours); // draw the text for this section colours = selectTextCol; - fnt->drawText(w->getGeometryBuffer(), sect, - lineRect.getPosition(), &dest_area, colours); + fnt->drawText(w->getGeometryBuffers(), sect, + lineRect.getPositionGLM(), &dest_area, true, colours); lineRect.top(text_top); @@ -300,8 +312,8 @@ void FalagardMultiLineEditbox::cacheTextLines(const Rectf& dest_area) // render the text for this section. colours = normalTextCol; - fnt->drawText(w->getGeometryBuffer(), sect, - lineRect.getPosition(), &dest_area, colours); + fnt->drawText(w->getGeometryBuffers(), sect, + lineRect.getPositionGLM(), &dest_area, true, colours); } } diff --git a/cegui/src/WindowRendererSets/Core/ScrollablePane.cpp b/cegui/src/WindowRendererSets/Core/ScrollablePane.cpp index a2a79df29..813c4ecde 100644 --- a/cegui/src/WindowRendererSets/Core/ScrollablePane.cpp +++ b/cegui/src/WindowRendererSets/Core/ScrollablePane.cpp @@ -66,7 +66,7 @@ namespace CEGUI } area_name += "Scroll"; - if (wlf.isNamedAreaDefined(area_name)) + if (wlf.isNamedAreaPresent(area_name)) { return wlf.getNamedArea(area_name).getArea().getPixelRect(*w); } diff --git a/cegui/src/WindowRendererSets/Core/Scrollbar.cpp b/cegui/src/WindowRendererSets/Core/Scrollbar.cpp index 0ba92b317..8f7d23619 100644 --- a/cegui/src/WindowRendererSets/Core/Scrollbar.cpp +++ b/cegui/src/WindowRendererSets/Core/Scrollbar.cpp @@ -56,7 +56,8 @@ namespace CEGUI // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); // try and get imagery for our current state - imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : "Enabled"); + imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" + : (d_window->isFocused() ? "EnabledFocused" : "Enabled")); // peform the rendering operation. imagery->render(*d_window); } @@ -130,18 +131,18 @@ namespace CEGUI } } - float FalagardScrollbar::getAdjustDirectionFromPoint(const Vector2f& pt) const + float FalagardScrollbar::getAdjustDirectionFromPoint(const glm::vec2& pt) const { Scrollbar* w = (Scrollbar*)d_window; const Rectf& absrect(w->getThumb()->getUnclippedOuterRect().get()); - if ((d_vertical && (pt.d_y > absrect.bottom())) || - (!d_vertical && (pt.d_x > absrect.right()))) + if ((d_vertical && (pt.y > absrect.bottom())) || + (!d_vertical && (pt.x > absrect.right()))) { return 1; } - else if ((d_vertical && (pt.d_y < absrect.top())) || - (!d_vertical && (pt.d_x < absrect.left()))) + else if ((d_vertical && (pt.y < absrect.top())) || + (!d_vertical && (pt.x < absrect.left()))) { return -1; } diff --git a/cegui/src/WindowRendererSets/Core/Slider.cpp b/cegui/src/WindowRendererSets/Core/Slider.cpp index 814d05fdd..16bccb44d 100644 --- a/cegui/src/WindowRendererSets/Core/Slider.cpp +++ b/cegui/src/WindowRendererSets/Core/Slider.cpp @@ -62,8 +62,9 @@ namespace CEGUI // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = getLookNFeel(); // try and get imagery for our current state - imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" : "Enabled"); - // peform the rendering operation. + imagery = &wlf.getStateImagery(d_window->isEffectiveDisabled() ? "Disabled" + : (d_window->isFocused() ? "EnabledFocused" : "Enabled")); + // perform the rendering operation. imagery->render(*d_window); } @@ -167,18 +168,18 @@ namespace CEGUI } } - float FalagardSlider::getAdjustDirectionFromPoint(const Vector2f& pt) const + float FalagardSlider::getAdjustDirectionFromPoint(const glm::vec2& pt) const { Slider* w = (Slider*)d_window; const Rectf absrect(w->getThumb()->getUnclippedOuterRect().get()); - if ((d_vertical && (pt.d_y < absrect.top())) || - (!d_vertical && (pt.d_x > absrect.right()))) + if ((d_vertical && (pt.y < absrect.top())) || + (!d_vertical && (pt.x > absrect.right()))) { return d_reversed ? -1.0f : 1.0f; } - else if ((d_vertical && (pt.d_y > absrect.bottom())) || - (!d_vertical && (pt.d_x < absrect.left()))) + else if ((d_vertical && (pt.y > absrect.bottom())) || + (!d_vertical && (pt.x < absrect.left()))) { return d_reversed ? 1.0f : -1.0f; } diff --git a/cegui/src/WindowRendererSets/Core/StaticText.cpp b/cegui/src/WindowRendererSets/Core/StaticText.cpp index fba03bb97..0ada91937 100644 --- a/cegui/src/WindowRendererSets/Core/StaticText.cpp +++ b/cegui/src/WindowRendererSets/Core/StaticText.cpp @@ -112,7 +112,7 @@ namespace CEGUI FalagardStaticText::~FalagardStaticText() { if (d_formattedRenderedString) - CEGUI_DELETE_AO d_formattedRenderedString; + delete d_formattedRenderedString; } //----------------------------------------------------------------------------// @@ -154,18 +154,18 @@ namespace CEGUI case HTF_WORDWRAP_LEFT_ALIGNED: case HTF_JUSTIFIED: case HTF_WORDWRAP_JUSTIFIED: - absarea.offset(Vector2f(-horzScrollbar->getScrollPosition(), 0)); + absarea.offset(glm::vec2(-horzScrollbar->getScrollPosition(), 0)); break; case HTF_CENTRE_ALIGNED: case HTF_WORDWRAP_CENTRE_ALIGNED: absarea.setWidth(horzScrollbar->getDocumentSize()); - absarea.offset(Vector2f(range / 2 - horzScrollbar->getScrollPosition(), 0)); + absarea.offset(glm::vec2(range / 2 - horzScrollbar->getScrollPosition(), 0)); break; case HTF_RIGHT_ALIGNED: case HTF_WORDWRAP_RIGHT_ALIGNED: - absarea.offset(Vector2f(range - horzScrollbar->getScrollPosition(), 0)); + absarea.offset(glm::vec2(range - horzScrollbar->getScrollPosition(), 0)); break; } } @@ -191,11 +191,10 @@ namespace CEGUI } // calculate final colours - ColourRect final_cols(d_textCols); - final_cols.modulateAlpha(d_window->getEffectiveAlpha()); + const ColourRect final_cols(d_textCols); // cache the text for rendering. - d_formattedRenderedString->draw(d_window, d_window->getGeometryBuffer(), - absarea.getPosition(), + d_formattedRenderedString->draw(d_window, d_window->getGeometryBuffers(), + absarea.getPositionGLM(), &final_cols, &clipper); } @@ -246,7 +245,7 @@ namespace CEGUI area_name += "Scroll"; } - if (wlf.isNamedAreaDefined(area_name)) + if (wlf.isNamedAreaPresent(area_name)) { return wlf.getNamedArea(area_name).getArea().getPixelRect(*d_window); } @@ -403,11 +402,11 @@ namespace CEGUI /************************************************************************* - Handler for mouse wheel changes + Handler for scroll actions *************************************************************************/ - bool FalagardStaticText::onMouseWheel(const EventArgs& event) + bool FalagardStaticText::onScroll(const EventArgs& event) { - const MouseEventArgs& e = static_cast(event); + const CursorInputEventArgs& e = static_cast(event); Scrollbar* vertScrollbar = getVertScrollbar(); Scrollbar* horzScrollbar = getHorzScrollbar(); @@ -417,11 +416,11 @@ namespace CEGUI if (vertScrollbarVisible && (vertScrollbar->getDocumentSize() > vertScrollbar->getPageSize())) { - vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.wheelChange); + vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.scroll); } else if (horzScrollbarVisible && (horzScrollbar->getDocumentSize() > horzScrollbar->getPageSize())) { - horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.wheelChange); + horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.scroll); } return vertScrollbarVisible || horzScrollbarVisible; @@ -471,8 +470,8 @@ namespace CEGUI Event::Subscriber(&FalagardStaticText::onFontChanged, this))); d_connections.push_back( - d_window->subscribeEvent(Window::EventMouseWheel, - Event::Subscriber(&FalagardStaticText::onMouseWheel, this))); + d_window->subscribeEvent(Window::EventScroll, + Event::Subscriber(&FalagardStaticText::onScroll, this))); } void FalagardStaticText::onLookNFeelUnassigned() @@ -500,45 +499,45 @@ namespace CEGUI { case HTF_LEFT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO LeftAlignedRenderedString(d_window->getRenderedString()); + new LeftAlignedRenderedString(d_window->getRenderedString()); break; case HTF_RIGHT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RightAlignedRenderedString(d_window->getRenderedString()); + new RightAlignedRenderedString(d_window->getRenderedString()); break; case HTF_CENTRE_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO CentredRenderedString(d_window->getRenderedString()); + new CentredRenderedString(d_window->getRenderedString()); break; case HTF_JUSTIFIED: d_formattedRenderedString = - CEGUI_NEW_AO JustifiedRenderedString(d_window->getRenderedString()); + new JustifiedRenderedString(d_window->getRenderedString()); break; case HTF_WORDWRAP_LEFT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (d_window->getRenderedString()); break; case HTF_WORDWRAP_RIGHT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (d_window->getRenderedString()); break; case HTF_WORDWRAP_CENTRE_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (d_window->getRenderedString()); break; case HTF_WORDWRAP_JUSTIFIED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (d_window->getRenderedString()); break; } diff --git a/cegui/src/WindowRendererSets/Core/TabButton.cpp b/cegui/src/WindowRendererSets/Core/TabButton.cpp index f5639d363..974fe4b4e 100644 --- a/cegui/src/WindowRendererSets/Core/TabButton.cpp +++ b/cegui/src/WindowRendererSets/Core/TabButton.cpp @@ -58,6 +58,8 @@ namespace CEGUI state = "Pushed"; else if (w->isHovering()) state = "Hover"; + else if (w->isFocused()) + state = "Focused"; else state = "Normal"; diff --git a/cegui/src/WindowRendererSets/Core/Tree.cpp b/cegui/src/WindowRendererSets/Core/Tree.cpp deleted file mode 100644 index 71eb724af..000000000 --- a/cegui/src/WindowRendererSets/Core/Tree.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/*********************************************************************** -created: 5-13-07 -author: Jonathan Welch (Based on Code by David Durant) -*************************************************************************/ -/*************************************************************************** -* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -* OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************/ -#include "CEGUI/WindowRendererSets/Core/Tree.h" -#include "CEGUI/falagard/WidgetLookManager.h" -#include "CEGUI/falagard/WidgetLookFeel.h" -#include "CEGUI/WindowManager.h" -#include "CEGUI/widgets/Scrollbar.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ - const String FalagardTree::TypeName("Core/Tree"); - - FalagardTree::FalagardTree(const String& type, const String&) : - WindowRenderer(type) - { - } - - FalagardTree::FalagardTree(const String& type) : - WindowRenderer(type) - { - } - - FalagardTree::~FalagardTree() - { - } - - Rectf FalagardTree::getTreeRenderArea(void) const - { - // get WidgetLookFeel for the assigned look. - const WidgetLookFeel& wlf = getLookNFeel(); - Tree* tree = (Tree*)d_window; - - bool v_visible = tree->getVertScrollbar()->isVisible(); - bool h_visible = tree->getHorzScrollbar()->isVisible(); - - // if either of the scrollbars are visible, we might want to use another text rendering area - if (v_visible || h_visible) - { - String area_name("ItemRenderingArea"); - - if (h_visible) - { - area_name += "H"; - } - if (v_visible) - { - area_name += "V"; - } - area_name += "Scroll"; - - if (wlf.isNamedAreaDefined(area_name)) - { - return wlf.getNamedArea(area_name).getArea().getPixelRect(*tree); - } - } - - // default to plain ItemRenderingArea - return wlf.getNamedArea("ItemRenderingArea").getArea().getPixelRect(*tree); - } - - void FalagardTree::render() - { - Tree* tree = (Tree*)d_window; - //Set the render area for this. - Rectf rect = getTreeRenderArea(); - tree->setItemRenderArea(rect); - const WidgetLookFeel& wlf = getLookNFeel(); - - const StateImagery* imagery; - //Get the Falagard imagery to render - imagery = &wlf.getStateImagery(tree->isEffectiveDisabled()? "Disabled" : "Enabled"); - //Render the window - imagery->render(*tree); - //Fix Scrollbars - tree->doScrollbars(); - //Render the tree. - tree->doTreeRender(); - } -} // End of CEGUI namespace section diff --git a/cegui/src/WindowRendererSets/Core/TreeView.cpp b/cegui/src/WindowRendererSets/Core/TreeView.cpp new file mode 100644 index 000000000..9995b0e60 --- /dev/null +++ b/cegui/src/WindowRendererSets/Core/TreeView.cpp @@ -0,0 +1,196 @@ +/*********************************************************************** + created: Fri Jun 06 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/WindowRendererSets/Core/TreeView.h" +#include "CEGUI/falagard/WidgetLookManager.h" +#include "CEGUI/falagard/WidgetLookFeel.h" +#include "CEGUI/Image.h" +#include "CEGUI/ImageManager.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +const String FalagardTreeView::TypeName("Core/TreeView"); +static ColourRect ICON_COLOUR_RECT(Colour(1, 1, 1, 1)); + +//----------------------------------------------------------------------------// +FalagardTreeView::FalagardTreeView(const String& type) : + TreeViewWindowRenderer(type), + d_subtreeExpanderImagery(0), + d_subtreeCollapserImagery(0), + d_subtreeExpanderImagerySize(0, 0) +{ +} + +//----------------------------------------------------------------------------// +void FalagardTreeView::render() +{ + const WidgetLookFeel& wlf = getLookNFeel(); + TreeView* tree_view = getView(); + + tree_view->prepareForRender(); + + bool has_focused_state = + tree_view->isFocused() && wlf.isStateImageryPresent("EnabledFocused"); + const StateImagery* imagery = &wlf.getStateImagery( + tree_view->isEffectiveDisabled() ? "Disabled" : + (has_focused_state ? "EnabledFocused" : "Enabled")); + imagery->render(*tree_view); + + Rectf items_area(getViewRenderArea()); + glm::vec2 item_pos(getItemRenderStartPosition(tree_view, items_area)); + renderTreeItem(tree_view, items_area, item_pos, &tree_view->getRootItemState(), 0); +} + +//----------------------------------------------------------------------------// +void FalagardTreeView::renderTreeItem(TreeView* tree_view, const Rectf& items_area, + glm::vec2& item_pos, const TreeViewItemRenderingState* item_to_render, + size_t depth) +{ + float expander_margin = tree_view->getSubtreeExpanderMargin(); + for (size_t i = 0; i < item_to_render->d_renderedChildren.size(); ++i) + { + TreeViewItemRenderingState* item = item_to_render->d_renderedChildren.at(i); + RenderedString& rendered_string = item->d_string; + Sizef size(item->d_size); + + // center the expander compared to the item's height + float half_diff = (size.d_height - d_subtreeExpanderImagerySize.d_height) / 2.0f; + + size.d_width = ceguimax(items_area.getWidth(), size.d_width); + float indent = d_subtreeExpanderImagerySize.d_width + expander_margin * 2; + if (item->d_totalChildCount > 0) + { + const ImagerySection* section = item->d_subtreeIsExpanded + ? d_subtreeCollapserImagery : d_subtreeExpanderImagery; + + Rectf button_rect; + button_rect.left(item_pos.x + expander_margin); + button_rect.top(item_pos.y + + (half_diff > 0 ? half_diff : 0)); + button_rect.setSize(d_subtreeExpanderImagerySize); + + Rectf button_clipper(button_rect.getIntersection(items_area)); + section->render(*tree_view, button_rect, 0, &button_clipper); + + indent = button_rect.getWidth() + expander_margin * 2; + } + + Rectf item_rect; + item_rect.left(item_pos.x + indent); + item_rect.top(item_pos.y + (half_diff < 0 ? -half_diff : 0)); + item_rect.setSize(size); + + if (!item->d_icon.empty()) + { + Image& img = ImageManager::getSingleton().get(item->d_icon); + + Rectf icon_rect(item_rect); + icon_rect.setWidth(size.d_height); + icon_rect.setHeight(size.d_height); + + Rectf icon_clipper(icon_rect.getIntersection(items_area)); + img.render(tree_view->getGeometryBuffers(), icon_rect, &icon_clipper, + true, ICON_COLOUR_RECT, 1.0f); + + item_rect.left(item_rect.left() + icon_rect.getWidth()); + } + + Rectf item_clipper(item_rect.getIntersection(items_area)); + renderString(tree_view, rendered_string, item_rect, + tree_view->getFont(), &item_clipper, item->d_isSelected); + + item_pos.y += ceguimax(size.d_height, d_subtreeExpanderImagerySize.d_height); + + if (item->d_renderedChildren.empty()) + continue; + + item_pos.x += indent; + + if (item->d_subtreeIsExpanded) + { + renderTreeItem(tree_view, items_area, item_pos, item, depth + 1); + } + + item_pos.x -= indent; + } +} + +static Sizef getImagerySize(const ImagerySection& section) +{ + //TODO: handle more than 1 imagerycomponent + const ImageryComponent& component = section.getImageryComponents().front(); + const Image* img = component.getImage(); + return img->getRenderedSize(); +} + +//----------------------------------------------------------------------------// +void FalagardTreeView::onLookNFeelAssigned() +{ + const WidgetLookFeel& wlf = getLookNFeel(); + d_subtreeExpanderImagery = &wlf.getImagerySection("SubtreeExpander"); + d_subtreeCollapserImagery = &wlf.getImagerySection("SubtreeCollapser"); + + Sizef open_size = getImagerySize(*d_subtreeExpanderImagery); + Sizef close_size = getImagerySize(*d_subtreeCollapserImagery); + d_subtreeExpanderImagerySize = Sizef( + (open_size.d_width + close_size.d_width) / 2.0f + getView()->getSubtreeExpanderMargin(), + (open_size.d_height + close_size.d_height) / 2.0f + getView()->getSubtreeExpanderMargin()); +} + +//----------------------------------------------------------------------------// +Sizef FalagardTreeView::getSubtreeExpanderSize(void) const +{ + return d_subtreeExpanderImagerySize; +} + +//----------------------------------------------------------------------------// +Rectf FalagardTreeView::getViewRenderArea(void) const +{ + return ItemViewRenderer::getViewRenderArea(getView()); +} + +//----------------------------------------------------------------------------// +float FalagardTreeView::getSubtreeExpanderXIndent(int depth) const +{ + return depth * ( + d_subtreeExpanderImagerySize.d_width + + getView()->getSubtreeExpanderMargin() * 2); +} + +//----------------------------------------------------------------------------// +TreeView* FalagardTreeView::getView() const +{ + return static_cast(d_window); +} + +//----------------------------------------------------------------------------// +void FalagardTreeView::resizeViewToContent(bool fit_width, bool fit_height) const +{ + ItemViewRenderer::resizeViewToContent(getView(), fit_width, fit_height); +} +} diff --git a/cegui/src/XMLParser.cpp b/cegui/src/XMLParser.cpp index dee88a17b..17ddb981f 100644 --- a/cegui/src/XMLParser.cpp +++ b/cegui/src/XMLParser.cpp @@ -53,7 +53,7 @@ namespace CEGUI return d_initialised; } - void XMLParser::parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup) + void XMLParser::parseXMLFile(XMLHandler& handler, const String& filename, const String& schemaName, const String& resourceGroup, bool allowXmlValidation) { // Acquire resource using CEGUI ResourceProvider RawDataContainer rawXMLData; @@ -62,7 +62,7 @@ namespace CEGUI try { // The actual parsing action (this is overridden and depends on the specific parser) - parseXML(handler, rawXMLData, schemaName); + parseXML(handler, rawXMLData, schemaName, allowXmlValidation); } catch (const Exception&) { @@ -80,7 +80,7 @@ namespace CEGUI System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawXMLData); } - void XMLParser::parseXMLString(XMLHandler& handler, const String& source, const String& schemaName) + void XMLParser::parseXMLString(XMLHandler& handler, const String& source, const String& schemaName, bool allowXmlValidation) { // Put the source string into a RawDataContainer RawDataContainer rawXMLData; @@ -92,7 +92,7 @@ namespace CEGUI try { // The actual parsing action (this is overridden and depends on the specific parser) - parseXML(handler, rawXMLData, schemaName); + parseXML(handler, rawXMLData, schemaName, allowXmlValidation); } catch(...) { diff --git a/cegui/src/XMLParserModules/Expat/XMLParser.cpp b/cegui/src/XMLParserModules/Expat/XMLParser.cpp index d74c1bbb6..39083dd78 100644 --- a/cegui/src/XMLParserModules/Expat/XMLParser.cpp +++ b/cegui/src/XMLParserModules/Expat/XMLParser.cpp @@ -46,7 +46,7 @@ ExpatParser::~ExpatParser(void) { } -void ExpatParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/) +void ExpatParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& /*schemaName*/, bool /*allowXmlValidation*/) { // All stuff goes here XML_Parser parser = XML_ParserCreate(0); // Create a parser diff --git a/cegui/src/XMLParserModules/Expat/XMLParserModule.cpp b/cegui/src/XMLParserModules/Expat/XMLParserModule.cpp index be2d07ab0..3a33f1622 100644 --- a/cegui/src/XMLParserModules/Expat/XMLParserModule.cpp +++ b/cegui/src/XMLParserModules/Expat/XMLParserModule.cpp @@ -29,10 +29,10 @@ CEGUI::XMLParser* createParser(void) { - return CEGUI_NEW_AO CEGUI::ExpatParser(); + return new CEGUI::ExpatParser(); } void destroyParser(CEGUI::XMLParser* parser) { - CEGUI_DELETE_AO parser; + delete parser; } diff --git a/cegui/src/XMLParserModules/Libxml2/XMLParser.cpp b/cegui/src/XMLParserModules/Libxml2/XMLParser.cpp index 73934d3fa..0973d7900 100644 --- a/cegui/src/XMLParserModules/Libxml2/XMLParser.cpp +++ b/cegui/src/XMLParserModules/Libxml2/XMLParser.cpp @@ -91,7 +91,8 @@ LibxmlParser::~LibxmlParser(void) void LibxmlParser::parseXML(XMLHandler& handler, const RawDataContainer& source, - const String& /*schemaName*/) + const String& /*schemaName*/, + bool /*allowXmlValidation*/) { xmlDocPtr doc = xmlParseMemory( reinterpret_cast(source.getDataPtr()), diff --git a/cegui/src/XMLParserModules/Libxml2/XMLParserModule.cpp b/cegui/src/XMLParserModules/Libxml2/XMLParserModule.cpp index f29ec0679..6b4737c15 100644 --- a/cegui/src/XMLParserModules/Libxml2/XMLParserModule.cpp +++ b/cegui/src/XMLParserModules/Libxml2/XMLParserModule.cpp @@ -29,10 +29,10 @@ CEGUI::XMLParser* createParser(void) { - return CEGUI_NEW_AO CEGUI::LibxmlParser(); + return new CEGUI::LibxmlParser(); } void destroyParser(CEGUI::XMLParser* parser) { - CEGUI_DELETE_AO parser; + delete parser; } diff --git a/cegui/src/XMLParserModules/RapidXML/XMLParser.cpp b/cegui/src/XMLParserModules/RapidXML/XMLParser.cpp index ac4ee7ff2..aad441828 100644 --- a/cegui/src/XMLParserModules/RapidXML/XMLParser.cpp +++ b/cegui/src/XMLParserModules/RapidXML/XMLParser.cpp @@ -177,7 +177,8 @@ RapidXMLParser::~RapidXMLParser(void) //----------------------------------------------------------------------------// void RapidXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, - const String& schemaName) + const String& schemaName, + bool /*allowXmlValidation*/) { RapidXMLDocument doc(handler, source, schemaName); } diff --git a/cegui/src/XMLParserModules/RapidXML/XMLParserModule.cpp b/cegui/src/XMLParserModules/RapidXML/XMLParserModule.cpp index b523d8d80..aa5cb549c 100644 --- a/cegui/src/XMLParserModules/RapidXML/XMLParserModule.cpp +++ b/cegui/src/XMLParserModules/RapidXML/XMLParserModule.cpp @@ -30,13 +30,13 @@ //----------------------------------------------------------------------------// CEGUI::XMLParser* createParser(void) { - return CEGUI_NEW_AO CEGUI::RapidXMLParser(); + return new CEGUI::RapidXMLParser(); } //----------------------------------------------------------------------------// void destroyParser(CEGUI::XMLParser* parser) { - CEGUI_DELETE_AO parser; + delete parser; } //----------------------------------------------------------------------------// diff --git a/cegui/src/XMLParserModules/TinyXML/XMLParser.cpp b/cegui/src/XMLParserModules/TinyXML/XMLParser.cpp index 1660499de..617ea16b8 100644 --- a/cegui/src/XMLParserModules/TinyXML/XMLParser.cpp +++ b/cegui/src/XMLParserModules/TinyXML/XMLParser.cpp @@ -152,7 +152,7 @@ namespace CEGUI TinyXMLParser::~TinyXMLParser(void) {} - void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName) + void TinyXMLParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool /*allowXmlValidation*/) { TinyXMLDocument doc(handler, source, schemaName); } diff --git a/cegui/src/XMLParserModules/TinyXML/XMLParserModule.cpp b/cegui/src/XMLParserModules/TinyXML/XMLParserModule.cpp index 431304096..f71490af9 100644 --- a/cegui/src/XMLParserModules/TinyXML/XMLParserModule.cpp +++ b/cegui/src/XMLParserModules/TinyXML/XMLParserModule.cpp @@ -29,10 +29,10 @@ CEGUI::XMLParser* createParser(void) { - return CEGUI_NEW_AO CEGUI::TinyXMLParser(); + return new CEGUI::TinyXMLParser(); } void destroyParser(CEGUI::XMLParser* parser) { - CEGUI_DELETE_AO parser; + delete parser; } diff --git a/cegui/src/XMLParserModules/Xerces/XMLParser.cpp b/cegui/src/XMLParserModules/Xerces/XMLParser.cpp index d8d826c12..3036605a9 100644 --- a/cegui/src/XMLParserModules/Xerces/XMLParser.cpp +++ b/cegui/src/XMLParserModules/Xerces/XMLParser.cpp @@ -58,12 +58,22 @@ namespace CEGUI d_identifierString = "CEGUI::XercesParser - Official Xerces-C++ based parser module for CEGUI"; // add property addProperty(&s_schemaDefaultResourceGroupProperty); + + String propertyOrigin("XercesParser"); + CEGUI_DEFINE_PROPERTY(XercesParser, bool, "isXmlValidationEnabled", + "Property to get/set if XML validation is enabled or disabled globally. " + "If it's disabled it will not allow any xml validation. " + "If it's enabled the validation behaviour is dependending on what is " + "passed to parseXML.", + &XercesParser::setXmlValidationEnabled, + &XercesParser::isXmlValidationEnabled, + true); } XercesParser::~XercesParser(void) {} - void XercesParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName) + void XercesParser::parseXML(XMLHandler& handler, const RawDataContainer& source, const String& schemaName, bool xmlValidationEnabled) { XERCES_CPP_NAMESPACE_USE; @@ -74,8 +84,17 @@ namespace CEGUI CEGUI_TRY { + bool forceXmlValidation; + + // ignore local settings if validation is disabled globally + if (!isXmlValidationEnabled()) + forceXmlValidation = false; + else + forceXmlValidation = xmlValidationEnabled; + // set up schema - initialiseSchema(reader, schemaName); + if (forceXmlValidation) + initialiseSchema(reader, schemaName); // do parse doParse(reader, source); } @@ -207,37 +226,46 @@ namespace CEGUI void XercesParser::initialiseSchema(XERCES_CPP_NAMESPACE::SAX2XMLReader* reader, const String& schemaName) { - XERCES_CPP_NAMESPACE_USE; - - // enable schema use and set validation options - reader->setFeature(XMLUni::fgXercesSchema, true); - reader->setFeature(XMLUni::fgSAX2CoreValidation, true); - reader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true); - - // load in the raw schema data - RawDataContainer rawSchemaData; - // load the schema from the resource group - Logger::getSingleton().logEvent("XercesParser::initialiseSchema - Attempting to load schema from file '" + schemaName + "'."); - System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaName, rawSchemaData, d_defaultSchemaResourceGroup); - - // wrap schema data in a xerces MemBufInputSource object - MemBufInputSource schemaData( - rawSchemaData.getDataPtr(), - static_cast(rawSchemaData.getSize()), - schemaName.c_str(), - false); - reader->loadGrammar(schemaData, Grammar::SchemaGrammarType, true); - // enable grammar reuse - reader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true); - - // set schema for usage - XMLCh* pval = XMLString::transcode(schemaName.c_str()); - reader->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval); - XMLString::release(&pval); - Logger::getSingleton().logEvent("XercesParser::initialiseSchema - XML schema file '" + schemaName + "' has been initialised."); - - // use resource provider to release loaded schema data (if it supports this) - System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawSchemaData); + // only load the schema if it's name is passed + if (!schemaName.empty()) + { + XERCES_CPP_NAMESPACE_USE; + + // enable schema use and set validation options + reader->setFeature(XMLUni::fgXercesSchema, true); + reader->setFeature(XMLUni::fgSAX2CoreValidation, true); + reader->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true); + + // load in the raw schema data + RawDataContainer rawSchemaData; + // load the schema from the resource group + Logger::getSingleton().logEvent("XercesParser::initialiseSchema - Attempting to load schema from file '" + schemaName + "'."); + System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaName, rawSchemaData, d_defaultSchemaResourceGroup); + + // wrap schema data in a xerces MemBufInputSource object + MemBufInputSource schemaData( + rawSchemaData.getDataPtr(), + static_cast(rawSchemaData.getSize()), + schemaName.c_str(), + false); + reader->loadGrammar(schemaData, Grammar::SchemaGrammarType, true); + // enable grammar reuse + reader->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true); + + // set schema for usage + XMLCh* pval = XMLString::transcode(schemaName.c_str()); + reader->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval); + XMLString::release(&pval); + Logger::getSingleton().logEvent("XercesParser::initialiseSchema - XML schema file '" + schemaName + "' has been initialised."); + + // use resource provider to release loaded schema data (if it supports this) + System::getSingleton().getResourceProvider()->unloadRawDataContainer(rawSchemaData); + } + else + { + // otherwise ignore the missing schema and proceed + Logger::getSingleton().logEvent("XercesParser::initialiseSchema - No schema specified. Proceeding."); + } } XERCES_CPP_NAMESPACE::SAX2XMLReader* XercesParser::createReader(XERCES_CPP_NAMESPACE::DefaultHandler& handler) diff --git a/cegui/src/XMLParserModules/Xerces/XMLParserModule.cpp b/cegui/src/XMLParserModules/Xerces/XMLParserModule.cpp index cf78589bf..108c953a2 100644 --- a/cegui/src/XMLParserModules/Xerces/XMLParserModule.cpp +++ b/cegui/src/XMLParserModules/Xerces/XMLParserModule.cpp @@ -29,10 +29,10 @@ CEGUI::XMLParser* createParser(void) { - return CEGUI_NEW_AO CEGUI::XercesParser(); + return new CEGUI::XercesParser(); } void destroyParser(CEGUI::XMLParser* parser) { - CEGUI_DELETE_AO parser; + delete parser; } diff --git a/cegui/src/XMLParserModules/Xerces/XMLParserProperties.cpp b/cegui/src/XMLParserModules/Xerces/XMLParserProperties.cpp index faa281068..10b7d3dde 100644 --- a/cegui/src/XMLParserModules/Xerces/XMLParserProperties.cpp +++ b/cegui/src/XMLParserModules/Xerces/XMLParserProperties.cpp @@ -32,9 +32,13 @@ namespace CEGUI { namespace XercesParserProperties -{ -//----------------------------------------------------------------------------// +{ + +//////////////////////////////////////////////////////////////////////////////// +// SchemaDefaultGroup +//////////////////////////////////////////////////////////////////////////////// +//----------------------------------------------------------------------------// String SchemaDefaultResourceGroup::get(const PropertyReceiver* receiver) const { return static_cast(receiver)-> @@ -51,11 +55,9 @@ void SchemaDefaultResourceGroup::set(PropertyReceiver* receiver, //----------------------------------------------------------------------------// Property* SchemaDefaultResourceGroup::clone() const { - return CEGUI_NEW_AO SchemaDefaultResourceGroup(*this); + return new SchemaDefaultResourceGroup(*this); } -//----------------------------------------------------------------------------// -// } // End of XercesParserProperties namespace section } // End of CEGUI namespace section diff --git a/cegui/src/falagard/Dimensions.cpp b/cegui/src/falagard/Dimensions.cpp index 457a5dfaf..ae26ca4ab 100644 --- a/cegui/src/falagard/Dimensions.cpp +++ b/cegui/src/falagard/Dimensions.cpp @@ -97,14 +97,14 @@ OperatorDim::OperatorDim(DimensionOperator op, BaseDim* left, BaseDim* right) : //----------------------------------------------------------------------------// OperatorDim::~OperatorDim() { - CEGUI_DELETE_AO d_right; - CEGUI_DELETE_AO d_left; + delete d_right; + delete d_left; } //----------------------------------------------------------------------------// void OperatorDim::setLeftOperand(const BaseDim* operand) { - CEGUI_DELETE_AO d_left; + delete d_left; d_left = operand ? operand->clone() : 0; } @@ -118,7 +118,7 @@ BaseDim* OperatorDim::getLeftOperand() const //----------------------------------------------------------------------------// void OperatorDim::setRightOperand(const BaseDim* operand) { - CEGUI_DELETE_AO d_right; + delete d_right; d_right = operand ? operand->clone() : 0; } @@ -202,7 +202,7 @@ float OperatorDim::getValueImpl(const float lval, const float rval) const //----------------------------------------------------------------------------// BaseDim* OperatorDim::clone() const { - return CEGUI_NEW_AO OperatorDim(d_op, d_left, d_right); + return new OperatorDim(d_op, d_left, d_right); } //----------------------------------------------------------------------------// @@ -267,7 +267,7 @@ float AbsoluteDim::getValue(const Window&, const Rectf&) const //----------------------------------------------------------------------------// BaseDim* AbsoluteDim::clone() const { - return CEGUI_NEW_AO AbsoluteDim(*this); + return new AbsoluteDim(*this); } //----------------------------------------------------------------------------// @@ -321,11 +321,11 @@ float ImageDimBase::getValue(const Window& wnd) const break; case DT_X_OFFSET: - return img->getRenderedOffset().d_x; + return img->getRenderedOffset().x; break; case DT_Y_OFFSET: - return img->getRenderedOffset().d_y; + return img->getRenderedOffset().y; break; default: @@ -379,7 +379,7 @@ const Image* ImageDim::getSourceImage(const Window& /*wnd*/) const //----------------------------------------------------------------------------// BaseDim* ImageDim::clone() const { - return CEGUI_NEW_AO ImageDim(*this); + return new ImageDim(*this); } //----------------------------------------------------------------------------// @@ -427,7 +427,7 @@ const Image* ImagePropertyDim::getSourceImage(const Window& wnd) const //----------------------------------------------------------------------------// BaseDim* ImagePropertyDim::clone() const { - return CEGUI_NEW_AO ImagePropertyDim(*this); + return new ImagePropertyDim(*this); } //----------------------------------------------------------------------------// @@ -549,7 +549,7 @@ float WidgetDim::getValue(const Window& wnd, const Rectf&) const //----------------------------------------------------------------------------// BaseDim* WidgetDim::clone() const { - return CEGUI_NEW_AO WidgetDim(*this); + return new WidgetDim(*this); } //----------------------------------------------------------------------------// @@ -690,7 +690,7 @@ float FontDim::getValue(const Window& wnd, const Rectf&) const //----------------------------------------------------------------------------// BaseDim* FontDim::clone() const { - return CEGUI_NEW_AO FontDim(*this); + return new FontDim(*this); } //----------------------------------------------------------------------------// @@ -814,7 +814,7 @@ float PropertyDim::getValue(const Window& wnd, const Rectf&) const //----------------------------------------------------------------------------// BaseDim* PropertyDim::clone() const { - return CEGUI_NEW_AO PropertyDim(*this); + return new PropertyDim(*this); } //----------------------------------------------------------------------------// @@ -846,7 +846,7 @@ Dimension::Dimension() Dimension::~Dimension() { if (d_value) - CEGUI_DELETE_AO d_value; + delete d_value; } //----------------------------------------------------------------------------// @@ -868,7 +868,7 @@ Dimension& Dimension::operator=(const Dimension& other) { // release old value, if any. if (d_value) - CEGUI_DELETE_AO d_value; + delete d_value; d_value = other.d_value ? other.d_value->clone() : 0; d_type = other.d_type; @@ -888,7 +888,7 @@ void Dimension::setBaseDimension(const BaseDim& dim) { // release old value, if any. if (d_value) - CEGUI_DELETE_AO d_value; + delete d_value; d_value = dim.clone(); } @@ -1016,7 +1016,7 @@ float UnifiedDim::getValue(const Window&, const Rectf& container) const //----------------------------------------------------------------------------// BaseDim* UnifiedDim::clone() const { - UnifiedDim* ndim = CEGUI_NEW_AO UnifiedDim(d_value, d_what); + UnifiedDim* ndim = new UnifiedDim(d_value, d_what); return ndim; } @@ -1194,7 +1194,7 @@ const String& ComponentArea::getNamedAreaSourceLook() const } //----------------------------------------------------------------------------// -void ComponentArea::setNamedAreaSouce(const String& widget_look, +void ComponentArea::setNamedAreaSource(const String& widget_look, const String& area_name) { d_namedSource = area_name; diff --git a/cegui/src/falagard/EventLinkDefinition.cpp b/cegui/src/falagard/EventLinkDefinition.cpp index 2041e244b..e9126376e 100644 --- a/cegui/src/falagard/EventLinkDefinition.cpp +++ b/cegui/src/falagard/EventLinkDefinition.cpp @@ -33,12 +33,6 @@ // Start of CEGUI namespace section namespace CEGUI { -//----------------------------------------------------------------------------// -// String holding parent link identifier -// This is deprecated and declared as an extern in PropertyLinkDefinition.h -static const String S_parentIdentifier("__parent__"); - - //----------------------------------------------------------------------------// EventLinkDefinition::EventLinkDefinition(const String& event_name) : d_eventName(event_name) @@ -66,7 +60,7 @@ void EventLinkDefinition::clearLinkTargets() //----------------------------------------------------------------------------// void EventLinkDefinition::initialiseWidget(Window& window) const { - LinkedEvent* e = CEGUI_NEW_AO LinkedEvent(d_eventName, &window); + LinkedEvent* e = new LinkedEvent(d_eventName, &window); LinkTargetCollection::const_iterator i = d_targets.begin(); for ( ; i != d_targets.end(); ++i) diff --git a/cegui/src/falagard/FrameComponent.cpp b/cegui/src/falagard/FrameComponent.cpp index 68a5d502e..d5afb21a3 100644 --- a/cegui/src/falagard/FrameComponent.cpp +++ b/cegui/src/falagard/FrameComponent.cpp @@ -32,7 +32,7 @@ #include "CEGUI/Image.h" #include "CEGUI/CoordConverter.h" #include -#include +#include namespace CEGUI { @@ -268,7 +268,7 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, Rectf backgroundRect(destRect); Rectf finalRect; Sizef imageSize; - Vector2f imageOffsets; + glm::vec2 imageOffsets; ColourRect imageColours; float leftfactor, rightfactor, topfactor, bottomfactor; bool calcColoursPerImage; @@ -304,24 +304,24 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection(finalRect); // update adjustments required to edges do to presence of this element. - topOffset += imageSize.d_width + imageOffsets.d_x; - leftOffset += imageSize.d_height + imageOffsets.d_y; + topOffset += imageSize.d_width + imageOffsets.x; + leftOffset += imageSize.d_height + imageOffsets.y; topWidth -= topOffset; leftHeight -= leftOffset; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + imageOffsets.d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + imageOffsets.x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + imageOffsets.d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + imageOffsets.y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle( leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - componentImage->render(srcWindow.getGeometryBuffer(), finalRect, clipper, imageColours); + componentImage->render(srcWindow.getGeometryBuffers(), finalRect, clipper, !clipToDisplay, imageColours); } // top-right image @@ -336,23 +336,23 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection(finalRect); // update adjustments required to edges do to presence of this element. - rightOffset += imageSize.d_height + imageOffsets.d_y; - topWidth -= imageSize.d_width - imageOffsets.d_x; + rightOffset += imageSize.d_height + imageOffsets.y; + topWidth -= imageSize.d_width - imageOffsets.x; rightHeight -= rightOffset; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + imageOffsets.d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + imageOffsets.x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + imageOffsets.d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + imageOffsets.y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle(leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - componentImage->render(srcWindow.getGeometryBuffer(), finalRect, clipper, imageColours); + componentImage->render(srcWindow.getGeometryBuffers(), finalRect, clipper, !clipToDisplay, imageColours); } // bottom-left image @@ -367,23 +367,23 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection(finalRect); // update adjustments required to edges do to presence of this element. - bottomOffset += imageSize.d_width + imageOffsets.d_x; + bottomOffset += imageSize.d_width + imageOffsets.x; bottomWidth -= bottomOffset; - leftHeight -= imageSize.d_height - imageOffsets.d_y; + leftHeight -= imageSize.d_height - imageOffsets.y; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + imageOffsets.d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + imageOffsets.x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + imageOffsets.d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + imageOffsets.y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle(leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - componentImage->render(srcWindow.getGeometryBuffer(), finalRect, clipper, imageColours); + componentImage->render(srcWindow.getGeometryBuffers(), finalRect, clipper, !clipToDisplay, imageColours); } // bottom-right image @@ -398,22 +398,22 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection(finalRect); // update adjustments required to edges do to presence of this element. - bottomWidth -= imageSize.d_width - imageOffsets.d_x; - rightHeight -= imageSize.d_height - imageOffsets.d_y; + bottomWidth -= imageSize.d_width - imageOffsets.x; + rightHeight -= imageSize.d_height - imageOffsets.y; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + componentImage->getRenderedOffset().d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + componentImage->getRenderedOffset().x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + componentImage->getRenderedOffset().d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + componentImage->getRenderedOffset().y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle( leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - componentImage->render(srcWindow.getGeometryBuffer(), finalRect, clipper, imageColours); + componentImage->render(srcWindow.getGeometryBuffers(), finalRect, clipper, !clipToDisplay, imageColours); } // top image @@ -428,21 +428,21 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection(finalRect); // adjust background area to miss this edge - backgroundRect.d_min.d_y += imageSize.d_height + componentImage->getRenderedOffset().d_y; + backgroundRect.d_min.d_y += imageSize.d_height + componentImage->getRenderedOffset().y; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + componentImage->getRenderedOffset().d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + componentImage->getRenderedOffset().x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + componentImage->getRenderedOffset().d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + componentImage->getRenderedOffset().y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle( leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - renderImage(srcWindow.getGeometryBuffer(), componentImage, + renderImage(srcWindow.getGeometryBuffers(), componentImage, VF_TOP_ALIGNED, d_topEdgeFormatting.get(srcWindow), finalRect, imageColours, clipper, clipToDisplay); } @@ -459,21 +459,21 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection (finalRect); // adjust background area to miss this edge - backgroundRect.d_max.d_y -= imageSize.d_height - componentImage->getRenderedOffset().d_y; + backgroundRect.d_max.d_y -= imageSize.d_height - componentImage->getRenderedOffset().y; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + componentImage->getRenderedOffset().d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + componentImage->getRenderedOffset().x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + componentImage->getRenderedOffset().d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + componentImage->getRenderedOffset().y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle(leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - renderImage(srcWindow.getGeometryBuffer(), componentImage, + renderImage(srcWindow.getGeometryBuffers(), componentImage, VF_BOTTOM_ALIGNED, d_bottomEdgeFormatting.get(srcWindow), finalRect, imageColours, clipper, clipToDisplay); } @@ -490,21 +490,21 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection(finalRect); // adjust background area to miss this edge - backgroundRect.d_min.d_x += imageSize.d_width + componentImage->getRenderedOffset().d_x; + backgroundRect.d_min.d_x += imageSize.d_width + componentImage->getRenderedOffset().x; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + componentImage->getRenderedOffset().d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + componentImage->getRenderedOffset().x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + componentImage->getRenderedOffset().d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + componentImage->getRenderedOffset().y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle( leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - renderImage(srcWindow.getGeometryBuffer(), componentImage, + renderImage(srcWindow.getGeometryBuffers(), componentImage, d_leftEdgeFormatting.get(srcWindow), HF_LEFT_ALIGNED, finalRect, imageColours, clipper, clipToDisplay); } @@ -521,21 +521,21 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, finalRect = destRect.getIntersection (finalRect); // adjust background area to miss this edge - backgroundRect.d_max.d_x -= imageSize.d_width - componentImage->getRenderedOffset().d_x; + backgroundRect.d_max.d_x -= imageSize.d_width - componentImage->getRenderedOffset().x; // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (finalRect.left() + componentImage->getRenderedOffset().d_x) / destRect.getWidth(); + leftfactor = (finalRect.left() + componentImage->getRenderedOffset().x) / destRect.getWidth(); rightfactor = leftfactor + finalRect.getWidth() / destRect.getWidth(); - topfactor = (finalRect.top() + componentImage->getRenderedOffset().d_y) / destRect.getHeight(); + topfactor = (finalRect.top() + componentImage->getRenderedOffset().y) / destRect.getHeight(); bottomfactor = topfactor + finalRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle( leftfactor, rightfactor, topfactor, bottomfactor); } // draw this element. - renderImage(srcWindow.getGeometryBuffer(), componentImage, + renderImage(srcWindow.getGeometryBuffers(), componentImage, d_rightEdgeFormatting.get(srcWindow), HF_RIGHT_ALIGNED, finalRect, imageColours, clipper, clipToDisplay); } @@ -545,9 +545,9 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, // calculate colours that are to be used to this component image if (calcColoursPerImage) { - leftfactor = (backgroundRect.left() + componentImage->getRenderedOffset().d_x) / destRect.getWidth(); + leftfactor = (backgroundRect.left() + componentImage->getRenderedOffset().x) / destRect.getWidth(); rightfactor = leftfactor + backgroundRect.getWidth() / destRect.getWidth(); - topfactor = (backgroundRect.top() + componentImage->getRenderedOffset().d_y) / destRect.getHeight(); + topfactor = (backgroundRect.top() + componentImage->getRenderedOffset().y) / destRect.getHeight(); bottomfactor = topfactor + backgroundRect.getHeight() / destRect.getHeight(); imageColours = finalColours.getSubRectangle( leftfactor, rightfactor, topfactor, bottomfactor); @@ -559,18 +559,18 @@ void FrameComponent::render_impl(Window& srcWindow, Rectf& destRect, const VerticalFormatting vertFormatting = d_backgroundVertFormatting.get(srcWindow); - renderImage(srcWindow.getGeometryBuffer(), componentImage, + renderImage(srcWindow.getGeometryBuffers(), componentImage, vertFormatting, horzFormatting, backgroundRect, imageColours, clipper, clipToDisplay); } } //----------------------------------------------------------------------------// -void FrameComponent::renderImage(GeometryBuffer& buffer, const Image* image, +void FrameComponent::renderImage(std::vector& geometry_buffers, const Image* image, VerticalFormatting vertFmt, HorizontalFormatting horzFmt, Rectf& destRect, const ColourRect& colours, - const Rectf* clipper, bool /*clipToDisplay*/) const + const Rectf* clipper, bool clip_to_display) const { uint horzTiles, vertTiles; float xpos, ypos; @@ -672,7 +672,7 @@ void FrameComponent::renderImage(GeometryBuffer& buffer, const Image* image, else clippingRect = clipper; - image->render(buffer, finalRect, clippingRect, colours); + image->render(geometry_buffers, finalRect, clippingRect, !clip_to_display, colours); finalRect.d_min.d_x += imgSz.d_width; finalRect.d_max.d_x += imgSz.d_width; diff --git a/cegui/src/falagard/ImageryComponent.cpp b/cegui/src/falagard/ImageryComponent.cpp index cf8c87019..e4a0f19d6 100644 --- a/cegui/src/falagard/ImageryComponent.cpp +++ b/cegui/src/falagard/ImageryComponent.cpp @@ -33,7 +33,7 @@ #include "CEGUI/PropertyHelper.h" #include "CEGUI/CoordConverter.h" #include -#include +#include // void draw(const Rect& dest_rect, float z, const Rect& clip_rect,const ColourRect& colours); @@ -120,7 +120,7 @@ namespace CEGUI d_vertFormatting.setPropertySource(property_name); } - void ImageryComponent::render_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool /*clipToDisplay*/) const + void ImageryComponent::render_impl(Window& srcWindow, Rectf& destRect, const CEGUI::ColourRect* modColours, const Rectf* clipper, bool clip_to_display) const { // get final image to use. const Image* img = isImageFetchedFromProperty() ? @@ -241,7 +241,7 @@ namespace CEGUI } // add geometry for image to the target window. - img->render(srcWindow.getGeometryBuffer(), finalRect, clippingRect, finalColours); + img->render(srcWindow.getGeometryBuffers(), finalRect, clippingRect, !clip_to_display, finalColours); finalRect.d_min.d_x += imgSz.d_width; finalRect.d_max.d_x += imgSz.d_width; diff --git a/cegui/src/falagard/ImagerySection.cpp b/cegui/src/falagard/ImagerySection.cpp index 8d454ad3a..b5b080e12 100644 --- a/cegui/src/falagard/ImagerySection.cpp +++ b/cegui/src/falagard/ImagerySection.cpp @@ -55,17 +55,17 @@ namespace CEGUI ColourRect* finalColsPtr = (finalCols.isMonochromatic() && finalCols.d_top_left.getARGB() == 0xFFFFFFFF) ? 0 : &finalCols; // render all frame components in this section - for(FrameList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) + for(FrameComponentList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) { (*frame).render(srcWindow, finalColsPtr, clipper, clipToDisplay); } // render all image components in this section - for(ImageryList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) + for(ImageryComponentList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) { (*image).render(srcWindow, finalColsPtr, clipper, clipToDisplay); } // render all text components in this section - for(TextList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) + for(TextComponentList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) { (*text).render(srcWindow, finalColsPtr, clipper, clipToDisplay); } @@ -83,17 +83,17 @@ namespace CEGUI ColourRect* finalColsPtr = (finalCols.isMonochromatic() && finalCols.d_top_left.getARGB() == 0xFFFFFFFF) ? 0 : &finalCols; // render all frame components in this section - for(FrameList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) + for(FrameComponentList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) { (*frame).render(srcWindow, baseRect, finalColsPtr, clipper, clipToDisplay); } // render all image components in this section - for(ImageryList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) + for(ImageryComponentList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) { (*image).render(srcWindow, baseRect, finalColsPtr, clipper, clipToDisplay); } // render all text components in this section - for(TextList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) + for(TextComponentList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) { (*text).render(srcWindow, baseRect, finalColsPtr, clipper, clipToDisplay); } @@ -106,8 +106,8 @@ namespace CEGUI void ImagerySection::removeImageryComponent(const ImageryComponent& imageryComponent) { - ImageryList::iterator imageryComponentIter = d_images.begin(); - ImageryList::iterator imageryComponentIterEnd = d_images.end(); + ImageryComponentList::iterator imageryComponentIter = d_images.begin(); + ImageryComponentList::iterator imageryComponentIterEnd = d_images.end(); while(imageryComponentIter != imageryComponentIterEnd) { if(&(*imageryComponentIter) == &imageryComponent) @@ -135,8 +135,8 @@ namespace CEGUI void ImagerySection::removeTextComponent(const TextComponent& textComponent) { - TextList::iterator textComponentIter = d_texts.begin(); - TextList::iterator textComponentIterEnd = d_texts.end(); + TextComponentList::iterator textComponentIter = d_texts.begin(); + TextComponentList::iterator textComponentIterEnd = d_texts.end(); while(textComponentIter != textComponentIterEnd) { if(&(*textComponentIter) == &textComponent) @@ -169,8 +169,8 @@ namespace CEGUI void ImagerySection::removeFrameComponent(const FrameComponent& frameComponent) { - FrameList::iterator frameComponentIter = d_frames.begin(); - FrameList::iterator frameComponentIterEnd = d_frames.end(); + FrameComponentList::iterator frameComponentIter = d_frames.begin(); + FrameComponentList::iterator frameComponentIterEnd = d_frames.end(); while(frameComponentIter != frameComponentIterEnd) { if(&(*frameComponentIter) == &frameComponent) @@ -240,7 +240,7 @@ namespace CEGUI std::numeric_limits::min()); // measure all frame components - for(FrameList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) + for(FrameComponentList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) { compRect = (*frame).getComponentArea().getPixelRect(wnd); @@ -250,7 +250,7 @@ namespace CEGUI bounds.bottom(ceguimax(bounds.bottom(), compRect.bottom())); } // measure all imagery components - for(ImageryList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) + for(ImageryComponentList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) { compRect = (*image).getComponentArea().getPixelRect(wnd); @@ -260,7 +260,7 @@ namespace CEGUI bounds.bottom(ceguimax(bounds.bottom(), compRect.bottom())); } // measure all text components - for(TextList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) + for(TextComponentList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) { compRect = (*text).getComponentArea().getPixelRect(wnd); @@ -282,7 +282,7 @@ namespace CEGUI std::numeric_limits::min()); // measure all frame components - for(FrameList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) + for(FrameComponentList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) { compRect = (*frame).getComponentArea().getPixelRect(wnd, rect); @@ -292,7 +292,7 @@ namespace CEGUI bounds.bottom(ceguimax(bounds.bottom(), compRect.bottom())); } // measure all imagery components - for(ImageryList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) + for(ImageryComponentList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) { compRect = (*image).getComponentArea().getPixelRect(wnd, rect); @@ -302,7 +302,7 @@ namespace CEGUI bounds.bottom(ceguimax(bounds.bottom(), compRect.bottom())); } // measure all text components - for(TextList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) + for(TextComponentList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) { compRect = (*text).getComponentArea().getPixelRect(wnd, rect); @@ -339,19 +339,19 @@ namespace CEGUI } // output all frame components. - for(FrameList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) + for(FrameComponentList::const_iterator frame = d_frames.begin(); frame != d_frames.end(); ++frame) { (*frame).writeXMLToStream(xml_stream); } // output all imagery components - for(ImageryList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) + for(ImageryComponentList::const_iterator image = d_images.begin(); image != d_images.end(); ++image) { (*image).writeXMLToStream(xml_stream); } // output all text components - for(TextList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) + for(TextComponentList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) { (*text).writeXMLToStream(xml_stream); } @@ -365,7 +365,7 @@ namespace CEGUI { bool result = false; - for(TextList::const_iterator text = d_texts.begin(); + for(TextComponentList::const_iterator text = d_texts.begin(); text != d_texts.end(); ++text) { @@ -375,28 +375,12 @@ namespace CEGUI return result; } - ImagerySection::ImageryComponentIterator - ImagerySection::getImageryComponentIterator() const - { - return ImageryComponentIterator(d_images.begin(), d_images.end()); - } - ImagerySection::TextComponentIterator - ImagerySection::getTextComponentIterator() const - { - return TextComponentIterator(d_texts.begin(), d_texts.end()); - } - ImagerySection::FrameComponentIterator - ImagerySection::getFrameComponentIterator() const - { - return FrameComponentIterator(d_frames.begin(), d_frames.end()); - } - ImagerySection::ImageryComponentPointerList ImagerySection::getImageryComponentPointers() { ImagerySection::ImageryComponentPointerList pointerList; - ImageryList::iterator imageryComponentIter = d_images.begin(); - ImageryList::iterator imageryComponentEnd = d_images.end(); + ImageryComponentList::iterator imageryComponentIter = d_images.begin(); + ImageryComponentList::iterator imageryComponentEnd = d_images.end(); while( imageryComponentIter != imageryComponentEnd ) { pointerList.push_back(&(*imageryComponentIter)); @@ -410,8 +394,8 @@ namespace CEGUI { ImagerySection::TextComponentPointerList pointerList; - TextList::iterator textComponentIter = d_texts.begin(); - TextList::iterator textComponentEnd = d_texts.end(); + TextComponentList::iterator textComponentIter = d_texts.begin(); + TextComponentList::iterator textComponentEnd = d_texts.end(); while( textComponentIter != textComponentEnd ) { pointerList.push_back(&(*textComponentIter)); @@ -425,8 +409,8 @@ namespace CEGUI { ImagerySection::FrameComponentPointerList pointerList; - FrameList::iterator frameComponentIter = d_frames.begin(); - FrameList::iterator frameComponentEnd = d_frames.end(); + FrameComponentList::iterator frameComponentIter = d_frames.begin(); + FrameComponentList::iterator frameComponentEnd = d_frames.end(); while( frameComponentIter != frameComponentEnd ) { pointerList.push_back(&(*frameComponentIter)); @@ -436,4 +420,19 @@ namespace CEGUI return pointerList; } + const ImagerySection::ImageryComponentList& ImagerySection::getImageryComponents() const + { + return d_images; + } + + const ImagerySection::TextComponentList& ImagerySection::getTextComponents() const + { + return d_texts; + } + + const ImagerySection::FrameComponentList& ImagerySection::getFrameComponents() const + { + return d_frames; + } + } // End of CEGUI namespace section diff --git a/cegui/src/falagard/LayerSpecification.cpp b/cegui/src/falagard/LayerSpecification.cpp index 2a413cab8..d0d04eb31 100644 --- a/cegui/src/falagard/LayerSpecification.cpp +++ b/cegui/src/falagard/LayerSpecification.cpp @@ -39,7 +39,7 @@ LayerSpecification::LayerSpecification(uint priority) : void LayerSpecification::render(Window& srcWindow, const ColourRect* modcols, const Rectf* clipper, bool clipToDisplay) const { // render all sections in this layer - for(SectionList::const_iterator curr = d_sections.begin(); curr != d_sections.end(); ++curr) + for(SectionSpecificationList::const_iterator curr = d_sections.begin(); curr != d_sections.end(); ++curr) { (*curr).render(srcWindow, modcols, clipper, clipToDisplay); } @@ -48,7 +48,7 @@ void LayerSpecification::render(Window& srcWindow, const ColourRect* modcols, co void LayerSpecification::render(Window& srcWindow, const Rectf& baseRect, const ColourRect* modcols, const Rectf* clipper, bool clipToDisplay) const { // render all sections in this layer - for(SectionList::const_iterator curr = d_sections.begin(); curr != d_sections.end(); ++curr) + for(SectionSpecificationList::const_iterator curr = d_sections.begin(); curr != d_sections.end(); ++curr) { (*curr).render(srcWindow, baseRect, modcols, clipper, clipToDisplay); } @@ -82,7 +82,7 @@ void LayerSpecification::writeXMLToStream(XMLSerializer& xml_stream) const xml_stream.attribute(Falagard_xmlHandler::PriorityAttribute, PropertyHelper::toString(d_layerPriority)); // ouput all sections in this layer - for(SectionList::const_iterator curr = d_sections.begin(); curr != d_sections.end(); ++curr) + for(SectionSpecificationList::const_iterator curr = d_sections.begin(); curr != d_sections.end(); ++curr) { (*curr).writeXMLToStream(xml_stream); } @@ -90,18 +90,12 @@ void LayerSpecification::writeXMLToStream(XMLSerializer& xml_stream) const xml_stream.closeTag(); } -LayerSpecification::SectionIterator -LayerSpecification::getSectionIterator() const -{ - return SectionIterator(d_sections.begin(), d_sections.end()); -} - LayerSpecification::SectionSpecificationPointerList LayerSpecification::getSectionSpecificationPointers() { LayerSpecification::SectionSpecificationPointerList pointerList; - SectionList::iterator sectionSpecificationIter = d_sections.begin(); - SectionList::iterator sectionSpecificationEnd = d_sections.end(); + SectionSpecificationList::iterator sectionSpecificationIter = d_sections.begin(); + SectionSpecificationList::iterator sectionSpecificationEnd = d_sections.end(); while( sectionSpecificationIter != sectionSpecificationEnd ) { pointerList.push_back(&(*sectionSpecificationIter)); @@ -111,6 +105,11 @@ LayerSpecification::SectionSpecificationPointerList LayerSpecification::getSecti return pointerList; } +const LayerSpecification::SectionSpecificationList& LayerSpecification::getSectionSpecifications() const +{ + return d_sections; +} + bool LayerSpecification::operator< (const LayerSpecification& otherLayerSpec) const { return d_layerPriority < otherLayerSpec.getLayerPriority(); diff --git a/cegui/src/falagard/SectionSpecification.cpp b/cegui/src/falagard/SectionSpecification.cpp index 6fd2d88ea..a0e34fa31 100644 --- a/cegui/src/falagard/SectionSpecification.cpp +++ b/cegui/src/falagard/SectionSpecification.cpp @@ -37,9 +37,6 @@ // Start of CEGUI namespace section namespace CEGUI { - // This is deprecated and declared as an extern in PropertyLinkDefinition.h - const String S_parentIdentifier("__parent__"); - SectionSpecification::SectionSpecification() : d_usingColourOverride(false) {} @@ -90,7 +87,6 @@ namespace CEGUI // decide what colours are to be used ColourRect finalColours; initColourRectForOverride(srcWindow, finalColours); - finalColours.modulateAlpha(srcWindow.getEffectiveAlpha()); if (modcols) finalColours *= *modcols; @@ -121,7 +117,6 @@ namespace CEGUI // decide what colours are to be used ColourRect finalColours; initColourRectForOverride(srcWindow, finalColours); - finalColours.modulateAlpha(srcWindow.getEffectiveAlpha()); if (modcols) finalColours *= *modcols; diff --git a/cegui/src/falagard/StateImagery.cpp b/cegui/src/falagard/StateImagery.cpp index 35a10a402..399e6b104 100644 --- a/cegui/src/falagard/StateImagery.cpp +++ b/cegui/src/falagard/StateImagery.cpp @@ -29,6 +29,8 @@ #include "CEGUI/GeometryBuffer.h" #include "CEGUI/System.h" #include "CEGUI/Renderer.h" + +#include #include // Start of CEGUI namespace section @@ -42,25 +44,28 @@ StateImagery::StateImagery(const String& name) : void StateImagery::render(Window& srcWindow, const ColourRect* modcols, const Rectf* clipper) const { - srcWindow.getGeometryBuffer().setClippingActive(!d_clipToDisplay); - // render all layers defined for this state - for(LayersList::const_iterator curr = d_layers.begin(); curr != d_layers.end(); ++curr) + for(LayerSpecificationList::const_iterator curr = d_layers.begin(); curr != d_layers.end(); ++curr) (*curr).render(srcWindow, modcols, clipper, d_clipToDisplay); } void StateImagery::render(Window& srcWindow, const Rectf& baseRect, const ColourRect* modcols, const Rectf* clipper) const { - srcWindow.getGeometryBuffer().setClippingActive(!d_clipToDisplay); - // render all layers defined for this state - for(LayersList::const_iterator curr = d_layers.begin(); curr != d_layers.end(); ++curr) + for(LayerSpecificationList::const_iterator curr = d_layers.begin(); curr != d_layers.end(); ++curr) (*curr).render(srcWindow, baseRect, modcols, clipper, d_clipToDisplay); } void StateImagery::addLayer(const LayerSpecification& layer) { - d_layers.insert(layer); + d_layers.push_back(layer); + + sort(); +} + +void StateImagery::sort() +{ + std::sort(d_layers.begin(), d_layers.end()); } void StateImagery::clearLayers() @@ -97,58 +102,30 @@ void StateImagery::writeXMLToStream(XMLSerializer& xml_stream) const xml_stream.attribute(Falagard_xmlHandler::ClippedAttribute, PropertyHelper::False); // output all layers defined for this state - for(LayersList::const_iterator curr = d_layers.begin(); curr != d_layers.end(); ++curr) + for(LayerSpecificationList::const_iterator curr = d_layers.begin(); curr != d_layers.end(); ++curr) (*curr).writeXMLToStream(xml_stream); // write closing
tag xml_stream.closeTag(); } -StateImagery::LayerIterator -StateImagery::getLayerIterator() const +const StateImagery::LayerSpecificationList& StateImagery::getLayerSpecifications() const { - return LayerIterator(d_layers.begin(),d_layers.end()); + return d_layers; } StateImagery::LayerSpecificationPointerList StateImagery::getLayerSpecificationPointers() { StateImagery::LayerSpecificationPointerList pointerList; - LayersList::iterator layerSpecIter = d_layers.begin(); - LayersList::iterator layerSpecIterEnd = d_layers.end(); + LayerSpecificationList::iterator layerSpecIter = d_layers.begin(); + LayerSpecificationList::iterator layerSpecIterEnd = d_layers.end(); while( layerSpecIter != layerSpecIterEnd ) { - //! This hack is necessary because in newer C++ versions the multiset and sets return only const iterators. - //! \deprecated This will be replaced with proper types and behaviour in the next version. - LayerSpecification* layerSpec = const_cast(&(*layerSpecIter)); - pointerList.push_back(layerSpec); + pointerList.push_back(&(*layerSpecIter)); ++layerSpecIter; } return pointerList; } -void StateImagery::sort() -{ - //! \deprecated Deprecated behaviour: We have to remove all elements and re-add them to force them to be sorted. - std::vector temporaryList; - - LayersList::iterator layerSpecMapIter = d_layers.begin(); - LayersList::iterator layerSpecMapIterEnd = d_layers.end(); - while( layerSpecMapIter != layerSpecMapIterEnd ) - { - temporaryList.push_back(*layerSpecMapIter); - ++layerSpecMapIter; - } - - clearLayers(); - - std::vector::iterator layerSpecVecIter = temporaryList.begin(); - std::vector::iterator layerSpecVecIterEnd = temporaryList.end(); - while( layerSpecVecIter != layerSpecVecIterEnd ) - { - addLayer(*layerSpecVecIter); - ++layerSpecVecIter; - } -} - } // End of CEGUI namespace section diff --git a/cegui/src/falagard/TextComponent.cpp b/cegui/src/falagard/TextComponent.cpp index c9de5ebcc..a43717753 100644 --- a/cegui/src/falagard/TextComponent.cpp +++ b/cegui/src/falagard/TextComponent.cpp @@ -53,14 +53,14 @@ namespace CEGUI #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), + d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), + d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), - d_formattedRenderedString(CEGUI_NEW_AO LeftAlignedRenderedString(d_renderedString)), + d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)), d_lastHorzFormatting(HTF_LEFT_ALIGNED), d_vertFormatting(VTF_TOP_ALIGNED), d_horzFormatting(HTF_LEFT_ALIGNED) @@ -68,7 +68,7 @@ namespace CEGUI TextComponent::~TextComponent() { - CEGUI_DELETE_AO d_bidiVisualMapping; + delete d_bidiVisualMapping; } TextComponent::TextComponent(const TextComponent& obj) : @@ -77,9 +77,9 @@ namespace CEGUI #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), + d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), + d_bidiVisualMapping(new MinibidiVisualMapping), #endif d_bidiDataValid(false), d_renderedString(obj.d_renderedString), @@ -208,45 +208,45 @@ namespace CEGUI { case HTF_LEFT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO LeftAlignedRenderedString(rendered_string); + new LeftAlignedRenderedString(rendered_string); break; case HTF_CENTRE_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO CentredRenderedString(rendered_string); + new CentredRenderedString(rendered_string); break; case HTF_RIGHT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RightAlignedRenderedString(rendered_string); + new RightAlignedRenderedString(rendered_string); break; case HTF_JUSTIFIED: d_formattedRenderedString = - CEGUI_NEW_AO JustifiedRenderedString(rendered_string); + new JustifiedRenderedString(rendered_string); break; case HTF_WORDWRAP_LEFT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (rendered_string); break; case HTF_WORDWRAP_CENTRE_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (rendered_string); break; case HTF_WORDWRAP_RIGHT_ALIGNED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (rendered_string); break; case HTF_WORDWRAP_JUSTIFIED: d_formattedRenderedString = - CEGUI_NEW_AO RenderedStringWordWrapper + new RenderedStringWordWrapper (rendered_string); break; } @@ -319,8 +319,8 @@ namespace CEGUI initColoursRect(srcWindow, modColours, finalColours); // add geometry for text to the target window. - d_formattedRenderedString->draw(&srcWindow, srcWindow.getGeometryBuffer(), - destRect.getPosition(), + d_formattedRenderedString->draw(&srcWindow, srcWindow.getGeometryBuffers(), + destRect.getPositionGLM(), &finalColours, clipper); } diff --git a/cegui/src/falagard/WidgetComponent.cpp b/cegui/src/falagard/WidgetComponent.cpp index 4efa544e7..2b3fc6ff4 100644 --- a/cegui/src/falagard/WidgetComponent.cpp +++ b/cegui/src/falagard/WidgetComponent.cpp @@ -34,18 +34,17 @@ // Start of CEGUI namespace section namespace CEGUI { + //! Default values const HorizontalAlignment WidgetComponent::HorizontalAlignmentDefault(HA_LEFT); const VerticalAlignment WidgetComponent::VerticalAlignmentDefault(VA_TOP); - WidgetComponent::WidgetComponent(const String& type, - const String& look, + WidgetComponent::WidgetComponent(const String& targetType, const String& suffix, const String& renderer, bool autoWindow) : - d_baseType(type), - d_imageryName(look), + d_targetType(targetType), d_name(suffix), d_rendererType(renderer), d_autoWindow(autoWindow), @@ -55,17 +54,13 @@ namespace CEGUI void WidgetComponent::create(Window& parent) const { - Window* widget = WindowManager::getSingleton().createWindow(d_baseType, d_name); + Window* widget = WindowManager::getSingleton().createWindow(d_targetType, d_name); widget->setAutoWindow(d_autoWindow); // set the window renderer if (!d_rendererType.empty()) widget->setWindowRenderer(d_rendererType); - // set the widget look - if (!d_imageryName.empty()) - widget->setLookNFeel(d_imageryName); - // add the new widget to its parent parent.addChild(widget); @@ -120,24 +115,14 @@ namespace CEGUI d_area = area; } - const String& WidgetComponent::getBaseWidgetType() const - { - return d_baseType; - } - - void WidgetComponent::setBaseWidgetType(const String& type) + const String& WidgetComponent::getTargetType() const { - d_baseType = type; + return d_targetType; } - const String& WidgetComponent::getWidgetLookName() const + void WidgetComponent::setTargetType(const String& type) { - return d_imageryName; - } - - void WidgetComponent::setWidgetLookName(const String& look) - { - d_imageryName = look; + d_targetType = type; } const String& WidgetComponent::getWidgetName() const @@ -242,10 +227,7 @@ namespace CEGUI // output opening tag xml_stream.openTag(Falagard_xmlHandler::ChildElement) .attribute(Falagard_xmlHandler::NameSuffixAttribute, d_name) - .attribute(Falagard_xmlHandler::TypeAttribute, d_baseType); - - if (!d_imageryName.empty()) - xml_stream.attribute(Falagard_xmlHandler::LookAttribute, d_imageryName); + .attribute(Falagard_xmlHandler::TypeAttribute, d_targetType); if (!d_rendererType.empty()) xml_stream.attribute(Falagard_xmlHandler::RendererAttribute, d_rendererType); diff --git a/cegui/src/falagard/WidgetLookFeel.cpp b/cegui/src/falagard/WidgetLookFeel.cpp index bbbd4747c..71c24d2f1 100644 --- a/cegui/src/falagard/WidgetLookFeel.cpp +++ b/cegui/src/falagard/WidgetLookFeel.cpp @@ -39,9 +39,9 @@ namespace CEGUI { //---------------------------------------------------------------------------// -WidgetLookFeel::WidgetLookFeel(const String& name, const String& inherits) : +WidgetLookFeel::WidgetLookFeel(const String& name, const String& inheritedLookName) : d_lookName(name), - d_inheritedLookName(inherits) + d_inheritedLookName(inheritedLookName) { } @@ -49,32 +49,17 @@ WidgetLookFeel::WidgetLookFeel(const String& name, const String& inherits) : WidgetLookFeel::WidgetLookFeel(const WidgetLookFeel& other) : d_lookName(other.d_lookName), d_inheritedLookName(other.d_inheritedLookName), - d_imagerySections(other.d_imagerySections), - d_childWidgets(other.d_childWidgets), - d_stateImagery(other.d_stateImagery), - d_properties(other.d_properties), - d_namedAreas(other.d_namedAreas), + d_imagerySectionMap(other.d_imagerySectionMap), + d_widgetComponentMap(other.d_widgetComponentMap), + d_stateImageryMap(other.d_stateImageryMap), + d_propertyInitialiserMap(other.d_propertyInitialiserMap), + d_namedAreaMap(other.d_namedAreaMap), d_animations(other.d_animations), d_animationInstances(other.d_animationInstances), - d_eventLinkDefinitions(other.d_eventLinkDefinitions) + d_eventLinkDefinitionMap(other.d_eventLinkDefinitionMap) { - for (PropertyDefinitionList::iterator i = other.d_propertyDefinitions.begin(); - i < other.d_propertyDefinitions.end(); - ++i) - { - d_propertyDefinitions.push_back( - dynamic_cast( - dynamic_cast(*i)->clone())); - } - - for (PropertyLinkDefinitionList::iterator i = other.d_propertyLinkDefinitions.begin(); - i < other.d_propertyLinkDefinitions.end(); - ++i) - { - d_propertyLinkDefinitions.push_back( - dynamic_cast( - dynamic_cast(*i)->clone())); - } + copyPropertyDefinitionsFrom(other); + copyPropertyLinkDefinitionsFrom(other); } //---------------------------------------------------------------------------// @@ -90,62 +75,135 @@ void WidgetLookFeel::swap(WidgetLookFeel& other) { std::swap(d_lookName, other.d_lookName); std::swap(d_inheritedLookName, other.d_inheritedLookName); - std::swap(d_imagerySections, other.d_imagerySections); - std::swap(d_childWidgets, other.d_childWidgets); - std::swap(d_stateImagery, other.d_stateImagery); - std::swap(d_properties, other.d_properties); - std::swap(d_namedAreas, other.d_namedAreas); - std::swap(d_propertyDefinitions, other.d_propertyDefinitions); - std::swap(d_propertyLinkDefinitions, other.d_propertyLinkDefinitions); + std::swap(d_imagerySectionMap, other.d_imagerySectionMap); + std::swap(d_widgetComponentMap, other.d_widgetComponentMap); + std::swap(d_stateImageryMap, other.d_stateImageryMap); + std::swap(d_propertyInitialiserMap, other.d_propertyInitialiserMap); + std::swap(d_namedAreaMap, other.d_namedAreaMap); + std::swap(d_propertyDefinitionMap, other.d_propertyDefinitionMap); + std::swap(d_propertyLinkDefinitionMap, other.d_propertyLinkDefinitionMap); std::swap(d_animations, other.d_animations); std::swap(d_animationInstances, other.d_animationInstances); - std::swap(d_eventLinkDefinitions, other.d_eventLinkDefinitions); + std::swap(d_eventLinkDefinitionMap, other.d_eventLinkDefinitionMap); } //---------------------------------------------------------------------------// WidgetLookFeel::~WidgetLookFeel() { - for (PropertyDefinitionList::reverse_iterator it = d_propertyDefinitions.rbegin(); - it < d_propertyDefinitions.rend(); ++it) - CEGUI_DELETE_AO (*it); + clearPropertyDefinitions(); + clearPropertyLinkDefinitions(); +} + +//---------------------------------------------------------------------------// +const StateImagery& WidgetLookFeel::getStateImagery(const CEGUI::String& name, bool includeInheritedLook) const +{ + StateImageryMap::const_iterator stateImageryIter = d_stateImageryMap.find(name); + + if (stateImageryIter != d_stateImageryMap.end()) + return stateImageryIter->second; + + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("StateImagery with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getStateImagery(name, true); +} + +//---------------------------------------------------------------------------// +const ImagerySection& WidgetLookFeel::getImagerySection(const CEGUI::String& name, bool includeInheritedLook) const +{ + ImagerySectionMap::const_iterator imagerySectIter = d_imagerySectionMap.find(name); - for (PropertyLinkDefinitionList::reverse_iterator it = d_propertyLinkDefinitions.rbegin(); - it < d_propertyLinkDefinitions.rend(); ++it) - CEGUI_DELETE_AO (*it); + if (imagerySectIter != d_imagerySectionMap.end()) + return imagerySectIter->second; + + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("ImagerySection with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getImagerySection(name, true); } //---------------------------------------------------------------------------// -const StateImagery& WidgetLookFeel::getStateImagery( - const CEGUI::String& state) const +const NamedArea& WidgetLookFeel::getNamedArea(const String& name, bool includeInheritedLook) const { - StateList::const_iterator imagery = d_stateImagery.find(state); + NamedAreaMap::const_iterator namedAreaIter = d_namedAreaMap.find(name); - if (imagery != d_stateImagery.end()) - return (*imagery).second; + if (namedAreaIter != d_namedAreaMap.end()) + return namedAreaIter->second; - if (d_inheritedLookName.empty()) - CEGUI_THROW(UnknownObjectException("unknown state '" + state + - "' in look '" + d_lookName + "'.")); + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("NamedArea with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getNamedArea(name, true); +} + +//---------------------------------------------------------------------------// +const PropertyInitialiser& WidgetLookFeel::getPropertyInitialiser(const String& name, bool includeInheritedLook) const +{ + PropertyInitialiserMap::const_iterator propertyInitialiserIter = d_propertyInitialiserMap.find(name); + + if (propertyInitialiserIter != d_propertyInitialiserMap.end()) + return propertyInitialiserIter->second; + + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("PropertyInitialiser with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getPropertyInitialiser(name, true); +} + +//---------------------------------------------------------------------------// +const PropertyDefinitionBase& WidgetLookFeel::getPropertyDefinition(const String& name, bool includeInheritedLook) const +{ + PropertyDefinitionMap::const_iterator propDefIter = d_propertyDefinitionMap.find(name); + + if (propDefIter != d_propertyDefinitionMap.end()) + return *(propDefIter->second); + + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("PropertyDefinition with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getPropertyDefinition(name, true); +} + +//---------------------------------------------------------------------------// +const PropertyDefinitionBase& WidgetLookFeel::getPropertyLinkDefinition(const String& name, bool includeInheritedLook) const +{ + PropertyLinkDefinitionMap::const_iterator propLinkDefIter = d_propertyLinkDefinitionMap.find(name); + + if (propLinkDefIter != d_propertyLinkDefinitionMap.end()) + return *(propLinkDefIter->second); + + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("PropertyLinkDefinition with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getPropertyLinkDefinition(name, true); +} + +//---------------------------------------------------------------------------// +const WidgetComponent& WidgetLookFeel::getWidgetComponent(const String& name, bool includeInheritedLook) const +{ + WidgetComponentMap::const_iterator widgetComponentIter = d_widgetComponentMap.find(name); - return WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getStateImagery(state); + if (widgetComponentIter != d_widgetComponentMap.end()) + return widgetComponentIter->second; + + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("WidgetComponent with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getWidgetComponent(name, true); } //---------------------------------------------------------------------------// -const ImagerySection& WidgetLookFeel::getImagerySection( - const CEGUI::String& section) const +const EventLinkDefinition& WidgetLookFeel::getEventLinkDefinition(const String& name, bool includeInheritedLook) const { - ImageryList::const_iterator imgSect = d_imagerySections.find(section); + EventLinkDefinitionMap::const_iterator eventLinkDefIter = d_eventLinkDefinitionMap.find(name); - if (imgSect != d_imagerySections.end()) - return (*imgSect).second; + if (eventLinkDefIter != d_eventLinkDefinitionMap.end()) + return eventLinkDefIter->second; - if (d_inheritedLookName.empty()) - CEGUI_THROW(UnknownObjectException("unknown imagery section '" + - section + "' in look '" + d_lookName + "'.")); + if (!includeInheritedLook || d_inheritedLookName.empty()) + CEGUI_THROW(UnknownObjectException("WidgetComponent with name '" + name + "' was not found in WidgetLookFeel '" + d_lookName + "'.")); - return WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getImagerySection(section); + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getEventLinkDefinition(name, true); } //---------------------------------------------------------------------------// @@ -157,78 +215,106 @@ const String& WidgetLookFeel::getName() const //---------------------------------------------------------------------------// void WidgetLookFeel::addImagerySection(const ImagerySection& section) { - if (d_imagerySections.find(section.getName()) != d_imagerySections.end()) - Logger::getSingleton().logEvent( - "WidgetLookFeel::addImagerySection - Defintion for imagery " - "section '" + section.getName() + "' already exists. " - "Replacing previous definition."); + String name = section.getName(); + ImagerySectionMap::iterator foundIter = d_imagerySectionMap.find(name); + + if(foundIter != d_imagerySectionMap.end()) + { + Logger::getSingleton().logEvent("WidgetLookFeel::addImagerySection - Entry for ImagerySection '" + + name + "' already exists. Replacing previous definition."); + d_imagerySectionMap.erase(foundIter); + } - d_imagerySections[section.getName()] = section; + d_imagerySectionMap.insert(ImagerySectionMap::value_type(name, section)); } + //---------------------------------------------------------------------------// void WidgetLookFeel::renameImagerySection(const String& oldName, const String& newName) { - ImageryList::iterator oldsection = d_imagerySections.find(oldName); - if (oldsection == d_imagerySections.end()) + ImagerySectionMap::iterator oldsection = d_imagerySectionMap.find(oldName); + if (oldsection == d_imagerySectionMap.end()) CEGUI_THROW(UnknownObjectException("unknown imagery section: '" + oldName + "' in look '" + d_lookName + "'.")); - if (d_imagerySections.find(newName) != d_imagerySections.end()) + if (d_imagerySectionMap.find(newName) != d_imagerySectionMap.end()) CEGUI_THROW(UnknownObjectException("imagery section: '" + newName + "' already exists in look '" + d_lookName + "'.")); oldsection->second.setName(newName); - d_imagerySections[newName] = d_imagerySections[oldName]; - d_imagerySections.erase(oldsection); + d_imagerySectionMap[newName] = d_imagerySectionMap[oldName]; + d_imagerySectionMap.erase(oldsection); } //---------------------------------------------------------------------------// void WidgetLookFeel::addWidgetComponent(const WidgetComponent& widget) { - d_childWidgets.push_back(widget); + String name = widget.getWidgetName(); + WidgetComponentMap::iterator foundIter = d_widgetComponentMap.find(name); + + if(foundIter != d_widgetComponentMap.end()) + { + Logger::getSingleton().logEvent("WidgetLookFeel::addWidgetComponent - Entry for WidgetComponent '" + + name + "' already exists. Replacing previous definition."); + d_widgetComponentMap.erase(foundIter); + } + + d_widgetComponentMap.insert(WidgetComponentMap::value_type(name, widget)); } //---------------------------------------------------------------------------// -void WidgetLookFeel::addStateSpecification(const StateImagery& state) +void WidgetLookFeel::addStateImagery(const StateImagery& state) { - if (d_stateImagery.find(state.getName()) != d_stateImagery.end()) - Logger::getSingleton().logEvent( - "WidgetLookFeel::addStateSpecification - Defintion for state '" + - state.getName() + "' already exists. Replacing previous " - "definition."); + String name = state.getName(); + StateImageryMap::iterator foundIter = d_stateImageryMap.find(name); + + if(foundIter != d_stateImageryMap.end()) + { + Logger::getSingleton().logEvent("WidgetLookFeel::addStateImagery - Entry for StateImagery '" + + name + "' already exists. Replacing previous definition."); + d_stateImageryMap.erase(foundIter); + } - d_stateImagery[state.getName()] = state; + d_stateImageryMap.insert(StateImageryMap::value_type(name, state)); } //---------------------------------------------------------------------------// -void WidgetLookFeel::addPropertyInitialiser( - const PropertyInitialiser& initialiser) +void WidgetLookFeel::addPropertyInitialiser(const PropertyInitialiser& initialiser) { - d_properties.push_back(initialiser); + String name = initialiser.getTargetPropertyName(); + PropertyInitialiserMap::iterator foundIter = d_propertyInitialiserMap.find(name); + + if(foundIter != d_propertyInitialiserMap.end()) + { + Logger::getSingleton().logEvent("WidgetLookFeel::addPropertyInitialiser - Entry for PropertyInitialiser '" + + name + "' already exists. Replacing previous definition."); + d_propertyInitialiserMap.erase(foundIter); + } + + d_propertyInitialiserMap.insert(PropertyInitialiserMap::value_type(name, initialiser)); } //---------------------------------------------------------------------------// void WidgetLookFeel::clearImagerySections() { - d_imagerySections.clear(); + d_imagerySectionMap.clear(); } //---------------------------------------------------------------------------// void WidgetLookFeel::clearWidgetComponents() { - d_childWidgets.clear(); + d_widgetComponentMap.clear(); } //---------------------------------------------------------------------------// void WidgetLookFeel::clearStateSpecifications() { - d_stateImagery.clear(); + d_stateImageryMap.clear(); } //---------------------------------------------------------------------------// void WidgetLookFeel::clearPropertyInitialisers() { - d_properties.clear(); + d_propertyInitialiserMap.clear(); } //---------------------------------------------------------------------------// @@ -297,7 +383,7 @@ void WidgetLookFeel::initialiseWidget(Window& widget) const AnimationInstance* instance = AnimationManager::getSingleton().instantiateAnimation(*ani); - d_animationInstances.insert(std::make_pair(&widget, instance)); + d_animationInstances.insert(AnimationInstanceMap::value_type(&widget, instance)); instance->setTargetWindow(&widget); } } @@ -363,424 +449,419 @@ void WidgetLookFeel::cleanUpWidget(Window& widget) const } //---------------------------------------------------------------------------// -bool WidgetLookFeel::isStateImageryPresent(const String& state) const +bool WidgetLookFeel::isStateImageryPresent(const String& name, bool includeInheritedLook) const { - StateList::const_iterator i = d_stateImagery.find(state); + StateImageryMap::const_iterator i = d_stateImageryMap.find(name); - if (i != d_stateImagery.end()) + if (i != d_stateImageryMap.end()) return true; - if (d_inheritedLookName.empty()) + if (d_inheritedLookName.empty() || !includeInheritedLook) return false; - return WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).isStateImageryPresent(state); + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isStateImageryPresent(name, true); } //---------------------------------------------------------------------------// -void WidgetLookFeel::addNamedArea(const NamedArea& area) +bool WidgetLookFeel::isImagerySectionPresent(const String& name, bool includeInheritedLook) const { - if (d_namedAreas.find(area.getName()) != d_namedAreas.end()) - Logger::getSingleton().logEvent( - "WidgetLookFeel::addNamedArea - Defintion for area '" + - area.getName() + "' already exists. Replacing previous " - "definition."); + ImagerySectionMap::const_iterator i = d_imagerySectionMap.find(name); + + if (i != d_imagerySectionMap.end()) + return true; - d_namedAreas[area.getName()] = area; + if (d_inheritedLookName.empty() || !includeInheritedLook) + return false; + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isImagerySectionPresent(name, true); } - //---------------------------------------------------------------------------// -void WidgetLookFeel::renameNamedArea(const String& oldName, const String& newName) +bool WidgetLookFeel::isNamedAreaPresent(const String& name, bool includeInheritedLook) const { - NamedAreaList::iterator oldarea = d_namedAreas.find(oldName); - NamedAreaList::const_iterator newarea = d_namedAreas.find(newName); - if (oldarea == d_namedAreas.end()) - CEGUI_THROW(UnknownObjectException("unknown named area: '" + oldName + - "' in look '" + d_lookName + "'.")); + NamedAreaMap::const_iterator area = d_namedAreaMap.find(name); - if (newarea != d_namedAreas.end()) - CEGUI_THROW(UnknownObjectException("named area: '" + newName + - "' already exists in look '" + d_lookName + "'.")); + if (area != d_namedAreaMap.end()) + return true; - oldarea->second.setName(newName); - d_namedAreas[newName] = d_namedAreas[oldName]; - d_namedAreas.erase(oldarea); -} -//---------------------------------------------------------------------------// -void WidgetLookFeel::clearNamedAreas() -{ - d_namedAreas.clear(); + if (d_inheritedLookName.empty() || !includeInheritedLook) + return false; + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isNamedAreaPresent(name, true); } //---------------------------------------------------------------------------// -const NamedArea& WidgetLookFeel::getNamedArea(const String& name) const +bool WidgetLookFeel::isWidgetComponentPresent(const String& name, bool includeInheritedLook) const { - NamedAreaList::const_iterator area = d_namedAreas.find(name); + WidgetComponentMap::const_iterator widgetComponentIter = d_widgetComponentMap.find(name); - if (area != d_namedAreas.end()) - return (*area).second; + if (widgetComponentIter != d_widgetComponentMap.end()) + return true; - if (d_inheritedLookName.empty()) - CEGUI_THROW(UnknownObjectException("unknown named area: '" + name + - "' in look '" + d_lookName + "'.")); + if (d_inheritedLookName.empty() || !includeInheritedLook) + return false; - return WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getNamedArea(name); + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isWidgetComponentPresent(name, true); } //---------------------------------------------------------------------------// -bool WidgetLookFeel::isNamedAreaDefined(const String& name) const +bool WidgetLookFeel::isPropertyInitialiserPresent(const String& name, bool includeInheritedLook) const { - NamedAreaList::const_iterator area = d_namedAreas.find(name); + PropertyInitialiserMap::const_iterator propInitialiserIter = d_propertyInitialiserMap.find(name); - if (area != d_namedAreas.end()) + if (propInitialiserIter != d_propertyInitialiserMap.end()) return true; - if (d_inheritedLookName.empty()) + if (d_inheritedLookName.empty() || !includeInheritedLook) return false; - return WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).isNamedAreaDefined(name); + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isPropertyInitialiserPresent(name, true); } //---------------------------------------------------------------------------// -void WidgetLookFeel::layoutChildWidgets(const Window& owner) const +bool WidgetLookFeel::isPropertyDefinitionPresent(const String& name, bool includeInheritedLook) const { - WidgetComponentCollator wcc; - appendChildWidgetComponents(wcc); + PropertyDefinitionMap::const_iterator propDefIter = d_propertyDefinitionMap.find(name); - for (WidgetComponentCollator::const_iterator wci = wcc.begin(); - wci != wcc.end(); - ++wci) - { - (*wci)->layout(owner); - } + if (propDefIter != d_propertyDefinitionMap.end()) + return true; + + if (d_inheritedLookName.empty() || !includeInheritedLook) + return false; + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isPropertyDefinitionPresent(name, true); } //---------------------------------------------------------------------------// -void WidgetLookFeel::addPropertyDefinition(PropertyDefinitionBase* propdef) +bool WidgetLookFeel::isPropertyLinkDefinitionPresent(const String& name, bool includeInheritedLook) const { - d_propertyDefinitions.push_back(propdef); + PropertyLinkDefinitionMap::const_iterator propLinkDefIter = d_propertyLinkDefinitionMap.find(name); + + if (propLinkDefIter != d_propertyLinkDefinitionMap.end()) + return true; + + if (d_inheritedLookName.empty() || !includeInheritedLook) + return false; + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isPropertyLinkDefinitionPresent(name, true); } //---------------------------------------------------------------------------// -void WidgetLookFeel::clearPropertyDefinitions() +bool WidgetLookFeel::isEventLinkDefinitionPresent(const String& name, bool includeInheritedLook) const { - d_propertyDefinitions.clear(); + EventLinkDefinitionMap::const_iterator eventLinkDefIter = d_eventLinkDefinitionMap.find(name); + + if (eventLinkDefIter != d_eventLinkDefinitionMap.end()) + return true; + + if (d_inheritedLookName.empty() || !includeInheritedLook) + return false; + + return WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).isEventLinkDefinitionPresent(name, true); } //---------------------------------------------------------------------------// -void WidgetLookFeel::addPropertyLinkDefinition(PropertyDefinitionBase* propdef) +void WidgetLookFeel::addNamedArea(const NamedArea& area) { - d_propertyLinkDefinitions.push_back(propdef); + String name = area.getName(); + NamedAreaMap::iterator foundIter = d_namedAreaMap.find(name); + + if(foundIter != d_namedAreaMap.end()) + { + Logger::getSingleton().logEvent("WidgetLookFeel::addNamedArea - Entry for NamedArea '" + + name + "' already exists. Replacing previous definition."); + d_namedAreaMap.erase(foundIter); + } + + d_namedAreaMap.insert(NamedAreaMap::value_type(name, area)); } + //---------------------------------------------------------------------------// -void WidgetLookFeel::clearPropertyLinkDefinitions() +void WidgetLookFeel::renameNamedArea(const String& oldName, const String& newName) { - d_propertyLinkDefinitions.clear(); -} + NamedAreaMap::iterator oldarea = d_namedAreaMap.find(oldName); + NamedAreaMap::const_iterator newarea = d_namedAreaMap.find(newName); + if (oldarea == d_namedAreaMap.end()) + CEGUI_THROW(UnknownObjectException("unknown named area: '" + oldName + + "' in look '" + d_lookName + "'.")); + + if (newarea != d_namedAreaMap.end()) + CEGUI_THROW(UnknownObjectException("named area: '" + newName + + "' already exists in look '" + d_lookName + "'.")); + oldarea->second.setName(newName); + d_namedAreaMap[newName] = d_namedAreaMap[oldName]; + d_namedAreaMap.erase(oldarea); +} //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet WidgetLookFeel::getStateNames(bool inherits) const +void WidgetLookFeel::clearNamedAreas() { - return getStateImageryNames(inherits); + d_namedAreaMap.clear(); } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet WidgetLookFeel::getStateImageryNames(bool inherits) const +void WidgetLookFeel::layoutChildWidgets(const Window& owner) const { - StringSet result; - for(StateList::const_iterator i = d_stateImagery.begin(); - i != d_stateImagery.end(); - ++i) - { - result.insert(i->first); - } - if (!d_inheritedLookName.empty() && inherits) + WidgetComponentCollator wcc; + appendChildWidgetComponents(wcc); + + for (WidgetComponentCollator::const_iterator wci = wcc.begin(); + wci != wcc.end(); + ++wci) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getStateNames(true); - result.insert(temp.begin(),temp.end()); + (*wci)->layout(owner); } - return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::StateIterator -WidgetLookFeel::getStateIterator(bool inherits) const +void WidgetLookFeel::addPropertyDefinition(PropertyDefinitionBase* propertyDefiniton) { - if(inherits) + String name = propertyDefiniton->getPropertyName(); + PropertyDefinitionMap::iterator foundIter = d_propertyDefinitionMap.find(name); + + if(foundIter != d_propertyDefinitionMap.end()) { - StringSet names = getStateNames(true); - StateList result; - for(StringSet::iterator i = names.begin();i != names.end();++i) - { - result.insert(std::make_pair(*i, getStateImagery(*i))); - } - return StateIterator(result.begin(),result.end()); - }else{ - return StateIterator(d_stateImagery.begin(),d_stateImagery.end()); + Logger::getSingleton().logEvent("WidgetLookFeel::addPropertyDefinition - Entry for PropertyDefinition '" + + name + "' already exists. Deleting and replacing previous definition."); + delete( foundIter->second ); + d_propertyDefinitionMap.erase(foundIter); } + + d_propertyDefinitionMap.insert(PropertyDefinitionMap::value_type(name, propertyDefiniton)); } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet WidgetLookFeel::getImageryNames(bool inherits) const +void WidgetLookFeel::clearPropertyDefinitions() { - return getImagerySectionNames(inherits); + PropertyDefinitionMap::iterator propDefIter = d_propertyDefinitionMap.begin(); + PropertyDefinitionMap::iterator propDefEnd = d_propertyDefinitionMap.end(); + while (propDefIter != propDefEnd) + { + delete (propDefIter->second); + ++propDefIter; + } + + d_propertyDefinitionMap.clear(); } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet WidgetLookFeel::getImagerySectionNames(bool inherits) const +void WidgetLookFeel::addPropertyLinkDefinition(PropertyDefinitionBase* propertyLinkDefiniton) { - StringSet result; + String name = propertyLinkDefiniton->getPropertyName(); + PropertyLinkDefinitionMap::iterator foundIter = d_propertyLinkDefinitionMap.find(name); - for(ImageryList::const_iterator i = d_imagerySections.begin(); - i != d_imagerySections.end(); - ++i) + if(foundIter != d_propertyLinkDefinitionMap.end()) { - result.insert(i->first); + Logger::getSingleton().logEvent("WidgetLookFeel::addPropertyLinkDefinition - Entry for PropertyLinkDefinition '" + + name + "' already exists. Deleting and replacing previous definition."); + delete( foundIter->second ); + d_propertyLinkDefinitionMap.erase(foundIter); } - if (!d_inheritedLookName.empty() && inherits) - { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getImageryNames(true); - result.insert(temp.begin(),temp.end()); - } - return result; + + d_propertyLinkDefinitionMap.insert(PropertyLinkDefinitionMap::value_type(name, propertyLinkDefiniton)); } //---------------------------------------------------------------------------// -WidgetLookFeel::ImageryIterator -WidgetLookFeel::getImageryIterator(bool inherits) const +void WidgetLookFeel::clearPropertyLinkDefinitions() { - if(inherits) + PropertyLinkDefinitionMap::iterator propLinkDefIter = d_propertyLinkDefinitionMap.begin(); + PropertyLinkDefinitionMap::iterator propLinkDefEnd = d_propertyLinkDefinitionMap.end(); + while (propLinkDefIter != propLinkDefEnd) { - StringSet names = getImageryNames(true); - ImageryList result; - for(StringSet::iterator i = names.begin();i != names.end();++i) - { - result.insert(std::make_pair(*i, getImagerySection(*i))); - } - return ImageryIterator(result.begin(),result.end()); - }else{ - return ImageryIterator(d_imagerySections.begin(),d_imagerySections.end()); + delete (propLinkDefIter->second); + ++propLinkDefIter; } + + d_propertyLinkDefinitionMap.clear(); } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet -WidgetLookFeel::getNamedAreaNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getStateImageryNames(bool includeInheritedLook) const { StringSet result; - for(NamedAreaList::const_iterator i = d_namedAreas.begin(); - i != d_namedAreas.end(); - ++i) + + StateImageryMap::const_iterator iter = d_stateImageryMap.begin(); + StateImageryMap::const_iterator iterEnd = d_stateImageryMap.end(); + while(iter != iterEnd) { - result.insert(i->first); + result.insert(iter->first); + ++iter; } - if (!d_inheritedLookName.empty() && inherits) + + if (!d_inheritedLookName.empty() && includeInheritedLook) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getNamedAreaNames(true); - result.insert(temp.begin(),temp.end()); + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getStateImageryNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); } + return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::NamedAreaIterator -WidgetLookFeel::getNamedAreaIterator(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getImagerySectionNames(bool includeInheritedLook) const { - if(inherits) + StringSet result; + + ImagerySectionMap::const_iterator iter = d_imagerySectionMap.begin(); + ImagerySectionMap::const_iterator iterEnd = d_imagerySectionMap.end(); + while(iter != iterEnd) { - StringSet names = getNamedAreaNames(true); - NamedAreaList result; - for(StringSet::iterator i = names.begin();i != names.end();++i) - { - result.insert(std::make_pair(*i, getNamedArea(*i))); - } - return NamedAreaIterator(result.begin(),result.end()); - }else{ - return NamedAreaIterator(d_namedAreas.begin(),d_namedAreas.end()); + result.insert(iter->first); + ++iter; } -} -//---------------------------------------------------------------------------// -WidgetLookFeel::StringSet WidgetLookFeel::getWidgetNames(bool inherits) const -{ - return getWidgetComponentNames(inherits); + if (!d_inheritedLookName.empty() && includeInheritedLook) + { + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getImagerySectionNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); + } + + return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet WidgetLookFeel::getWidgetComponentNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getNamedAreaNames(bool includeInheritedLook) const { StringSet result; - for(WidgetList::const_iterator i = d_childWidgets.begin(); - i != d_childWidgets.end(); - ++i) + + NamedAreaMap::const_iterator iter = d_namedAreaMap.begin(); + NamedAreaMap::const_iterator iterEnd = d_namedAreaMap.end(); + while(iter != iterEnd) { - result.insert(i->getWidgetName()); + result.insert(iter->first); + ++iter; } - if (!d_inheritedLookName.empty() && inherits) + + if (!d_inheritedLookName.empty() && includeInheritedLook) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getWidgetNames(true); - result.insert(temp.begin(),temp.end()); + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getNamedAreaNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); } + return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::WidgetComponentIterator -WidgetLookFeel::getWidgetComponentIterator(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getWidgetComponentNames(bool includeInheritedLook) const { - WidgetComponentCollator wcc; - appendChildWidgetComponents(wcc, inherits); + StringSet result; + + WidgetComponentMap::const_iterator iter = d_widgetComponentMap.begin(); + WidgetComponentMap::const_iterator iterEnd = d_widgetComponentMap.end(); + while(iter != iterEnd) + { + result.insert(iter->first); + ++iter; + } + + if (!d_inheritedLookName.empty() && includeInheritedLook) + { + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getWidgetComponentNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); + } - return WidgetComponentIterator(wcc.begin(), wcc.end()); + return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet -WidgetLookFeel::getPropertyDefinitionNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getPropertyDefinitionNames(bool includeInheritedLook) const { StringSet result; - for(PropertyDefinitionList::const_iterator i = d_propertyDefinitions.begin(); - i != d_propertyDefinitions.end(); - ++i) + + PropertyDefinitionMap::const_iterator iter = d_propertyDefinitionMap.begin(); + PropertyDefinitionMap::const_iterator iterEnd = d_propertyDefinitionMap.end(); + while(iter != iterEnd) { - result.insert((*i)->getPropertyName()); + result.insert(iter->first); + ++iter; } - if (!d_inheritedLookName.empty() && inherits) + + if (!d_inheritedLookName.empty() && includeInheritedLook) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getPropertyDefinitionNames(true); - result.insert(temp.begin(),temp.end()); + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getPropertyDefinitionNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); } + return result; } -//---------------------------------------------------------------------------// -WidgetLookFeel::PropertyDefinitionIterator -WidgetLookFeel::getPropertyDefinitionIterator(bool inherits) const -{ - PropertyDefinitionCollator pdc; - appendPropertyDefinitions(pdc, inherits); - - return PropertyDefinitionIterator(pdc.begin(), pdc.end()); -} //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet -WidgetLookFeel::getPropertyLinkDefinitionNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getPropertyLinkDefinitionNames(bool includeInheritedLook) const { StringSet result; - for(PropertyLinkDefinitionList::const_iterator i = d_propertyLinkDefinitions.begin(); - i != d_propertyLinkDefinitions.end(); - ++i) + + PropertyLinkDefinitionMap::const_iterator iter = d_propertyLinkDefinitionMap.begin(); + PropertyLinkDefinitionMap::const_iterator iterEnd = d_propertyLinkDefinitionMap.end(); + while(iter != iterEnd) { - result.insert((*i)->getPropertyName()); + result.insert(iter->first); + ++iter; } - if (!d_inheritedLookName.empty() && inherits) + + if (!d_inheritedLookName.empty() && includeInheritedLook) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getPropertyLinkDefinitionNames(true); - result.insert(temp.begin(),temp.end()); + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getPropertyLinkDefinitionNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); } - return result; -} - -//---------------------------------------------------------------------------// -WidgetLookFeel::PropertyLinkDefinitionIterator -WidgetLookFeel::getPropertyLinkDefinitionIterator(bool inherits) const -{ - PropertyLinkDefinitionCollator pldc; - appendPropertyLinkDefinitions(pldc, inherits); - return PropertyLinkDefinitionIterator(pldc.begin(), pldc.end()); + return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet -WidgetLookFeel::getPropertyInitialiserNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getPropertyInitialiserNames(bool includeInheritedLook) const { StringSet result; - for(PropertyList::const_iterator i = d_properties.begin(); - i != d_properties.end(); - ++i) + + PropertyInitialiserMap::const_iterator iter = d_propertyInitialiserMap.begin(); + PropertyInitialiserMap::const_iterator iterEnd = d_propertyInitialiserMap.end(); + while(iter != iterEnd) { - result.insert(i->getTargetPropertyName()); + result.insert(iter->first); + ++iter; } - if (!d_inheritedLookName.empty() && inherits) + + if (!d_inheritedLookName.empty() && includeInheritedLook) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getPropertyInitialiserNames(true); - result.insert(temp.begin(),temp.end()); + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getPropertyInitialiserNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); } + return result; } -//---------------------------------------------------------------------------// -WidgetLookFeel::PropertyInitialiserIterator -WidgetLookFeel::getPropertyInitialiserIterator(bool inherits) const -{ - PropertyInitialiserCollator pic; - appendPropertyInitialisers(pic, inherits); - - return PropertyInitialiserIterator(pic.begin(), pic.end()); -} //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet -WidgetLookFeel::getEventLinkDefinitionNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getEventLinkDefinitionNames(bool includeInheritedLook) const { StringSet result; - for(EventLinkDefinitionList::const_iterator i = d_eventLinkDefinitions.begin(); - i != d_eventLinkDefinitions.end(); - ++i) + + EventLinkDefinitionMap::const_iterator iter = d_eventLinkDefinitionMap.begin(); + EventLinkDefinitionMap::const_iterator iterEnd = d_eventLinkDefinitionMap.end(); + while(iter != iterEnd) { - result.insert(i->getName()); + result.insert(iter->first); + ++iter; } - if (!d_inheritedLookName.empty() && inherits) + + if (!d_inheritedLookName.empty() && includeInheritedLook) { - StringSet temp = WidgetLookManager::getSingleton(). - getWidgetLook(d_inheritedLookName).getEventLinkDefinitionNames(true); - result.insert(temp.begin(),temp.end()); + StringSet inheritedStringSet = WidgetLookManager::getSingleton().getWidgetLook(d_inheritedLookName).getEventLinkDefinitionNames(true); + result.insert(inheritedStringSet.begin(), inheritedStringSet.end()); } - return result; -} -//---------------------------------------------------------------------------// -WidgetLookFeel::EventLinkDefinitionIterator -WidgetLookFeel::getEventLinkDefinitionIterator(bool inherits) const -{ - EventLinkDefinitionCollator eldc; - appendEventLinkDefinitions(eldc, inherits); - - return EventLinkDefinitionIterator(eldc.begin(), eldc.end()); + return result; } //---------------------------------------------------------------------------// -WidgetLookFeel::StringSet -WidgetLookFeel::getAnimationNames(bool inherits) const +WidgetLookFeel::StringSet WidgetLookFeel::getAnimationNames(bool includeInheritedLook) const { AnimationNameSet ans; - appendAnimationNames(ans,inherits); + appendAnimationNames(ans, includeInheritedLook); return ans; } -//---------------------------------------------------------------------------// -WidgetLookFeel::AnimationNameIterator -WidgetLookFeel::getAnimationNameIterator(bool inherits) const -{ - AnimationNameSet wcl; - appendAnimationNames(wcl,inherits); - - return AnimationNameIterator(wcl.begin(),wcl.end()); -} - //---------------------------------------------------------------------------// void WidgetLookFeel::writeXMLToStream(XMLSerializer& xml_stream) const { @@ -795,71 +876,71 @@ void WidgetLookFeel::writeXMLToStream(XMLSerializer& xml_stream) const // compile error on VC6++ { // output property definitions - for (PropertyDefinitionList::const_iterator curr = d_propertyDefinitions.begin(); - curr != d_propertyDefinitions.end(); + for (PropertyDefinitionMap::const_iterator curr = d_propertyDefinitionMap.begin(); + curr != d_propertyDefinitionMap.end(); ++curr) { - (*curr)->writeDefinitionXMLToStream(xml_stream); + curr->second->writeDefinitionXMLToStream(xml_stream); } } { // output property link definitions - for (PropertyLinkDefinitionList::const_iterator curr = d_propertyLinkDefinitions.begin(); - curr != d_propertyLinkDefinitions.end(); + for (PropertyLinkDefinitionMap::const_iterator curr = d_propertyLinkDefinitionMap.begin(); + curr != d_propertyLinkDefinitionMap.end(); ++curr) { - (*curr)->writeDefinitionXMLToStream(xml_stream); + curr->second->writeDefinitionXMLToStream(xml_stream); } } { // output property initialisers. - for (PropertyList::const_iterator curr = d_properties.begin(); - curr != d_properties.end(); + for (PropertyInitialiserMap::const_iterator curr = d_propertyInitialiserMap.begin(); + curr != d_propertyInitialiserMap.end(); ++curr) { - (*curr).writeXMLToStream(xml_stream); + curr->second.writeXMLToStream(xml_stream); } } { // output named areas - for (NamedAreaList::const_iterator curr = d_namedAreas.begin(); - curr != d_namedAreas.end(); + for (NamedAreaMap::const_iterator curr = d_namedAreaMap.begin(); + curr != d_namedAreaMap.end(); ++curr) { - (*curr).second.writeXMLToStream(xml_stream); + curr->second.writeXMLToStream(xml_stream); } } { // output child widgets - for (WidgetList::const_iterator curr = d_childWidgets.begin(); - curr != d_childWidgets.end(); + for (WidgetComponentMap::const_iterator curr = d_widgetComponentMap.begin(); + curr != d_widgetComponentMap.end(); ++curr) { - (*curr).writeXMLToStream(xml_stream); + curr->second.writeXMLToStream(xml_stream); } } { // output imagery sections - for (ImageryList::const_iterator curr = d_imagerySections.begin(); - curr != d_imagerySections.end(); + for (ImagerySectionMap::const_iterator curr = d_imagerySectionMap.begin(); + curr != d_imagerySectionMap.end(); ++curr) { - (*curr).second.writeXMLToStream(xml_stream); + curr->second.writeXMLToStream(xml_stream); } } { // output states - for (StateList::const_iterator curr = d_stateImagery.begin(); - curr != d_stateImagery.end(); + for (StateImageryMap::const_iterator curr = d_stateImageryMap.begin(); + curr != d_stateImageryMap.end(); ++curr) { - (*curr).second.writeXMLToStream(xml_stream); + curr->second.writeXMLToStream(xml_stream); } } @@ -880,147 +961,6 @@ const PropertyInitialiser* WidgetLookFeel::findPropertyInitialiser(const String& return *i; } -//---------------------------------------------------------------------------// -const WidgetComponent* WidgetLookFeel::findWidgetComponent(const String& name) const -{ - WidgetComponentCollator wcc; - appendChildWidgetComponents(wcc); - - WidgetComponentCollator::const_iterator wci = wcc.find(name); - - if (wci == wcc.end()) - return 0; - - return *wci; -} - -//---------------------------------------------------------------------------// -WidgetComponent* WidgetLookFeel::retrieveWidgetComponentFromList(const String& name, bool includeInheritedElements) -{ - WidgetList::iterator iter = d_childWidgets.begin(); - WidgetList::iterator iterEnd = d_childWidgets.end(); - - while(iter != iterEnd) - { - if(iter->getWidgetName().compare(name) == 0) - return &(*iter); - - ++iter; - } - - if(includeInheritedElements) - { - WidgetLookFeel* inheritedWidgetLook = getInheritedWidgetLookFeel(); - if(inheritedWidgetLook != 0) - return inheritedWidgetLook->retrieveWidgetComponentFromList(name, true); - } - - return 0; -} - -//---------------------------------------------------------------------------// -PropertyInitialiser* WidgetLookFeel::retrievePropertyInitialiserFromList(const String& name, bool includeInheritedElements) -{ - PropertyList::iterator iter = d_properties.begin(); - PropertyList::iterator iterEnd = d_properties.end(); - - while(iter != iterEnd) - { - PropertyInitialiser& propInit = *iter; - if(propInit.getTargetPropertyName().compare(name) == 0) - return &propInit; - - ++iter; - } - - if(includeInheritedElements) - { - WidgetLookFeel* inheritedWidgetLook = getInheritedWidgetLookFeel(); - if(inheritedWidgetLook != 0) - return inheritedWidgetLook->retrievePropertyInitialiserFromList(name, true); - } - - return 0; -} - -//---------------------------------------------------------------------------// -PropertyDefinitionBase* WidgetLookFeel::retrievePropertyDefinitionFromList(const String& name, bool includeInheritedElements) -{ - PropertyDefinitionList::iterator iter = d_propertyDefinitions.begin(); - PropertyDefinitionList::iterator iterEnd = d_propertyDefinitions.end(); - - while(iter != iterEnd) - { - PropertyDefinitionBase* propDefBase = *iter; - if(propDefBase->getPropertyName().compare(name) == 0) - return propDefBase; - - ++iter; - } - - - if(includeInheritedElements) - { - WidgetLookFeel* inheritedWidgetLook = getInheritedWidgetLookFeel(); - if(inheritedWidgetLook != 0) - return inheritedWidgetLook->retrievePropertyDefinitionFromList(name, true); - } - - return 0; -} - - -//---------------------------------------------------------------------------// -PropertyDefinitionBase* WidgetLookFeel::retrievePropertyLinkDefinitionFromList(const String& name, bool includeInheritedElements) -{ - PropertyLinkDefinitionList::iterator iter = d_propertyLinkDefinitions.begin(); - PropertyLinkDefinitionList::iterator iterEnd = d_propertyLinkDefinitions.end(); - - while(iter != iterEnd) - { - PropertyDefinitionBase* propDefBase = *iter; - if(propDefBase->getPropertyName().compare(name) == 0) - return propDefBase; - - ++iter; - } - - if(includeInheritedElements) - { - WidgetLookFeel* inheritedWidgetLook = getInheritedWidgetLookFeel(); - if(inheritedWidgetLook != 0) - return inheritedWidgetLook->retrievePropertyLinkDefinitionFromList(name, true); - } - - return 0; -} - -//---------------------------------------------------------------------------// -EventLinkDefinition* WidgetLookFeel::retrieveEventLinkDefinitionFromList(const String& name, bool includeInheritedElements) -{ - EventLinkDefinitionList::iterator iter = d_eventLinkDefinitions.begin(); - EventLinkDefinitionList::iterator iterEnd = d_eventLinkDefinitions.end(); - - while(iter != iterEnd) - { - EventLinkDefinition& eventLinkDef = *iter; - if(eventLinkDef.getName().compare(name) == 0) - return &eventLinkDef; - - ++iter; - } - - if(includeInheritedElements) - { - WidgetLookFeel* inheritedWidgetLook = getInheritedWidgetLookFeel(); - if(inheritedWidgetLook != 0) - return inheritedWidgetLook->retrieveEventLinkDefinitionFromList(name, true); - } - - return 0; -} - - //---------------------------------------------------------------------------// void WidgetLookFeel::addAnimationName(const String& anim_name) { @@ -1035,13 +975,23 @@ void WidgetLookFeel::addAnimationName(const String& anim_name) //---------------------------------------------------------------------------// void WidgetLookFeel::addEventLinkDefinition(const EventLinkDefinition& evtdef) { - d_eventLinkDefinitions.push_back(evtdef); + String name = evtdef.getName(); + EventLinkDefinitionMap::iterator foundIter = d_eventLinkDefinitionMap.find(name); + + if(foundIter != d_eventLinkDefinitionMap.end()) + { + Logger::getSingleton().logEvent("WidgetLookFeel::addEventLinkDefinition - Entry for EventLinkDefinition '" + + name + "' already exists. Replacing previous definition."); + d_eventLinkDefinitionMap.erase(foundIter); + } + + d_eventLinkDefinitionMap.insert(EventLinkDefinitionMap::value_type(name, evtdef)); } //---------------------------------------------------------------------------// void WidgetLookFeel::clearEventLinkDefinitions() { - d_eventLinkDefinitions.clear(); + d_eventLinkDefinitionMap.clear(); } //---------------------------------------------------------------------------// @@ -1052,11 +1002,11 @@ void WidgetLookFeel::appendChildWidgetComponents(WidgetComponentCollator& col, WidgetLookManager::getSingleton(). getWidgetLook(d_inheritedLookName).appendChildWidgetComponents(col); - for (WidgetList::const_iterator i = d_childWidgets.begin(); - i != d_childWidgets.end(); - ++i) + for (WidgetComponentMap::const_iterator iter = d_widgetComponentMap.begin(); + iter != d_widgetComponentMap.end(); + ++iter) { - col.set(i->getWidgetName(), &*i); + col.set(iter->first, &(iter->second)); } } @@ -1069,11 +1019,11 @@ void WidgetLookFeel::appendPropertyDefinitions(PropertyDefinitionCollator& col, WidgetLookManager::getSingleton(). getWidgetLook(d_inheritedLookName).appendPropertyDefinitions(col); - for (PropertyDefinitionList::iterator i = d_propertyDefinitions.begin(); - i != d_propertyDefinitions.end(); - ++i) + for (PropertyDefinitionMap::iterator iter = d_propertyDefinitionMap.begin(); + iter != d_propertyDefinitionMap.end(); + ++iter) { - col.set((*i)->getPropertyName(), *i); + col.set(iter->first, iter->second); } } @@ -1086,11 +1036,11 @@ void WidgetLookFeel::appendPropertyLinkDefinitions( WidgetLookManager::getSingleton(). getWidgetLook(d_inheritedLookName).appendPropertyLinkDefinitions(col); - for (PropertyLinkDefinitionList::iterator i = d_propertyLinkDefinitions.begin(); - i != d_propertyLinkDefinitions.end(); - ++i) + for (PropertyLinkDefinitionMap::iterator iter = d_propertyLinkDefinitionMap.begin(); + iter != d_propertyLinkDefinitionMap.end(); + ++iter) { - col.set((*i)->getPropertyName(), *i); + col.set(iter->first, iter->second); } } @@ -1102,11 +1052,11 @@ void WidgetLookFeel::appendPropertyInitialisers( WidgetLookManager::getSingleton(). getWidgetLook(d_inheritedLookName).appendPropertyInitialisers(col); - for (PropertyList::const_iterator i = d_properties.begin(); - i != d_properties.end(); - ++i) + for (PropertyInitialiserMap::const_iterator iter = d_propertyInitialiserMap.begin(); + iter != d_propertyInitialiserMap.end(); + ++iter) { - col.set(i->getTargetPropertyName(), &*i); + col.set(iter->first, &(iter->second)); } } @@ -1118,11 +1068,11 @@ void WidgetLookFeel::appendEventLinkDefinitions( WidgetLookManager::getSingleton(). getWidgetLook(d_inheritedLookName).appendEventLinkDefinitions(col); - for (EventLinkDefinitionList::const_iterator i = d_eventLinkDefinitions.begin(); - i != d_eventLinkDefinitions.end(); - ++i) + for (EventLinkDefinitionMap::const_iterator iter = d_eventLinkDefinitionMap.begin(); + iter != d_eventLinkDefinitionMap.end(); + ++iter) { - col.set(i->getName(), &*i); + col.set(iter->first, &(iter->second)); } } @@ -1143,18 +1093,18 @@ bool WidgetLookFeel::handleFontRenderSizeChange(Window& window, { bool result = false; - for(ImageryList::const_iterator i = d_imagerySections.begin(); - i != d_imagerySections.end(); + for(ImagerySectionMap::const_iterator i = d_imagerySectionMap.begin(); + i != d_imagerySectionMap.end(); ++i) { result |= i->second.handleFontRenderSizeChange(window, font); } - for(WidgetList::const_iterator i = d_childWidgets.begin(); - i != d_childWidgets.end(); + for(WidgetComponentMap::const_iterator i = d_widgetComponentMap.begin(); + i != d_widgetComponentMap.end(); ++i) { - result |= i->handleFontRenderSizeChange(window, font); + result |= i->second.handleFontRenderSizeChange(window, font); } if (!d_inheritedLookName.empty()) @@ -1166,28 +1116,28 @@ bool WidgetLookFeel::handleFontRenderSizeChange(Window& window, } //---------------------------------------------------------------------------// -WidgetLookFeel::StateImageryPointerMap WidgetLookFeel::getStateImageryMap(bool includeInheritedElements) +WidgetLookFeel::StateImageryPointerMap WidgetLookFeel::getStateImageryMap(bool includeInheritedLook) { StateImageryPointerMap pointerMap; - StringSet nameSet = getStateNames(includeInheritedElements); + StringSet nameSet = getStateImageryNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - StateList::iterator stateImageryIter = d_stateImagery.find(currentElementName); + StateImageryMap::iterator stateImageryIter = d_stateImageryMap.find(currentElementName); - if(stateImageryIter == d_stateImagery.end()) + if(stateImageryIter == d_stateImageryMap.end()) { CEGUI_THROW(UnknownObjectException("Error: StateImagery with name: \"" + currentElementName + "\" exists in the list of names but a StateImagery with this name" + "could not be found in the map")); } else - { + { StateImagery* stateImagery = &stateImageryIter->second; - pointerMap.insert(std::make_pair(currentElementName, stateImagery)); + pointerMap.insert(StateImageryPointerMap::value_type(currentElementName, stateImagery)); } ++iter; @@ -1197,28 +1147,28 @@ WidgetLookFeel::StateImageryPointerMap WidgetLookFeel::getStateImageryMap(bool i } //---------------------------------------------------------------------------// -WidgetLookFeel::ImagerySectionPointerMap WidgetLookFeel::getImagerySectionMap(bool includeInheritedElements) +WidgetLookFeel::ImagerySectionPointerMap WidgetLookFeel::getImagerySectionMap(bool includeInheritedLook) { ImagerySectionPointerMap pointerMap; - StringSet nameSet = getImageryNames(includeInheritedElements); + StringSet nameSet = getImagerySectionNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - ImageryList::iterator imagerySectionIter = d_imagerySections.find(currentElementName); + ImagerySectionMap::iterator imagerySectionIter = d_imagerySectionMap.find(currentElementName); - if(imagerySectionIter == d_imagerySections.end()) + if(imagerySectionIter == d_imagerySectionMap.end()) { CEGUI_THROW(UnknownObjectException("Error: ImagerySection with name: \"" + currentElementName + "\" exists in the list of names but a ImagerySection with this name" + "could not be found in the map")); } else - { + { ImagerySection* imagerySection = &imagerySectionIter->second; - pointerMap.insert(std::make_pair(currentElementName, imagerySection)); + pointerMap.insert(ImagerySectionPointerMap::value_type(currentElementName, imagerySection)); } ++iter; @@ -1228,28 +1178,28 @@ WidgetLookFeel::ImagerySectionPointerMap WidgetLookFeel::getImagerySectionMap(bo } //---------------------------------------------------------------------------// -WidgetLookFeel::NamedAreaPointerMap WidgetLookFeel::getNamedAreaMap(bool includeInheritedElements) +WidgetLookFeel::NamedAreaPointerMap WidgetLookFeel::getNamedAreaMap(bool includeInheritedLook) { NamedAreaPointerMap pointerMap; - StringSet nameSet = getNamedAreaNames(includeInheritedElements); + StringSet nameSet = getNamedAreaNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - NamedAreaList::iterator namedAreaIter = d_namedAreas.find(currentElementName); + NamedAreaMap::iterator namedAreaIter = d_namedAreaMap.find(currentElementName); - if(namedAreaIter == d_namedAreas.end()) + if(namedAreaIter == d_namedAreaMap.end()) { CEGUI_THROW(UnknownObjectException("Error: NamedArea with name: \"" + currentElementName + "\" exists in the list of names but a NamedArea with this name" + "could not be found in the map")); } else - { + { NamedArea* namedArea = &namedAreaIter->second; - pointerMap.insert(std::make_pair(currentElementName, namedArea)); + pointerMap.insert(NamedAreaPointerMap::value_type(currentElementName, namedArea)); } ++iter; @@ -1259,28 +1209,28 @@ WidgetLookFeel::NamedAreaPointerMap WidgetLookFeel::getNamedAreaMap(bool include } //---------------------------------------------------------------------------// -WidgetLookFeel::WidgetComponentPointerMap WidgetLookFeel::getWidgetComponentMap(bool includeInheritedElements) +WidgetLookFeel::WidgetComponentPointerMap WidgetLookFeel::getWidgetComponentMap(bool includeInheritedLook) { WidgetComponentPointerMap pointerMap; - StringSet nameSet = getWidgetNames(includeInheritedElements); + StringSet nameSet = getWidgetComponentNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - // This is deprecated in the next version, instead we will directly access the WidgetComponent map, which will be added. - WidgetComponent* widgetComponent = retrieveWidgetComponentFromList(currentElementName, includeInheritedElements); + WidgetComponentMap::iterator widgetComponentIter = d_widgetComponentMap.find(currentElementName); - if(widgetComponent == 0) + if(widgetComponentIter == d_widgetComponentMap.end()) { CEGUI_THROW(UnknownObjectException("Error: WidgetComponent with name: \"" + currentElementName + "\" exists in the list of names but a WidgetComponent with this name" + "could not be found in the map")); } else - { - pointerMap.insert(std::make_pair(currentElementName, widgetComponent)); + { + WidgetComponent* widgetComponent = &widgetComponentIter->second; + pointerMap.insert(WidgetComponentPointerMap::value_type(currentElementName, widgetComponent)); } ++iter; @@ -1290,28 +1240,28 @@ WidgetLookFeel::WidgetComponentPointerMap WidgetLookFeel::getWidgetComponentMap( } //---------------------------------------------------------------------------// -WidgetLookFeel::PropertyInitialiserPointerMap WidgetLookFeel::getPropertyInitialiserMap(bool includeInheritedElements) +WidgetLookFeel::PropertyInitialiserPointerMap WidgetLookFeel::getPropertyInitialiserMap(bool includeInheritedLook) { PropertyInitialiserPointerMap pointerMap; - StringSet nameSet = getPropertyInitialiserNames(includeInheritedElements); + StringSet nameSet = getPropertyInitialiserNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - // This is deprecated in the next version, instead we will directly access the PropertyInitialiser map, which will be added. - PropertyInitialiser* propertyInitialiser = retrievePropertyInitialiserFromList(currentElementName, includeInheritedElements); + PropertyInitialiserMap::iterator propertyInitIter = d_propertyInitialiserMap.find(currentElementName); - if(propertyInitialiser == 0) + if(propertyInitIter == d_propertyInitialiserMap.end()) { CEGUI_THROW(UnknownObjectException("Error: PropertyInitialiser with name: \"" + currentElementName + "\" exists in the list of names but a PropertyInitialiser with this name" + "could not be found in the map")); } else - { - pointerMap.insert(std::make_pair(currentElementName, propertyInitialiser)); + { + PropertyInitialiser* propInitialiser = &propertyInitIter->second; + pointerMap.insert(PropertyInitialiserPointerMap::value_type(currentElementName, propInitialiser)); } ++iter; @@ -1322,28 +1272,28 @@ WidgetLookFeel::PropertyInitialiserPointerMap WidgetLookFeel::getPropertyInitial //---------------------------------------------------------------------------// -WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyDefinitionMap(bool includeInheritedElements) +WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyDefinitionMap(bool includeInheritedLook) { PropertyDefinitionBasePointerMap pointerMap; - StringSet nameSet = getPropertyDefinitionNames(includeInheritedElements); + StringSet nameSet = getPropertyDefinitionNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - // This is deprecated in the next version, instead we will directly access the PropertyDefinition map, which will be added. - PropertyDefinitionBase* propertyDefinition = retrievePropertyDefinitionFromList(currentElementName, includeInheritedElements); + PropertyDefinitionMap::iterator propDefIter = d_propertyDefinitionMap.find(currentElementName); - if(propertyDefinition == 0) + if(propDefIter == d_propertyDefinitionMap.end()) { CEGUI_THROW(UnknownObjectException("Error: PropertyDefinition with name: \"" + currentElementName + "\" exists in the list of names but a PropertyDefinition with this name" + "could not be found in the map")); } else - { - pointerMap.insert(std::make_pair(currentElementName, propertyDefinition)); + { + PropertyDefinitionBase* propertyDefinition = propDefIter->second; + pointerMap.insert(PropertyDefinitionBasePointerMap::value_type(currentElementName, propertyDefinition)); } ++iter; @@ -1353,20 +1303,19 @@ WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyDefi } //---------------------------------------------------------------------------// -WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyLinkDefinitionMap(bool includeInheritedElements) +WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyLinkDefinitionMap(bool includeInheritedLook) { PropertyDefinitionBasePointerMap pointerMap; - StringSet nameSet = getPropertyLinkDefinitionNames(includeInheritedElements); + StringSet nameSet = getPropertyLinkDefinitionNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - // This is deprecated in the next version, instead we will directly access the PropertyLinkDefinition map, which will be added. - PropertyDefinitionBase* propertyLinkDefinition = retrievePropertyLinkDefinitionFromList(currentElementName, includeInheritedElements); + PropertyLinkDefinitionMap::iterator propLinkDefIter = d_propertyLinkDefinitionMap.find(currentElementName); - if(propertyLinkDefinition == 0) + if(propLinkDefIter == d_propertyLinkDefinitionMap.end()) { CEGUI_THROW(UnknownObjectException("Error: PropertyLinkDefinition with name: \"" + currentElementName + "\" exists in the list of names but a PropertyLinkDefinition with this name" @@ -1374,7 +1323,8 @@ WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyLink } else { - pointerMap.insert(std::make_pair(currentElementName, propertyLinkDefinition)); + PropertyDefinitionBase* propertyLinkDefinition = propLinkDefIter->second; + pointerMap.insert(PropertyDefinitionBasePointerMap::value_type(currentElementName, propertyLinkDefinition)); } ++iter; @@ -1385,28 +1335,28 @@ WidgetLookFeel::PropertyDefinitionBasePointerMap WidgetLookFeel::getPropertyLink //---------------------------------------------------------------------------// -WidgetLookFeel::EventLinkDefinitionPointerMap WidgetLookFeel::getEventLinkDefinitionMap(bool includeInheritedElements) +WidgetLookFeel::EventLinkDefinitionPointerMap WidgetLookFeel::getEventLinkDefinitionMap(bool includeInheritedLook) { EventLinkDefinitionPointerMap pointerMap; - StringSet nameSet = getEventLinkDefinitionNames(includeInheritedElements); + StringSet nameSet = getEventLinkDefinitionNames(includeInheritedLook); StringSet::iterator iter = nameSet.begin(); StringSet::iterator iterEnd = nameSet.end(); while(iter != iterEnd) { const CEGUI::String& currentElementName = *iter; - // This is deprecated in the next version, instead we will directly access the EventLinkDefinition map, which will be added. - EventLinkDefinition* eventLinkDef = retrieveEventLinkDefinitionFromList(currentElementName, includeInheritedElements); + EventLinkDefinitionMap::iterator eventLinkDefIter = d_eventLinkDefinitionMap.find(currentElementName); - if(eventLinkDef == 0) + if(eventLinkDefIter == d_eventLinkDefinitionMap.end()) { CEGUI_THROW(UnknownObjectException("Error: EventLinkDefinition with name: \"" + currentElementName + "\" exists in the list of names but a EventLinkDefinition with this name" + "could not be found in the map")); } else - { - pointerMap.insert(std::make_pair(currentElementName, eventLinkDef)); + { + EventLinkDefinition* eventLinkDefinition = &eventLinkDefIter->second; + pointerMap.insert(EventLinkDefinitionPointerMap::value_type(currentElementName, eventLinkDefinition)); } ++iter; @@ -1438,6 +1388,38 @@ WidgetLookFeel* WidgetLookFeel::getInheritedWidgetLookFeel() return foundIter->second; } +//---------------------------------------------------------------------------// +void WidgetLookFeel::copyPropertyDefinitionsFrom(const WidgetLookFeel& widgetLook) +{ + PropertyDefinitionMap::iterator iter = widgetLook.d_propertyDefinitionMap.begin(); + PropertyDefinitionMap::iterator iterEnd = widgetLook.d_propertyDefinitionMap.end(); + + while(iter != iterEnd) + { + PropertyDefinitionMap::value_type insertValue(iter->first, + dynamic_cast(dynamic_cast(iter->second)->clone())); + d_propertyDefinitionMap.insert(insertValue); + + ++iter; + } +} + +//---------------------------------------------------------------------------// +void WidgetLookFeel::copyPropertyLinkDefinitionsFrom(const WidgetLookFeel& widgetLook) +{ + PropertyLinkDefinitionMap::iterator iter = widgetLook.d_propertyLinkDefinitionMap.begin(); + PropertyLinkDefinitionMap::iterator iterEnd = widgetLook.d_propertyLinkDefinitionMap.end(); + + while(iter != iterEnd) + { + PropertyLinkDefinitionMap::value_type insertValue(iter->first, + dynamic_cast(dynamic_cast(iter->second)->clone())); + d_propertyLinkDefinitionMap.insert(insertValue); + + ++iter; + } +} + //---------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/falagard/WidgetLookManager.cpp b/cegui/src/falagard/WidgetLookManager.cpp index fb3beefe9..05a454c50 100644 --- a/cegui/src/falagard/WidgetLookManager.cpp +++ b/cegui/src/falagard/WidgetLookManager.cpp @@ -263,12 +263,6 @@ namespace CEGUI return String(reinterpret_cast(str.str().c_str())); } - WidgetLookManager::WidgetLookIterator - WidgetLookManager::getWidgetLookIterator() const - { - return WidgetLookIterator(d_widgetLooks.begin(),d_widgetLooks.end()); - } - WidgetLookManager::WidgetLookPointerMap WidgetLookManager::getWidgetLookPointerMap() { WidgetLookPointerMap pointerMap; diff --git a/cegui/src/falagard/XMLHandler.cpp b/cegui/src/falagard/XMLHandler.cpp index aac177708..ebd58a684 100644 --- a/cegui/src/falagard/XMLHandler.cpp +++ b/cegui/src/falagard/XMLHandler.cpp @@ -393,8 +393,8 @@ namespace CEGUI void Falagard_xmlHandler::elementWidgetLookStart(const XMLAttributes& attributes) { assert(d_widgetlook == 0); - d_widgetlook = CEGUI_NEW_AO WidgetLookFeel(attributes.getValueAsString(NameAttribute), - attributes.getValueAsString(InheritsAttribute)); + d_widgetlook = new WidgetLookFeel(attributes.getValueAsString(NameAttribute), + attributes.getValueAsString(InheritsAttribute)); Logger::getSingleton().logEvent("---> Start of definition for widget look '" + d_widgetlook->getName() + "'.", Informative); } @@ -405,17 +405,15 @@ namespace CEGUI void Falagard_xmlHandler::elementChildStart(const XMLAttributes& attributes) { assert(d_childcomponent == 0); - d_childcomponent = CEGUI_NEW_AO WidgetComponent( + d_childcomponent = new WidgetComponent( attributes.getValueAsString(TypeAttribute), - attributes.getValueAsString(LookAttribute), attributes.getValueAsString(NameSuffixAttribute), attributes.getValueAsString(RendererAttribute), attributes.getValueAsBool(AutoWindowAttribute, true)); CEGUI_LOGINSANE("-----> Start of definition for child widget." - " Type: " + d_childcomponent->getBaseWidgetType() + + " Type: " + d_childcomponent->getTargetType() + " Name: " + d_childcomponent->getWidgetName() + - " Look: " + d_childcomponent->getWidgetLookName() + " Auto: " + (d_childcomponent->isAutoWindow() ? "Yes" : "No")); } @@ -425,7 +423,7 @@ namespace CEGUI void Falagard_xmlHandler::elementImagerySectionStart(const XMLAttributes& attributes) { assert(d_imagerysection == 0); - d_imagerysection = CEGUI_NEW_AO ImagerySection(attributes.getValueAsString(NameAttribute)); + d_imagerysection = new ImagerySection(attributes.getValueAsString(NameAttribute)); CEGUI_LOGINSANE("-----> Start of definition for imagery section '" + d_imagerysection->getName() + "'."); } @@ -436,7 +434,7 @@ namespace CEGUI void Falagard_xmlHandler::elementStateImageryStart(const XMLAttributes& attributes) { assert(d_stateimagery == 0); - d_stateimagery = CEGUI_NEW_AO StateImagery(attributes.getValueAsString(NameAttribute)); + d_stateimagery = new StateImagery(attributes.getValueAsString(NameAttribute)); d_stateimagery->setClippedToDisplay(!attributes.getValueAsBool(ClippedAttribute, true)); CEGUI_LOGINSANE("-----> Start of definition for imagery for state '" + d_stateimagery->getName() + "'."); @@ -448,7 +446,7 @@ namespace CEGUI void Falagard_xmlHandler::elementLayerStart(const XMLAttributes& attributes) { assert(d_layer == 0); - d_layer = CEGUI_NEW_AO LayerSpecification(attributes.getValueAsInteger(PriorityAttribute, 0)); + d_layer = new LayerSpecification(attributes.getValueAsInteger(PriorityAttribute, 0)); CEGUI_LOGINSANE("-------> Start of definition of new imagery layer, priority: " + attributes.getValueAsString(PriorityAttribute, "0")); } @@ -462,7 +460,7 @@ namespace CEGUI assert(d_widgetlook != 0); String owner(attributes.getValueAsString(LookAttribute)); d_section = - CEGUI_NEW_AO SectionSpecification(owner.empty() ? d_widgetlook->getName() : owner, + new SectionSpecification(owner.empty() ? d_widgetlook->getName() : owner, attributes.getValueAsString(SectionNameAttribute), attributes.getValueAsString(ControlPropertyAttribute), attributes.getValueAsString(ControlValueAttribute), @@ -477,7 +475,7 @@ namespace CEGUI void Falagard_xmlHandler::elementImageryComponentStart(const XMLAttributes&) { assert(d_imagerycomponent == 0); - d_imagerycomponent = CEGUI_NEW_AO ImageryComponent(); + d_imagerycomponent = new ImageryComponent(); CEGUI_LOGINSANE("-------> Image component definition..."); } @@ -488,7 +486,7 @@ namespace CEGUI void Falagard_xmlHandler::elementTextComponentStart(const XMLAttributes&) { assert(d_textcomponent == 0); - d_textcomponent = CEGUI_NEW_AO TextComponent(); + d_textcomponent = new TextComponent(); CEGUI_LOGINSANE("-------> Text component definition..."); } @@ -499,7 +497,7 @@ namespace CEGUI void Falagard_xmlHandler::elementFrameComponentStart(const XMLAttributes&) { assert(d_framecomponent == 0); - d_framecomponent = CEGUI_NEW_AO FrameComponent(); + d_framecomponent = new FrameComponent(); CEGUI_LOGINSANE("-------> Frame component definition..."); } @@ -510,7 +508,7 @@ namespace CEGUI void Falagard_xmlHandler::elementAreaStart(const XMLAttributes&) { assert(d_area == 0); - d_area = CEGUI_NEW_AO ComponentArea(); + d_area = new ComponentArea(); } /************************************************************************* @@ -836,7 +834,7 @@ namespace CEGUI void Falagard_xmlHandler::elementNamedAreaStart(const XMLAttributes& attributes) { assert(d_namedArea == 0); - d_namedArea = CEGUI_NEW_AO NamedArea(attributes.getValueAsString(NameAttribute)); + d_namedArea = new NamedArea(attributes.getValueAsString(NameAttribute)); CEGUI_LOGINSANE("-----> Creating named area: " + d_namedArea->getName()); } @@ -860,73 +858,73 @@ namespace CEGUI typedef std::pair Range; if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName() ); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName() ); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); - else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); - else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + else if(type == PropertyHelper::getDataTypeName()) + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + else if(type == PropertyHelper::getDataTypeName()) + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); - else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + else if(type == PropertyHelper::getDataTypeName()) + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if(type == PropertyHelper::getDataTypeName()) - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else { if (type != GenericDataType && type != "String") @@ -935,7 +933,7 @@ namespace CEGUI Logger::getSingleton().logEvent("Type '" + type + "' wasn't recognized in property definition (name: '" + name + "').", Warnings); } - prop = CEGUI_NEW_AO PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); + prop = new PropertyDefinition(name, init, help, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); } CEGUI_LOGINSANE("-----> Adding PropertyDefiniton. Name: " + name + " Default Value: " + init); @@ -962,118 +960,118 @@ namespace CEGUI typedef std::pair Range; if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, widget, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, widget, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); - else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + else if (type == PropertyHelper::getDataTypeName()) + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); - else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + else if (type == PropertyHelper::getDataTypeName()) + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); - else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + else if (type == PropertyHelper::getDataTypeName()) + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink =CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink =new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition( + d_propertyLink = new PropertyLinkDefinition( name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< HorizontalTextFormatting>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< VerticalTextFormatting>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition( + d_propertyLink = new PropertyLinkDefinition( name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, widget, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, widget, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition( + d_propertyLink = new PropertyLinkDefinition( name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, widget, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< TabControl::TabPanePosition>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< Spinner::TextInputMode>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< ItemListBase::SortMode>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< ListHeaderSegment::SortDirection>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition< + d_propertyLink = new PropertyLinkDefinition< MultiColumnList::SelectionMode>(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition( + d_propertyLink = new PropertyLinkDefinition( name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName() ); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition( + d_propertyLink = new PropertyLinkDefinition( name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName() ); else if (type == PropertyHelper::getDataTypeName()) - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); else { @@ -1083,7 +1081,7 @@ namespace CEGUI Logger::getSingleton().logEvent("Type '" + type + "' wasn't recognized in property link definition (name: '" + name + "').", Warnings); } - d_propertyLink = CEGUI_NEW_AO PropertyLinkDefinition(name, + d_propertyLink = new PropertyLinkDefinition(name, widget, target, init, d_widgetlook->getName(), redraw, layout, eventName, d_widgetlook->getName()); } CEGUI_LOGINSANE("-----> Adding PropertyLinkDefiniton. Name: " + @@ -1271,7 +1269,7 @@ namespace CEGUI { Logger::getSingleton().logEvent("---< End of definition for widget look '" + d_widgetlook->getName() + "'.", Informative); d_manager->addWidgetLook(*d_widgetlook); - CEGUI_DELETE_AO d_widgetlook; + delete d_widgetlook; d_widgetlook = 0; } } @@ -1285,9 +1283,9 @@ namespace CEGUI if (d_childcomponent) { - CEGUI_LOGINSANE("-----< End of definition for child widget. Type: " + d_childcomponent->getBaseWidgetType() + "."); + CEGUI_LOGINSANE("-----< End of definition for child widget. Type: " + d_childcomponent->getTargetType() + "."); d_widgetlook->addWidgetComponent(*d_childcomponent); - CEGUI_DELETE_AO d_childcomponent; + delete d_childcomponent; d_childcomponent = 0; } } @@ -1303,7 +1301,7 @@ namespace CEGUI { CEGUI_LOGINSANE("-----< End of definition for imagery section '" + d_imagerysection->getName() + "'."); d_widgetlook->addImagerySection(*d_imagerysection); - CEGUI_DELETE_AO d_imagerysection; + delete d_imagerysection; d_imagerysection = 0; } } @@ -1318,8 +1316,8 @@ namespace CEGUI if (d_stateimagery) { CEGUI_LOGINSANE("-----< End of definition for imagery for state '" + d_stateimagery->getName() + "'."); - d_widgetlook->addStateSpecification(*d_stateimagery); - CEGUI_DELETE_AO d_stateimagery; + d_widgetlook->addStateImagery(*d_stateimagery); + delete d_stateimagery; d_stateimagery = 0; } } @@ -1335,7 +1333,7 @@ namespace CEGUI { CEGUI_LOGINSANE("-------< End of definition of imagery layer."); d_stateimagery->addLayer(*d_layer); - CEGUI_DELETE_AO d_layer; + delete d_layer; d_layer = 0; } } @@ -1350,7 +1348,7 @@ namespace CEGUI if (d_section) { d_layer->addSectionSpecification(*d_section); - CEGUI_DELETE_AO d_section; + delete d_section; d_section = 0; } } @@ -1365,7 +1363,7 @@ namespace CEGUI if (d_imagerycomponent) { d_imagerysection->addImageryComponent(*d_imagerycomponent); - CEGUI_DELETE_AO d_imagerycomponent; + delete d_imagerycomponent; d_imagerycomponent = 0; } } @@ -1380,7 +1378,7 @@ namespace CEGUI if (d_textcomponent) { d_imagerysection->addTextComponent(*d_textcomponent); - CEGUI_DELETE_AO d_textcomponent; + delete d_textcomponent; d_textcomponent = 0; } } @@ -1395,7 +1393,7 @@ namespace CEGUI if (d_framecomponent) { d_imagerysection->addFrameComponent(*d_framecomponent); - CEGUI_DELETE_AO d_framecomponent; + delete d_framecomponent; d_framecomponent = 0; } } @@ -1429,7 +1427,7 @@ namespace CEGUI d_namedArea->setArea(*d_area); } - CEGUI_DELETE_AO d_area; + delete d_area; d_area = 0; } @@ -1443,7 +1441,7 @@ namespace CEGUI if (d_namedArea) { d_widgetlook->addNamedArea(*d_namedArea); - CEGUI_DELETE_AO d_namedArea; + delete d_namedArea; d_namedArea = 0; } } @@ -1470,7 +1468,7 @@ namespace CEGUI } // release the dim we popped. - CEGUI_DELETE_AO currDim; + delete currDim; } } @@ -1513,18 +1511,18 @@ namespace CEGUI dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); else if(type == PropertyHelper::getDataTypeName()) dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); - else if(type == PropertyHelper::getDataTypeName()) - dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); - else if(type == PropertyHelper::getDataTypeName()) - dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); + else if(type == PropertyHelper::getDataTypeName()) + dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); + else if(type == PropertyHelper::getDataTypeName()) + dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); else if(type == PropertyHelper::getDataTypeName()) dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); else if(type == PropertyHelper::getDataTypeName()) dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); else if(type == PropertyHelper::getDataTypeName()) dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); - else if(type == PropertyHelper::getDataTypeName()) - dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); + else if(type == PropertyHelper::getDataTypeName()) + dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); else if(type == PropertyHelper::getDataTypeName()) dynamic_cast* >(d_propertyLink)->addLinkTarget(w, p); else if(type == PropertyHelper::getDataTypeName()) @@ -1594,7 +1592,7 @@ namespace CEGUI } else { - d_chainedHandler = CEGUI_NEW_AO AnimationDefinitionHandler( + d_chainedHandler = new AnimationDefinitionHandler( attributes, anim_name_prefix); } @@ -1615,7 +1613,7 @@ namespace CEGUI const String widget(attributes.getValueAsString(WidgetAttribute)); const String event(attributes.getValueAsString(EventAttribute)); - d_eventLink = CEGUI_NEW_AO EventLinkDefinition( + d_eventLink = new EventLinkDefinition( attributes.getValueAsString(NameAttribute)); CEGUI_LOGINSANE("-----> Adding EventLinkDefiniton. Name: " + @@ -1653,7 +1651,7 @@ namespace CEGUI CEGUI_LOGINSANE("<----- End of EventLinkDefiniton. Name: " + d_eventLink->getName()); - CEGUI_DELETE_AO d_eventLink; + delete d_eventLink; d_eventLink = 0; } @@ -1663,7 +1661,7 @@ namespace CEGUI const String look(attributes.getValueAsString(LookAttribute)); - d_area->setNamedAreaSouce(look.empty() ? d_widgetlook->getName() : look, + d_area->setNamedAreaSource(look.empty() ? d_widgetlook->getName() : look, attributes.getValueAsString(NameAttribute)); } diff --git a/cegui/src/svg/SVGBasicShape.cpp b/cegui/src/svg/SVGBasicShape.cpp new file mode 100644 index 000000000..4f6173581 --- /dev/null +++ b/cegui/src/svg/SVGBasicShape.cpp @@ -0,0 +1,199 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/svg/SVGBasicShape.h" + +#include "CEGUI/svg/SVGTesselator.h" + + +// Start of CEGUI namespace section +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +SVGBasicShape::SVGBasicShape(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation) + : d_paintStyle(paint_style) + , d_transformation(transformation) +{ +} + +//----------------------------------------------------------------------------// +SVGBasicShape::~SVGBasicShape() +{ +} + +//----------------------------------------------------------------------------// +SVGRect::SVGRect(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const float x, + const float y, + const float width, + const float height, + const float rx, + const float ry) : + SVGBasicShape(paint_style, transformation), + d_x(x), + d_y(y), + d_width(width), + d_height(height), + d_rx(rx), + d_ry(ry) +{ +} + +//----------------------------------------------------------------------------// +void SVGRect::render(std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const +{ + SVGTesselator::tesselateRect(this, + image_geometry_buffers, + render_settings); +} + +//----------------------------------------------------------------------------// +SVGCircle::SVGCircle(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const float cx, + const float cy, + const float r) : + SVGBasicShape(paint_style, transformation), + d_cx(cx), + d_cy(cy), + d_r(r) +{ +} + +//----------------------------------------------------------------------------// +void SVGCircle::render(std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const +{ + SVGTesselator::tesselateCircle(this, + image_geometry_buffers, + render_settings); +} + +//----------------------------------------------------------------------------// +SVGEllipse::SVGEllipse(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const float cx, + const float cy, + const float rx, + const float ry) + : SVGBasicShape(paint_style, transformation) + , d_cx(cx) + , d_cy(cy) + , d_rx(rx) + , d_ry(ry) +{ +} + +//----------------------------------------------------------------------------// +void SVGEllipse::render(std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const +{ + SVGTesselator::tesselateEllipse(this, + image_geometry_buffers, + render_settings); +} + + +//----------------------------------------------------------------------------// +SVGLine::SVGLine(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const float x1, + const float y1, + const float x2, + const float y2) : + SVGBasicShape(paint_style, transformation), + d_x1(x1), + d_y1(y1), + d_x2(x2), + d_y2(y2) +{ +} + +//----------------------------------------------------------------------------// +SVGLine::SVGLine(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const glm::vec2& line_start, + const glm::vec2& line_end) + : SVGBasicShape(paint_style, transformation) + , d_x1(line_start.x) + , d_y1(line_start.y) + , d_x2(line_end.x) + , d_y2(line_end.y) +{ +} + +//----------------------------------------------------------------------------// +void SVGLine::render(std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const +{ + SVGTesselator::tesselateLine(this, + image_geometry_buffers, + render_settings); +} + +//----------------------------------------------------------------------------// +SVGPolyline::SVGPolyline(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const std::vector& points) : + SVGBasicShape(paint_style, transformation), + d_points(points) +{ +} + +//----------------------------------------------------------------------------// +void SVGPolyline::render(std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const +{ + SVGTesselator::tesselatePolyline(this, + image_geometry_buffers, + render_settings); +} + +//----------------------------------------------------------------------------// +SVGPolygon::SVGPolygon(const SVGPaintStyle& paint_style, + const glm::mat3x3& transformation, + const std::vector& points) : + SVGBasicShape(paint_style, transformation), + d_points(points) +{ +} + +//----------------------------------------------------------------------------// +void SVGPolygon::render(std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) const +{ + SVGTesselator::tesselatePolygon(this, + image_geometry_buffers, + render_settings); +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/svg/SVGData.cpp b/cegui/src/svg/SVGData.cpp new file mode 100644 index 000000000..29f8d53af --- /dev/null +++ b/cegui/src/svg/SVGData.cpp @@ -0,0 +1,794 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/svg/SVGData.h" +#include "CEGUI/svg/SVGBasicShape.h" +#include "CEGUI/ResourceProvider.h" +#include "CEGUI/System.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/Logger.h" +// for the XML parsing part. +#include "CEGUI/XMLParser.h" +#include "CEGUI/XMLAttributes.h" + +namespace CEGUI +{ +//----------------------------------------------------------------------------// +// Internal Strings holding XML element and attribute names +const String ImagesetSchemaName("Imageset.xsd"); +//SVG elements and attributes +const String SVGElement( "svg" ); +const String SVGElementAttributeVersion( "version" ); +const String SVGElementAttributeWidth( "width" ); +const String SVGElementAttributeHeight( "height" ); + +//SVG Basic Shapes +const String SVGRectElement( "rect" ); +const String SVGCircleElement( "circle" ); +const String SVGEllipseElement( "ellipse" ); +const String SVGLineElement( "line" ); +const String SVGPolylineElement( "polyline" ); +const String SVGPolygonElement( "polygon" ); + +// SVG graphics elements paint attributes +const String SVGGraphicsElementAttributeFill( "fill" ); +const String SVGGraphicsElementAttributeFillRule( "fill-rule" ); +const String SVGGraphicsElementAttributeFillOpacity( "fill-opacity" ); +const String SVGGraphicsElementAttributeStroke( "stroke" ); +const String SVGGraphicsElementAttributeStrokeWidth( "stroke-width" ); +const String SVGGraphicsElementAttributeStrokeLinecap( "stroke-linecap" ); +const String SVGGraphicsElementAttributeStrokeLinejoin( "stroke-linejoin" ); +const String SVGGraphicsElementAttributeStrokeMiterLimit( "stroke-miterlimit" ); +const String SVGGraphicsElementAttributeStrokeDashArray( "stroke-dasharray" ); +const String SVGGraphicsElementAttributeStrokeDashOffset( "stroke-dashoffset" ); +const String SVGGraphicsElementAttributeStrokeOpacity( "stroke-opacity" ); + +// SVG transform attribute +const String SVGTransformAttribute( "transform" ); + +// SVG 'rect' element attributes +const String SVGRectAttributeXPos( "x" ); +const String SVGRectAttributeYPos( "y" ); +const String SVGRectAttributeWidth( "width" ); +const String SVGRectAttributeHeight( "height" ); +const String SVGRectAttributeRoundedX( "rx" ); +const String SVGRectAttributeRoundedY( "ry" ); +// SVG 'circle' element attributes +const String SVGCircleAttributeCX( "cx" ); +const String SVGCircleAttributeCY( "cy" ); +const String SVGCircleAttributeRadius( "r" ); +// SVG 'ellipse' element attributes +const String SVGEllipseAttributeCX( "cx" ); +const String SVGEllipseAttributeCY( "cy" ); +const String SVGEllipseAttributeRX( "rx" ); +const String SVGEllipseAttributeRY( "ry" ); +// SVG 'polyline' element attributes +const String SVGPolylineAttributePoints( "points" ); +// SVG 'polyline' element attributes +const String SVGLineAttributeX1( "x1" ); +const String SVGLineAttributeY1( "y1" ); +const String SVGLineAttributeX2( "x2" ); +const String SVGLineAttributeY2( "y2" ); + +//----------------------------------------------------------------------------// +SVGData::SVGData(const String& name) : + d_name(name) +{ +} + +//----------------------------------------------------------------------------// +SVGData::SVGData(const String& name, + const String& filename, + const String& resourceGroup) : + d_name(name) +{ + loadFromFile(filename, resourceGroup); +} + +//----------------------------------------------------------------------------// +SVGData::~SVGData() +{ + destroyShapes(); +} + +//----------------------------------------------------------------------------// +const String& SVGData::getName() const +{ + return d_name; +} + +//----------------------------------------------------------------------------// +void SVGData::loadFromFile(const String& file_name, + const String& resource_group) +{ + System::getSingleton().getXMLParser()->parseXMLFile( + *this, file_name, + "", resource_group, false); +} + +//----------------------------------------------------------------------------// +void SVGData::addShape(SVGBasicShape* svg_shape) +{ + d_svgBasicShapes.push_back(svg_shape); +} + +//----------------------------------------------------------------------------// +void SVGData::destroyShapes() +{ + const unsigned int shape_count = d_svgBasicShapes.size(); + for (unsigned int i = 0; i < shape_count; ++i) + delete d_svgBasicShapes[i]; + + d_svgBasicShapes.clear(); +} + +//----------------------------------------------------------------------------// +const std::vector& SVGData::getShapes() const +{ + return d_svgBasicShapes; +} + +//----------------------------------------------------------------------------// +float SVGData::getWidth() const +{ + return d_width; +} + +//----------------------------------------------------------------------------// +void SVGData::setWidth(float width) +{ + d_width = width; +} + +//----------------------------------------------------------------------------// +float SVGData::getHeight() const +{ + return d_height; +} + +//----------------------------------------------------------------------------// +void SVGData::setHeight(float height) +{ + d_height = height; +} + +//----------------------------------------------------------------------------// +void SVGData::elementStartLocal(const String& element, + const XMLAttributes& attributes) +{ + // handle SVG document fragment element + if (element == SVGElement) + { + elementSVGStart(attributes); + } + + // handle SVG 'rect' element + else if(element == SVGRectElement) + { + elementSVGRect(attributes); + } + // handle SVG 'circle' fragment element + else if(element == SVGCircleElement) + { + elementSVGCircle(attributes); + } + // handle SVG 'ellipse' element + else if(element == SVGEllipseElement) + { + elementSVGEllipse(attributes); + } + // handle SVG 'line' element + else if(element == SVGLineElement) + { + elementSVGLine(attributes); + } + // handle SVG 'polyline' element + else if(element == SVGPolylineElement) + { + elementSVGPolyline(attributes); + } + // handle SVG document fragment element + else if(element == SVGPolygonElement) + { + elementSVGPolygon(attributes); + } +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGStart(const XMLAttributes& attributes) +{ + // Get the SVG version + const String version( + attributes.getValueAsString(SVGElementAttributeVersion)); + + // Todo: Currently we only support pixels as units and interpret everything as + // such, probably some default conversion from inch/mm to pixels should happen + const String width( + attributes.getValueAsString(SVGElementAttributeWidth)); + d_width = parseLengthDataType(width).d_value; + + const String height( + attributes.getValueAsString(SVGElementAttributeHeight)); + d_height = parseLengthDataType(height).d_value; +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGRect(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style = parsePaintStyle(attributes); + glm::mat3x3 transform = parseTransform(attributes); + + const String xString( + attributes.getValueAsString(SVGRectAttributeXPos, "0")); + float x = parseLengthDataType(xString).d_value; + + const String yString( + attributes.getValueAsString(SVGRectAttributeYPos, "0")); + float y = parseLengthDataType(yString).d_value; + + const String widthString( + attributes.getValueAsString(SVGRectAttributeWidth, "0")); + float width = parseLengthDataType(widthString).d_value; + + const String heightString( + attributes.getValueAsString(SVGRectAttributeHeight, "0")); + float height = parseLengthDataType(heightString).d_value; + + const String rxString( + attributes.getValueAsString(SVGRectAttributeRoundedX, "0")); + float rx = parseLengthDataType(rxString).d_value; + + const String ryString( + attributes.getValueAsString(SVGRectAttributeRoundedY, "0")); + float ry = parseLengthDataType(ryString).d_value; + + SVGRect* rect = new SVGRect(paint_style, transform, x, y, width, height, rx, ry); + addShape(rect); +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGCircle(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style = parsePaintStyle(attributes); + glm::mat3x3 transform = parseTransform(attributes); + + const String cxString( + attributes.getValueAsString(SVGCircleAttributeCX, "0")); + float cx = parseLengthDataType(cxString).d_value; + + const String cyString( + attributes.getValueAsString(SVGCircleAttributeCY, "0")); + float cy = parseLengthDataType(cyString).d_value; + + const String radiusString( + attributes.getValueAsString(SVGCircleAttributeRadius, "0")); + float radius = parseLengthDataType(radiusString).d_value; + + SVGCircle* circle = new SVGCircle(paint_style, transform, cx, cy, radius); + addShape(circle); +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGEllipse(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style = parsePaintStyle(attributes); + glm::mat3x3 transform = parseTransform(attributes); + + const String cxString( + attributes.getValueAsString(SVGEllipseAttributeCX, "0")); + float cx = parseLengthDataType(cxString).d_value; + + const String cyString( + attributes.getValueAsString(SVGEllipseAttributeCY, "0")); + float cy = parseLengthDataType(cyString).d_value; + + const String rxString( + attributes.getValueAsString(SVGEllipseAttributeRX, "0")); + float rx = parseLengthDataType(rxString).d_value; + + const String ryString( + attributes.getValueAsString(SVGEllipseAttributeRY, "0")); + float ry = parseLengthDataType(ryString).d_value; + + SVGEllipse* ellipse = new SVGEllipse(paint_style, transform, cx, cy, rx, ry); + addShape(ellipse); +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGLine(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style = parsePaintStyle(attributes); + glm::mat3x3 transform = parseTransform(attributes); + + const String x1String( + attributes.getValueAsString(SVGLineAttributeX1, "0")); + float x1 = parseLengthDataType(x1String).d_value; + + const String y1String( + attributes.getValueAsString(SVGLineAttributeY1, "0")); + float y1 = parseLengthDataType(y1String).d_value; + + const String x2String( + attributes.getValueAsString(SVGLineAttributeX2, "0")); + float x2 = parseLengthDataType(x2String).d_value; + + const String y2String( + attributes.getValueAsString(SVGLineAttributeY2, "0")); + float y2 = parseLengthDataType(y2String).d_value; + + SVGLine* line = new SVGLine(paint_style, transform, + x1, y1, x2, y2); + addShape(line); +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGPolyline(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style = parsePaintStyle(attributes); + glm::mat3x3 transform = parseTransform(attributes); + + const String pointsString( + attributes.getValueAsString(SVGPolylineAttributePoints, "")); + + std::vector points; + parsePointsString(pointsString, points); + + SVGPolyline* polyline = new SVGPolyline(paint_style, transform, points); + addShape(polyline); +} + +//----------------------------------------------------------------------------// +void SVGData::elementSVGPolygon(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style = parsePaintStyle(attributes); + glm::mat3x3 transform = parseTransform(attributes); + + const String pointsString( + attributes.getValueAsString(SVGPolylineAttributePoints, "")); + + std::vector points; + parsePointsString(pointsString, points); + + SVGPolygon* polygon = new SVGPolygon(paint_style, transform, points); + addShape(polygon); +} + +//----------------------------------------------------------------------------// +void SVGData::elementEndLocal(const String& element) +{ +} + +//----------------------------------------------------------------------------// +SVGData::SVGLength SVGData::parseLengthDataType(const String& length_string) +{ + SVGLength length; + char lengthEnding[3] = ""; + String unitString; + + sscanf(length_string.c_str(), "%f%2s", &length.d_value, lengthEnding); + unitString = lengthEnding; + + if(unitString.empty()) + return length; + else if(unitString.length() == 2) + { + if(unitString.compare("in") == 0) + length.d_unit = SLU_IN; + else if(unitString.compare("cm") == 0) + length.d_unit = SLU_CM; + else if(unitString.compare("mm") == 0) + length.d_unit = SLU_MM; + else if(unitString.compare("pt") == 0) + length.d_unit = SLU_PT; + else if(unitString.compare("pc") == 0) + length.d_unit = SLU_PC; + else if(unitString.compare("px") == 0) + length.d_unit = SLU_PX; + } + else if(unitString.length() == 1) + { + if(unitString.compare("%") == 0) + length.d_unit = SLU_PERCENT; + } + else + // Parse error + CEGUI_THROW(SVGParsingException( + "SVG file parsing was aborted because of an invalid value of an SVG 'length' type")); + + return length; +} + +//----------------------------------------------------------------------------// +SVGPaintStyle SVGData::parsePaintStyle(const XMLAttributes& attributes) +{ + SVGPaintStyle paint_style; + + //TODO: unsupported/unspecified values should be inherited from the parents if possible, this + // however would require adding an additional bool to every attribute member variable to check if + // it is to be inherited or not + const String fillString( + attributes.getValueAsString(SVGGraphicsElementAttributeFill)); + parsePaintStyleFill(fillString, paint_style); + + const String fillRuleString( + attributes.getValueAsString(SVGGraphicsElementAttributeFillRule)); + parsePaintStyleFillRule(fillRuleString, paint_style); + + const String fillOpacityString( + attributes.getValueAsString(SVGGraphicsElementAttributeFillOpacity)); + parsePaintStyleFillOpacity(fillOpacityString, paint_style); + + const String strokeString( + attributes.getValueAsString(SVGGraphicsElementAttributeStroke)); + parsePaintStyleStroke(strokeString, paint_style); + + const String strokeWidthString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeWidth, "1")); + parsePaintStyleStrokeWidth(strokeWidthString, paint_style); + + const String strokeLinecapString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeLinecap, "butt")); + parsePaintStyleStrokeLinecap(strokeLinecapString, paint_style); + + const String strokeLinejoinString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeLinejoin, "miter")); + parsePaintStyleStrokeLinejoin(strokeLinejoinString, paint_style); + + const String strokeMiterLimitString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeMiterLimit, "4")); + parsePaintStyleMiterlimitString(strokeMiterLimitString, paint_style); + + const String strokeDashArrayString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeDashArray)); + parsePaintStyleStrokeDashArray(strokeDashArrayString, paint_style); + + const String strokeDashOffsetString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeDashOffset)); + parsePaintStyleStrokeDashOffset(strokeDashOffsetString, paint_style); + + const String strokeOpacityString( + attributes.getValueAsString(SVGGraphicsElementAttributeStrokeOpacity)); + parsePaintStyleStrokeOpacity(strokeOpacityString, paint_style); + + return paint_style; +} + +//----------------------------------------------------------------------------// +glm::vec3 SVGData::parseColour(const CEGUI::String& colour_string) +{ + if(colour_string.at(0) == '#') + { + glm::vec3 colour; + + if(colour_string.size() == 7) + { + int value; + sscanf(colour_string.c_str() + 1, " %2X ", &value); + colour.x = value / 255.0f; + sscanf(colour_string.c_str() + 3, " %2X ", &value); + colour.y = value / 255.0f; + sscanf(colour_string.c_str() + 5, " %2X ", &value); + colour.z = value / 255.0f; + + return colour; + } + else if(colour_string.size() == 4) + { + CEGUI::String mod_colour_string = CEGUI::String("") + + colour_string[1] + colour_string[1] + + colour_string[2] + colour_string[2] + + colour_string[3] + colour_string[3]; + + int value; + sscanf(mod_colour_string.c_str(), " %2X ", &value); + colour.x = value / 255.0f; + sscanf(mod_colour_string.c_str() + 2, " %2X ", &value); + colour.y = value / 255.0f; + sscanf(mod_colour_string.c_str() + 4, " %2X ", &value); + colour.z = value / 255.0f; + + return colour; + } + } + else if(colour_string.compare("rgb(") > 0) + { + CEGUI::String mod_colour_string = colour_string.substr(4, colour_string.length() - 5); + + int r, g, b; + sscanf(mod_colour_string.c_str(), " %i , %i , %i ", &r, &g, &b); + + return glm::vec3(r / 255.0f, g / 255.0f, b / 255.0f); + } + // SVG's default colours + else if(colour_string.compare("black") == 0) + return glm::vec3(0.0f, 0.0f, 0.0f); + else if(colour_string.compare("green") == 0) + return glm::vec3(0.0f, 128.0f / 255.0f, 0.0f); + else if(colour_string.compare("silver") == 0) + return glm::vec3(192.0f / 255.0f, 192.0f / 255.0f, 192.0f / 255.0f); + else if(colour_string.compare("lime") == 0) + return glm::vec3(0.0f, 1.0f, 0.0f); + else if(colour_string.compare("gray") == 0) + return glm::vec3(128.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f); + else if(colour_string.compare("olive") == 0) + return glm::vec3(128.0f / 255.0f, 128.0f / 255.0f, 0.f); + else if(colour_string.compare("white") == 0) + return glm::vec3(1.0f, 1.0f, 1.0f); + else if(colour_string.compare("yellow") == 0) + return glm::vec3(1.0f, 1.0f, 0.0f); + else if(colour_string.compare("maroon") == 0) + return glm::vec3(128.0f / 255.0f, 0.0f, 0.0f); + else if(colour_string.compare("navy") == 0) + return glm::vec3(0.0f, 0.0f, 128.0f / 255.0f); + else if(colour_string.compare("red") == 0) + return glm::vec3(1.0f, 0.0f, 0.0f); + else if(colour_string.compare("blue") == 0) + return glm::vec3(0.0f, 0.0f, 1.0f); + else if(colour_string.compare("purple") == 0) + return glm::vec3(128.0f / 255.0f, 0.0f, 128.0f / 255.0f); + else if(colour_string.compare("teal") == 0) + return glm::vec3(0.0f, 128.0f / 255.0f, 128.0f / 255.0f); + else if(colour_string.compare("fuchsia") == 0) + return glm::vec3(1.0f, 0.0f, 1.0f); + else if(colour_string.compare("aqua") == 0) + return glm::vec3(0.0f, 1.0f, 1.0f); + + // Parse error + CEGUI_THROW(SVGParsingException( + "SVG file parsing was aborted because of an invalid colour value")); + + return glm::vec3(); +} + +//----------------------------------------------------------------------------// +std::vector SVGData::parseListOfLengths(const String& list_of_lengths_string) +{ + std::vector list_of_lengths; + const char* lengths_array_pointer = list_of_lengths_string.c_str(); + float value; + int offset; + + while (1 == sscanf(lengths_array_pointer, " %f ,%n", &value, &offset)) + { + list_of_lengths.push_back(value); + lengths_array_pointer += offset; + } + + return list_of_lengths; +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleFill(const String& fillString, SVGPaintStyle& paint_style) +{ + if (fillString.compare("none") == 0) + paint_style.d_fill.d_none = true; + else if(fillString.empty()) + { + // Inherit value or use default + paint_style.d_fill.d_none = false; + paint_style.d_fill.d_colour = parseColour("black"); + } + else + { + paint_style.d_fill.d_none = false; + paint_style.d_fill.d_colour = parseColour(fillString); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleFillRule(const String& fillRuleString, SVGPaintStyle& paint_style) +{ + if(fillRuleString.empty()) + // Inherit value or use default + paint_style.d_fillRule = PFR_NON_ZERO; + else if(fillRuleString.compare("nonzero")) + paint_style.d_fillRule = PFR_NON_ZERO; + else if(fillRuleString.compare("evenodd")) + paint_style.d_fillRule = PFR_EVEN_ODD; +} + + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleFillOpacity(const String& fillOpacityString, SVGPaintStyle& paint_style) +{ + if(fillOpacityString.empty()) + // Inherit value or use default + paint_style.d_fillOpacity = 1.0f; + else + { + sscanf(fillOpacityString.c_str(), "%f", &paint_style.d_fillOpacity); + //! Clamp value in each case without throwing a warning if the values are below 0 or above 1 + paint_style.d_fillOpacity = std::min( std::max(0.0f, paint_style.d_fillOpacity), 1.0f ); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStroke(const String& strokeString, SVGPaintStyle& paint_style) +{ + if (strokeString.compare("none") == 0 || strokeString.empty()) + paint_style.d_stroke.d_none = true; + else + { + paint_style.d_stroke.d_none = false; + paint_style.d_stroke.d_colour = parseColour(strokeString); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStrokeWidth(const String& strokeWidthString, SVGPaintStyle& paint_style) +{ + sscanf(strokeWidthString.c_str(), "%f", &paint_style.d_strokeWidth); + if(paint_style.d_strokeWidth < 0.0f) + { + paint_style.d_strokeWidth = 1.0f; + Logger::getSingleton().logEvent("SVGData::parsePaintStyle - An unsupported value for stroke-width was specified in the SVG file. The value is set to the initial value '1'.", Errors); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStrokeLinecap(const String& strokeLinecapString, SVGPaintStyle& paint_style) +{ + if(strokeLinecapString.compare("butt") == 0) + paint_style.d_strokeLinecap = SVGPaintStyle::SLC_BUTT; + else if(strokeLinecapString.compare("round") == 0) + paint_style.d_strokeLinecap = SVGPaintStyle::SLC_ROUND; + else if(strokeLinecapString.compare("square") == 0) + paint_style.d_strokeLinecap = SVGPaintStyle::SLC_SQUARE; + else + CEGUI_THROW(SVGParsingException( + "SVG file parsing was aborted because of an invalid value for the SVG 'linecap' type")); +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStrokeLinejoin(const String& strokeLinejoinString, SVGPaintStyle& paint_style) +{ + if(strokeLinejoinString.compare("miter") == 0) + paint_style.d_strokeLinejoin = SVGPaintStyle::SLJ_MITER; + else if(strokeLinejoinString.compare("round") == 0) + paint_style.d_strokeLinejoin = SVGPaintStyle::SLJ_ROUND; + else if(strokeLinejoinString.compare("bevel") == 0) + paint_style.d_strokeLinejoin = SVGPaintStyle::SLJ_BEVEL; + else + CEGUI_THROW(SVGParsingException( + "SVG file parsing was aborted because of an invalid value for the SVG 'linejoin' type")); +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleMiterlimitString(const String& strokeMiterLimitString, SVGPaintStyle& paint_style) +{ + sscanf(strokeMiterLimitString.c_str(), "%f", &paint_style.d_strokeMiterlimit); + if(paint_style.d_strokeMiterlimit < 1.0f) + { + paint_style.d_strokeMiterlimit = 4.0f; + Logger::getSingleton().logEvent("SVGData::parsePaintStyle - An unsupported value for stroke-miterlimit was specified in the SVG file. The value is set to the initial value '4'.", Errors); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStrokeDashArray(const String& strokeDashArrayString, SVGPaintStyle& paint_style) +{ + if(strokeDashArrayString.compare("none") == 0) + { + paint_style.d_strokeDashArrayNone = true; + paint_style.d_strokeDashArray.clear(); + } + else + { + paint_style.d_strokeDashArray = parseListOfLengths(strokeDashArrayString); + + const size_t dashArraySize = paint_style.d_strokeDashArray.size(); + paint_style.d_strokeDashArrayNone = dashArraySize != 0; + //! If an odd number of values is provided, then the list of values shall be repeated to yield an even number of values + if(paint_style.d_strokeDashArrayNone == false && (dashArraySize % 2) == 1) + paint_style.d_strokeDashArray.insert( paint_style.d_strokeDashArray.end(), paint_style.d_strokeDashArray.begin(), paint_style.d_strokeDashArray.end() ); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStrokeOpacity(const String& strokeOpacityString, SVGPaintStyle& paint_style) +{ + if(strokeOpacityString.empty()) + paint_style.d_strokeOpacity = 1.0f; + else + { + sscanf(strokeOpacityString.c_str(), "%f", &paint_style.d_strokeOpacity); + //! Clamp value without ever throwing a warning + paint_style.d_strokeOpacity = std::min( std::max(0.0f, paint_style.d_strokeOpacity), 1.0f ); + } +} + +//----------------------------------------------------------------------------// +void SVGData::parsePaintStyleStrokeDashOffset(const String& strokeDashOffsetString, SVGPaintStyle& paint_style) +{ + if(strokeDashOffsetString.empty()) + paint_style.d_strokeDashOffset = 0.0f; + else + sscanf(strokeDashOffsetString.c_str(), "%f", &paint_style.d_strokeDashOffset); +} + +//----------------------------------------------------------------------------// +glm::mat3x3 SVGData::parseTransform(const XMLAttributes& attributes) +{ + const String transformString( + attributes.getValueAsString(SVGTransformAttribute)); + + const char* transformStringSegment = transformString.c_str(); + int offset = 0; + // Unity matrix is our default/basis + glm::mat3x3 currentMatrix(1.0f); + + if(sscanf(transformStringSegment, " matrix( %n", &offset) == 0 && offset != 0) + { + transformStringSegment += offset; + float matrixValues[6]; + + int i = 0; + while( (i < 6) && ( sscanf(transformStringSegment, " %f %n", &matrixValues[i], &offset) == 1 || + sscanf(transformStringSegment, " , %f %n", &matrixValues[i], &offset) == 1 ) ) + { + transformStringSegment += offset; + ++i; + } + + //If we parsed the expected amount of matrix elements we will multiply the matrix to our transformation + if(i == 6) + currentMatrix *= glm::mat3x3(matrixValues[0], matrixValues[2], matrixValues[4], + matrixValues[1], matrixValues[3], matrixValues[5], + 0.0f, 0.0f, 1.0f); + } + + return currentMatrix; +} + +//----------------------------------------------------------------------------// +void SVGData::parsePointsString(const String& pointsString, std::vector& points) +{ + const char* currentStringSegment = pointsString.c_str(); + int offset; + glm::vec2 currentPoint; + + while(true) + { + int successful_args = sscanf(currentStringSegment, " %f , %f%n", ¤tPoint.x, ¤tPoint.y, &offset); + + if(successful_args == 2) + { + points.push_back(currentPoint); + currentStringSegment += offset; + } + else if(successful_args == 1) + { + points.clear(); + currentStringSegment += offset; + } + else + break; + } +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/svg/SVGDataManager.cpp b/cegui/src/svg/SVGDataManager.cpp new file mode 100644 index 000000000..e9b0ab41c --- /dev/null +++ b/cegui/src/svg/SVGDataManager.cpp @@ -0,0 +1,156 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "CEGUI/svg/SVGDataManager.h" +#include "CEGUI/svg/SVGData.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/Logger.h" + +namespace CEGUI +{ +//----------------------------------------------------------------------------// +// Singleton instance pointer +template<> SVGDataManager* Singleton::ms_Singleton = 0; + + +//----------------------------------------------------------------------------// +SVGDataManager::SVGDataManager() +{ + +} + +//----------------------------------------------------------------------------// +SVGDataManager::~SVGDataManager() +{ + destroyAll(); +} + +//----------------------------------------------------------------------------// +SVGDataManager& SVGDataManager::getSingleton(void) +{ + return Singleton::getSingleton(); +} + +//----------------------------------------------------------------------------// +SVGDataManager* SVGDataManager::getSingletonPtr(void) +{ + return Singleton::getSingletonPtr(); +} + +//----------------------------------------------------------------------------// +SVGData& SVGDataManager::create(const String& name) +{ + if (d_svgDataMap.find(name) != d_svgDataMap.end()) + CEGUI_THROW(AlreadyExistsException( + "An SVGData object named " + name + " already exists.")); + + SVGData* svg_data = new SVGData(name); + d_svgDataMap[name] = svg_data; + + logSVGDataCreation(svg_data); + + return *svg_data; +} + +//----------------------------------------------------------------------------// +SVGData& SVGDataManager::create(const String& name, + const String& filename, + const String& resourceGroup) +{ + if (d_svgDataMap.find(name) != d_svgDataMap.end()) + CEGUI_THROW(AlreadyExistsException( + "An SVGData object named " + name + " already exists.")); + + SVGData* svg_data = new SVGData(name, filename, resourceGroup); + d_svgDataMap[name] = svg_data; + + logSVGDataCreation(svg_data); + + return *svg_data; +} + +//----------------------------------------------------------------------------// +SVGData& SVGDataManager::getSVGData(const String& name) const +{ + SVGDataMap::const_iterator i = d_svgDataMap.find(name); + + if (i == d_svgDataMap.end()) + CEGUI_THROW(UnknownObjectException( + "No SVGData named '" + name + "' is available.")); + + return *i->second; +} + +//----------------------------------------------------------------------------// +bool SVGDataManager::isSVGDataDefined(const String& name) const +{ + return d_svgDataMap.find(name) != d_svgDataMap.end(); +} + + +//----------------------------------------------------------------------------// +void SVGDataManager::logSVGDataCreation(SVGData* svgData) +{ + char addr_buff[32]; + sprintf(addr_buff, "%p", static_cast(svgData)); + + Logger::getSingleton().logEvent( + "[SVGDataManager] Created SVGData object: '" + svgData->getName() + "' (" + addr_buff + + ")"); +} + +//----------------------------------------------------------------------------// +void SVGDataManager::destroy(SVGData& svgData) +{ + destroy(svgData.getName()); +} + +//----------------------------------------------------------------------------// +void SVGDataManager::destroy(const String& name) +{ + SVGDataIterator iter = d_svgDataMap.find(name); + + if (iter != d_svgDataMap.end()) + { + delete iter->second; + + Logger::getSingleton().logEvent( + "[SVGDataManager] Deleted SVGData object: " + iter->first); + + d_svgDataMap.erase(iter); + } +} + +//----------------------------------------------------------------------------// +void SVGDataManager::destroyAll() +{ + while (!d_svgDataMap.empty()) + destroy(d_svgDataMap.begin()->first); +} + +//----------------------------------------------------------------------------// +} diff --git a/cegui/src/svg/SVGImage.cpp b/cegui/src/svg/SVGImage.cpp new file mode 100644 index 000000000..ca8e3a509 --- /dev/null +++ b/cegui/src/svg/SVGImage.cpp @@ -0,0 +1,155 @@ +/*********************************************************************** + created: 30th July 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/svg/SVGImage.h" +#include "CEGUI/GeometryBuffer.h" +#include "CEGUI/CoordConverter.h" +#include "CEGUI/svg/SVGTesselator.h" +#include "CEGUI/svg/SVGData.h" +#include "CEGUI/svg/SVGBasicShape.h" +#include "CEGUI/svg/SVGDataManager.h" +#include "CEGUI/XMLAttributes.h" + + + +// Start of CEGUI namespace section +namespace CEGUI +{ +const String ImageTypeAttribute( "type" ); +const String ImageNameAttribute( "name" ); +const String ImageSVGDataAttribute( "SVGData" ); +const String ImageXPosAttribute( "xPos" ); +const String ImageYPosAttribute( "yPos" ); +const String ImageWidthAttribute( "width" ); +const String ImageHeightAttribute( "height" ); +const String ImageXOffsetAttribute( "xOffset" ); +const String ImageYOffsetAttribute( "yOffset" ); +const String ImageAutoScaledAttribute( "autoScaled" ); +const String ImageNativeHorzResAttribute( "nativeHorzRes" ); +const String ImageNativeVertResAttribute( "nativeVertRes" ); + +//----------------------------------------------------------------------------// +SVGImage::SVGImage(const String& name) : + Image(name), + d_svgData(0), + d_useGeometryAntialiasing(true) +{ +} + +//----------------------------------------------------------------------------// +SVGImage::SVGImage(const String& name, SVGData& svg_data) : + Image(name, + glm::vec2(0.0f, 0.0f), + Rectf(glm::vec2(0.0f, 0.0f), + glm::vec2(svg_data.getWidth(), svg_data.getHeight())), + ASM_Disabled, + Sizef(640, 480)), + d_svgData(&svg_data), + d_useGeometryAntialiasing(true) +{ +} + +//----------------------------------------------------------------------------// +SVGImage::SVGImage(const XMLAttributes& attributes) : + Image(attributes.getValueAsString(ImageNameAttribute), + glm::vec2(static_cast(attributes.getValueAsInteger(ImageXOffsetAttribute, 0)), + static_cast(attributes.getValueAsInteger(ImageYOffsetAttribute, 0))), + Rectf(glm::vec2(static_cast(attributes.getValueAsInteger(ImageXPosAttribute, 0)), + static_cast(attributes.getValueAsInteger(ImageYPosAttribute, 0))), + Sizef(static_cast(attributes.getValueAsInteger(ImageWidthAttribute, 0)), + static_cast(attributes.getValueAsInteger(ImageHeightAttribute, 0)))), + PropertyHelper::fromString(attributes.getValueAsString(ImageAutoScaledAttribute)), + Sizef(static_cast(attributes.getValueAsInteger(ImageNativeHorzResAttribute, 640)), + static_cast(attributes.getValueAsInteger(ImageNativeVertResAttribute, 480)))), + d_svgData(&SVGDataManager::getSingleton().getSVGData( + attributes.getValueAsString(ImageSVGDataAttribute))), + d_useGeometryAntialiasing(true) +{ +} + +//----------------------------------------------------------------------------// +void SVGImage::setSVGData(SVGData* svg_Data) +{ + d_svgData = svg_Data; +} + +//----------------------------------------------------------------------------// +SVGData* SVGImage::getSVGData() +{ + return d_svgData; +} + +//----------------------------------------------------------------------------// +void SVGImage::render(std::vector& image_geometry_buffers, + const ImageRenderSettings& render_settings) const +{ + Rectf dest(render_settings.d_destArea); + // apply rendering offset to the destination Rect + dest.offset(d_scaledOffset); + + const CEGUI::Rectf*const& clip_area = render_settings.d_clipArea; + // Calculate the actual (clipped) area to which we want to render to + Rectf final_rect(clip_area ? dest.getIntersection(*clip_area) : dest ); + + // check if our Image is totally clipped and return if it is + if ((final_rect.getWidth() == 0) || (final_rect.getHeight() == 0)) + return; + + // Calculate the scale factor for our Image which is the scaling of the Image + // area to the destination area of our render call + const glm::vec2 scale_factor(dest.getWidth() / d_imageArea.getWidth(), dest.getHeight() / d_imageArea.getHeight()); + + // URGENT FIXME: Shouldn't this be in the hands of the user? + final_rect.d_min.d_x = CoordConverter::alignToPixels(final_rect.d_min.d_x); + final_rect.d_min.d_y = CoordConverter::alignToPixels(final_rect.d_min.d_y); + final_rect.d_max.d_x = CoordConverter::alignToPixels(final_rect.d_max.d_x); + final_rect.d_max.d_y = CoordConverter::alignToPixels(final_rect.d_max.d_y); + + SVGImageRenderSettings svg_render_settings(render_settings, + scale_factor, + d_useGeometryAntialiasing); + + const std::vector& shapes = d_svgData->getShapes(); + const unsigned int shape_count = shapes.size(); + for (unsigned int i = 0; i < shape_count; ++i) + shapes[i]->render(image_geometry_buffers, svg_render_settings); +} + +//----------------------------------------------------------------------------// +bool SVGImage::getUsesGeometryAntialiasing() const +{ + return d_useGeometryAntialiasing; +} + +//----------------------------------------------------------------------------// +void SVGImage::setUseGeometryAntialiasing(bool use_geometry_antialiasing) +{ + d_useGeometryAntialiasing = use_geometry_antialiasing; +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/svg/SVGPaintStyle.cpp b/cegui/src/svg/SVGPaintStyle.cpp new file mode 100644 index 000000000..5bb01de0e --- /dev/null +++ b/cegui/src/svg/SVGPaintStyle.cpp @@ -0,0 +1,60 @@ +/*********************************************************************** + created: 1st August 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/svg/SVGPaintStyle.h" + + +// Start of CEGUI namespace section +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +SVGPaint::SVGPaint() : + d_none(false), + d_colour(0.0f, 0.0f, 0.0f) +{ +} + +//----------------------------------------------------------------------------// +SVGPaintStyle::SVGPaintStyle() : + d_fill(), + d_fillRule(PFR_NON_ZERO), + d_fillOpacity(1.0f), + d_stroke(), + d_strokeWidth(1.0f), + d_strokeLinecap(SLC_BUTT), + d_strokeLinejoin(SLJ_MITER), + d_strokeMiterlimit(4.0f), + d_strokeDashArray(), + d_strokeDashOffset(0.0f), + d_strokeOpacity(1.0f) +{ +} + + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/svg/SVGTesselator.cpp b/cegui/src/svg/SVGTesselator.cpp new file mode 100644 index 000000000..a6ef37fd8 --- /dev/null +++ b/cegui/src/svg/SVGTesselator.cpp @@ -0,0 +1,1999 @@ +/*********************************************************************** + created: 1st August 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/svg/SVGTesselator.h" + +#include "CEGUI/svg/SVGBasicShape.h" +#include "CEGUI/GeometryBuffer.h" +#include "CEGUI/System.h" +#include "CEGUI/Vertex.h" +#include "glm/gtx/constants.hpp" + +#include + + +// Start of CEGUI namespace section +namespace CEGUI +{ +//Internal numeric value for circle roundness. The lower, the better tesselated the +//circle will be. We will set it to an, for our needs, appropriate fixed value. +const float CircleRoundnessValue = 0.8f; + +//----------------------------------------------------------------------------// +SVGTesselator::StrokeSegmentData::StrokeSegmentData(GeometryBuffer& geometry_buffer, + const float stroke_half_width, + const SVGPaintStyle& paint_style, + const float max_scale) : + d_geometryBuffer(geometry_buffer), + d_strokeHalfWidth(stroke_half_width), + d_paintStyle(paint_style), + d_maxScale(max_scale), + d_prevPoint(0), + d_curPoint(0), + d_nextPoint(0) +{ + // Get and add the stroke colour + d_strokeVertex.d_colour = SVGTesselator::getStrokeColour(paint_style); + // Set the z coordinate + d_strokeVertex.d_position.z = 0.0f; + //Create the fade stroke colour from the normal colour and set the alpha to 0 + d_strokeFadeVertex = d_strokeVertex; + d_strokeFadeVertex.d_colour.w = 0.0f; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::StrokeSegmentData::setPoints(const glm::vec2& prev_point, + const glm::vec2& cur_point, + const glm::vec2& next_point) +{ + d_prevPoint = &prev_point; + d_curPoint = &cur_point; + d_nextPoint = &next_point; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::tesselateRect(const SVGRect* rect, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) +{ + glm::mat3x3 transformation = glm::mat3(1.0f, 0.0f, rect->d_x, + 0.0f, 1.0f, rect->d_y, + 0.0f, 0.0f, 1.0f ) * rect->d_transformation; + + //Setup the required Geometrybuffers + GeometryBuffer* fill_geometry_buffer; + GeometryBuffer* stroke_geometry_buffer; + setupGeometryBuffers(fill_geometry_buffer, stroke_geometry_buffer, image_geometry_buffers, render_settings, transformation, false); + + //The shape's paint styles + const SVGPaintStyle& paint_style = rect->d_paintStyle; + + //Get the final scale by extracting the scale from the matrix and combining it with the image scale + glm::vec2 scale_factors = determineScaleFactors(rect->d_transformation, render_settings); + + //Make a list of rectangle (corner) points + std::vector rectangle_points; + rectangle_points.push_back( glm::vec2(0.0f, 0.0f ) ); + rectangle_points.push_back( glm::vec2(0.0f, rect->d_height) ); + rectangle_points.push_back( glm::vec2(rect->d_width, rect->d_height) ); + rectangle_points.push_back( glm::vec2(rect->d_width, 0.0f ) ); + + //Create and append the rectangle's fill geometry + createTriangleStripFillGeometry(rectangle_points, *fill_geometry_buffer, paint_style); + + //Create and append the rectangle's stroke geometry + createStroke(rectangle_points, *stroke_geometry_buffer, paint_style, render_settings, scale_factors, true); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::tesselateCircle(const SVGCircle* circle, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) +{ + glm::mat3x3 transformation = glm::mat3(1.0f, 0.0f, circle->d_cx, + 0.0f, 1.0f, circle->d_cy, + 0.0f, 0.0f, 1.0f ) * circle->d_transformation; + + //Setup the required Geometrybuffers + GeometryBuffer* fill_geometry_buffer; + GeometryBuffer* stroke_geometry_buffer; + setupGeometryBuffers(fill_geometry_buffer, stroke_geometry_buffer, image_geometry_buffers, render_settings, transformation, false); + + //The shape's paint styles + const SVGPaintStyle& paint_style = circle->d_paintStyle; + + //Get the final scale by extracting the scale from the matrix and combining it with the image scale + glm::vec2 scale_factors = determineScaleFactors(circle->d_transformation, render_settings); + + //We need this to determine the degree of tesselation required for the curved elements + float max_scale = std::max(render_settings.d_scaleFactor.x, render_settings.d_scaleFactor.y); + + //Get the radius + const float& radius = circle->d_r; + + //Precalculate values needed for the circle tesselation + float num_segments, cos_value, sin_value; + calculateCircleTesselationParameters(radius, max_scale, num_segments, cos_value, sin_value); + + //Create circle points + std::vector circle_points; + createCirclePoints(radius, num_segments, cos_value, sin_value, circle_points); + + if(circle_points.size() < 3) + return; + + //Create and append the circle's fill geometry + createCircleFill(circle_points, max_scale, paint_style, *fill_geometry_buffer, render_settings, scale_factors); + //Create and append the circle's stroke geometry + createCircleStroke(circle_points, max_scale, paint_style, *stroke_geometry_buffer, render_settings, scale_factors); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::tesselateEllipse(const SVGEllipse* ellipse, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) +{ + glm::mat3x3 transformation = glm::mat3(1.0f, 0.0f, ellipse->d_cx, + 0.0f, 1.0f, ellipse->d_cy, + 0.0f, 0.0f, 1.0f ) * ellipse->d_transformation; + + //Setup the required Geometrybuffers + GeometryBuffer* fill_geometry_buffer; + GeometryBuffer* stroke_geometry_buffer; + setupGeometryBuffers(fill_geometry_buffer, stroke_geometry_buffer, image_geometry_buffers, render_settings, transformation, false); + + //The shape's paint styles + const SVGPaintStyle& paint_style = ellipse->d_paintStyle; + + //Get the final scale by extracting the scale from the matrix and combining it with the image scale + glm::vec2 scale_factors = determineScaleFactors(ellipse->d_transformation, render_settings); + + //We need this to determine the degree of tesselation required for the curved elements + float max_scale = std::max(render_settings.d_scaleFactor.x, render_settings.d_scaleFactor.y); + + //Get the radii + const float& radiusX = ellipse->d_rx; + const float& radiusY = ellipse->d_ry; + + //Create ellipse points + std::vector ellipse_points; + createEllipsePoints(radiusX, radiusY, max_scale, ellipse_points); + + if(ellipse_points.size() < 3) + return; + + //Create and append the ellipse's fill geometry + createEllipseFill(ellipse_points, max_scale, paint_style, *fill_geometry_buffer, render_settings, scale_factors); + //Create and append the ellipse's stroke geometry + createEllipseStroke(ellipse_points, max_scale, paint_style, *stroke_geometry_buffer, render_settings, scale_factors); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::tesselateLine(const SVGLine* line, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) +{ + //Setup the required Geometrybuffers + GeometryBuffer* fill_geometry_buffer; + GeometryBuffer* stroke_geometry_buffer; + setupGeometryBuffers(fill_geometry_buffer, stroke_geometry_buffer, image_geometry_buffers, render_settings, line->d_transformation, false); + + //The shape's paint styles + const SVGPaintStyle& paint_style = line->d_paintStyle; + + //Get the final scale by extracting the scale from the matrix and combining it with the image scale + glm::vec2 scale_factors = determineScaleFactors(line->d_transformation, render_settings); + + //Create the line points and add them to the stroke points list + std::vector points; + points.push_back(glm::vec2(line->d_x1, line->d_y1)); + points.push_back(glm::vec2(line->d_x2, line->d_y2)); + + + + //Create and append the polyline's stroke geometry + createStroke(points, *stroke_geometry_buffer, paint_style, render_settings, scale_factors, false); +} + + +//----------------------------------------------------------------------------// +void SVGTesselator::tesselatePolyline(const SVGPolyline* polyline, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) +{ + //Setup the required Geometrybuffers + GeometryBuffer* fill_geometry_buffer; + GeometryBuffer* stroke_geometry_buffer; + setupGeometryBuffers(fill_geometry_buffer, stroke_geometry_buffer, image_geometry_buffers, render_settings, polyline->d_transformation, true); + + //The shape's paint styles + const SVGPaintStyle& paint_style = polyline->d_paintStyle; + + //Getting the points defining the polyline + const std::vector& points = polyline->d_points; + + //Get the final scale by extracting the scale from the matrix and combining it with the image scale + glm::vec2 scale_factors = determineScaleFactors(polyline->d_transformation, render_settings); + + //Create and append the polyline's fill geometry + createFill(points, *fill_geometry_buffer, paint_style, render_settings, scale_factors); + + //Create and append the polyline's stroke geometry + createStroke(points, *stroke_geometry_buffer, paint_style, render_settings, scale_factors, false); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::tesselatePolygon(const SVGPolygon* polygon, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings) +{ + //Setup the required Geometrybuffers + GeometryBuffer* fill_geometry_buffer; + GeometryBuffer* stroke_geometry_buffer; + setupGeometryBuffers(fill_geometry_buffer, stroke_geometry_buffer, image_geometry_buffers, render_settings, polygon->d_transformation, true); + + //The shape's paint styles + const SVGPaintStyle& paint_style = polygon->d_paintStyle; + + //Getting the points defining the polyline + const std::vector& points = polygon->d_points; + + //Get the final scale by extracting the scale from the matrix and combining it with the image scale + glm::vec2 scale_factors = determineScaleFactors(polygon->d_transformation, render_settings); + + //Create and append the polyline's fill geometry + createFill(points, *fill_geometry_buffer, paint_style, render_settings, scale_factors); + + //Create and append the polyline's stroke geometry + createStroke(points, *stroke_geometry_buffer, paint_style, render_settings, scale_factors, true); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setupGeometryBuffers(GeometryBuffer*& fill_geometry_buffer, + GeometryBuffer*& stroke_geometry_buffer, + std::vector& image_geometry_buffers, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::mat3x3& svg_transformation, + const bool is_fill_needing_stencil) +{ + //Calculate the transformation matrix for the CEGUI rendering system based on the SVG transformation matrix + glm::mat4 cegui_transformation_matrix = createRenderableMatrixFromSVGMatrix(svg_transformation); + + fill_geometry_buffer = &System::getSingleton().getRenderer()->createGeometryBufferColoured(); + + setupGeometryBufferSettings(fill_geometry_buffer, render_settings, cegui_transformation_matrix); + image_geometry_buffers.push_back(fill_geometry_buffer); + + //TODO Ident: For gradients ability we will also need to perform a check for the DS_type here to see if we need a seperate buffer or not + if(!is_fill_needing_stencil) + { + //We can use the GeometryBuffer of the fill also for the stroke + stroke_geometry_buffer = fill_geometry_buffer; + } + else + { + stroke_geometry_buffer = &System::getSingleton().getRenderer()->createGeometryBufferColoured(); + + setupGeometryBufferSettings(stroke_geometry_buffer, render_settings, cegui_transformation_matrix); + image_geometry_buffers.push_back(stroke_geometry_buffer); + } +} + +//----------------------------------------------------------------------------// +glm::vec4 SVGTesselator::getFillColour(const SVGPaintStyle &paint_style) +{ + const glm::vec3& fill_colour_values = paint_style.d_fill.d_colour; + return glm::vec4(fill_colour_values.x, fill_colour_values.y, fill_colour_values.z, paint_style.d_fillOpacity); +} + +//----------------------------------------------------------------------------// +glm::vec4 SVGTesselator::getStrokeColour(const SVGPaintStyle &paint_style) +{ + const glm::vec3& stroke_colour_values = paint_style.d_stroke.d_colour; + return glm::vec4(stroke_colour_values.x, stroke_colour_values.y, stroke_colour_values.z, paint_style.d_strokeOpacity); +} + +//----------------------------------------------------------------------------// +glm::mat4 SVGTesselator::createRenderableMatrixFromSVGMatrix(glm::mat3 svg_matrix) +{ + return glm::mat4(svg_matrix[0].x, svg_matrix[1].x, 0.0f, 0.0f, + svg_matrix[0].y, svg_matrix[1].y, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + svg_matrix[0].z, svg_matrix[1].z, 0.0f, 1.0f); +} + + +//----------------------------------------------------------------------------// +SVGTesselator::LineIntersectResult SVGTesselator::intersectLines(const glm::vec2& line1_start, const glm::vec2& line1_end, + const glm::vec2& line2_start, const glm::vec2& line2_end, + glm::vec2& intersection) +{ + float denom = ((line2_end.y - line2_start.y)*(line1_end.x - line1_start.x)) - + ((line2_end.x - line2_start.x)*(line1_end.y - line1_start.y)); + + float nume_a = ((line2_end.x - line2_start.x)*(line1_start.y - line2_start.y)) - + ((line2_end.y - line2_start.y)*(line1_start.x - line2_start.x)); + + float nume_b = ((line1_end.x - line1_start.x)*(line1_start.y - line2_start.y)) - + ((line1_end.y - line1_start.y)*(line1_start.x - line2_start.x)); + + if(denom == 0.0f) + { + if(nume_a == 0.0f && nume_b == 0.0f) + return LIR_COINCIDENT; + else + return LIR_PARALLEL; + } + + float ua = nume_a / denom; + float ub = nume_b / denom; + + if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) + { + //Get the intersection point + intersection.x = line1_start.x + ua*(line1_end.x - line1_start.x); + intersection.y = line1_start.y + ua*(line1_end.y - line1_start.y); + + return LIR_INTERESECTING; + } + + return LIR_NOT_INTERSECTING; +} + +//----------------------------------------------------------------------------// +bool SVGTesselator::isPolygonClockwise(const glm::vec2& point1, const glm::vec2& point2, const glm::vec2& point3) +{ + return ( (point2.x-point1.x)*(point3.y-point1.y) - (point3.x-point1.x)*(point2.y-point1.y) ) < 0.0f; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStroke(const std::vector& points, + GeometryBuffer& geometry_buffer, + const SVGPaintStyle& paint_style, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const bool is_shape_closed) +{ + if(points.size() < 2 || paint_style.d_stroke.d_none || paint_style.d_strokeWidth == 0.0f) + return; + + //We need this to determine the degree of tesselation required for the curved elements + float max_scale = std::max(render_settings.d_scaleFactor.x, render_settings.d_scaleFactor.y); + + // Create an object containing all the data we need for our segment processing + StrokeSegmentData stroke_data(geometry_buffer, paint_style.d_strokeWidth * 0.5f, paint_style, max_scale); + + // If doing anti-aliasing, get the anti-aliasing offsets + if(render_settings.d_antiAliasing) + determineAntiAliasingOffsets(stroke_data.d_paintStyle.d_strokeWidth, stroke_data.d_antiAliasingOffsets); + + const size_t points_count = points.size(); + size_t i = 0; + + // Handle the beginning of the stroke considering that the shape might be open and therefore needs linecaps + if(!is_shape_closed) + { + //Create the starting linecap + stroke_data.setPoints(points[0], points[0], points[1]); + createStrokeLinecap(stroke_data, render_settings, scale_factors, true); + + ++i; + } + else + { + //Get the first two stroke points without drawing anything + stroke_data.setPoints(points[points_count - 2], points[points_count - 1], points[0]); + createStrokeLinejoin(stroke_data, render_settings, scale_factors, false); + + if(!render_settings.d_antiAliasing) + setStrokeDataSubsequentPointsAsLastPoints(stroke_data); + else + setStrokeDataSubsequentPointsAsLastPointsAA(stroke_data); + + + //Add the segment connected via the first point + stroke_data.setPoints(points[points_count - 1], points[i], points[i + 1]); + createStrokeLinejoin(stroke_data, render_settings, scale_factors, true); + + if(!render_settings.d_antiAliasing) + { + createStrokeSegmentConnection(stroke_data); + setStrokeDataSubsequentPointsAsLastPoints(stroke_data); + } + else + { + createStrokeSegmentConnectionAA(stroke_data); + setStrokeDataSubsequentPointsAsLastPointsAA(stroke_data); + } + + ++i; + } + + // Handle segments between start and end of the stroke + for(; i < points_count - 1; ++i) + { + stroke_data.setPoints(points[i - 1], points[i], points[i + 1]); + createStrokeLinejoin(stroke_data, render_settings, scale_factors, true); + + if(!render_settings.d_antiAliasing) + { + createStrokeSegmentConnection(stroke_data); + setStrokeDataSubsequentPointsAsLastPoints(stroke_data); + } + else + { + createStrokeSegmentConnectionAA(stroke_data); + setStrokeDataSubsequentPointsAsLastPointsAA(stroke_data); + } + } + + // Handle the end of the stroke considering that the shape might be open and therefore needs linecaps + if(!is_shape_closed) + { + //Set out last points as current points so we do not override them with he linecap creation + if(!render_settings.d_antiAliasing) + setStrokeDataLastPointsAsCurrentPoints(stroke_data); + else + setStrokeDataLastPointsAsCurrentPointsAA(stroke_data); + + //Create linecap + stroke_data.setPoints(points[points_count - 2], points[points_count - 1], points[points_count - 1]); + createStrokeLinecap(stroke_data, render_settings, scale_factors, false); + + //Connect to the linecap + if(!render_settings.d_antiAliasing) + createStrokeSegmentConnection(stroke_data); + else + createStrokeSegmentConnectionAA(stroke_data); + } + else + { + //Add the segment connected via the last point + stroke_data.setPoints(points[points_count - 2], points[points_count - 1], points[0]); + createStrokeLinejoin(stroke_data, render_settings, scale_factors, true); + + if(!render_settings.d_antiAliasing) + createStrokeSegmentConnection(stroke_data); + else + createStrokeSegmentConnectionAA(stroke_data); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeLinejoin(StrokeSegmentData& stroke_data, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const bool draw) +{ + SVGPaintStyle::SVGLinejoin linejoin = stroke_data.d_paintStyle.d_strokeLinejoin; + const glm::vec2& prev_point = *stroke_data.d_prevPoint; + const glm::vec2& cur_point = *stroke_data.d_curPoint; + const glm::vec2& next_point = *stroke_data.d_nextPoint; + + // Check if our corner points form a clockwise or anticlockwise polygon + bool polygon_is_clockwise = isPolygonClockwise(prev_point, cur_point, next_point); + float direction_sign = polygon_is_clockwise ? 1.0f : -1.0f; + + glm::vec2 prev_to_cur( glm::normalize(cur_point - prev_point) ); + glm::vec2 prev_dir_to_inside ( direction_sign * glm::vec2(prev_to_cur.y, -prev_to_cur.x) ); + glm::vec2 prev_vec_to_inside = stroke_data.d_strokeHalfWidth * prev_dir_to_inside; + + glm::vec2 cur_to_next( glm::normalize(next_point - cur_point) ); + glm::vec2 next_dir_to_inside( direction_sign * glm::vec2(cur_to_next.y, -cur_to_next.x) ); + glm::vec2 next_vec_to_inside = stroke_data.d_strokeHalfWidth * next_dir_to_inside; + + // We calculate the intersection of the inner lines along the stroke + glm::vec2 inner_intersection; + intersectLines(prev_point + prev_vec_to_inside, cur_point + prev_vec_to_inside, + next_point + next_vec_to_inside, cur_point + next_vec_to_inside, + inner_intersection); + + // The outer connection point of the stroke + glm::vec2 outer_point; + // Reference to the end-points of our stroke segment + const glm::vec2& segment_end_left = polygon_is_clockwise ? outer_point : inner_intersection; + const glm::vec2& segment_end_right = polygon_is_clockwise ? inner_intersection : outer_point; + + //If the stroke miter is exceeded we fall back to bevel + if(linejoin == SVGPaintStyle::SLJ_MITER) + handleStrokeMiterExceedance(stroke_data, cur_point, inner_intersection, linejoin); + + //Switch through the types and render them if required + if(linejoin == SVGPaintStyle::SLJ_MITER) + { + //We calculate the connection point of the outer lines + outer_point = cur_point + cur_point - inner_intersection; + + if(!render_settings.d_antiAliasing) + { + setStrokeDataCurrentPoints(stroke_data, segment_end_left, segment_end_right); + setStrokeDataSubsequentPoints(stroke_data, segment_end_left, segment_end_right); + } + else + calculateAAMiterAndSetConnectionPoints(stroke_data, segment_end_left, segment_end_right, polygon_is_clockwise, + prev_to_cur, cur_to_next, prev_dir_to_inside, next_dir_to_inside, scale_factors); + } + else if(linejoin == SVGPaintStyle::SLJ_BEVEL || linejoin == SVGPaintStyle::SLJ_ROUND) + { + //Is the first bevel corner point + outer_point = cur_point - prev_vec_to_inside; + //The second bevel corner point + const glm::vec2 second_bevel_point = cur_point - next_vec_to_inside; + + if(!render_settings.d_antiAliasing) + createStrokeLinejoinBevelOrRound(stroke_data, cur_point, prev_dir_to_inside, next_dir_to_inside, segment_end_left, segment_end_right, + second_bevel_point, linejoin, polygon_is_clockwise, draw); + else + createStrokeLinejoinBevelOrRoundAA(stroke_data, render_settings, scale_factors, cur_point, second_bevel_point, + segment_end_left, segment_end_right, prev_to_cur, cur_to_next, + prev_dir_to_inside, next_dir_to_inside, linejoin, polygon_is_clockwise, draw); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::determineAntiAliasingOffsets(float width, glm::vec2& antialiasing_offsets) +{ + float remainder = width - static_cast(width); + + float& core_offset = antialiasing_offsets.x; + float& fade_offset = antialiasing_offsets.y; + + core_offset = -0.5f; + fade_offset = 0.5f; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeLinecap(StrokeSegmentData& stroke_data, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const bool is_start) +{ + const SVGPaintStyle::SVGLinecap& linecap = stroke_data.d_paintStyle.d_strokeLinecap; + const glm::vec2& point1 = is_start ? *stroke_data.d_curPoint : *stroke_data.d_prevPoint; + const glm::vec2& point2 = is_start ? *stroke_data.d_nextPoint : *stroke_data.d_curPoint; + + // Direction towards the linecap + glm::vec2 linecap_dir( glm::normalize(point2 - point1) ); + // Direction to the left side in linecap direction + glm::vec2 dir_to_outside( -linecap_dir.y, linecap_dir.x ); + glm::vec2 vec_to_outside = stroke_data.d_strokeHalfWidth * dir_to_outside; + //Turn around direction to the linecap if we are at the starting cap + if(is_start) + linecap_dir *= -1.0f; + + glm::vec2 linecap_left, linecap_right, linecap_left_fade, linecap_right_fade; + glm::vec2 linecap_center_point = *stroke_data.d_curPoint; + + //We offset the linecap points in case we want a squared cap + if(linecap == SVGPaintStyle::SLC_SQUARE) + linecap_center_point += stroke_data.d_strokeHalfWidth * linecap_dir; + + //We get the lincap points + linecap_left = linecap_center_point + vec_to_outside; + linecap_right = linecap_center_point - vec_to_outside; + glm::vec2 linecap_left_AA, linecap_right_AA; + + //We determine our linecap points for anti-aliasing if required. Also we call the draw commands for squared and butt linecaps. + if(render_settings.d_antiAliasing) + { + //We calculate the stretch factors in directions of our offsets and then offset the vertices + float length_side_scale = calculateLengthScale(dir_to_outside, scale_factors); + glm::vec2 lineside_offset_vec = length_side_scale * dir_to_outside; + + linecap_left_fade = linecap_left + stroke_data.d_antiAliasingOffsets.y * lineside_offset_vec; + linecap_right_fade = linecap_right + stroke_data.d_antiAliasingOffsets.y * -lineside_offset_vec; + linecap_left_AA = linecap_left + stroke_data.d_antiAliasingOffsets.x * lineside_offset_vec; + linecap_right_AA = linecap_right + stroke_data.d_antiAliasingOffsets.x * -lineside_offset_vec; + } + + if( linecap == SVGPaintStyle::SLC_BUTT || linecap == SVGPaintStyle::SLC_SQUARE ) + { + if(render_settings.d_antiAliasing) + { + float length_cap_scale = calculateLengthScale(linecap_dir, scale_factors); + glm::vec2 linecap_offset_vec = length_cap_scale * linecap_dir; + linecap_left_AA += stroke_data.d_antiAliasingOffsets.x * linecap_offset_vec; + linecap_right_AA += stroke_data.d_antiAliasingOffsets.x * linecap_offset_vec; + linecap_left_fade += stroke_data.d_antiAliasingOffsets.y * linecap_offset_vec; + linecap_right_fade += stroke_data.d_antiAliasingOffsets.y * linecap_offset_vec; + + //Create the outer AA quad of the butt or square linecap + addStrokeLinecapAAGeometryVertices(stroke_data, linecap_left_AA, linecap_right_AA, linecap_left_fade, linecap_right_fade); + //Add the anti-aliased connection points to the stroke data + setStrokeDataLastPointsAA(stroke_data, linecap_left_AA, linecap_right_AA, linecap_left_fade, linecap_right_fade); + } + else + //Add the connection points to the stroke data + setStrokeDataLastPoints(stroke_data, linecap_left, linecap_right); + } + + //In case we got rounded linecaps we want to determine our points first and draw then + if(linecap == SVGPaintStyle::SLC_ROUND) + { + static const float half_circle_angle = glm::pi(); + + //Get the parameters + float num_segments, tangential_factor, radial_factor; + calculateArcTesselationParameters(stroke_data.d_strokeHalfWidth, half_circle_angle, stroke_data.d_maxScale, + num_segments, tangential_factor, radial_factor); + + //Get the arc points + std::vector arc_points; + createArcPoints(linecap_center_point, linecap_left, linecap_right, num_segments, + is_start ? tangential_factor : -tangential_factor, radial_factor, arc_points); + + if(!render_settings.d_antiAliasing) + { + //Calculate the arc points + createArcStrokeGeometry(arc_points, stroke_data.d_geometryBuffer, stroke_data.d_strokeVertex); + + setStrokeDataLastPoints(stroke_data, linecap_left, linecap_right); + } + else + { + //Calculate the anti-aliased arc points + createArcStrokeAAGeometry(arc_points, linecap_center_point, linecap_center_point, stroke_data, scale_factors, + is_start, linecap_left_AA, linecap_right_AA, linecap_left_fade, linecap_right_fade); + + setStrokeDataLastPointsAA(stroke_data, linecap_left_AA, linecap_right_AA, + linecap_left_fade, linecap_right_fade); + } + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::calculateAAMiterAndSetConnectionPoints(StrokeSegmentData& stroke_data, + const glm::vec2& segment_end_left_orig, + const glm::vec2& segment_end_right_orig, + const bool polygon_is_clockwise, + const glm::vec2& prev_to_cur, + const glm::vec2& cur_to_next, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const glm::vec2& scale_factors) +{ + glm::vec2 vec_to_corner = calculateScaledCombinedVector(scale_factors, prev_to_cur, cur_to_next, + prev_dir_to_inside, next_dir_to_inside, polygon_is_clockwise); + + // Calculate the offset vectors from the original area + glm::vec2 core_offset_vec = stroke_data.d_antiAliasingOffsets.x * vec_to_corner; + glm::vec2 fade_offset_vec = stroke_data.d_antiAliasingOffsets.y * vec_to_corner; + // Calculate the segment positions + const glm::vec2 segmentFadeLeftEnd = segment_end_left_orig + fade_offset_vec; + const glm::vec2 segmentLeftEnd = segment_end_left_orig + core_offset_vec; + const glm::vec2 segmentRightEnd = segment_end_right_orig - core_offset_vec; + const glm::vec2 segmentFadeRightEnd = segment_end_right_orig - fade_offset_vec; + + // If we want to draw we have to combine the vertices + setStrokeDataCurrentPointsAA(stroke_data, segmentLeftEnd, segmentRightEnd, segmentFadeLeftEnd, segmentFadeRightEnd); + setStrokeDataSubsequentPointsAA(stroke_data, segmentLeftEnd, segmentRightEnd, segmentFadeLeftEnd, segmentFadeRightEnd); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createTriangleStripFillGeometry(const std::vector& points, + GeometryBuffer& geometry_buffer, + const SVGPaintStyle& paint_style) +{ + if(points.size() < 3 || paint_style.d_fill.d_none) + return; + + //Create the rectangle fill vertex + ColouredVertex fill_vertex(glm::vec3(), getFillColour(paint_style)); + + //Fixed triangle fan point + const glm::vec2& point1 = points[0]; + + const size_t maximum_index = points.size() - 1; + for(size_t i = 1; i < maximum_index; ++i) + addTriangleGeometry(point1, points[i], points[i + 1], geometry_buffer, fill_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createCircleFill(const std::vector& circle_points, + float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors) +{ + if(paint_style.d_fill.d_none) + return; + + //Append the geometry based on the the circle points + if(!render_settings.d_antiAliasing) + createTriangleStripFillGeometry(circle_points, geometry_buffer, paint_style); + else + { + //We calculate the anti-aliasing offsets based on an arbitrary width + glm::vec2 antiAliasingOffsets; + determineAntiAliasingOffsets(10.0f, antiAliasingOffsets); + + std::vector circle_modified_points; + std::vector circle_fade_points; + createCircleOrEllipseFillPointsAA(circle_points, antiAliasingOffsets, scale_factors, + circle_modified_points, circle_fade_points); + + createTriangleStripFillGeometry(circle_modified_points, geometry_buffer, paint_style); + createFillGeometryAAFadeOnly(circle_modified_points, circle_fade_points, paint_style, geometry_buffer, true); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createCircleStroke(const std::vector& circle_points, + float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors) +{ + if(paint_style.d_stroke.d_none || paint_style.d_strokeWidth == 0.0f) + return; + + StrokeSegmentData stroke_data(geometry_buffer, paint_style.d_strokeWidth * 0.5f, paint_style, max_scale); + + if(!render_settings.d_antiAliasing) + { + //Calculate stroke points + std::vector outer_circle_points; + std::vector inner_circle_points; + createCircleOrEllipseStrokePoints(circle_points, stroke_data, outer_circle_points, inner_circle_points); + + //Create the geometry from the points + createStrokeGeometry(outer_circle_points, inner_circle_points, stroke_data, true); + } + else + { + determineAntiAliasingOffsets(stroke_data.d_paintStyle.d_strokeWidth, stroke_data.d_antiAliasingOffsets); + + //Calculate stroke points + std::vector outer_circle_points; + std::vector outer_circle_points_fade; + std::vector inner_circle_points; + std::vector inner_circle_points_fade; + createCircleOrEllipseStrokePointsAA(circle_points, stroke_data, scale_factors, outer_circle_points, + outer_circle_points_fade, inner_circle_points, inner_circle_points_fade); + + //Create the geometry from the points + createStrokeGeometryAA(outer_circle_points, outer_circle_points_fade, inner_circle_points, inner_circle_points_fade, + stroke_data, true); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createCirclePoints(const float radius, + const float num_segments, + const float cos_value, + const float sin_value, + std::vector& circle_points) +{ + //Create the circle points + //We start at angle = 0 + glm::vec2 current_pos(radius, 0.0f); + for(int i = 0; i < num_segments; i++) + { + //Rotate + float temp_value = current_pos.x; + current_pos.x = cos_value * current_pos.x - sin_value * current_pos.y; + current_pos.y = sin_value * temp_value + cos_value * current_pos.y; + + circle_points.push_back(current_pos); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::calculateCircleTesselationParameters(const float radius, + const float max_scale, + float& num_segments, + float& cos_value, + float& sin_value) +{ + //Adapt the tesselation to the scale + float segment_length = CircleRoundnessValue / max_scale; + float theta = std::acos( 1.0f - ( segment_length / radius ) ); + + static const float two_pi = 2.0f * glm::pi(); + //Calculate the number of segments using 360° as angle and using theta + num_segments = two_pi / theta; + + //Precalculate values we will need for our circle tesselation + cos_value = std::cos(theta); + sin_value = std::sin(theta); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createArcStrokeGeometry(std::vector& points, + GeometryBuffer& geometry_buffer, + ColouredVertex& stroke_vertex) +{ + //Fixed triangle fan point + const glm::vec2& point1 = points[0]; + + const size_t maximum_index = points.size() - 1; + for(size_t i = 1; i < maximum_index; ++i) + addTriangleGeometry(point1, points[i], points[i + 1], geometry_buffer, stroke_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createArcStrokeAAGeometry(const std::vector& points, + const glm::vec2& arc_center_point, + const glm::vec2& arc_draw_origin_point, + StrokeSegmentData& stroke_data, + const glm::vec2& scale_factors, + const bool polygon_is_clockwise, + glm::vec2& linecap_left_AA, + glm::vec2& linecap_right_AA, + glm::vec2& linecap_left_fade, + glm::vec2& linecap_right_fade) +{ + if(points.empty()) + return; + + glm::vec2 previous_normal_point, previous_fade_point; + + //Draw all arc parts + const size_t index_limit = points.size(); + for(size_t i = 0; i < index_limit; ++i) + { + bool is_first = (i == 0); + bool is_last = (i == index_limit-1); + + //Calculate the scale vector for our offset + glm::vec2 vec_to_outside = glm::normalize(points[i] - arc_center_point); + float lengthScale = calculateLengthScale(vec_to_outside, scale_factors); + vec_to_outside *= lengthScale; + + // Calculate the positions + glm::vec2 current_normal_point = points[i] + vec_to_outside * stroke_data.d_antiAliasingOffsets.x; + glm::vec2 current_fade_point = points[i] + vec_to_outside * stroke_data.d_antiAliasingOffsets.y; + + + //Once we determined the first AA points we need to set the references to them + if(is_first) + { + linecap_left_AA = current_normal_point; + linecap_left_fade = current_fade_point; + } + else + { + addStrokeQuadAA(current_normal_point, previous_normal_point, current_fade_point, previous_fade_point, + stroke_data.d_geometryBuffer, stroke_data.d_strokeVertex, stroke_data.d_strokeFadeVertex); + + addTriangleGeometry(current_normal_point, previous_normal_point, arc_draw_origin_point, + stroke_data.d_geometryBuffer, stroke_data.d_strokeVertex); + } + + if(is_last) + { + linecap_right_AA = current_normal_point; + linecap_right_fade = current_fade_point; + } + + previous_normal_point = current_normal_point; + previous_fade_point = current_fade_point; + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::calculateArcTesselationParameters(const float radius, + const float arc_angle, + const float max_scale, + float& num_segments, + float& tangential_factor, + float& radial_factor) +{ + //Adapt the tesselation to the scale + float segment_length = CircleRoundnessValue / max_scale; + float theta = std::acos( 1.0f - ( segment_length / radius ) ); + + //Calculate the number of segments from the arc angle and theta + num_segments = arc_angle / theta; + + //Precalculate values we will need for our arc tesselation + tangential_factor = std::tan(theta); + radial_factor = std::cos(theta); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createArcPoints(const glm::vec2& center_point, + const glm::vec2& start_point, + const glm::vec2& end_point, + const float num_segments, + const float tangential_factor, + const float radial_factor, + std::vector& arc_points) +{ + //Add the start points of the arc to our list and set the current position to be the + arc_points.push_back(start_point); + // arc's start point in object coordinates + glm::vec2 current_pos( start_point - center_point ); + + //Calculate the arc points, skip last segment because that will be our endpoint + for(int i = 0; i < num_segments - 1.0f; ++i) + { + glm::vec2 temp( -current_pos.y, current_pos.x ); + + current_pos += temp * tangential_factor; + current_pos *= radial_factor; + + arc_points.push_back( center_point + current_pos ); + } + + //Add the end point of the arc to our list + arc_points.push_back(end_point); +} + + +//----------------------------------------------------------------------------// +void SVGTesselator::createEllipseFill(const std::vector& ellipse_points, + const float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors) +{ + if(paint_style.d_fill.d_none) + return; + + //Append the geometry based on the the ellipse points + if(!render_settings.d_antiAliasing) + createTriangleStripFillGeometry(ellipse_points, geometry_buffer, paint_style); + else + { + //We calculate the anti-aliasing offsets based on an arbitrary width + glm::vec2 antiAliasingOffsets; + determineAntiAliasingOffsets(10.0f, antiAliasingOffsets); + + std::vector ellipse_modified_points; + std::vector ellipse_fade_points; + createCircleOrEllipseFillPointsAA(ellipse_points, antiAliasingOffsets, scale_factors, + ellipse_modified_points, ellipse_fade_points); + + createTriangleStripFillGeometry(ellipse_modified_points, geometry_buffer, paint_style); + createFillGeometryAAFadeOnly(ellipse_modified_points, ellipse_fade_points, paint_style, geometry_buffer, true); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createEllipseStroke(const std::vector& ellipse_points, + const float max_scale, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors) +{ + if(paint_style.d_stroke.d_none || paint_style.d_strokeWidth == 0.0f) + return; + + StrokeSegmentData stroke_data(geometry_buffer, paint_style.d_strokeWidth * 0.5f, paint_style, max_scale); + + if(!render_settings.d_antiAliasing) + { + //Calculate stroke points + std::vector outer_ellipse_points; + std::vector inner_ellipse_points; + createCircleOrEllipseStrokePoints(ellipse_points, stroke_data, outer_ellipse_points, inner_ellipse_points); + + //Create the geometry from the points + createStrokeGeometry(outer_ellipse_points, inner_ellipse_points, stroke_data, true); + } + else + { + determineAntiAliasingOffsets(stroke_data.d_paintStyle.d_strokeWidth, stroke_data.d_antiAliasingOffsets); + + //Calculate stroke points + std::vector outer_ellipse_points; + std::vector outer_ellipse_points_fade; + std::vector inner_ellipse_points; + std::vector inner_ellipse_points_fade; + createCircleOrEllipseStrokePointsAA(ellipse_points, stroke_data, scale_factors, outer_ellipse_points, + outer_ellipse_points_fade, inner_ellipse_points, inner_ellipse_points_fade); + + //Create the geometry from the points + createStrokeGeometryAA(outer_ellipse_points, outer_ellipse_points_fade, inner_ellipse_points, inner_ellipse_points_fade, + stroke_data, true); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::scaleEllipsePoints(std::vector& circle_points, + const bool isRadiusXBigger, + const float radiusRatio) +{ + const size_t circlePointsCount = circle_points.size(); + if(isRadiusXBigger) + { + for(size_t i = 0; i < circlePointsCount; ++i) + circle_points[i].y *= radiusRatio; + } + else + { + for(size_t i = 0; i < circlePointsCount; ++i) + circle_points[i].x *= radiusRatio; + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::handleStrokeMiterExceedance(const StrokeSegmentData& stroke_data, + const glm::vec2& cur_point, + const glm::vec2& inner_intersection, + SVGPaintStyle::SVGLinejoin& linejoin) +{ + //If the miter length we exceeds the limit we will use a regular bevel instead + const float& miterlimit = stroke_data.d_paintStyle.d_strokeMiterlimit; + + float half_miter_extension = glm::length(cur_point - inner_intersection); + if(half_miter_extension > (miterlimit * stroke_data.d_strokeHalfWidth)) + linejoin = SVGPaintStyle::SLJ_BEVEL; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeLinejoinBevelOrRound(StrokeSegmentData &stroke_data, + const glm::vec2& cur_point, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const glm::vec2& segment_end_left, + const glm::vec2& segment_end_right, + const glm::vec2& second_bevel_point, + const SVGPaintStyle::SVGLinejoin linejoin, + const bool polygon_is_clockwise, + const bool draw) +{ + if(draw) + { + setStrokeDataCurrentPoints(stroke_data, segment_end_left, segment_end_right); + + if(linejoin == SVGPaintStyle::SLJ_BEVEL) + { + //Simply add a triangle for the bevel + addTriangleGeometry(segment_end_left, segment_end_right, second_bevel_point, stroke_data.d_geometryBuffer, stroke_data.d_strokeVertex); + } + else if(linejoin == SVGPaintStyle::SLJ_ROUND) + { + //Determine the linejoin angle + float arc_angle = std::acos( glm::dot(prev_dir_to_inside, next_dir_to_inside) ); + + //Get the parameters + float num_segments, tangential_factor, radial_factor; + calculateArcTesselationParameters(stroke_data.d_strokeHalfWidth, arc_angle, stroke_data.d_maxScale, + num_segments, tangential_factor, radial_factor); + + //Get the arc points and add them to the geometrybuffer + std::vector arc_points; + arc_points.push_back(polygon_is_clockwise ? segment_end_right : segment_end_left); + + createArcPoints(cur_point, polygon_is_clockwise ? second_bevel_point : segment_end_right, + polygon_is_clockwise ? segment_end_left : second_bevel_point, num_segments, + tangential_factor, radial_factor, arc_points); + + createArcStrokeGeometry(arc_points, stroke_data.d_geometryBuffer, stroke_data.d_strokeVertex); + } + } + + setStrokeDataSubsequentPoints(stroke_data, polygon_is_clockwise ? second_bevel_point : segment_end_left, polygon_is_clockwise ? segment_end_right : second_bevel_point); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeLinejoinBevelOrRoundAA(StrokeSegmentData &stroke_data, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors, + const glm::vec2& cur_point, + const glm::vec2& second_bevel_point, + const glm::vec2& segment_end_left, + const glm::vec2& segment_end_right, + const glm::vec2& prev_to_cur, + const glm::vec2& cur_to_next, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const SVGPaintStyle::SVGLinejoin linejoin, + const bool polygon_is_clockwise, + const bool draw) +{ + ColouredVertex& stroke_vertex = stroke_data.d_strokeVertex; + ColouredVertex& stroke_fade_vertex = stroke_data.d_strokeFadeVertex; + GeometryBuffer& geometry_buffer = stroke_data.d_geometryBuffer; + + const glm::vec2& inner_point = polygon_is_clockwise ? segment_end_right : segment_end_left; + const glm::vec2& outer_point = polygon_is_clockwise ? segment_end_left : segment_end_right; + + // Get the scaled vector for the inner AA points + glm::vec2 inner_scaled_vec = calculateScaledCombinedVector(scale_factors, prev_to_cur, cur_to_next, + prev_dir_to_inside, next_dir_to_inside, false); + // Calculate the offset vectors for the inner points from the original point + glm::vec2 core_offset_vec_inner = stroke_data.d_antiAliasingOffsets.x * inner_scaled_vec; + glm::vec2 fade_offset_vec_inner = stroke_data.d_antiAliasingOffsets.y * inner_scaled_vec; + // Calculate the inner positions of our bevel + const glm::vec2 inner_AA = inner_point + core_offset_vec_inner; + const glm::vec2 inner_fade_AA = inner_point + fade_offset_vec_inner; + + // Get the dir to the edge between the two outer corner points and its orthogonal direction + glm::vec2 edge_dir; + if (!(second_bevel_point == outer_point)) + edge_dir = glm::normalize(second_bevel_point - outer_point); + else //TODO Ident: Check if this is a sufficient workaround + edge_dir = prev_to_cur; + glm::vec2 edge_perpendicular_dir( polygon_is_clockwise ? edge_dir.y : -edge_dir.y, + polygon_is_clockwise ? -edge_dir.x : edge_dir.x); + + // Get the scaled-widths of the perpendicular directions of the edges + float length_scale1 = calculateLengthScale(prev_dir_to_inside, scale_factors); + float length_scale2 = calculateLengthScale(edge_perpendicular_dir, scale_factors); + float length_scale3 = calculateLengthScale(next_dir_to_inside, scale_factors); + + // Calculate scale-distorted direction + glm::vec2 fadecorner_vec1 = prev_to_cur * length_scale2 - edge_dir * length_scale1; + glm::vec2 fadecorner_vec2 = edge_dir * length_scale3 - cur_to_next * length_scale2; + + //We do not need to normalize at this point, as our result after the dot product division gives us the same result in either case + //Apply dot product scales + fadecorner_vec1 /= glm::dot(-prev_dir_to_inside, fadecorner_vec1); + fadecorner_vec2 /= glm::dot(-edge_perpendicular_dir, fadecorner_vec2); + //Apply length factors + fadecorner_vec1 *= length_scale1; + fadecorner_vec2 *= length_scale2; + + // Calculate the segment positions + glm::vec2 outer_AA = outer_point + stroke_data.d_antiAliasingOffsets.x * fadecorner_vec1; + glm::vec2 outer_fade_AA = outer_point + stroke_data.d_antiAliasingOffsets.y * fadecorner_vec1; + glm::vec2 outer2_AA = second_bevel_point + stroke_data.d_antiAliasingOffsets.x * fadecorner_vec2; + glm::vec2 outer2_fade_AA = second_bevel_point + stroke_data.d_antiAliasingOffsets.y * fadecorner_vec2; + + //The lines to the points can overlap in case the vectors point to different directions, which happens in extreme scale cases. + // Normally the 2 points can be merged into 1 point here, so we need to consider this case + bool could_vectors_overlap = !isVectorLeftOfOtherVector(polygon_is_clockwise ? fadecorner_vec1 : fadecorner_vec2, + polygon_is_clockwise ? fadecorner_vec2 : fadecorner_vec1); + bool are_lines_overlapping = false; + glm::vec2 intersection_point; + if(could_vectors_overlap) + are_lines_overlapping = ( intersectLines(outer_point, outer_fade_AA, second_bevel_point, outer2_fade_AA, intersection_point) == LIR_INTERESECTING ); + + + if(are_lines_overlapping) + { + //In case of an overlap we fall back to just using single vertex, similar to the miter linejoin + glm::vec2 outer_point_miter = cur_point + cur_point - inner_point; + + // Calculate the corrected outer positions + const glm::vec2 outer_AA_corrected = outer_point_miter - core_offset_vec_inner; + const glm::vec2 outer_AA_fade_corrected = outer_point_miter - fade_offset_vec_inner; + + // Set the connection + if(polygon_is_clockwise) + { + setStrokeDataCurrentPointsAA(stroke_data, outer_AA_corrected, inner_AA, + outer_AA_fade_corrected, inner_fade_AA); + setStrokeDataSubsequentPointsAA(stroke_data, outer_AA_corrected, inner_AA, + outer_AA_fade_corrected, inner_fade_AA); + } + else + { + setStrokeDataCurrentPointsAA(stroke_data, inner_AA, outer_AA_corrected, + inner_fade_AA, outer_AA_fade_corrected); + setStrokeDataSubsequentPointsAA(stroke_data, inner_AA, outer_AA_corrected, + inner_fade_AA, outer_AA_fade_corrected); + } + } + else + { + if(draw && linejoin == SVGPaintStyle::SLJ_BEVEL) + { + //Add the geometry for bevel + addTriangleGeometry(outer2_AA, inner_AA, outer_AA, + geometry_buffer, stroke_vertex); + + addStrokeQuadAA(outer_AA, outer2_AA, outer_fade_AA, outer2_fade_AA, + geometry_buffer, stroke_vertex, stroke_fade_vertex); + } + else if(draw && linejoin == SVGPaintStyle::SLJ_ROUND) + { + //Add the geometry for rounded linejoin + float arc_angle = std::acos( glm::dot(prev_dir_to_inside, next_dir_to_inside) ); + + //Get the parameters + float num_segments, tangential_factor, radial_factor; + calculateArcTesselationParameters(stroke_data.d_strokeHalfWidth, arc_angle, stroke_data.d_maxScale, + num_segments, tangential_factor, radial_factor); + + //Get the arc points + std::vector arc_points; + createArcPoints(cur_point, outer_point, second_bevel_point, num_segments, + polygon_is_clockwise ? -tangential_factor : tangential_factor, radial_factor, arc_points); + + createArcStrokeAAGeometry(arc_points, cur_point, inner_AA, stroke_data, scale_factors, + !polygon_is_clockwise, outer_AA, outer2_AA, outer_fade_AA, outer2_fade_AA); + } + + + // We add the geometry of the segment that connects to the last linecap/linejoin + if(polygon_is_clockwise) + { + setStrokeDataCurrentPointsAA(stroke_data, outer_AA, inner_AA, outer_fade_AA, inner_fade_AA); + setStrokeDataSubsequentPointsAA(stroke_data, outer2_AA, inner_AA, outer2_fade_AA, inner_fade_AA); + } + else + { + setStrokeDataCurrentPointsAA(stroke_data, inner_AA, outer_AA, inner_fade_AA, outer_fade_AA); + setStrokeDataSubsequentPointsAA(stroke_data, inner_AA, outer2_AA, inner_fade_AA, outer2_fade_AA); + } + } +} + +//----------------------------------------------------------------------------// +glm::vec2 SVGTesselator::determineScaleFactors(const glm::mat3& transformation, const SVGImage::SVGImageRenderSettings& render_settings) +{ + glm::vec2 scale ( glm::length(glm::vec3(transformation[0].x, transformation[1].x, transformation[2].x)), + glm::length(glm::vec3(transformation[0].y, transformation[1].y, transformation[2].y)) ); + + scale *= glm::vec2( render_settings.d_scaleFactor.x, render_settings.d_scaleFactor.y ); + scale = 1.0f / scale; + + return scale; +} + +//----------------------------------------------------------------------------// +float SVGTesselator::calculateLengthScale(const glm::vec2 &direction, const glm::vec2& scale_factors) +{ + static const float half_pi = glm::half_pi(); + static const float one_over_pi_half = 1.0f / half_pi; + + float angle_to_x_axis = std::acos( std::abs(direction.x) ); + float angle_to_y_axis = half_pi - angle_to_x_axis; + return one_over_pi_half * (scale_factors.x * angle_to_y_axis + scale_factors.y * angle_to_x_axis); +} + +//----------------------------------------------------------------------------// +glm::vec2 SVGTesselator::calculateScaledCombinedVector(const glm::vec2& scale_factors, + const glm::vec2& prev_to_cur, + const glm::vec2& cur_to_next, + const glm::vec2& prev_dir_to_inside, + const glm::vec2& next_dir_to_inside, + const bool polygon_is_clockwise) +{ + bool almost_parallel = glm::dot(prev_dir_to_inside, next_dir_to_inside)/ ( glm::length(prev_dir_to_inside) * glm::length(next_dir_to_inside) ) > 0.9999f; + + if(!almost_parallel) + { + // Get the scaled-widths of the incoming and outgoing line segments + float length_scale1 = calculateLengthScale(prev_dir_to_inside, scale_factors); + float length_scale2 = calculateLengthScale(next_dir_to_inside, scale_factors); + + glm::vec2 vec_to_outer_corner = glm::normalize(prev_to_cur * length_scale2 - cur_to_next * length_scale1); + + // Calculate scale-distorted direction + // glm::vec2 vec_to_corner = glm::normalize(prev_to_cur * length_scale2 - cur_to_next * length_scale1); + + // Calculate how much we need to offset along the direction depending on the angle + /* We get the distance to our new corner using a factor. The factor would, in case we didn't prepare for non-uniform scaling, just consist + of a simple vector projection. However, here we also need to multiply the local stroke width's scale factor (in the direction of the stroke) + to get currect results. We have two alternative calculations available for this with the same results. + Alternative version: length_scale2 / glm::dot( (polygon_is_clockwise ? -next_dir_to_inside : next_dir_to_inside) , vec_to_corner ); + */ + float length_to_corner = length_scale1 / glm::dot( (polygon_is_clockwise ? -prev_dir_to_inside : prev_dir_to_inside) , vec_to_outer_corner ); + + return vec_to_outer_corner * length_to_corner; + } + //TODO Ident: Check if this fix is valid in all cases + else + { + //If we are near-parallel we need to calculate the corner vector differently + float length_scale1 = calculateLengthScale(prev_dir_to_inside, scale_factors); + + glm::vec2 vec_to_outer_corner = 0.5f * ( next_dir_to_inside + prev_dir_to_inside ); + + float length_to_corner = length_scale1 / glm::dot( (polygon_is_clockwise ? -prev_dir_to_inside : prev_dir_to_inside) , vec_to_outer_corner ); + + + return vec_to_outer_corner * length_to_corner; + } +} + +//----------------------------------------------------------------------------// +bool SVGTesselator::isVectorLeftOfOtherVector(const glm::vec2& vector, + const glm::vec2& vector_other) +{ + float dot_result = (vector.x * -vector_other.y) + (vector.y * vector_other.x); + return dot_result > 0.0f; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataLastPoints(StrokeSegmentData &stroke_data, + const glm::vec2& last_point_left, + const glm::vec2& last_point_right) +{ + //We set our lastPoint values + stroke_data.d_lastPointLeft = last_point_left; + stroke_data.d_lastPointRight = last_point_right; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataLastPointsAA(StrokeSegmentData &stroke_data, + const glm::vec2& last_point_left, + const glm::vec2& last_point_right, + const glm::vec2& last_point_left_fade, + const glm::vec2& last_point_right_fade) +{ + // We set our lastPoint values + stroke_data.d_lastPointLeft = last_point_left; + stroke_data.d_lastPointRight = last_point_right; + stroke_data.d_lastFadePointLeft = last_point_left_fade; + stroke_data.d_lastFadePointRight = last_point_right_fade; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataCurrentPoints(StrokeSegmentData &stroke_data, + const glm::vec2& current_point_left, + const glm::vec2& current_point_right) +{ + //We set our currentPoint values + stroke_data.d_currentPointLeft = current_point_left; + stroke_data.d_currentPointRight = current_point_right; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataCurrentPointsAA(StrokeSegmentData &stroke_data, + const glm::vec2& current_point_left, + const glm::vec2& current_point_right, + const glm::vec2& current_point_left_fade, + const glm::vec2& current_point_right_fade) +{ + // We set our currentPoint values + stroke_data.d_currentPointLeft = current_point_left; + stroke_data.d_currentPointRight = current_point_right; + stroke_data.d_currentFadePointLeft = current_point_left_fade; + stroke_data.d_currentFadePointRight = current_point_right_fade; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataSubsequentPoints(StrokeSegmentData &stroke_data, + const glm::vec2& subsequent_point_left, + const glm::vec2& subsequent_point_right) +{ + //We set our subsequentPoint values + stroke_data.d_subsequentPointLeft = subsequent_point_left; + stroke_data.d_subsequentPointRight = subsequent_point_right; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataSubsequentPointsAA(StrokeSegmentData &stroke_data, + const glm::vec2& subsequent_point_left, + const glm::vec2& subsequent_point_right, + const glm::vec2& subsequent_point_left_fade, + const glm::vec2& subsequent_point_right_fade) +{ + // We set our subsequentPoint values + stroke_data.d_subsequentPointLeft = subsequent_point_left; + stroke_data.d_subsequentPointRight = subsequent_point_right; + stroke_data.d_subsequentFadePointLeft = subsequent_point_left_fade; + stroke_data.d_subsequentFadePointRight = subsequent_point_right_fade; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataSubsequentPointsAsLastPoints(StrokeSegmentData &stroke_data) +{ + stroke_data.d_lastPointLeft = stroke_data.d_subsequentPointLeft; + stroke_data.d_lastPointRight = stroke_data.d_subsequentPointRight; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataSubsequentPointsAsLastPointsAA(StrokeSegmentData &stroke_data) +{ + stroke_data.d_lastPointLeft = stroke_data.d_subsequentPointLeft; + stroke_data.d_lastPointRight = stroke_data.d_subsequentPointRight; + stroke_data.d_lastFadePointLeft = stroke_data.d_subsequentFadePointLeft; + stroke_data.d_lastFadePointRight = stroke_data.d_subsequentFadePointRight; +} + + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataLastPointsAsCurrentPoints(StrokeSegmentData &stroke_data) +{ + stroke_data.d_currentPointLeft = stroke_data.d_lastPointLeft; + stroke_data.d_currentPointRight = stroke_data.d_lastPointRight; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setStrokeDataLastPointsAsCurrentPointsAA(StrokeSegmentData &stroke_data) +{ + stroke_data.d_currentPointLeft = stroke_data.d_lastPointLeft; + stroke_data.d_currentPointRight = stroke_data.d_lastPointRight; + stroke_data.d_currentFadePointLeft = stroke_data.d_lastFadePointLeft; + stroke_data.d_currentFadePointRight = stroke_data.d_lastFadePointRight; +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createFill(const std::vector& points, + GeometryBuffer& geometry_buffer, + const SVGPaintStyle& paint_style, + const SVGImage::SVGImageRenderSettings& render_settings, + const glm::vec2& scale_factors) +{ + if(points.size() < 3 || paint_style.d_fill.d_none) + return; + + //Create the rectangle fill vertex + ColouredVertex fill_vertex(glm::vec3(), getFillColour(paint_style)); + + //Switches the stencil mode on + geometry_buffer.setStencilRenderingActive(paint_style.d_fillRule); + + addTriangleFanGeometry(points, geometry_buffer, fill_vertex); + //Set the vertex count to the quad's vertex count + geometry_buffer.setStencilPostRenderingVertexCount(6); + + //Calculate the axis-aligned bounding box for the vertices that we will use to create a minimally sized quad + glm::vec2 min, max; + calculateMinMax(points, min, max); + + //Add the quad + addFillQuad(min, glm::vec2(min.x, max.y), glm::vec2(max.x, min.y), max, + geometry_buffer, fill_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::calculateMinMax(const std::vector& points, + glm::vec2& min, + glm::vec2& max) +{ + if(points.empty()) + return; + + min = points[0]; + max = points[0]; + + const size_t points_count = points.size(); + for(size_t i = 1; i < points_count; ++i) + { + min = glm::min(points[i], min); + max = glm::max(points[i], max); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createEllipsePoints(const float radiusX, + const float radiusY, + const float max_scale, + std::vector& ellipse_points) +{ + bool isRadiusXBigger; + float biggerRadius, radiusRatio; + if(radiusX >= radiusY) + { + biggerRadius = radiusX; + isRadiusXBigger = true; + radiusRatio = radiusY / radiusX; + } + else + { + biggerRadius = radiusY; + isRadiusXBigger = false; + radiusRatio = radiusX / radiusY; + } + + //Precalculate values needed for the circle tesselation + float num_segments, cos_value, sin_value; + calculateCircleTesselationParameters(biggerRadius, max_scale, num_segments, cos_value, sin_value); + + //Create the circle points + createCirclePoints(biggerRadius, num_segments, cos_value, sin_value, ellipse_points); + + //Scale the circle so we get an ellipse + scaleEllipsePoints(ellipse_points, isRadiusXBigger, radiusRatio); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createCircleOrEllipseStrokePoints(const std::vector& points, + StrokeSegmentData& stroke_data, + std::vector& outer_points, + std::vector& inner_points) +{ + const size_t points_count = points.size(); + for(size_t i = 0; i < points_count; ++i) + { + size_t index1 = (i == points_count - 1) ? 0 : (i + 1); + size_t index2 = (i == 0) ? (points_count - 1) : (i - 1); + + glm::vec2 direction = glm::normalize(points[index1] - points[index2]); + direction = glm::vec2(direction.y, -direction.x); + + outer_points.push_back( points[i] + direction * stroke_data.d_strokeHalfWidth ); + inner_points.push_back( points[i] - direction * stroke_data.d_strokeHalfWidth ); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createCircleOrEllipseStrokePointsAA(const std::vector& points, + StrokeSegmentData& stroke_data, + const glm::vec2& scale_factors, + std::vector& outer_points, + std::vector& outer_points_fade, + std::vector& inner_points, + std::vector& inner_points_fade) +{ + const size_t points_count = points.size(); + for(size_t i = 0; i < points_count; ++i) + { + size_t index1 = (i == points_count - 1) ? 0 : (i + 1); + size_t index2 = (i == 0) ? (points_count - 1) : (i - 1); + + glm::vec2 direction = glm::normalize(points[index1] - points[index2]); + direction = glm::vec2(direction.y, -direction.x); + + float length_scale = calculateLengthScale(direction, scale_factors); + glm::vec2 scaled_dir_vec = direction * length_scale; + glm::vec2 stroke_offset_vec = direction * stroke_data.d_strokeHalfWidth; + + outer_points.push_back( points[i] + stroke_offset_vec + scaled_dir_vec * stroke_data.d_antiAliasingOffsets.x); + outer_points_fade.push_back( points[i] + stroke_offset_vec + scaled_dir_vec * stroke_data.d_antiAliasingOffsets.y); + inner_points.push_back( points[i] - stroke_offset_vec - scaled_dir_vec * stroke_data.d_antiAliasingOffsets.x); + inner_points_fade.push_back( points[i] - stroke_offset_vec - scaled_dir_vec * stroke_data.d_antiAliasingOffsets.y); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createRectangleFill(const SVGPaintStyle& paint_style, std::vector& rectangle_points, GeometryBuffer& geometry_buffer) +{ + if(paint_style.d_fill.d_none) + return; + + //Get colours + const glm::vec4 fill_colour = getFillColour(paint_style); + + //Create the rectangle fill vertex + ColouredVertex rectFillVertex(glm::vec3(), fill_colour); + //Apply z-depth + rectFillVertex.d_position.z = 0.0f; + + //Add the rectangle fill vertices + rectFillVertex.d_position.x = rectangle_points[0].x; + rectFillVertex.d_position.y = rectangle_points[0].y; + geometry_buffer.appendVertex(rectFillVertex); + + rectFillVertex.d_position.x = rectangle_points[1].x; + rectFillVertex.d_position.y = rectangle_points[1].y; + geometry_buffer.appendVertex(rectFillVertex); + + rectFillVertex.d_position.x = rectangle_points[2].x; + rectFillVertex.d_position.y = rectangle_points[2].y; + geometry_buffer.appendVertex(rectFillVertex); + + rectFillVertex.d_position.x = rectangle_points[2].x; + rectFillVertex.d_position.y = rectangle_points[2].y; + geometry_buffer.appendVertex(rectFillVertex); + + rectFillVertex.d_position.x = rectangle_points[0].x; + rectFillVertex.d_position.y = rectangle_points[0].y; + geometry_buffer.appendVertex(rectFillVertex); + + rectFillVertex.d_position.x = rectangle_points[3].x; + rectFillVertex.d_position.y = rectangle_points[3].y; + geometry_buffer.appendVertex(rectFillVertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeSegmentConnection(StrokeSegmentData& stroke_data) +{ + // Add the geometry + ColouredVertex& stroke_vertex = stroke_data.d_strokeVertex; + GeometryBuffer& geometry_buffer = stroke_data.d_geometryBuffer; + + stroke_vertex.d_position.x = stroke_data.d_currentPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_currentPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_currentPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); +} + + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeSegmentConnectionAA(StrokeSegmentData &stroke_data) +{ + ColouredVertex& stroke_vertex = stroke_data.d_strokeVertex; + ColouredVertex& stroke_fade_vertex = stroke_data.d_strokeFadeVertex; + GeometryBuffer& geometry_buffer = stroke_data.d_geometryBuffer; + + //Fade1 + stroke_fade_vertex.d_position.x = stroke_data.d_currentFadePointLeft.x; + stroke_fade_vertex.d_position.y = stroke_data.d_currentFadePointLeft.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_fade_vertex.d_position.x = stroke_data.d_lastFadePointLeft.x; + stroke_fade_vertex.d_position.y = stroke_data.d_lastFadePointLeft.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_vertex.d_position.x = stroke_data.d_currentPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_currentPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_fade_vertex.d_position.x = stroke_data.d_lastFadePointLeft.x; + stroke_fade_vertex.d_position.y = stroke_data.d_lastFadePointLeft.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + + //Core + stroke_vertex.d_position.x = stroke_data.d_currentPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_currentPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_currentPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointLeft.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointLeft.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + + //Fade1 + stroke_vertex.d_position.x = stroke_data.d_currentPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_currentPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_fade_vertex.d_position.x = stroke_data.d_currentFadePointRight.x; + stroke_fade_vertex.d_position.y = stroke_data.d_currentFadePointRight.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_fade_vertex.d_position.x = stroke_data.d_currentFadePointRight.x; + stroke_fade_vertex.d_position.y = stroke_data.d_currentFadePointRight.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_vertex.d_position.x = stroke_data.d_lastPointRight.x; + stroke_vertex.d_position.y = stroke_data.d_lastPointRight.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_fade_vertex.d_position.x = stroke_data.d_lastFadePointRight.x; + stroke_fade_vertex.d_position.y = stroke_data.d_lastFadePointRight.y; + geometry_buffer.appendVertex(stroke_fade_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::addStrokeLinecapAAGeometryVertices(StrokeSegmentData &stroke_data, + const glm::vec2& linecap_left, const glm::vec2& linecap_right, + const glm::vec2& linecap_fade_left, const glm::vec2& linecap_fade_right) +{ + ColouredVertex& stroke_vertex = stroke_data.d_strokeVertex; + ColouredVertex& stroke_fade_vertex = stroke_data.d_strokeFadeVertex; + GeometryBuffer& geometry_buffer = stroke_data.d_geometryBuffer; + + stroke_fade_vertex.d_position.x = linecap_fade_left.x; + stroke_fade_vertex.d_position.y = linecap_fade_left.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + stroke_fade_vertex.d_position.x = linecap_fade_right.x; + stroke_fade_vertex.d_position.y = linecap_fade_right.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + stroke_vertex.d_position.x = linecap_left.x; + stroke_vertex.d_position.y = linecap_left.y; + geometry_buffer.appendVertex(stroke_vertex); + stroke_vertex.d_position.x = linecap_left.x; + stroke_vertex.d_position.y = linecap_left.y; + geometry_buffer.appendVertex(stroke_vertex); + stroke_fade_vertex.d_position.x = linecap_fade_right.x; + stroke_fade_vertex.d_position.y = linecap_fade_right.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + stroke_vertex.d_position.x = linecap_right.x; + stroke_vertex.d_position.y = linecap_right.y; + geometry_buffer.appendVertex(stroke_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::addTriangleGeometry(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3, + GeometryBuffer &geometry_buffer, + ColouredVertex &vertex) +{ + vertex.d_position.x = point1.x; + vertex.d_position.y = point1.y; + geometry_buffer.appendVertex(vertex); + + vertex.d_position.x = point2.x; + vertex.d_position.y = point2.y; + geometry_buffer.appendVertex(vertex); + + vertex.d_position.x = point3.x; + vertex.d_position.y = point3.y; + geometry_buffer.appendVertex(vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeGeometry(const std::vector& outer_points, + const std::vector& inner_points, + StrokeSegmentData &stroke_data, + const bool is_surface_closed) +{ + ColouredVertex& stroke_vertex = stroke_data.d_strokeVertex; + GeometryBuffer& geometry_buffer = stroke_data.d_geometryBuffer; + + size_t circle_points_count = outer_points.size(); + for(size_t i = 0; i < circle_points_count - 1; ++i) + addStrokeQuad(outer_points[i], outer_points[i + 1], inner_points[i], inner_points[i + 1], + geometry_buffer, stroke_vertex); + + if(is_surface_closed) + addStrokeQuad(outer_points[circle_points_count - 1], outer_points[0], inner_points[circle_points_count - 1], inner_points[0], + geometry_buffer, stroke_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createStrokeGeometryAA(const std::vector& outer_points, + const std::vector& outer_points_fade, + const std::vector& inner_points, + const std::vector& inner_points_fade, + StrokeSegmentData &stroke_data, + const bool is_surface_closed) +{ + ColouredVertex& stroke_vertex = stroke_data.d_strokeVertex; + ColouredVertex& stroke_fade_vertex = stroke_data.d_strokeFadeVertex; + GeometryBuffer& geometry_buffer = stroke_data.d_geometryBuffer; + + size_t points_count = outer_points.size(); + for(size_t i = 0; i < points_count - 1; ++i) + { + addStrokeQuadAA(outer_points[i], outer_points[i + 1], outer_points_fade[i], outer_points_fade[i + 1], + geometry_buffer, stroke_vertex, stroke_fade_vertex); + addStrokeQuad(outer_points[i], outer_points[i + 1], inner_points[i], inner_points[i + 1], + geometry_buffer, stroke_vertex); + addStrokeQuadAA(inner_points[i], inner_points[i + 1], inner_points_fade[i], inner_points_fade[i + 1], + geometry_buffer, stroke_vertex, stroke_fade_vertex); + } + + if(is_surface_closed) + { + addStrokeQuadAA(outer_points[points_count - 1], outer_points[0], outer_points_fade[points_count - 1], outer_points_fade[0], + geometry_buffer, stroke_vertex, stroke_fade_vertex); + addStrokeQuad(outer_points[points_count - 1], outer_points[0], inner_points[points_count - 1], inner_points[0], + geometry_buffer, stroke_vertex); + addStrokeQuadAA(inner_points[points_count - 1], inner_points[0], inner_points_fade[points_count - 1], inner_points_fade[0], + geometry_buffer, stroke_vertex, stroke_fade_vertex); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createFillGeometryAAFadeOnly(const std::vector& points, + const std::vector& points_fade, + const SVGPaintStyle& paint_style, + GeometryBuffer& geometry_buffer, + const bool is_surface_closed) +{ + // Get and add the fill colour + ColouredVertex fill_vertex; + fill_vertex.d_colour = SVGTesselator::getFillColour(paint_style); + // Set the z coordinate + fill_vertex.d_position.z = 0.0f; + //Create the fade fill vertex from the fill vertex and set its alpha to 0 + ColouredVertex fill_fade_vertex = fill_vertex; + fill_fade_vertex.d_colour.w = 0.0f; + + size_t points_count = points.size(); + for(size_t i = 0; i < points_count - 1; ++i) + addStrokeQuadAA(points[i], points[i + 1], points_fade[i], points_fade[i + 1], + geometry_buffer, fill_vertex, fill_fade_vertex); + + if(is_surface_closed) + addStrokeQuadAA(points[points_count - 1], points[0], points_fade[points_count - 1], points_fade[0], + geometry_buffer, fill_vertex, fill_fade_vertex); +} + + +//----------------------------------------------------------------------------// +void SVGTesselator::addFillQuad(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3, + const glm::vec2& point4, + GeometryBuffer& geometry_buffer, + ColouredVertex& fill_vertex) +{ + fill_vertex.d_position.x = point1.x; + fill_vertex.d_position.y = point1.y; + geometry_buffer.appendVertex(fill_vertex); + + fill_vertex.d_position.x = point2.x; + fill_vertex.d_position.y = point2.y; + geometry_buffer.appendVertex(fill_vertex); + + fill_vertex.d_position.x = point3.x; + fill_vertex.d_position.y = point3.y; + geometry_buffer.appendVertex(fill_vertex); + + fill_vertex.d_position.x = point3.x; + fill_vertex.d_position.y = point3.y; + geometry_buffer.appendVertex(fill_vertex); + + fill_vertex.d_position.x = point2.x; + fill_vertex.d_position.y = point2.y; + geometry_buffer.appendVertex(fill_vertex); + + fill_vertex.d_position.x = point4.x; + fill_vertex.d_position.y = point4.y; + geometry_buffer.appendVertex(fill_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::addStrokeQuad(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& point3, + const glm::vec2& point4, + GeometryBuffer& geometry_buffer, + ColouredVertex& stroke_vertex) +{ + stroke_vertex.d_position.x = point1.x; + stroke_vertex.d_position.y = point1.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = point2.x; + stroke_vertex.d_position.y = point2.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = point3.x; + stroke_vertex.d_position.y = point3.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = point3.x; + stroke_vertex.d_position.y = point3.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = point2.x; + stroke_vertex.d_position.y = point2.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = point4.x; + stroke_vertex.d_position.y = point4.y; + geometry_buffer.appendVertex(stroke_vertex); +} + + +//----------------------------------------------------------------------------// +void SVGTesselator::addStrokeQuadAA(const glm::vec2& point1, + const glm::vec2& point2, + const glm::vec2& fade_point1, + const glm::vec2& fade_point2, + GeometryBuffer& geometry_buffer, + ColouredVertex& stroke_vertex, + ColouredVertex& stroke_fade_vertex) +{ + stroke_fade_vertex.d_position.x = fade_point1.x; + stroke_fade_vertex.d_position.y = fade_point1.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_fade_vertex.d_position.x = fade_point2.x; + stroke_fade_vertex.d_position.y = fade_point2.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_vertex.d_position.x = point1.x; + stroke_vertex.d_position.y = point1.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_vertex.d_position.x = point1.x; + stroke_vertex.d_position.y = point1.y; + geometry_buffer.appendVertex(stroke_vertex); + + stroke_fade_vertex.d_position.x = fade_point2.x; + stroke_fade_vertex.d_position.y = fade_point2.y; + geometry_buffer.appendVertex(stroke_fade_vertex); + + stroke_vertex.d_position.x = point2.x; + stroke_vertex.d_position.y = point2.y; + geometry_buffer.appendVertex(stroke_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::createCircleOrEllipseFillPointsAA(const std::vector &points, + const glm::vec2 &anti_aliasing_offsets, + const glm::vec2 &scale_factors, + std::vector &modified_points, + std::vector &fade_points) +{ + const size_t points_count = points.size(); + for(size_t i = 0; i < points_count; ++i) + { + size_t index1 = (i == points_count - 1) ? 0 : (i + 1); + size_t index2 = (i == 0) ? (points_count - 1) : (i - 1); + + glm::vec2 direction = glm::normalize(points[index1] - points[index2]); + direction = glm::vec2(direction.y, -direction.x); + + float length_scale = calculateLengthScale(direction, scale_factors); + direction *= length_scale; + + modified_points.push_back( points[i] + direction * anti_aliasing_offsets.x ); + fade_points.push_back( points[i] + direction * anti_aliasing_offsets.y ); + } +} + +//----------------------------------------------------------------------------// +void SVGTesselator::addTriangleFanGeometry(const std::vector &points, + GeometryBuffer& geometry_buffer, + ColouredVertex& coloured_vertex) +{ + //Fixed triangle fan point + const glm::vec2& point1 = points[0]; + + const size_t maximum_index = points.size() - 1; + for(size_t i = 1; i < maximum_index; ++i) + addTriangleGeometry(point1, points[i], points[i + 1], geometry_buffer, coloured_vertex); +} + +//----------------------------------------------------------------------------// +void SVGTesselator::setupGeometryBufferSettings(CEGUI::GeometryBuffer* geometry_buffer, + const SVGImage::SVGImageRenderSettings &render_settings, + const glm::mat4& cegui_transformation_matrix) +{ + if(render_settings.d_clipArea) + { + geometry_buffer->setClippingActive(true); + geometry_buffer->setClippingRegion(*render_settings.d_clipArea); + } + else + geometry_buffer->setClippingActive(false); + + geometry_buffer->setScale(glm::vec2(render_settings.d_scaleFactor.x, render_settings.d_scaleFactor.y)); + geometry_buffer->setCustomTransform(cegui_transformation_matrix); + geometry_buffer->setAlpha(render_settings.d_alpha); +} + +//----------------------------------------------------------------------------// +} + diff --git a/cegui/src/views/GenericItemModel.cpp b/cegui/src/views/GenericItemModel.cpp new file mode 100644 index 000000000..dcb8a10b1 --- /dev/null +++ b/cegui/src/views/GenericItemModel.cpp @@ -0,0 +1,99 @@ +/*********************************************************************** + created: Sat Aug 09 2014 + author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/views/GenericItemModel.h" +#include "CEGUI/Exceptions.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +GenericItem::GenericItem() : d_text(""), d_parent(0) +{ +} + +//----------------------------------------------------------------------------// +GenericItem::GenericItem(const String& text) : d_text(text), d_parent(0) +{ +} + +//----------------------------------------------------------------------------// +GenericItem::GenericItem(const String& text, const String& icon) : +d_text(text), d_icon(icon), d_parent(0) +{ +} + +//----------------------------------------------------------------------------// +GenericItem::~GenericItem() +{ + while (!d_children.empty()) + { + GenericItem* item = d_children.back(); + d_children.pop_back(); + delete item; + } +} + +//----------------------------------------------------------------------------// +bool GenericItem::operator==(const GenericItem& other) const +{ + if (d_text != other.d_text) + return false; + + if (d_icon != other.d_icon) + return false; + + if (d_children.size() != other.d_children.size()) return false; + + for (size_t i = 0; i < d_children.size(); ++i) + { + if (d_children.at(i) != other.d_children.at(i)) + return false; + } + + return true; +} + +//----------------------------------------------------------------------------// +bool GenericItem::operator!=(const GenericItem& other) const +{ + return !(*this == other); +} + +//----------------------------------------------------------------------------// +bool GenericItem::operator<(const GenericItem& other) const +{ + return d_text < other.d_text; +} + +//----------------------------------------------------------------------------// +void GenericItem::addItem(GenericItem* child) +{ + d_children.push_back(child); + child->setParent(this); +} + +} diff --git a/cegui/src/views/ItemModel.cpp b/cegui/src/views/ItemModel.cpp new file mode 100644 index 000000000..ebf531f38 --- /dev/null +++ b/cegui/src/views/ItemModel.cpp @@ -0,0 +1,114 @@ +/*********************************************************************** + created: Wed May 21 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/views/ItemModel.h" + +#include + +namespace CEGUI +{ +//----------------------------------------------------------------------------// +const String ItemModel::EventChildrenWillBeAdded("ChildrenWillBeAdded"); +const String ItemModel::EventChildrenAdded("ChildrenAdded"); +const String ItemModel::EventChildrenWillBeRemoved("ChildrenWillBeRemoved"); +const String ItemModel::EventChildrenRemoved("ChildrenRemoved"); +const String ItemModel::EventChildrenDataWillChange; +const String ItemModel::EventChildrenDataChanged("ChildrenDataChanged"); + +//----------------------------------------------------------------------------// +std::ostream& operator<< (std::ostream& os, const ModelIndex& arg) +{ + return os << "CEGUI::ModelIndex(" << arg.d_modelData << ")"; +} + +//----------------------------------------------------------------------------// +ModelEventArgs::ModelEventArgs(ItemModel* item_model, ModelIndex parent_index, size_t start_id, size_t count /*= 1*/) : + d_itemModel(item_model), + d_parentIndex(parent_index), + d_startId(start_id), + d_count(count) +{ +} + +//----------------------------------------------------------------------------// +ModelIndex::ModelIndex(void* model_data /*= 0*/) : + d_modelData(model_data) +{ +} + +//----------------------------------------------------------------------------// +ItemModel::~ItemModel() +{ +} + +//----------------------------------------------------------------------------// +void ItemModel::notifyChildrenWillBeAdded(ModelIndex parent_index, size_t start_id, size_t count) +{ + ModelEventArgs args(this, parent_index, start_id, count); + fireEvent(EventChildrenWillBeAdded, args); +} + +//----------------------------------------------------------------------------// +void ItemModel::notifyChildrenAdded(ModelIndex parent_index, size_t start_id, size_t count) +{ + ModelEventArgs args(this, parent_index, start_id, count); + fireEvent(EventChildrenAdded, args); +} + +//----------------------------------------------------------------------------// +void ItemModel::notifyChildrenWillBeRemoved(ModelIndex parent_index, size_t start_id, size_t count) +{ + ModelEventArgs args(this, parent_index, start_id, count); + fireEvent(EventChildrenWillBeRemoved, args); +} + +//----------------------------------------------------------------------------// +void ItemModel::notifyChildrenRemoved(ModelIndex parent_index, size_t start_id, size_t count) +{ + ModelEventArgs args(this, parent_index, start_id, count); + fireEvent(EventChildrenRemoved, args); +} + +//----------------------------------------------------------------------------// +void ItemModel::notifyChildrenDataWillChange(ModelIndex parent_index, size_t start_id, size_t count) +{ + ModelEventArgs args(this, parent_index, start_id, count); + fireEvent(EventChildrenDataWillChange, args); +} + +//----------------------------------------------------------------------------// +void ItemModel::notifyChildrenDataChanged(ModelIndex parent_index, size_t start_id, size_t count) +{ + ModelEventArgs args(this, parent_index, start_id, count); + fireEvent(EventChildrenDataChanged, args); +} + +//----------------------------------------------------------------------------// +bool ItemModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const +{ + return compareIndices(index1, index2) == 0; +} +} diff --git a/cegui/src/views/ItemView.cpp b/cegui/src/views/ItemView.cpp new file mode 100644 index 000000000..82248bf1a --- /dev/null +++ b/cegui/src/views/ItemView.cpp @@ -0,0 +1,1018 @@ +/*********************************************************************** + created: Sat May 24 2014 + author: Timotei Dolean + + purpose: Implementation of the base class for all item model-based views. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include "CEGUI/ImageManager.h" +#include "CEGUI/views/ItemView.h" +#include "CEGUI/widgets/Tooltip.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +ItemViewWindowRenderer::ItemViewWindowRenderer(const String& name) : + WindowRenderer(name, "ItemView") +{ +} + +//----------------------------------------------------------------------------// +ItemView* ItemViewWindowRenderer::getView() const +{ + return static_cast(d_window); +} + +//----------------------------------------------------------------------------// +const String& PropertyHelper::getDataTypeName() +{ + static String type("ScrollbarDisplayMode"); + + return type; +} + +//----------------------------------------------------------------------------// +PropertyHelper::return_type +PropertyHelper::fromString(const String& str) +{ + if (str == "Shown") return SDM_Shown; + if (str == "Hidden") return SDM_Hidden; + + // default + return SDM_WhenNeeded; +} + +//----------------------------------------------------------------------------// +PropertyHelper::string_return_type +PropertyHelper::toString(pass_type val) +{ + switch(val) + { + case SDM_Shown: return "Shown"; + case SDM_Hidden: return "Hidden"; + case SDM_WhenNeeded: return "WhenNeeded"; + default: return "InvalidDisplayMode"; + } +} + +//----------------------------------------------------------------------------// +const String& PropertyHelper::getDataTypeName() +{ + static String type("ViewSortMode"); + + return type; +} + +//----------------------------------------------------------------------------// +PropertyHelper::return_type +PropertyHelper::fromString(const String& str) +{ + if (str == "Ascending") return VSM_Ascending; + if (str == "Descending") return VSM_Descending; + + // default + return VSM_None; +} + +//----------------------------------------------------------------------------// +PropertyHelper::string_return_type +PropertyHelper::toString(pass_type val) +{ + switch (val) + { + case VSM_Ascending: return "Ascending"; + case VSM_Descending: return "Descending"; + default: return "None"; + } +} + +//----------------------------------------------------------------------------// +const Colour ItemView::DefaultTextColour = 0xFFFFFFFF; +const Colour ItemView::DefaultSelectionColour = Colour(0xFF4444AA); +const String ItemView::HorzScrollbarName("__auto_hscrollbar__"); +const String ItemView::VertScrollbarName("__auto_vscrollbar__"); +const String ItemView::EventVertScrollbarDisplayModeChanged("VertScrollbarDisplayModeChanged"); +const String ItemView::EventHorzScrollbarDisplayModeChanged("HorzScrollbarDisplayModeChanged"); +const String ItemView::EventSelectionChanged("SelectionChanged"); +const String ItemView::EventMultiselectModeChanged("MultiselectModeChanged"); +const String ItemView::EventSortModeChanged("SortModeChanged"); +const String ItemView::EventViewContentsChanged("ViewContentsChanged"); + +//----------------------------------------------------------------------------// +ItemView::ItemView(const String& type, const String& name) : + Window(type, name), + d_itemModel(0), + d_textColourRect(ColourRect(DefaultTextColour)), + d_selectionColourRect(ColourRect(DefaultSelectionColour)), + d_isDirty(true), + d_needsFullRender(true), + d_lastSelectedIndex(0), + d_selectionBrush(0), + d_vertScrollbarDisplayMode(SDM_WhenNeeded), + d_horzScrollbarDisplayMode(SDM_WhenNeeded), + d_isItemTooltipsEnabled(false), + d_isMultiSelectEnabled(false), + d_sortMode(VSM_None), + d_isAutoResizeHeightEnabled(false), + d_isAutoResizeWidthEnabled(false), + d_renderedMaxWidth(0), + d_renderedTotalHeight(0), + d_eventChildrenAddedConnection(0), + d_eventChildrenRemovedConnection(0) +{ + addItemViewProperties(); +} + +//----------------------------------------------------------------------------// +ItemView::~ItemView() +{ + disconnectModelEvents(); +} + +//----------------------------------------------------------------------------// +void ItemView::addItemViewProperties() +{ + const String& propertyOrigin = "ItemView"; + + CEGUI_DEFINE_PROPERTY(ItemView, Image*, + "SelectionBrushImage", + "Property to get/set the selection brush image for the item view. " + "Value should be \"set:[imageset name] image:[image name]\".", + &ItemView::setSelectionBrushImage, &ItemView::getSelectionBrushImage, 0 + ) + + CEGUI_DEFINE_PROPERTY(ItemView, ScrollbarDisplayMode, + "VertScrollbarDisplayMode", + "Property to get/set the display mode of the vertical scroll bar of the " + "item view. Value can be \"Shown\", \"Hidden\" or \"WhenNeeded\".", + &ItemView::setVertScrollbarDisplayMode, + &ItemView::getVertScrollbarDisplayMode, SDM_WhenNeeded + ) + + CEGUI_DEFINE_PROPERTY(ItemView, ScrollbarDisplayMode, + "HorzScrollbarDisplayMode", + "Property to get/set the display mode of the horizontal scroll bar of " + "the item view. Value can be \"Shown\", \"Hidden\" or \"WhenNeeded\".", + &ItemView::setHorzScrollbarDisplayMode, + &ItemView::getHorzScrollbarDisplayMode, SDM_WhenNeeded + ) + + CEGUI_DEFINE_PROPERTY(ItemView, bool, + "ItemTooltips", + "Property to access the show item tooltips setting of the item view. " + "Value is either \"True\" or \"False\".", + &ItemView::setItemTooltipsEnabled, &ItemView::isItemTooltipsEnabled, false + ) + + CEGUI_DEFINE_PROPERTY(ItemView, bool, + "MultiSelect", + "Property to get/set the multi-select setting of the item view. " + "Value is either \"True\" or \"False\".", + &ItemView::setMultiSelectEnabled, &ItemView::isMultiSelectEnabled, false + ) + + CEGUI_DEFINE_PROPERTY(ItemView, ViewSortMode, + "SortMode", + "Property to get/set how the item view is sorting its items. " + "Value is either \"None\", \"Ascending\" or \"Descending\".", + &ItemView::setSortMode, &ItemView::getSortMode, VSM_None + ) + + + CEGUI_DEFINE_PROPERTY(ItemView, bool, + "AutoSizeHeight", + "Property to get/set whether the item view will vertically auto-size " + "itself to fit its content. Value is either \"true\" or \"false\".", + &ItemView::setAutoResizeHeightEnabled, + &ItemView::isAutoResizeHeightEnabled, false + ) + + CEGUI_DEFINE_PROPERTY(ItemView, bool, + "AutoSizeWidth", + "Property to get/set whether the item view will vertically auto-size " + "itself to fit its content. Value is either \"true\" or \"false\".", + &ItemView::setAutoResizeWidthEnabled, + &ItemView::isAutoResizeWidthEnabled, false + ) +} + +//----------------------------------------------------------------------------// +void ItemView::initialiseComponents(void) +{ + getVertScrollbar()->subscribeEvent(Scrollbar::EventScrollPositionChanged, + Event::Subscriber(&ItemView::onScrollPositionChanged, this)); + getHorzScrollbar()->subscribeEvent(Scrollbar::EventScrollPositionChanged, + Event::Subscriber(&ItemView::onScrollPositionChanged, this)); + + performChildWindowLayout(); +} + +//----------------------------------------------------------------------------// +void ItemView::setModel(ItemModel* item_model) +{ + if (item_model == d_itemModel) + return; + + if (d_itemModel != 0) + { + disconnectModelEvents(); + d_lastSelectedIndex = ModelIndex(0); + } + + d_itemModel = item_model; + + connectToModelEvents(d_itemModel); + d_indexSelectionStates.clear(); + d_needsFullRender = true; + + ItemViewEventArgs args(this); + onSelectionChanged(args); +} + +//----------------------------------------------------------------------------// +void ItemView::connectToModelEvents(ItemModel* d_itemModel) +{ + if (d_itemModel == 0) + return; + + d_eventChildrenWillBeAddedConnection = d_itemModel->subscribeEvent( + ItemModel::EventChildrenWillBeAdded, + &ItemView::onChildrenWillBeAdded, this); + d_eventChildrenAddedConnection = d_itemModel->subscribeEvent( + ItemModel::EventChildrenAdded, + &ItemView::onChildrenAdded, this); + + d_eventChildrenWillBeRemovedConnection = d_itemModel->subscribeEvent( + ItemModel::EventChildrenWillBeRemoved, + &ItemView::onChildrenWillBeRemoved, this); + d_eventChildrenRemovedConnection = d_itemModel->subscribeEvent( + ItemModel::EventChildrenRemoved, + &ItemView::onChildrenRemoved, this); + + d_eventChildrenDataWillChangeConnection = d_itemModel->subscribeEvent( + ItemModel::EventChildrenDataWillChange, + &ItemView::onChildrenDataWillChange, this); + d_eventChildrenDataChangedConnection = d_itemModel->subscribeEvent( + ItemModel::EventChildrenDataChanged, + &ItemView::onChildrenDataChanged, this); +} + +//----------------------------------------------------------------------------// +bool ItemView::onChildrenWillBeAdded(const EventArgs& args) +{ + return true; +} + +//----------------------------------------------------------------------------// +bool ItemView::onChildrenAdded(const EventArgs& args) +{ + const ModelEventArgs& model_args = static_cast(args); + + for (SelectionStatesVector::iterator itor = d_indexSelectionStates.begin(); + itor != d_indexSelectionStates.end(); ++itor) + { + ModelIndexSelectionState& state = *itor; + + if (state.d_childId >= model_args.d_startId && + d_itemModel->areIndicesEqual(state.d_parentIndex, model_args.d_parentIndex)) + { + state.d_childId += model_args.d_count; + state.d_selectedIndex = d_itemModel->makeIndex(state.d_childId, state.d_parentIndex); + } + } + + invalidateView(false); + WindowEventArgs evt_args(this); + onViewContentsChanged(evt_args); + return true; +} + +//----------------------------------------------------------------------------// +bool ItemView::onChildrenWillBeRemoved(const EventArgs& args) +{ + if (d_itemModel == 0) + return false; + + const ModelEventArgs& model_args = static_cast(args); + + SelectionStatesVector::iterator itor = d_indexSelectionStates.begin(); + while (itor != d_indexSelectionStates.end()) + { + ModelIndexSelectionState& state = *itor; + + if (state.d_childId >= model_args.d_startId && + state.d_childId <= model_args.d_startId + model_args.d_count) + { + if (d_itemModel->areIndicesEqual(d_lastSelectedIndex, state.d_selectedIndex)) + d_lastSelectedIndex = ModelIndex(0); + + itor = d_indexSelectionStates.erase(itor); + } + else + { + ++itor; + } + } + + return true; +} + +//----------------------------------------------------------------------------// +bool ItemView::onChildrenRemoved(const EventArgs& args) +{ + + ItemViewEventArgs wargs(this); + onSelectionChanged(wargs); + + WindowEventArgs evt_args(this); + onViewContentsChanged(evt_args); + return true; +} + +//----------------------------------------------------------------------------// +bool ItemView::onChildrenDataWillChange(const EventArgs& args) +{ + return true; +} + +//----------------------------------------------------------------------------// +bool ItemView::onChildrenDataChanged(const EventArgs& args) +{ + invalidateView(false); + return true; +} + +//----------------------------------------------------------------------------// +void ItemView::onSelectionChanged(ItemViewEventArgs& args) +{ + invalidateView(false); + fireEvent(EventSelectionChanged, args); +} + +//----------------------------------------------------------------------------// +bool ItemView::onScrollPositionChanged(const EventArgs& args) +{ + invalidateView(false); + return true; +} + +//----------------------------------------------------------------------------// +void ItemView::onCursorPressHold(CursorInputEventArgs& e) +{ + if (e.source != CIS_Left) + return; + + handleSelection(e.position, true, false, false); + + ++e.handled; + Window::onCursorPressHold(e); +} + +//----------------------------------------------------------------------------// +void ItemView::onCursorMove(CursorInputEventArgs& e) +{ + if (d_isItemTooltipsEnabled) + setupTooltip(e.position); + + ++e.handled; + Window::onCursorMove(e); +} + +static void disconnectIfNotNull(Event::Connection& connection) +{ + if (connection != 0) + connection->disconnect(); +} + +//----------------------------------------------------------------------------// +void ItemView::disconnectModelEvents() +{ + disconnectIfNotNull(d_eventChildrenWillBeAddedConnection); + disconnectIfNotNull(d_eventChildrenAddedConnection); + disconnectIfNotNull(d_eventChildrenWillBeRemovedConnection); + disconnectIfNotNull(d_eventChildrenRemovedConnection); + disconnectIfNotNull(d_eventChildrenDataWillChangeConnection); + disconnectIfNotNull(d_eventChildrenDataChangedConnection); +} + +//----------------------------------------------------------------------------// +void ItemView::invalidateView(bool recursive) +{ + //TODO: allow invalidation only of certain parts (e.g.: items/indices) + updateScrollbars(); + resizeToContent(); + setIsDirty(true); + invalidate(recursive); +} + +//----------------------------------------------------------------------------// +ItemModel* ItemView::getModel() const +{ + return d_itemModel; +} + +//----------------------------------------------------------------------------// +void ItemView::prepareForRender() +{ +} + +//----------------------------------------------------------------------------// +const ColourRect& ItemView::getTextColourRect() const +{ + return d_textColourRect; +} + +//----------------------------------------------------------------------------// +void ItemView::setTextColourRect(const ColourRect& colour_rect) +{ + d_textColourRect = colour_rect; +} + +//----------------------------------------------------------------------------// +void ItemView::setTextColour(Colour colour) +{ + ColourRect rect(colour); + setTextColourRect(rect); +} + +//----------------------------------------------------------------------------// +const ColourRect& ItemView::getSelectionColourRect() const +{ + return d_selectionColourRect; +} + +//----------------------------------------------------------------------------// +void ItemView::setSelectionColourRect(const ColourRect& colour_rect) +{ + d_selectionColourRect = colour_rect; +} + +//----------------------------------------------------------------------------// +const std::vector& ItemView::getIndexSelectionStates() const +{ + return d_indexSelectionStates; +} + +//----------------------------------------------------------------------------// +bool ItemView::isDirty() const +{ + return d_isDirty; +} + +//----------------------------------------------------------------------------// +void ItemView::setIsDirty(bool value) +{ + d_isDirty = value; +} + +//----------------------------------------------------------------------------// +int ItemView::getSelectedIndexPosition(const ModelIndex& index) const +{ + if (d_itemModel == 0) + return false; + + for (size_t i = 0; i < d_indexSelectionStates.size(); ++i) + { + if (d_itemModel->areIndicesEqual(index, d_indexSelectionStates.at(i).d_selectedIndex)) + return i; + } + + return -1; +} + +//----------------------------------------------------------------------------// +bool ItemView::isIndexSelected(const ModelIndex& index) const +{ + return getSelectedIndexPosition(index) != -1; +} + +//----------------------------------------------------------------------------// +bool ItemView::setSelectedIndex(const ModelIndex& index) +{ + // simple calls of this method shouldn't do cumulative selection + return handleSelection(index, true, false, false); +} + +//----------------------------------------------------------------------------// +bool ItemView::setIndexSelectionState(const ModelIndex& index, bool selected) +{ + return handleSelection(index, selected, d_isMultiSelectEnabled, false); +} + +//----------------------------------------------------------------------------// +void ItemView::setSelectionBrushImage(const String& name) +{ + setSelectionBrushImage(&ImageManager::getSingleton().get(name)); +} + +//----------------------------------------------------------------------------// +void ItemView::setSelectionBrushImage(const Image* image) +{ + d_selectionBrush = image; + invalidateView(false); +} + +//----------------------------------------------------------------------------// +const Image* ItemView::getSelectionBrushImage(void) const +{ + return d_selectionBrush; +} + +//----------------------------------------------------------------------------// +Scrollbar* ItemView::getVertScrollbar() const +{ + return static_cast(getChild(VertScrollbarName)); +} + +//----------------------------------------------------------------------------// +Scrollbar* ItemView::getHorzScrollbar() const +{ + return static_cast(getChild(HorzScrollbarName)); +} + +//----------------------------------------------------------------------------// +void ItemView::updateScrollbars() +{ + Rectf render_area = getViewRenderer()->getViewRenderArea(); + + updateScrollbar(getVertScrollbar(), render_area.getHeight(), + d_renderedTotalHeight, d_vertScrollbarDisplayMode); + updateScrollbar(getHorzScrollbar(), render_area.getWidth(), + d_renderedMaxWidth, d_horzScrollbarDisplayMode); +} + +//----------------------------------------------------------------------------// +void ItemView::updateScrollbar(Scrollbar* scrollbar, float available_area, + float rendered_area, ScrollbarDisplayMode display_mode) +{ + scrollbar->setDocumentSize(rendered_area); + scrollbar->setPageSize(available_area); + scrollbar->setStepSize(ceguimax(1.0f, rendered_area / 10.0f)); + scrollbar->setScrollPosition(scrollbar->getScrollPosition()); + + if (display_mode == SDM_Hidden) + { + scrollbar->hide(); + return; + } + + if (display_mode == SDM_Shown || + rendered_area > available_area) + { + scrollbar->show(); + return; + } + + scrollbar->hide(); +} + +//----------------------------------------------------------------------------// +void ItemView::setVertScrollbarDisplayMode(ScrollbarDisplayMode mode) +{ + updateScrollbarDisplayMode(d_vertScrollbarDisplayMode, mode, + EventVertScrollbarDisplayModeChanged); +} + +//----------------------------------------------------------------------------// +ScrollbarDisplayMode ItemView::getVertScrollbarDisplayMode() const +{ + return d_vertScrollbarDisplayMode; +} + +//----------------------------------------------------------------------------// +void ItemView::setHorzScrollbarDisplayMode(ScrollbarDisplayMode mode) +{ + updateScrollbarDisplayMode(d_horzScrollbarDisplayMode, mode, + EventHorzScrollbarDisplayModeChanged); +} + +//----------------------------------------------------------------------------// +ScrollbarDisplayMode ItemView::getHorzScrollbarDisplayMode() const +{ + return d_horzScrollbarDisplayMode; +} + +//----------------------------------------------------------------------------// +ItemViewWindowRenderer* ItemView::getViewRenderer() +{ + if (d_windowRenderer == 0) + { + CEGUI_THROW(InvalidRequestException( + "The view should have a window renderer attached!")); + } + + return static_cast(d_windowRenderer); +} + +//----------------------------------------------------------------------------// +void ItemView::updateScrollbarDisplayMode(ScrollbarDisplayMode& target_mode, + ScrollbarDisplayMode new_mode, String change_event) +{ + if (target_mode == new_mode) + return; + + target_mode = new_mode; + + updateScrollbars(); + invalidateView(false); + WindowEventArgs args(this); + fireEvent(change_event, args); +} + +//----------------------------------------------------------------------------// +void ItemView::onScroll(CursorInputEventArgs& e) +{ + handleOnScroll(getVertScrollbar(), e.scroll); + + ++e.handled; + Window::onScroll(e); +} + +//----------------------------------------------------------------------------// +void ItemView::handleOnScroll(Scrollbar* scrollbar, float scroll) +{ + if (scrollbar->isEffectiveVisible() && + scrollbar->getDocumentSize() > scrollbar->getPageSize()) + { + scrollbar->setScrollPosition( + scrollbar->getScrollPosition() + scrollbar->getStepSize() * -scroll); + } +} + +//----------------------------------------------------------------------------// +bool ItemView::isItemTooltipsEnabled() const +{ + return d_isItemTooltipsEnabled; +} + +//----------------------------------------------------------------------------// +void ItemView::setItemTooltipsEnabled(bool enabled) +{ + d_isItemTooltipsEnabled = enabled; +} + +//----------------------------------------------------------------------------// +void ItemView::setupTooltip(glm::vec2 position) +{ + if (d_itemModel == 0) + return; + + static ModelIndex last_model_index; + + ModelIndex index = indexAt(position); + if (d_itemModel->areIndicesEqual(index, last_model_index)) + return; + + Tooltip* tooltip = getTooltip(); + if (tooltip == 0) + return; + + if (tooltip->getTargetWindow() != this) + tooltip->setTargetWindow(this); + else + tooltip->positionSelf(); + + last_model_index = index; + + if (!d_itemModel->isValidIndex(index)) + setTooltipText(""); + else + setTooltipText(d_itemModel->getData(index, IDR_Tooltip)); +} + +//----------------------------------------------------------------------------// +bool ItemView::isMultiSelectEnabled() const +{ + return d_isMultiSelectEnabled; +} + +//----------------------------------------------------------------------------// +void ItemView::setMultiSelectEnabled(bool enabled) +{ + if (d_isMultiSelectEnabled == enabled) + { + return; + } + + d_isMultiSelectEnabled = enabled; + + // deselect others + if (!d_isItemTooltipsEnabled && d_indexSelectionStates.size() > 1) + { + setIndexSelectionState(d_indexSelectionStates.front().d_selectedIndex, true); + } + + WindowEventArgs args(this); + onMultiselectModeChanged(args); +} + +//----------------------------------------------------------------------------// +void ItemView::onMultiselectModeChanged(WindowEventArgs& args) +{ + fireEvent(EventMultiselectModeChanged, args, EventNamespace); +} + +//----------------------------------------------------------------------------// +void ItemView::onSemanticInputEvent(SemanticEventArgs& e) +{ + if (e.d_semanticValue == SV_SelectRange || + e.d_semanticValue == SV_SelectCumulative) + { + handleSelection(getGUIContext().getCursor().getPosition(), + true, d_isMultiSelectEnabled, e.d_semanticValue == SV_SelectRange); + } + + handleSelectionNavigation(e); + + ++e.handled; + Window::onSemanticInputEvent(e); +} + +//----------------------------------------------------------------------------// +void ItemView::onParentSized(ElementEventArgs& e) +{ + Window::onParentSized(e); + + resizeToContent(); +} + +//----------------------------------------------------------------------------// +bool ItemView::handleSelection(const glm::vec2& position, bool should_select, + bool is_cumulative, bool is_range) +{ + return handleSelection(indexAt(position), should_select, is_cumulative, is_range); +} + +//----------------------------------------------------------------------------// +bool ItemView::handleSelection(const ModelIndex& index, bool should_select, + bool is_cumulative, bool is_range) +{ + if (d_itemModel == 0 || + !d_itemModel->isValidIndex(index)) + return false; + + int index_position = getSelectedIndexPosition(index); + if (index_position != -1) + { + if (!should_select) + { + d_indexSelectionStates.erase(d_indexSelectionStates.begin() + index_position); + + ItemViewEventArgs args(this, index); + onSelectionChanged(args); + return true; + } + + // if we select the node again, and we don't cumulate selection, we need + // to make just that one be selected now + if (is_cumulative) + return true; + } + + if (!is_cumulative) + d_indexSelectionStates.clear(); + + ModelIndex parent_index = d_itemModel->getParentIndex(index); + size_t end_child_id = d_itemModel->getChildId(index); + size_t start_child_id = end_child_id; + if (is_range && is_cumulative && d_lastSelectedIndex.d_modelData != 0) + { + start_child_id = d_itemModel->getChildId(d_lastSelectedIndex); + } + + for (size_t id = start_child_id; id <= end_child_id; ++id) + { + ModelIndexSelectionState selection_state; + selection_state.d_selectedIndex = d_itemModel->makeIndex(id, parent_index); + + // ignore already selected indices + if (getSelectedIndexPosition(selection_state.d_selectedIndex) != -1) + continue; + + selection_state.d_childId = id; + selection_state.d_parentIndex = parent_index; + + d_indexSelectionStates.push_back(selection_state); + } + + d_lastSelectedIndex = index; + + ItemViewEventArgs args(this, index); + onSelectionChanged(args); + return true; +} + +//----------------------------------------------------------------------------// +ViewSortMode ItemView::getSortMode() const +{ + return d_sortMode; +} + +//----------------------------------------------------------------------------// +void ItemView::setSortMode(ViewSortMode sort_mode) +{ + if (d_sortMode == sort_mode) + return; + + d_sortMode = sort_mode; + + resortView(); + + WindowEventArgs args(this); + onSortModeChanged(args); +} + +//----------------------------------------------------------------------------// +void ItemView::onSortModeChanged(WindowEventArgs& args) +{ + invalidateView(false); + //TODO: make all events be triggered on view's event namespace. + fireEvent(EventSortModeChanged, args); +} + +//----------------------------------------------------------------------------// +void ItemView::onViewContentsChanged(WindowEventArgs& args) +{ + fireEvent(EventViewContentsChanged, args, EventNamespace); +} + +//----------------------------------------------------------------------------// +void ItemView::clearSelections() +{ + d_indexSelectionStates.clear(); +} + +//----------------------------------------------------------------------------// +void ItemView::handleSelectionNavigation(SemanticEventArgs& e) +{ + ModelIndex parent_index = d_itemModel->getRootIndex(); + int last_selected_child_id = -1; + if (!d_indexSelectionStates.empty()) + { + ModelIndexSelectionState last_selection = d_indexSelectionStates.back(); + last_selected_child_id = last_selection.d_childId; + parent_index = last_selection.d_parentIndex; + } + + size_t children_count = d_itemModel->getChildCount(parent_index); + if (children_count == 0) + return; + + int next_selected_child_id = last_selected_child_id; + if (e.d_semanticValue == SV_GoDown) + { + next_selected_child_id = std::min( + next_selected_child_id + 1, + static_cast(children_count)-1 + ); + } + else if (e.d_semanticValue == SV_GoUp) + { + next_selected_child_id = std::max(0, next_selected_child_id - 1); + } + + if (next_selected_child_id == -1 || + next_selected_child_id == last_selected_child_id) + return; + + setSelectedIndex(d_itemModel->makeIndex( + static_cast(next_selected_child_id), parent_index)); +} + +//----------------------------------------------------------------------------// +float ItemView::getRenderedMaxWidth() const +{ + return d_renderedMaxWidth; +} + +//----------------------------------------------------------------------------// +float ItemView::getRenderedTotalHeight() const +{ + return d_renderedTotalHeight; +} + +//----------------------------------------------------------------------------// +void ItemView::ensureIndexIsVisible(const ModelIndex& index) +{ + Scrollbar* vert_scroll = getVertScrollbar(); + Scrollbar* horz_scroll = getHorzScrollbar(); + Rectf render_area = getViewRenderer()->getViewRenderArea(); + float view_height = render_area.getHeight(); + float view_width = render_area.getWidth(); + + Rectf rect = getIndexRect(index); + float bottom = rect.bottom(); + float top = rect.top(); + + // account for current scrollbar value + float currPos = vert_scroll->getScrollPosition(); + top -= currPos; + bottom -= currPos; + + // if top is above the view area, or if item is too big to fit + if ((top < 0.0f) || ((bottom - top) > view_height)) + { + // scroll top of item to top of box. + vert_scroll->setScrollPosition(currPos + top); + } + // if bottom is below the view area + else if (bottom >= view_height) + { + // position bottom of item at the bottom of the list + vert_scroll->setScrollPosition(currPos + bottom - view_height); + } + + const float left = rect.left() - currPos; + const float right = left + rect.getWidth(); + + // if left is left of the view area, or if item too big + if ((left < render_area.d_min.d_x) || ((right - left) > view_width)) + { + // scroll item to left + horz_scroll->setScrollPosition(currPos + left); + } + // if right is right of the view area + else if (right >= render_area.d_max.d_x) + { + // scroll item to right of list + horz_scroll->setScrollPosition(currPos + right - view_width); + } +} + +//----------------------------------------------------------------------------// +void ItemView::setAutoResizeHeightEnabled(bool enabled) +{ + updateAutoResizeFlag(d_isAutoResizeHeightEnabled, enabled); +} + +//----------------------------------------------------------------------------// +bool ItemView::isAutoResizeHeightEnabled() const +{ + return d_isAutoResizeHeightEnabled; +} + +//----------------------------------------------------------------------------// +void ItemView::setAutoResizeWidthEnabled(bool enabled) +{ + updateAutoResizeFlag(d_isAutoResizeWidthEnabled, enabled); +} + +//----------------------------------------------------------------------------// +bool ItemView::isAutoResizeWidthEnabled() const +{ + return d_isAutoResizeWidthEnabled; +} + +//----------------------------------------------------------------------------// +void ItemView::updateAutoResizeFlag(bool& flag, bool enabled) +{ + if (flag != enabled) + { + return; + } + + flag = enabled; + resizeToContent(); +} + +//----------------------------------------------------------------------------// +void ItemView::resizeToContent() +{ + if (d_initialising || + !(d_isAutoResizeWidthEnabled || d_isAutoResizeHeightEnabled)) + return; + + getViewRenderer()->resizeViewToContent( + d_isAutoResizeWidthEnabled, d_isAutoResizeHeightEnabled); +} + +//----------------------------------------------------------------------------// +ItemViewEventArgs::ItemViewEventArgs(ItemView* wnd, ModelIndex index) : +WindowEventArgs(wnd), +d_index(index) +{ + +} +} diff --git a/cegui/src/views/ListView.cpp b/cegui/src/views/ListView.cpp new file mode 100644 index 000000000..c7f25c317 --- /dev/null +++ b/cegui/src/views/ListView.cpp @@ -0,0 +1,288 @@ +/*********************************************************************** + created: Sat May 24 2014 + author: Timotei Dolean + + purpose: Implementation for a view that displays a list of model items. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include "CEGUI/views/ListView.h" +#include "CEGUI/CoordConverter.h" +#include + +namespace CEGUI +{ +typedef std::vector ViewItemsVector; + +//----------------------------------------------------------------------------// +static bool listViewItemPointerLess( + const ListViewItemRenderingState* item1, + const ListViewItemRenderingState* item2) +{ + return *item1 < *item2; +} + +//----------------------------------------------------------------------------// +static bool listViewItemPointerGreater( + const ListViewItemRenderingState* item1, + const ListViewItemRenderingState* item2) +{ + return *item1 > *item2; +} + +//----------------------------------------------------------------------------// +const String ListView::EventNamespace("ListView"); +const String ListView::WidgetTypeName("CEGUI/ListView"); + +//----------------------------------------------------------------------------// +ListViewItemRenderingState::ListViewItemRenderingState(ListView* list_view) : + d_isSelected(false), + d_attachedListView(list_view) +{ +} + +bool ListViewItemRenderingState::operator<(ListViewItemRenderingState const& other) const +{ + return d_attachedListView->getModel()->compareIndices(d_index, other.d_index) < 0; +} + +//----------------------------------------------------------------------------// +bool ListViewItemRenderingState::operator>(const ListViewItemRenderingState& other) const +{ + return d_attachedListView->getModel()->compareIndices(d_index, other.d_index) > 0; +} + +//----------------------------------------------------------------------------// +ListView::ListView(const String& type, const String& name) : + ItemView(type, name) +{ +} + +//----------------------------------------------------------------------------// +ListView::~ListView() +{ +} + +//----------------------------------------------------------------------------// +void ListView::prepareForRender() +{ + ItemView::prepareForRender(); + if (d_itemModel == 0 || !isDirty()) + return; + + if (d_needsFullRender) + { + d_renderedMaxWidth = d_renderedTotalHeight = 0; + d_items.clear(); + } + + ModelIndex root_index = d_itemModel->getRootIndex(); + size_t child_count = d_itemModel->getChildCount(root_index); + + for (size_t child = 0; child < child_count; ++child) + { + ModelIndex index = d_itemModel->makeIndex(child, root_index); + + if (d_needsFullRender) + { + ListViewItemRenderingState state = ListViewItemRenderingState(this); + updateItem(state, index, d_renderedMaxWidth, d_renderedTotalHeight); + d_items.push_back(state); + } + else + { + ListViewItemRenderingState& item = d_items.at(child); + d_renderedTotalHeight -= item.d_size.d_height; + + updateItem(item, index, d_renderedMaxWidth, d_renderedTotalHeight); + } + } + + updateScrollbars(); + setIsDirty(false); + resortListView(); + d_needsFullRender = false; +} + +//----------------------------------------------------------------------------// +ModelIndex ListView::indexAt(const glm::vec2& position) +{ + if (d_itemModel == 0) + return ModelIndex(); + + //TODO: add prepareForLayout() as a cheaper operation alternative? + prepareForRender(); + + glm::vec2 window_position = CoordConverter::screenToWindow(*this, position); + Rectf render_area(getViewRenderer()->getViewRenderArea()); + + if (!render_area.isPointInRect(window_position)) + return ModelIndex(); + + float cur_height = render_area.d_min.d_y - getVertScrollbar()->getScrollPosition(); + //TODO: start only on the visible area + for (size_t index = 0; index < d_sortedItems.size(); ++index) + { + ListViewItemRenderingState* item = d_sortedItems.at(index); + Sizef size = item->d_size; + float next_height = cur_height + size.d_height; + + if (window_position.y >= cur_height && + window_position.y <= next_height) + { + return item->d_index; + } + + cur_height = next_height; + } + + return ModelIndex(); +} + +//----------------------------------------------------------------------------// +const std::vector& ListView::getItems() const +{ + return d_sortedItems; +} + +//----------------------------------------------------------------------------// +void ListView::resortListView() +{ + d_sortedItems.clear(); + + for (ViewItemsVector::iterator itor = d_items.begin(); + itor != d_items.end(); ++itor) + { + d_sortedItems.push_back(&(*itor)); + } + + if (d_sortMode == VSM_None) + return; + + sort(d_sortedItems.begin(), d_sortedItems.end(), + d_sortMode == VSM_Ascending ? &listViewItemPointerLess : &listViewItemPointerGreater); +} + +//----------------------------------------------------------------------------// +void ListView::resortView() +{ + resortListView(); + invalidateView(false); +} + +//----------------------------------------------------------------------------// +void ListView::updateItem(ListViewItemRenderingState &item, ModelIndex index, + float& max_width, float& total_height) +{ + String text = d_itemModel->getData(index); + + RenderedString rendered_string = + getRenderedStringParser().parse(text, getFont(), &d_textColourRect); + item.d_string = rendered_string; + item.d_index = index; + item.d_text = text; + item.d_icon = d_itemModel->getData(index, IDR_Icon); + + item.d_size = Sizef( + rendered_string.getHorizontalExtent(this), + rendered_string.getVerticalExtent(this)); + + max_width = ceguimax(item.d_size.d_width, max_width); + + total_height += item.d_size.d_height; + + item.d_isSelected = isIndexSelected(index); +} + +//----------------------------------------------------------------------------// +bool ListView::onChildrenAdded(const EventArgs& args) +{ + ItemView::onChildrenAdded(args); + const ModelEventArgs& margs = static_cast(args); + + if (!d_itemModel->areIndicesEqual(margs.d_parentIndex, d_itemModel->getRootIndex())) + return true; + + ViewItemsVector items; + for (size_t i = 0; i < margs.d_count; ++i) + { + ListViewItemRenderingState item(this); + + updateItem(item, + d_itemModel->makeIndex(margs.d_startId + i, margs.d_parentIndex), + d_renderedMaxWidth, d_renderedTotalHeight); + + items.push_back(item); + } + + d_items.insert(d_items.begin() + margs.d_startId, items.begin(), items.end()); + + //TODO: insert in the right place directly! + resortListView(); + invalidateView(false); + return true; +} + +//----------------------------------------------------------------------------// +bool ListView::onChildrenRemoved(const EventArgs& args) +{ + ItemView::onChildrenRemoved(args); + const ModelEventArgs& margs = static_cast(args); + + if (!d_itemModel->areIndicesEqual(margs.d_parentIndex, d_itemModel->getRootIndex())) + return true; + + ViewItemsVector::iterator begin = d_items.begin() + margs.d_startId; + ViewItemsVector::iterator end = begin + margs.d_count; + + for (ViewItemsVector::iterator itor = begin; itor < end; ++itor) + { + d_renderedTotalHeight -= (*itor).d_size.d_height; + } + + d_items.erase(begin, end); + + resortListView(); + invalidateView(false); + return true; +} + +//----------------------------------------------------------------------------// +Rectf ListView::getIndexRect(const ModelIndex& index) +{ + int child_id = d_itemModel->getChildId(index); + if (child_id == -1) + { + return Rectf(0, 0, 0, 0); + } + + glm::vec2 pos(0, 0); + + for (size_t i = 0; i < static_cast(child_id); ++i) + { + pos.y += d_items.at(i).d_size.d_height; + } + + return Rectf(pos, d_items.at(static_cast(child_id)).d_size); +} +} diff --git a/cegui/src/RendererModules/Direct3D10/ViewportTarget.cpp b/cegui/src/views/StandardItemModel.cpp similarity index 59% rename from cegui/src/RendererModules/Direct3D10/ViewportTarget.cpp rename to cegui/src/views/StandardItemModel.cpp index b45937845..cdd12add9 100644 --- a/cegui/src/RendererModules/Direct3D10/ViewportTarget.cpp +++ b/cegui/src/views/StandardItemModel.cpp @@ -1,9 +1,9 @@ /*********************************************************************** - created: Sat Mar 7 2009 - author: Paul D Turner (parts based on code by Rajko Stojadinovic) + created: Wed May 23 2014 + author: Timotei Dolean *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,52 +24,42 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "CEGUI/RendererModules/Direct3D10/ViewportTarget.h" +#include "CEGUI/views/StandardItemModel.h" #include "CEGUI/Exceptions.h" -// Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// -Direct3D10ViewportTarget::Direct3D10ViewportTarget(Direct3D10Renderer& owner) : - Direct3D10RenderTarget<>(owner) +StandardItem::StandardItem() : GenericItem() { - // initialise renderer size - D3D10_VIEWPORT vp; - UINT vp_count = 1; - d_device.RSGetViewports(&vp_count, &vp); - if (vp_count != 1) - CEGUI_THROW(RendererException( - "Unable to access required view port information from " - "ID3D10Device.")); - - Rectf area( - Vector2f(static_cast(vp.TopLeftX), static_cast(vp.TopLeftY)), - Sizef(static_cast(vp.Width), static_cast(vp.Height)) - ); +} - setArea(area); +//----------------------------------------------------------------------------// +StandardItem::StandardItem(const String& text, uint id) : GenericItem(text), d_id(id) +{ } //----------------------------------------------------------------------------// -Direct3D10ViewportTarget::Direct3D10ViewportTarget(Direct3D10Renderer& owner, - const Rectf& area) : - Direct3D10RenderTarget<>(owner) +StandardItem::StandardItem(const String& text, const String& icon, uint id /*= 0*/) : +GenericItem(text, icon), d_id(id) { - setArea(area); } //----------------------------------------------------------------------------// -bool Direct3D10ViewportTarget::isImageryCache() const +StandardItemModel::StandardItemModel() : +GenericItemModel(new StandardItem) { - return false; } //----------------------------------------------------------------------------// +void StandardItemModel::updateItemText(StandardItem* item, const String& new_text) +{ + ModelIndex parent_index = getParentIndex(getIndexForItem(item)); -} // End of CEGUI namespace section + notifyChildrenDataWillChange(parent_index, 0, 1); -//----------------------------------------------------------------------------// -// Implementation of template base class -#include "./RenderTarget.inl" + item->setText(new_text); + notifyChildrenDataChanged(parent_index, 0, 1); +} +} diff --git a/cegui/src/views/TreeView.cpp b/cegui/src/views/TreeView.cpp new file mode 100644 index 000000000..eb8b54f4e --- /dev/null +++ b/cegui/src/views/TreeView.cpp @@ -0,0 +1,594 @@ +/*********************************************************************** + created: Fri Jun 06 2014 + author: Timotei Dolean + + purpose: Implementation of the base class for all item model-based views. +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include "CEGUI/CoordConverter.h" +#include "CEGUI/Exceptions.h" +#include "CEGUI/views/TreeView.h" + +#if defined (_MSC_VER) +# pragma warning(push) +# pragma warning(disable : 4355) +#endif + +//TODO: handle semantic event for up/down and left/right (open/close subtree) + +namespace CEGUI +{ +typedef std::vector ViewItemsVector; + +//----------------------------------------------------------------------------// +static bool treeViewItemPointerLess( + const TreeViewItemRenderingState* item1, + const TreeViewItemRenderingState* item2) +{ + return *item1 < *item2; +} + +//----------------------------------------------------------------------------// +static bool treeViewItemPointerGreater( + const TreeViewItemRenderingState* item1, + const TreeViewItemRenderingState* item2) +{ + return *item1 > *item2; +} + +//----------------------------------------------------------------------------// +TreeViewWindowRenderer::TreeViewWindowRenderer(const String& type) : + ItemViewWindowRenderer(type) +{ +} +static const float DefaultSubtreeExpanderMargin = 5.0f; +//----------------------------------------------------------------------------// +const String TreeView::EventNamespace("TreeView"); +const String TreeView::WidgetTypeName("CEGUI/TreeView"); +const String TreeView::EventSubtreeExpanded("SubtreeExpanded"); +const String TreeView::EventSubtreeCollapsed("SubtreeCollapsed"); + +//----------------------------------------------------------------------------// +TreeViewItemRenderingState::TreeViewItemRenderingState(TreeView* attached_tree_view) : + d_totalChildCount(0), + d_size(0, 0), + d_isSelected(false), + d_childId(0), + d_subtreeIsExpanded(false), + d_nestedLevel(0), + d_attachedTreeView(attached_tree_view) +{ +} + +//----------------------------------------------------------------------------// +void TreeViewItemRenderingState::sortChildren() +{ + d_renderedChildren.clear(); + + for (ViewItemsVector::iterator itor = d_children.begin(); + itor != d_children.end(); ++itor) + { + d_renderedChildren.push_back(&(*itor)); + + (*itor).sortChildren(); + } + + if (d_attachedTreeView->getSortMode() == VSM_None) + return; + + sort(d_renderedChildren.begin(), d_renderedChildren.end(), + d_attachedTreeView->getSortMode() == VSM_Ascending + ? &treeViewItemPointerLess : &treeViewItemPointerGreater); +} + +//----------------------------------------------------------------------------// +bool TreeViewItemRenderingState::operator<(const TreeViewItemRenderingState& other) const +{ + ItemModel* model = d_attachedTreeView->getModel(); + + return model->compareIndices( + model->makeIndex(d_childId, d_parentIndex), + model->makeIndex(other.d_childId, other.d_parentIndex) + ) < 0; +} + +//----------------------------------------------------------------------------// +bool TreeViewItemRenderingState::operator>(const TreeViewItemRenderingState& other) const +{ + ItemModel* model = d_attachedTreeView->getModel(); + + return model->compareIndices( + model->makeIndex(d_childId, d_parentIndex), + model->makeIndex(other.d_childId, other.d_parentIndex) + ) > 0; +} + +//----------------------------------------------------------------------------// +TreeView::TreeView(const String& type, const String& name) : + ItemView(type, name), + d_rootItemState(this), + d_subtreeExpanderMargin(DefaultSubtreeExpanderMargin) +{ + addTreeViewProperties(); +} + +//----------------------------------------------------------------------------// +void TreeView::addTreeViewProperties() +{ + const String& propertyOrigin = "TreeView"; + + CEGUI_DEFINE_PROPERTY(TreeView, float, + "SubtreeExpanderMargin", "Property to access the margin around the subtree expander. Value is a float. Default is 5.0f", + &TreeView::setSubtreeExpanderMargin, &TreeView::getSubtreeExpanderMargin, + DefaultSubtreeExpanderMargin + ) +} + +//----------------------------------------------------------------------------// +TreeView::~TreeView() +{ +} + +//----------------------------------------------------------------------------// +const TreeViewItemRenderingState& TreeView::getRootItemState() const +{ + return d_rootItemState; +} + +//----------------------------------------------------------------------------// +float TreeView::getSubtreeExpanderMargin() const +{ + return d_subtreeExpanderMargin; +} + +//----------------------------------------------------------------------------// +void TreeView::setSubtreeExpanderMargin(float value) +{ + d_subtreeExpanderMargin = value; +} + +//----------------------------------------------------------------------------// +void TreeView::prepareForRender() +{ + ItemView::prepareForRender(); + //TODO: better way of ignoring the null item model? E.g.: warn? Throw an exception? + if (d_itemModel == 0 || !isDirty()) + return; + + if (d_needsFullRender) + { + ModelIndex root_index = d_itemModel->getRootIndex(); + d_renderedMaxWidth = 0; + d_renderedTotalHeight = 0; + + d_rootItemState = TreeViewItemRenderingState(this); + // root item isn't a proper item so it does not have a nested level. + d_rootItemState.d_nestedLevel = -1; + d_rootItemState.d_subtreeIsExpanded = true; + + computeRenderedChildrenForItem(d_rootItemState, root_index, + d_renderedMaxWidth, d_renderedTotalHeight); + } + else + { + updateRenderingStateForItem(d_rootItemState, + d_renderedMaxWidth, d_renderedTotalHeight); + } + + updateScrollbars(); + setIsDirty(false); + d_needsFullRender = false; +} + +//----------------------------------------------------------------------------// +bool TreeView::handleSelection(const glm::vec2& position, bool should_select, + bool is_cumulative, bool is_range) +{ + return handleSelection( + indexAtWithAction(position, &TreeView::handleSelectionAction), + should_select, is_cumulative, is_range); +} + +//----------------------------------------------------------------------------// +bool TreeView::handleSelection(const ModelIndex& index, bool should_select, + bool is_cumulative, bool is_range) +{ + return ItemView::handleSelection(index, should_select, is_cumulative, is_range); +} + +//----------------------------------------------------------------------------// +TreeViewItemRenderingState TreeView::computeRenderingStateForIndex( + const ModelIndex& parent_index, size_t child_id, size_t nested_level, + float& rendered_max_width, float& rendered_total_height) +{ + ModelIndex index = d_itemModel->makeIndex(child_id, parent_index); + TreeViewItemRenderingState state(this); + state.d_nestedLevel = nested_level; + state.d_parentIndex = parent_index; + state.d_childId = child_id; + + fillRenderingState(state, index, rendered_max_width, rendered_total_height); + + computeRenderedChildrenForItem(state, index, rendered_max_width, + rendered_total_height); + + return state; +} + +//----------------------------------------------------------------------------// +void TreeView::computeRenderedChildrenForItem(TreeViewItemRenderingState &item, + const ModelIndex& index, float& rendered_max_width, float& rendered_total_height) +{ + size_t child_count = d_itemModel->getChildCount(index); + item.d_totalChildCount = child_count; + + if (!item.d_subtreeIsExpanded) + return; + + for (size_t child = 0; child < child_count; ++child) + { + item.d_children.push_back( + computeRenderingStateForIndex(index, child, item.d_nestedLevel + 1, + rendered_max_width, rendered_total_height)); + } + + item.sortChildren(); +} + +//----------------------------------------------------------------------------// +void TreeView::updateRenderingStateForItem(TreeViewItemRenderingState& item, + float& rendered_max_width, float& rendered_total_height) +{ + // subtract the previous height + rendered_total_height -= item.d_size.d_height; + + fillRenderingState(item, + d_itemModel->makeIndex(item.d_childId, item.d_parentIndex), + rendered_max_width, rendered_total_height); + + for (ItemStateVector::iterator itor = item.d_children.begin(); + itor != item.d_children.end(); ++itor) + { + (*itor).d_nestedLevel = item.d_nestedLevel + 1; + updateRenderingStateForItem(*itor, rendered_max_width, rendered_total_height); + } +} + +//----------------------------------------------------------------------------// +void TreeView::fillRenderingState(TreeViewItemRenderingState& item, + const ModelIndex& index, float& rendered_max_width, float& rendered_total_height) +{ + String text = d_itemModel->getData(index); + RenderedString rendered_string = getRenderedStringParser().parse( + text, getFont(), &d_textColourRect); + item.d_string = rendered_string; + item.d_text = text; + item.d_icon = d_itemModel->getData(index, IDR_Icon); + + item.d_size = Sizef( + rendered_string.getHorizontalExtent(this), + rendered_string.getVerticalExtent(this)); + + float indent = getViewRenderer()->getSubtreeExpanderXIndent(item.d_nestedLevel) + + getViewRenderer()->getSubtreeExpanderSize().d_width; + rendered_max_width = ceguimax(rendered_max_width, item.d_size.d_width + indent); + rendered_total_height += item.d_size.d_height; + + item.d_isSelected = isIndexSelected(index); +} + +//----------------------------------------------------------------------------// +ModelIndex TreeView::indexAt(const glm::vec2& position) +{ + return indexAtWithAction(position, &TreeView::noopAction); +} + +//----------------------------------------------------------------------------// +ModelIndex TreeView::indexAtWithAction(const glm::vec2& position, + TreeViewItemAction action) +{ + if (d_itemModel == 0) + return ModelIndex(); + + //TODO: add prepareForLayout() as a cheaper operation alternative? + prepareForRender(); + + glm::vec2 window_position = CoordConverter::screenToWindow(*this, position); + Rectf render_area(getViewRenderer()->getViewRenderArea()); + if (!render_area.isPointInRect(window_position)) + return ModelIndex(); + + float cur_height = render_area.d_min.d_y - getVertScrollbar()->getScrollPosition(); + bool handled = false; + return indexAtRecursive(d_rootItemState, cur_height, window_position, + handled, action); +} + +//----------------------------------------------------------------------------// +ModelIndex TreeView::indexAtRecursive(TreeViewItemRenderingState& item, + float& cur_height, const glm::vec2& window_position, bool& handled, + TreeViewItemAction action) +{ + float next_height = cur_height + item.d_size.d_height; + + if (window_position.y >= cur_height && + window_position.y <= next_height) + { + handled = true; + + float expander_width = getViewRenderer()->getSubtreeExpanderSize().d_width; + float base_x = getViewRenderer()->getSubtreeExpanderXIndent(item.d_nestedLevel); + base_x -= getHorzScrollbar()->getScrollPosition(); + if (window_position.x >= base_x && + window_position.x <= base_x + expander_width) + { + (this->*action)(item, true); + return ModelIndex(); + } + + (this->*action)(item, false); + return ModelIndex(d_itemModel->makeIndex(item.d_childId, item.d_parentIndex)); + } + + cur_height = next_height; + + for (size_t i = 0; i < item.d_renderedChildren.size(); ++i) + { + ModelIndex index = indexAtRecursive(*item.d_renderedChildren.at(i), + cur_height, window_position, handled, action); + if (handled) + return index; + } + + return ModelIndex(); +} + +//----------------------------------------------------------------------------// +TreeViewWindowRenderer* TreeView::getViewRenderer() +{ + return static_cast(ItemView::getViewRenderer()); +} + +//----------------------------------------------------------------------------// +void TreeView::toggleSubtree(TreeViewItemRenderingState& item) +{ + if (d_itemModel == 0) + return; + + item.d_subtreeIsExpanded = !item.d_subtreeIsExpanded; + + ItemViewEventArgs args(this, + d_itemModel->makeIndex(item.d_childId, item.d_parentIndex)); + + if (item.d_subtreeIsExpanded) + { + computeRenderedChildrenForItem(item, + d_itemModel->makeIndex(item.d_childId, item.d_parentIndex), + d_renderedMaxWidth, d_renderedTotalHeight); + onSubtreeExpanded(args); + } + else + { + clearItemRenderedChildren(item, d_renderedTotalHeight); + onSubtreeCollapsed(args); + } + + updateScrollbars(); + // we need just a simple invalidation. No need to redo the render state + // as we modified it ourself directly. + invalidate(false); +} + +//----------------------------------------------------------------------------// +void TreeView::clearItemRenderedChildren(TreeViewItemRenderingState& item, + float& renderedTotalHeight) +{ + ViewItemsVector::iterator itor = + item.d_children.begin(); + + while (itor != item.d_children.end()) + { + clearItemRenderedChildren(*itor, renderedTotalHeight); + + d_renderedTotalHeight -= item.d_size.d_height; + ++itor; + } + + item.d_children.clear(); + item.sortChildren(); +} + +//----------------------------------------------------------------------------// +void TreeView::handleSelectionAction(TreeViewItemRenderingState& item, bool toggles_expander) +{ + if (!toggles_expander) + return; + + toggleSubtree(item); +} + +//----------------------------------------------------------------------------// +bool TreeView::onChildrenRemoved(const EventArgs& args) +{ + ItemView::onChildrenRemoved(args); + + const ModelEventArgs& margs = static_cast(args); + TreeViewItemRenderingState* item = getTreeViewItemForIndex(margs.d_parentIndex); + + if (item == 0) + return true; + + item->d_totalChildCount -= margs.d_count; + + if (!item->d_subtreeIsExpanded) + return true; + + ViewItemsVector::iterator begin = item->d_children.begin() + margs.d_startId; + ViewItemsVector::iterator end = begin + margs.d_count; + + // update existing child ids + for (ItemStateVector::iterator itor = begin; itor != item->d_children.end(); ++itor) + { + (*itor).d_childId -= margs.d_count; + + if (itor < end) + d_renderedTotalHeight -= (*itor).d_size.d_height; + } + + item->d_children.erase(begin, end); + + item->sortChildren(); + invalidateView(false); + return true; +} + +//----------------------------------------------------------------------------// +bool TreeView::onChildrenAdded(const EventArgs& args) +{ + ItemView::onChildrenAdded(args); + + const ModelEventArgs& margs = static_cast(args); + TreeViewItemRenderingState* item = getTreeViewItemForIndex(margs.d_parentIndex); + + if (item == 0) + return true; + + item->d_totalChildCount += margs.d_count; + + if (!item->d_subtreeIsExpanded) + return true; + + ViewItemsVector states; + for (size_t id = margs.d_startId; id < margs.d_startId + margs.d_count; ++id) + { + states.push_back(computeRenderingStateForIndex(margs.d_parentIndex, id, + item->d_nestedLevel + 1, d_renderedMaxWidth, d_renderedTotalHeight)); + } + + // update existing child ids + for (ItemStateVector::iterator + itor = item->d_children.begin() + margs.d_startId; + itor != item->d_children.end(); ++itor) + { + (*itor).d_childId += margs.d_count; + } + + item->d_children.insert( + item->d_children.begin() + margs.d_startId, + states.begin(), states.end()); + + item->sortChildren(); + invalidateView(false); + return true; +} + +//----------------------------------------------------------------------------// +void TreeView::onSubtreeExpanded(ItemViewEventArgs& args) +{ + fireEvent(EventSubtreeExpanded, args, EventNamespace); +} + +//----------------------------------------------------------------------------// +void TreeView::onSubtreeCollapsed(ItemViewEventArgs& args) +{ + fireEvent(EventSubtreeCollapsed, args, EventNamespace); +} + +//----------------------------------------------------------------------------// +TreeViewItemRenderingState* TreeView::getTreeViewItemForIndex(const ModelIndex& index) +{ + std::vector ids_stack; + ModelIndex root_index = d_itemModel->getRootIndex(); + ModelIndex temp_index = index; + + // we create a stack of child ids which will allow us to drill back + // in the right hierarchy. + do + { + int id = d_itemModel->getChildId(temp_index); + if (id == -1) + break; + + ids_stack.push_back(id); + temp_index = d_itemModel->getParentIndex(temp_index); + } while (d_itemModel->isValidIndex(temp_index) && + !d_itemModel->areIndicesEqual(temp_index, root_index)); + + TreeViewItemRenderingState* item = &d_rootItemState; + while(!ids_stack.empty()) + { + int child_id = ids_stack.back(); + ids_stack.pop_back(); + + if (static_cast(child_id) >= item->d_children.size()) + return 0; + + item = &item->d_children.at(child_id); + } + + return item; +} + +//----------------------------------------------------------------------------// +void TreeView::resortView() +{ + d_rootItemState.sortChildren(); + invalidateView(false); +} + +//----------------------------------------------------------------------------// +void TreeView::expandAllSubtrees() +{ + expandSubtreeRecursive(d_rootItemState); +} + +//----------------------------------------------------------------------------// +void TreeView::expandSubtreeRecursive(TreeViewItemRenderingState& item) +{ + if (!item.d_subtreeIsExpanded) + toggleSubtree(item); + + if (item.d_totalChildCount == 0) + return; + + for (ViewItemsVector::iterator + itor = item.d_children.begin(); + itor != item.d_children.end(); ++itor) + { + expandSubtreeRecursive(*itor); + } +} + +//----------------------------------------------------------------------------// +Rectf TreeView::getIndexRect(const ModelIndex& index) +{ + //TODO: implement for tree view. What do we do for indices in closed subtrees? + CEGUI_THROW(InvalidRequestException("Not implemented for tree view yet.")); +} + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +} diff --git a/cegui/src/widgets/ButtonBase.cpp b/cegui/src/widgets/ButtonBase.cpp index 7d12a8c7b..9c6483a75 100644 --- a/cegui/src/widgets/ButtonBase.cpp +++ b/cegui/src/widgets/ButtonBase.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 13/4/2004 author: Paul D Turner - + purpose: Implementation of ButtonBase widget *************************************************************************/ /*************************************************************************** @@ -27,7 +27,7 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/widgets/ButtonBase.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" // Start of CEGUI namespace section namespace CEGUI @@ -55,40 +55,40 @@ ButtonBase::~ButtonBase(void) /************************************************************************* Update the internal state of the Widget *************************************************************************/ -void ButtonBase::updateInternalState(const Vector2f& mouse_pos) +void ButtonBase::updateInternalState(const glm::vec2& cursor_pos) { const bool oldstate = d_hovering; - d_hovering = calculateCurrentHoverState(mouse_pos); + d_hovering = calculateCurrentHoverState(cursor_pos); if (oldstate != d_hovering) invalidate(); } //----------------------------------------------------------------------------// -bool ButtonBase::calculateCurrentHoverState(const Vector2f& mouse_pos) +bool ButtonBase::calculateCurrentHoverState(const glm::vec2& cursor_pos) { if (const Window* capture_wnd = getCaptureWindow()) return (capture_wnd == this || - (capture_wnd->distributesCapturedInputs() && isAncestor(capture_wnd))) && isHit(mouse_pos); + (capture_wnd->distributesCapturedInputs() && isAncestor(capture_wnd))) && isHit(cursor_pos); else - return getGUIContext().getWindowContainingMouse() == this; + return getGUIContext().getWindowContainingCursor() == this; } /************************************************************************* - Handler for when the mouse moves + Handler for when the cursor moves *************************************************************************/ -void ButtonBase::onMouseMove(MouseEventArgs& e) +void ButtonBase::onCursorMove(CursorInputEventArgs& e) { - // this is needed to discover whether mouse is in the widget area or not. + // this is needed to discover whether cursor is in the widget area or not. // The same thing used to be done each frame in the rendering method, // but in this version the rendering method may not be called every frame // so we must discover the internal widget state here - which is actually // more efficient anyway. // base class processing - Window::onMouseMove(e); + Window::onCursorMove(e); updateInternalState(e.position); ++e.handled; @@ -96,14 +96,14 @@ void ButtonBase::onMouseMove(MouseEventArgs& e) /************************************************************************* - Handler for mouse button pressed events + Handler for cursor press hold events *************************************************************************/ -void ButtonBase::onMouseButtonDown(MouseEventArgs& e) +void ButtonBase::onCursorPressHold(CursorInputEventArgs& e) { // default processing - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { if (captureInput()) { @@ -115,7 +115,6 @@ void ButtonBase::onMouseButtonDown(MouseEventArgs& e) // event was handled by us. ++e.handled; } - } //----------------------------------------------------------------------------// @@ -125,7 +124,7 @@ void ButtonBase::setPushedState(const bool pushed) if (!pushed) updateInternalState(getUnprojectedPosition( - getGUIContext().getMouseCursor().getPosition())); + getGUIContext().getCursor().getPosition())); else d_hovering = true; @@ -133,14 +132,14 @@ void ButtonBase::setPushedState(const bool pushed) } /************************************************************************* - Handler for mouse button release events + Handler for cursor activation events *************************************************************************/ -void ButtonBase::onMouseButtonUp(MouseEventArgs& e) +void ButtonBase::onCursorActivate(CursorInputEventArgs& e) { // default processing - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { releaseInput(); @@ -151,7 +150,7 @@ void ButtonBase::onMouseButtonUp(MouseEventArgs& e) } /************************************************************************* - Handler for when mouse capture is lost + Handler for when cursor capture is lost *************************************************************************/ void ButtonBase::onCaptureLost(WindowEventArgs& e) { @@ -159,7 +158,7 @@ void ButtonBase::onCaptureLost(WindowEventArgs& e) Window::onCaptureLost(e); d_pushed = false; - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); invalidate(); // event was handled by us. @@ -168,12 +167,12 @@ void ButtonBase::onCaptureLost(WindowEventArgs& e) /************************************************************************* - Handler for when mouse leaves the widget + Handler for when cursor leaves the widget *************************************************************************/ -void ButtonBase::onMouseLeaves(MouseEventArgs& e) +void ButtonBase::onCursorLeaves(CursorInputEventArgs& e) { - // deafult processing - Window::onMouseLeaves(e); + // default processing + Window::onCursorLeaves(e); d_hovering = false; invalidate(); diff --git a/cegui/src/widgets/ClippedContainer.cpp b/cegui/src/widgets/ClippedContainer.cpp deleted file mode 100644 index fd99d070d..000000000 --- a/cegui/src/widgets/ClippedContainer.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/*********************************************************************** - created: Sun Jun 11 2006 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/widgets/ClippedContainer.h" -#include "CEGUI/CoordConverter.h" - -// Start of CEGUI namespace section -namespace CEGUI -{ -const String ClippedContainer::WidgetTypeName("ClippedContainer"); -const String ClippedContainer::EventNamespace("ClippedContainer"); - -ClippedContainer::ClippedContainer(const String& type, const String& name) : - Window(type, name), - d_clipArea(0,0,0,0), - d_clipperWindow(0) -{ -} - -ClippedContainer::~ClippedContainer(void) -{ -} - -Rectf ClippedContainer::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const -{ - // This is obviously doing nothing. The reason being that whas this - // used to to is now handled correctly via the fixed 'inner rect' usage, - // meaning that the looknfeel named areas can be employed to do the correct - // clipping. Fixing the inner rect support actually broke this anyhow, - // since it only worked because the inner rect support was broken. As - // such, ClippedContainer serves no useful purpose and will be removed. - return Window::getUnclippedInnerRect_impl(skipAllPixelAlignment); -} - -const Rectf& ClippedContainer::getClipArea(void) const -{ - return d_clipArea; -} - -Window* ClippedContainer::getClipperWindow() const -{ - return d_clipperWindow; -} - -void ClippedContainer::setClipArea(const Rectf& r) -{ - if (d_clipArea != r) - { - d_clipArea = r; - invalidate(); - notifyClippingChanged(); - } -} - -void ClippedContainer::setClipperWindow(Window* w) -{ - if (d_clipperWindow != w) - { - d_clipperWindow = w; - invalidate(); - notifyClippingChanged(); - } -} - -} // End of CEGUI namespace section diff --git a/cegui/src/widgets/ComboDropList.cpp b/cegui/src/widgets/ComboDropList.cpp index 7dc17cbe0..a5cb0d0dc 100644 --- a/cegui/src/widgets/ComboDropList.cpp +++ b/cegui/src/widgets/ComboDropList.cpp @@ -28,7 +28,6 @@ ***************************************************************************/ #include "CEGUI/widgets/ComboDropList.h" #include "CEGUI/widgets/Scrollbar.h" -#include "CEGUI/widgets/ListboxItem.h" #include "CEGUI/CoordConverter.h" // Start of CEGUI namespace section @@ -49,11 +48,11 @@ const String ComboDropList::EventListSelectionAccepted( "ListSelectionAccepted" Constructor for ComboDropList base class *************************************************************************/ ComboDropList::ComboDropList(const String& type, const String& name) : - Listbox(type, name) + ListWidget(type, name) { d_autoArm = false; d_armed = false; - d_lastClickSelected = 0; + d_lastItemSelected = 0; hide(); @@ -76,7 +75,7 @@ ComboDropList::~ComboDropList(void) *************************************************************************/ void ComboDropList::initialiseComponents(void) { - Listbox::initialiseComponents(); + ListWidget::initialiseComponents(); // set-up scroll bars so they return capture to us. getVertScrollbar()->setRestoreOldCapture(true); @@ -94,9 +93,8 @@ void ComboDropList::resizeToContent(bool fit_width, bool fit_height) CEGUI_THROW(InvalidRequestException( "Function requires a valid WindowRenderer object to be set.")); - static_cast(d_windowRenderer)-> - resizeListToContent(fit_width, fit_height); - + static_cast(d_windowRenderer)-> + resizeViewToContent(fit_width, fit_height); } /************************************************************************* @@ -104,42 +102,42 @@ void ComboDropList::resizeToContent(bool fit_width, bool fit_height) *************************************************************************/ void ComboDropList::onListSelectionAccepted(WindowEventArgs& e) { - d_lastClickSelected = getFirstSelectedItem(); + d_lastItemSelected = getFirstSelectedItem(); fireEvent(EventListSelectionAccepted, e, EventNamespace); } /************************************************************************* Handler for when list content has changed *************************************************************************/ -void ComboDropList::onListContentsChanged(WindowEventArgs& e) +void ComboDropList::onViewContentsChanged(WindowEventArgs& e) { // basically see if our 'sticky' selection was removed - if ((d_lastClickSelected) && !isListboxItemInList(d_lastClickSelected)) - d_lastClickSelected = 0; + if ((d_lastItemSelected) && !isItemInList(d_lastItemSelected)) + d_lastItemSelected = 0; // base class processing - Listbox::onListContentsChanged(e); + ListWidget::onViewContentsChanged(e); } /************************************************************************* Handler for when list selection has changed *************************************************************************/ -void ComboDropList::onSelectionChanged(WindowEventArgs& e) +void ComboDropList::onSelectionChanged(ItemViewEventArgs& e) { if (!isActive()) - d_lastClickSelected = getFirstSelectedItem(); + d_lastItemSelected = getFirstSelectedItem(); - Listbox::onSelectionChanged(e); + ListWidget::onSelectionChanged(e); } /************************************************************************* - Handler for mouse movement events + Handler for cursor movement events *************************************************************************/ -void ComboDropList::onMouseMove(MouseEventArgs& e) +void ComboDropList::onCursorMove(CursorInputEventArgs& e) { - Listbox::onMouseMove(e); + ListWidget::onCursorMove(e); - // if mouse is within our area (but not our children) + // if cursor is within our area (but not our children) if (isHit(e.position)) { if (!getChildAtPosition(e.position)) @@ -152,19 +150,18 @@ void ComboDropList::onMouseMove(MouseEventArgs& e) if (d_armed) { - // check for an item under the mouse - ListboxItem* selItem = getItemAtPoint(e.position); - - // if an item is under mouse, select it - if (selItem) - { - setItemSelectState(selItem, true); - } - else - { - clearAllSelections(); - } - + // check for an item under the cursor + StandardItem* item = d_itemModel.getItemForIndex(indexAt(e.position)); + + // if an item is under cursor, select it + if (item != 0) + { + setIndexSelectionState(item, true); + } + else + { + clearSelections(); + } } } @@ -173,29 +170,27 @@ void ComboDropList::onMouseMove(MouseEventArgs& e) // not within the list area else { - // if left mouse button is down, clear any selection - if (e.sysKeys & LeftMouse) + // if left cursor is held, clear any selection + if (e.state.isHeld(CIS_Left)) { - clearAllSelections(); + clearSelections(); } - } - } /************************************************************************* - Handler for mouse button pressed events + Handler for cursor pressed events *************************************************************************/ -void ComboDropList::onMouseButtonDown(MouseEventArgs& e) +void ComboDropList::onCursorPressHold(CursorInputEventArgs& e) { - Listbox::onMouseButtonDown(e); + ListWidget::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { if (!isHit(e.position)) { - clearAllSelections(); + clearSelections(); releaseInput(); } else @@ -205,31 +200,30 @@ void ComboDropList::onMouseButtonDown(MouseEventArgs& e) ++e.handled; } - } /************************************************************************* - Handler for mouse button release events + Handler for cursor activation events *************************************************************************/ -void ComboDropList::onMouseButtonUp(MouseEventArgs& e) +void ComboDropList::onCursorActivate(CursorInputEventArgs& e) { - Listbox::onMouseButtonUp(e); + ListWidget::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { if (d_armed && (getChildAtPosition(e.position) == 0)) { - // if something was selected, confirm that selection. - if (getSelectedCount() > 0) - { - WindowEventArgs args(this); - onListSelectionAccepted(args); - } + // if something was selected, confirm that selection. + if (getIndexSelectionStates().size() > 0) + { + WindowEventArgs args(this); + onListSelectionAccepted(args); + } releaseInput(); } - // if we are not already armed, in response to a left button up event, we auto-arm. + // if we are not already armed, in response to a left cursor activation event, we auto-arm. else { d_armed = true; @@ -246,26 +240,17 @@ void ComboDropList::onMouseButtonUp(MouseEventArgs& e) *************************************************************************/ void ComboDropList::onCaptureLost(WindowEventArgs& e) { - Listbox::onCaptureLost(e); + ListWidget::onCaptureLost(e); d_armed = false; hide(); ++e.handled; // ensure 'sticky' selection remains. - if ((d_lastClickSelected) && !d_lastClickSelected->isSelected()) + if (d_lastItemSelected != 0 && isItemSelected(d_lastItemSelected)) { - clearAllSelections_impl(); - setItemSelectState(d_lastClickSelected, true); + clearSelections(); + setIndexSelectionState(d_lastItemSelected, true); } } - -/************************************************************************* - Handler for when window is activated -*************************************************************************/ -void ComboDropList::onActivated(ActivationEventArgs& e) -{ - Listbox::onActivated(e); -} - } // End of CEGUI namespace section diff --git a/cegui/src/widgets/Combobox.cpp b/cegui/src/widgets/Combobox.cpp index 254a588ab..56565f7a7 100644 --- a/cegui/src/widgets/Combobox.cpp +++ b/cegui/src/widgets/Combobox.cpp @@ -30,14 +30,13 @@ #include "CEGUI/widgets/Editbox.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/ComboDropList.h" -#include "CEGUI/widgets/ListboxItem.h" #include "CEGUI/WindowManager.h" /************************************************************************* General information. The Combobox class is, for the most part, a huge proxy to the - component Editbox and ComboDropList (Listbox) widgets. The Combobox + component Editbox and ComboDropList (ListWidget) widgets. The Combobox widget itself actually does very little. *************************************************************************/ @@ -60,7 +59,7 @@ const String Combobox::EventTextSelectionChanged( "TextSelectionChanged" ); const String Combobox::EventEditboxFull( "EditboxFull" ); const String Combobox::EventTextAccepted( "TextAccepted" ); -// event names from list box +// event names from list widget const String Combobox::EventListContentsChanged( "ListContentsChanged" ); const String Combobox::EventListSelectionChanged( "ListSelectionChanged" ); const String Combobox::EventSortModeChanged( "SortModeChanged" ); @@ -117,10 +116,10 @@ void Combobox::initialiseComponents(void) editbox->banPropertyFromXML("MaxTextLength"); // internal event wiring - button->subscribeEvent(PushButton::EventMouseButtonDown, Event::Subscriber(&CEGUI::Combobox::button_PressHandler, this)); + button->subscribeEvent(PushButton::EventCursorPressHold, Event::Subscriber(&CEGUI::Combobox::button_PressHandler, this)); droplist->subscribeEvent(ComboDropList::EventListSelectionAccepted, Event::Subscriber(&CEGUI::Combobox::droplist_SelectionAcceptedHandler, this)); droplist->subscribeEvent(Window::EventHidden, Event::Subscriber(&CEGUI::Combobox::droplist_HiddenHandler, this)); - editbox->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&CEGUI::Combobox::editbox_MouseDownHandler, this)); + editbox->subscribeEvent(Window::EventCursorPressHold, Event::Subscriber(&CEGUI::Combobox::editbox_PointerPressHoldHandler, this)); // event forwarding setup editbox->subscribeEvent(Editbox::EventReadOnlyModeChanged, Event::Subscriber(&CEGUI::Combobox::editbox_ReadOnlyChangedHandler, this)); @@ -132,11 +131,16 @@ void Combobox::initialiseComponents(void) editbox->subscribeEvent(Editbox::EventEditboxFull, Event::Subscriber(&CEGUI::Combobox::editbox_EditboxFullEventHandler, this)); editbox->subscribeEvent(Editbox::EventTextAccepted, Event::Subscriber(&CEGUI::Combobox::editbox_TextAcceptedEventHandler, this)); editbox->subscribeEvent(Editbox::EventTextChanged, Event::Subscriber(&CEGUI::Combobox::editbox_TextChangedEventHandler, this)); - droplist->subscribeEvent(Listbox::EventListContentsChanged, Event::Subscriber(&CEGUI::Combobox::listbox_ListContentsChangedHandler, this)); - droplist->subscribeEvent(Listbox::EventSelectionChanged, Event::Subscriber(&CEGUI::Combobox::listbox_ListSelectionChangedHandler, this)); - droplist->subscribeEvent(Listbox::EventSortModeChanged, Event::Subscriber(&CEGUI::Combobox::listbox_SortModeChangedHandler, this)); - droplist->subscribeEvent(Listbox::EventVertScrollbarModeChanged, Event::Subscriber(&CEGUI::Combobox::listbox_VertScrollModeChangedHandler, this)); - droplist->subscribeEvent(Listbox::EventHorzScrollbarModeChanged, Event::Subscriber(&CEGUI::Combobox::listbox_HorzScrollModeChangedHandler, this)); + droplist->subscribeEvent(ListWidget::EventViewContentsChanged, + Event::Subscriber(&Combobox::listwidget_ListContentsChangedHandler, this)); + droplist->subscribeEvent(ListWidget::EventSelectionChanged, + Event::Subscriber(&Combobox::listwidget_ListSelectionChangedHandler, this)); + droplist->subscribeEvent(ListWidget::EventSortModeChanged, + Event::Subscriber(&Combobox::listwidget_SortModeChangedHandler, this)); + droplist->subscribeEvent(ListWidget::EventVertScrollbarDisplayModeChanged, + Event::Subscriber(&Combobox::listwidget_VertScrollModeChangedHandler, this)); + droplist->subscribeEvent(ListWidget::EventHorzScrollbarDisplayModeChanged, + Event::Subscriber(&Combobox::listwidget_HorzScrollModeChangedHandler, this)); // put components in their initial positions performChildWindowLayout(); @@ -316,7 +320,7 @@ void Combobox::setMaxTextLength(size_t max_len) /************************************************************************* - Return number of items attached to the list box + Return number of items attached to the list widget *************************************************************************/ size_t Combobox::getItemCount(void) const { @@ -325,9 +329,9 @@ size_t Combobox::getItemCount(void) const /************************************************************************* - Return a pointer to the currently selected item. + Return a cursor to the currently selected item. *************************************************************************/ -ListboxItem* Combobox::getSelectedItem(void) const +StandardItem* Combobox::getSelectedItem(void) const { return getDropList()->getFirstSelectedItem(); } @@ -336,27 +340,26 @@ ListboxItem* Combobox::getSelectedItem(void) const /************************************************************************* Return the item at index position \a index. *************************************************************************/ -ListboxItem* Combobox::getListboxItemFromIndex(size_t index) const +StandardItem* Combobox::getItemFromIndex(size_t index) const { - return getDropList()->getListboxItemFromIndex(index); + return getDropList()->getItemAtIndex(index); } /************************************************************************* - Return the index of ListboxItem 'item' + Return the index of StandardItem 'item' *************************************************************************/ -size_t Combobox::getItemIndex(const ListboxItem* item) const +size_t Combobox::getItemIndex(const StandardItem* item) const { - return getDropList()->getItemIndex(item); + return getDropList()->getModel()->getChildId(item); } - /************************************************************************* return whether list sorting is enabled *************************************************************************/ bool Combobox::isSortEnabled(void) const { - return getDropList()->isSortEnabled(); + return getDropList()->getSortMode() != VSM_None; } @@ -365,25 +368,25 @@ bool Combobox::isSortEnabled(void) const *************************************************************************/ bool Combobox::isItemSelected(size_t index) const { - return getDropList()->isItemSelected(index); + return getDropList()->isIndexSelected(index); } /************************************************************************* Search the list for an item with the specified text *************************************************************************/ -ListboxItem* Combobox::findItemWithText(const String& text, const ListboxItem* start_item) +StandardItem* Combobox::findItemWithText(const String& text, const StandardItem* start_item) { - return getDropList()->findItemWithText(text, start_item); + return getDropList()->findItemWithText(text, start_item); } /************************************************************************* - Return whether the specified ListboxItem is in the List + Return whether the specified StandardItem is in the list *************************************************************************/ -bool Combobox::isListboxItemInList(const ListboxItem* item) const +bool Combobox::isItemInList(const StandardItem* item) const { - return getDropList()->isListboxItemInList(item); + return getDropList()->isItemInList(item); } @@ -392,35 +395,31 @@ bool Combobox::isListboxItemInList(const ListboxItem* item) const *************************************************************************/ void Combobox::resetList(void) { - getDropList()->resetList(); + getDropList()->clearList(); } - -/************************************************************************* - Add the given ListboxItem to the list. -*************************************************************************/ -void Combobox::addItem(ListboxItem* item) +//----------------------------------------------------------------------------// +void Combobox::addItem(StandardItem* item) { - getDropList()->addItem(item); + getDropList()->addItem(item); } /************************************************************************* - Insert an item into the list box after a specified item already in - the list. + Insert an item into the list after a specified item already in the list. *************************************************************************/ -void Combobox::insertItem(ListboxItem* item, const ListboxItem* position) +void Combobox::insertItem(StandardItem* item, const StandardItem* position) { - getDropList()->insertItem(item, position); + getDropList()->insertItem(item, position); } /************************************************************************* - Removes the given item from the list box. + Removes the given item from the list. *************************************************************************/ -void Combobox::removeItem(const ListboxItem* item) +void Combobox::removeItem(const StandardItem* item) { - getDropList()->removeItem(item); + getDropList()->removeItem(item); } @@ -429,16 +428,17 @@ void Combobox::removeItem(const ListboxItem* item) *************************************************************************/ void Combobox::clearAllSelections(void) { - getDropList()->clearAllSelections(); + getDropList()->clearSelections(); } /************************************************************************* - Set whether the list should be sorted. + Sets how the list should be sorted. *************************************************************************/ void Combobox::setSortingEnabled(bool setting) { - getDropList()->setSortingEnabled(setting); + //TODO: migrate the sorting. + getDropList()->setSortMode(setting ? VSM_Ascending : VSM_None); } @@ -447,7 +447,8 @@ void Combobox::setSortingEnabled(bool setting) *************************************************************************/ void Combobox::setShowVertScrollbar(bool setting) { - getDropList()->setShowVertScrollbar(setting); + //TODO: migrate the scrollbar display mode + getDropList()->setVertScrollbarDisplayMode(setting ? SDM_Shown : SDM_WhenNeeded); } @@ -456,49 +457,50 @@ void Combobox::setShowVertScrollbar(bool setting) *************************************************************************/ void Combobox::setShowHorzScrollbar(bool setting) { - getDropList()->setShowHorzScrollbar(setting); + //TODO: migrate the scrollbar display mode + getDropList()->setHorzScrollbarDisplayMode(setting ? SDM_Shown : SDM_WhenNeeded); } /************************************************************************* - Set the select state of an attached ListboxItem. + Set the select state of an attached StandardItem. *************************************************************************/ -void Combobox::setItemSelectState(ListboxItem* item, bool state) +void Combobox::setItemSelectState(StandardItem* item, bool state) { - bool was_selected = (item && item->isSelected()); + bool was_selected = (item && getDropList()->isItemSelected(item)); - getDropList()->setItemSelectState(item, state); + getDropList()->setIndexSelectionState(item, state); itemSelectChangeTextUpdate(item, state, was_selected); } /************************************************************************* - Set the select state of an attached ListboxItem. + Set the select state of an attached StandardItem. *************************************************************************/ void Combobox::setItemSelectState(size_t item_index, bool state) { ComboDropList* droplist = getDropList(); - ListboxItem* item = (droplist->getItemCount() > item_index) ? - droplist->getListboxItemFromIndex(item_index) : + StandardItem* item = (droplist->getItemCount() > item_index) ? + droplist->getItemAtIndex(item_index) : 0; - bool was_selected = (item && item->isSelected()); + bool was_selected = (item && droplist->isItemSelected(item)); - droplist->setItemSelectState(item_index, state); + droplist->setIndexSelectionState(item_index, state); itemSelectChangeTextUpdate(item, state, was_selected); } /************************************************************************* - Causes the list box to update it's internal state after changes have - been made to one or more attached ListboxItem objects. + Causes the list widget to update it's internal state after changes have + been made to one or more attached StandardItem objects. *************************************************************************/ void Combobox::handleUpdatedListItemData(void) { - getDropList()->handleUpdatedItemData(); + getDropList()->invalidateView(false); } @@ -625,7 +627,7 @@ void Combobox::onHorzScrollbarModeChanged(WindowEventArgs& e) *************************************************************************/ void Combobox::onDropListDisplayed(WindowEventArgs& e) { - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); getPushButton()->setPushedState(true); fireEvent(EventDropListDisplayed, e, EventNamespace); } @@ -636,7 +638,7 @@ void Combobox::onDropListDisplayed(WindowEventArgs& e) *************************************************************************/ void Combobox::onDroplistRemoved(WindowEventArgs& e) { - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); getPushButton()->setPushedState(false); fireEvent(EventDropListRemoved, e, EventNamespace); } @@ -704,13 +706,13 @@ void Combobox::selectListItemWithEditboxText() { ComboDropList* const droplist = getDropList(); - if (ListboxItem* item = droplist->findItemWithText(getEditbox()->getText(), 0)) + if (StandardItem* item = droplist->findItemWithText(getEditbox()->getText(), 0)) { - droplist->setItemSelectState(item, true); - droplist->ensureItemIsVisible(item); + droplist->setIndexSelectionState(item, true); + droplist->ensureIndexIsVisible(item); } else - droplist->clearAllSelections(); + droplist->clearSelections(); } //----------------------------------------------------------------------------// @@ -755,7 +757,8 @@ void Combobox::updateAutoSizedDropList() bool Combobox::droplist_SelectionAcceptedHandler(const EventArgs& e) { // copy the text from the selected item into the edit box - ListboxItem* item = ((ComboDropList*)((WindowEventArgs&)e).window)->getFirstSelectedItem(); + StandardItem* item = static_cast( + static_cast(e).window)->getFirstSelectedItem(); if (item) { @@ -795,13 +798,13 @@ bool Combobox::droplist_HiddenHandler(const EventArgs&) /************************************************************************* - Handler for mouse button down events in editbox + Handler for cursor press & hold events in editbox *************************************************************************/ -bool Combobox::editbox_MouseDownHandler(const EventArgs& e) +bool Combobox::editbox_PointerPressHoldHandler(const EventArgs& e) { - // only interested in left button - if (((const MouseEventArgs&)e).button == LeftButton) - { + // only interested in left source + if (static_cast(e).source == CIS_Left) + { Editbox* editbox = getEditbox(); // if edit box is read-only, show list @@ -810,17 +813,17 @@ bool Combobox::editbox_MouseDownHandler(const EventArgs& e) ComboDropList* droplist = getDropList(); // if there is an item with the same text as the edit box, pre-select it - ListboxItem* item = droplist->findItemWithText(editbox->getText(), 0); + StandardItem* item = droplist->findItemWithText(editbox->getText(), 0); if (item) { - droplist->setItemSelectState(item, true); - droplist->ensureItemIsVisible(item); + droplist->setIndexSelectionState(item, true); + droplist->ensureIndexIsVisible(item); } // no matching item, so select nothing else { - droplist->clearAllSelections(); + droplist->clearSelections(); } showDropList(); @@ -838,7 +841,8 @@ bool Combobox::editbox_MouseDownHandler(const EventArgs& e) *************************************************************************/ bool Combobox::isVertScrollbarAlwaysShown(void) const { - return getDropList()->isVertScrollbarAlwaysShown(); + //TODO: migrate the combobox's sorting option to the new one + return getDropList()->getVertScrollbarDisplayMode() == SDM_Shown; } @@ -847,7 +851,8 @@ bool Combobox::isVertScrollbarAlwaysShown(void) const *************************************************************************/ bool Combobox::isHorzScrollbarAlwaysShown(void) const { - return getDropList()->isHorzScrollbarAlwaysShown(); + //TODO: migrate the combobox's sorting option to the new one + return getDropList()->getHorzScrollbarDisplayMode() == SDM_Shown; } @@ -857,7 +862,7 @@ bool Combobox::isHorzScrollbarAlwaysShown(void) const void Combobox::addComboboxProperties(void) { const String& propertyOrigin = WidgetTypeName; - + CEGUI_DEFINE_PROPERTY(Combobox, bool, "ReadOnly","Property to get/set the read-only setting for the Editbox. Value is either \"true\" or \"false\".", &Combobox::setReadOnly, &Combobox::isReadOnly, false @@ -883,20 +888,20 @@ void Combobox::addComboboxProperties(void) &Combobox::setMaxTextLength, &Combobox::getMaxTextLength, String().max_size() ); CEGUI_DEFINE_PROPERTY(Combobox, bool, - "SortList","Property to get/set the sort setting of the list box. Value is either \"true\" or \"false\".", + "SortList","Property to get/set the sort setting of the list widget. Value is either \"true\" or \"false\".", &Combobox::setSortingEnabled, &Combobox::isSortEnabled, false /* TODO: Inconsistency between setter, getter and property name */ ); CEGUI_DEFINE_PROPERTY(Combobox, bool, - "ForceVertScrollbar", "Property to get/set the 'always show' setting for the vertical scroll bar of the list box. Value is either \"true\" or \"false\".", + "ForceVertScrollbar", "Property to get/set the 'always show' setting for the vertical scroll bar of the list widget. Value is either \"true\" or \"false\".", &Combobox::setShowVertScrollbar, &Combobox::isVertScrollbarAlwaysShown, false /* TODO: Inconsistency between setter, getter and property name */ ); CEGUI_DEFINE_PROPERTY(Combobox, bool, - "ForceHorzScrollbar","Property to get/set the 'always show' setting for the horizontal scroll bar of the list box. Value is either \"true\" or \"false\".", + "ForceHorzScrollbar","Property to get/set the 'always show' setting for the horizontal scroll bar of the list widget. Value is either \"true\" or \"false\".", &Combobox::setShowHorzScrollbar, &Combobox::isHorzScrollbarAlwaysShown, false /* TODO: Inconsistency between setter, getter and property name */ ); CEGUI_DEFINE_PROPERTY(Combobox, bool, - "SingleClickMode","Property to get/set the 'single click mode' setting for the combo box. Value is either \"true\" or \"false\".", - &Combobox::setSingleClickEnabled, &Combobox::getSingleClickEnabled, false /* TODO: Inconsistency between setter, getter and property name */ + "SingleCursorActivationMode","Property to get/set the 'single activation mode' setting for the combo box. Value is either \"true\" or \"false\".", + &Combobox::setSingleCursorActivationEnabled, &Combobox::getSingleCursorActivationEnabled, false /* TODO: Inconsistency between setter, getter and property name */ ); CEGUI_DEFINE_PROPERTY(Combobox, bool, "AutoSizeListHeight", @@ -958,7 +963,7 @@ void Combobox::onSized(ElementEventArgs& e) /************************************************************************* Return operation mode for the combo box *************************************************************************/ -bool Combobox::getSingleClickEnabled(void) const +bool Combobox::getSingleCursorActivationEnabled(void) const { return d_singleClickOperation; } @@ -976,7 +981,7 @@ bool Combobox::isDropDownListVisible(void) const /************************************************************************* Set the operation mode for the combo box. *************************************************************************/ -void Combobox::setSingleClickEnabled(bool setting) +void Combobox::setSingleCursorActivationEnabled(bool setting) { d_singleClickOperation = setting; getDropList()->setAutoArmEnabled(setting); @@ -992,7 +997,7 @@ Editbox* Combobox::getEditbox() const } /************************************************************************ - Return a pointer to the PushButton component widget for this Combobox. + Return a cursor to the PushButton component widget for this Combobox. ************************************************************************/ PushButton* Combobox::getPushButton() const { @@ -1000,7 +1005,7 @@ PushButton* Combobox::getPushButton() const } /************************************************************************ - Return a pointer to the ComboDropList component widget for this + Return a cursor to the ComboDropList component widget for this Combobox. ************************************************************************/ ComboDropList* Combobox::getDropList() const @@ -1009,7 +1014,7 @@ ComboDropList* Combobox::getDropList() const } //----------------------------------------------------------------------------// -void Combobox::itemSelectChangeTextUpdate(const ListboxItem* const item, +void Combobox::itemSelectChangeTextUpdate(const StandardItem* const item, bool new_state, bool old_state) { if (!new_state) @@ -1025,7 +1030,7 @@ void Combobox::itemSelectChangeTextUpdate(const ListboxItem* const item, } //----------------------------------------------------------------------------// -bool Combobox::isHit(const Vector2f& /*position*/, +bool Combobox::isHit(const glm::vec2& /*position*/, const bool /*allow_disabled*/) const { return false; @@ -1118,7 +1123,7 @@ bool Combobox::editbox_TextChangedEventHandler(const EventArgs& e) } -bool Combobox::listbox_ListContentsChangedHandler(const EventArgs&) +bool Combobox::listwidget_ListContentsChangedHandler(const EventArgs&) { if (isDropDownListVisible()) updateAutoSizedDropList(); @@ -1130,7 +1135,7 @@ bool Combobox::listbox_ListContentsChangedHandler(const EventArgs&) } -bool Combobox::listbox_ListSelectionChangedHandler(const EventArgs&) +bool Combobox::listwidget_ListSelectionChangedHandler(const EventArgs&) { WindowEventArgs args(this); onListSelectionChanged(args); @@ -1139,7 +1144,7 @@ bool Combobox::listbox_ListSelectionChangedHandler(const EventArgs&) } -bool Combobox::listbox_SortModeChangedHandler(const EventArgs&) +bool Combobox::listwidget_SortModeChangedHandler(const EventArgs&) { WindowEventArgs args(this); onSortModeChanged(args); @@ -1148,7 +1153,7 @@ bool Combobox::listbox_SortModeChangedHandler(const EventArgs&) } -bool Combobox::listbox_VertScrollModeChangedHandler(const EventArgs&) +bool Combobox::listwidget_VertScrollModeChangedHandler(const EventArgs&) { WindowEventArgs args(this); onVertScrollbarModeChanged(args); @@ -1157,7 +1162,7 @@ bool Combobox::listbox_VertScrollModeChangedHandler(const EventArgs&) } -bool Combobox::listbox_HorzScrollModeChangedHandler(const EventArgs&) +bool Combobox::listwidget_HorzScrollModeChangedHandler(const EventArgs&) { WindowEventArgs args(this); onHorzScrollbarModeChanged(args); diff --git a/cegui/src/widgets/DefaultWindow.cpp b/cegui/src/widgets/DefaultWindow.cpp index 721d1b89a..c8787f8ff 100644 --- a/cegui/src/widgets/DefaultWindow.cpp +++ b/cegui/src/widgets/DefaultWindow.cpp @@ -25,7 +25,7 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/widgets/DefaultWindow.h" - +#include // Start of CEGUI namespace section namespace CEGUI @@ -42,75 +42,50 @@ const String DefaultWindow::WidgetTypeName("DefaultWindow"); DefaultWindow::DefaultWindow(const String& type, const String& name) : Window(type, name) { - USize sz(cegui_reldim(1.0f), cegui_reldim(1.0f)); - setMaxSize(sz); - setSize(sz); -} - -//----------------------------------------------------------------------------// -void DefaultWindow::onMouseMove(MouseEventArgs& e) -{ - // always call the base class handler - Window::onMouseMove(e); - updateMouseEventHandled(e); -} - -//----------------------------------------------------------------------------// -void DefaultWindow::onMouseWheel(MouseEventArgs& e) -{ - // always call the base class handler - Window::onMouseWheel(e); - updateMouseEventHandled(e); -} + const float maximum_float = std::numeric_limits::max(); + setMaxSize(USize(cegui_absdim(maximum_float), cegui_absdim(maximum_float))); -//----------------------------------------------------------------------------// -void DefaultWindow::onMouseButtonDown(MouseEventArgs& e) -{ - // always call the base class handler - Window::onMouseButtonDown(e); - updateMouseEventHandled(e); + setSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); } //----------------------------------------------------------------------------// -void DefaultWindow::onMouseButtonUp(MouseEventArgs& e) +void DefaultWindow::onCursorMove(CursorInputEventArgs& e) { // always call the base class handler - Window::onMouseButtonUp(e); - updateMouseEventHandled(e); + Window::onCursorMove(e); + updatePointerEventHandled(e); } //----------------------------------------------------------------------------// -void DefaultWindow::onMouseClicked(MouseEventArgs& e) +void DefaultWindow::onScroll(CursorInputEventArgs& e) { // always call the base class handler - Window::onMouseClicked(e); - // only adjust the handled state if event was directly injected - if (!getGUIContext().isMouseClickEventGenerationEnabled()) - updateMouseEventHandled(e); + Window::onScroll(e); + updatePointerEventHandled(e); } //----------------------------------------------------------------------------// -void DefaultWindow::onMouseDoubleClicked(MouseEventArgs& e) +void DefaultWindow::onCursorPressHold(CursorInputEventArgs& e) { // always call the base class handler - Window::onMouseDoubleClicked(e); - updateMouseEventHandled(e); + Window::onCursorPressHold(e); + updatePointerEventHandled(e); } //----------------------------------------------------------------------------// -void DefaultWindow::onMouseTripleClicked(MouseEventArgs& e) +void DefaultWindow::onCursorActivate(CursorInputEventArgs& e) { // always call the base class handler - Window::onMouseTripleClicked(e); - updateMouseEventHandled(e); + Window::onCursorActivate(e); + updatePointerEventHandled(e); } //----------------------------------------------------------------------------// -void DefaultWindow::updateMouseEventHandled(MouseEventArgs& e) const +void DefaultWindow::updatePointerEventHandled(CursorInputEventArgs& e) const { // by default, if we are a root window (no parent) with pass-though enabled - // we do /not/ mark mouse events as handled. - if (!d_parent && e.handled && d_mousePassThroughEnabled) + // we do /not/ mark cursor events as handled. + if (!d_parent && e.handled && d_cursorPassThroughEnabled) --e.handled; } @@ -119,12 +94,26 @@ bool DefaultWindow::moveToFront_impl(bool wasClicked) { const bool took_action = Window::moveToFront_impl(wasClicked); - if (!d_parent && d_mousePassThroughEnabled) + if (!d_parent && d_cursorPassThroughEnabled) return false; else return took_action; } +//----------------------------------------------------------------------------// +void DefaultWindow::onSemanticInputEvent(SemanticEventArgs& e) +{ + // always call the base class handler + Window::onSemanticInputEvent(e); +} + +//----------------------------------------------------------------------------// +bool DefaultWindow::canFocus() +{ + // cannot focus something that doesn't have an explicit visual appearance + return false; +} + //----------------------------------------------------------------------------// } // End of CEGUI namespace section diff --git a/cegui/src/widgets/DragContainer.cpp b/cegui/src/widgets/DragContainer.cpp index 2d5ed1ed9..4adf1fb00 100644 --- a/cegui/src/widgets/DragContainer.cpp +++ b/cegui/src/widgets/DragContainer.cpp @@ -43,7 +43,7 @@ namespace CEGUI const String DragContainer::EventDragPositionChanged("DragPositionChanged"); const String DragContainer::EventDragEnabledChanged("DragEnabledChanged"); const String DragContainer::EventDragAlphaChanged("DragAlphaChanged"); - const String DragContainer::EventDragMouseCursorChanged("DragMouseCursorChanged"); + const String DragContainer::EventDragCursorChanged("DragCursorChanged"); const String DragContainer::EventDragThresholdChanged("DragThresholdChanged"); const String DragContainer::EventDragDropTargetChanged("DragDropTargetChanged"); @@ -52,12 +52,12 @@ namespace CEGUI DragContainer::DragContainer(const String& type, const String& name) : Window(type, name), d_draggingEnabled(true), - d_leftMouseDown(false), + d_leftPointerHeld(false), d_dragging(false), d_dragThreshold(8.0f), d_dragAlpha(0.5f), d_dropTarget(0), - d_dragCursorImage(0), + d_dragIndicatorImage(0), d_dropflag(false), d_stickyMode(false), d_pickedUp(false), @@ -121,25 +121,25 @@ namespace CEGUI } } - const Image* DragContainer::getDragCursorImage(void) const + const Image* DragContainer::getDragIndicatorImage(void) const { - return d_dragCursorImage ? d_dragCursorImage : - getGUIContext().getMouseCursor().getDefaultImage(); + return d_dragIndicatorImage ? d_dragIndicatorImage : + getGUIContext().getCursor().getDefaultImage(); } - void DragContainer::setDragCursorImage(const Image* image) + void DragContainer::setDragIndicatorImage(const Image* image) { - if (d_dragCursorImage != image) + if (d_dragIndicatorImage != image) { - d_dragCursorImage = image; + d_dragIndicatorImage = image; WindowEventArgs args(this); - onDragMouseCursorChanged(args); + onDragCursorChanged(args); } } - void DragContainer::setDragCursorImage(const String& name) + void DragContainer::setDragIndicatorImage(const String& name) { - setDragCursorImage(&ImageManager::getSingleton().get(name)); + setDragIndicatorImage(&ImageManager::getSingleton().get(name)); } Window* DragContainer::getCurrentDropTarget(void) const @@ -155,35 +155,35 @@ namespace CEGUI "DraggingEnabled", "Property to get/set the state of the dragging enabled setting for the DragContainer. Value is either \"true\" or \"false\".", &DragContainer::setDraggingEnabled, &DragContainer::isDraggingEnabled, true ); - + CEGUI_DEFINE_PROPERTY(DragContainer, float, "DragAlpha", "Property to get/set the dragging alpha value. Value is a float.", &DragContainer::setDragAlpha, &DragContainer::getDragAlpha, 0.5f ); - + CEGUI_DEFINE_PROPERTY(DragContainer, float, "DragThreshold", "Property to get/set the dragging threshold value. Value is a float.", &DragContainer::setPixelDragThreshold, &DragContainer::getPixelDragThreshold, 8.0f /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(DragContainer, Image*, - "DragCursorImage", "Property to get/set the mouse cursor image used when dragging. Value should be \"set: image:\".", - &DragContainer::setDragCursorImage, &DragContainer::getDragCursorImage, 0 + "DragIndicatorImage", "Property to get/set the cursor image used when dragging. Value should be \"set: image:\".", + &DragContainer::setDragIndicatorImage, &DragContainer::getDragIndicatorImage, 0 ); - + CEGUI_DEFINE_PROPERTY(DragContainer, bool, "StickyMode", "Property to get/set the state of the sticky mode setting for the " "DragContainer. Value is either \"true\" or \"false\".", &DragContainer::setStickyModeEnabled, &DragContainer::isStickyModeEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(DragContainer, UVector2, "FixedDragOffset", "Property to get/set the state of the fixed dragging offset " "setting for the DragContainer. " "Value is a UVector2 property value.", &DragContainer::setFixedDragOffset, &DragContainer::getFixedDragOffset, UVector2::zero() ); - + CEGUI_DEFINE_PROPERTY(DragContainer, bool, "UseFixedDragOffset", "Property to get/set the setting that control whether the fixed " "dragging offset will be used. " @@ -192,13 +192,13 @@ namespace CEGUI ); } - bool DragContainer::isDraggingThresholdExceeded(const Vector2f& local_mouse) + bool DragContainer::isDraggingThresholdExceeded(const glm::vec2& local_cursor) { - // calculate amount mouse has moved. - float deltaX = fabsf(local_mouse.d_x - CoordConverter::asAbsolute(d_dragPoint.d_x, d_pixelSize.d_width)); - float deltaY = fabsf(local_mouse.d_y - CoordConverter::asAbsolute(d_dragPoint.d_y, d_pixelSize.d_height)); + // calculate amount cursor has moved. + const float deltaX = fabsf(local_cursor.x - CoordConverter::asAbsolute(d_dragPoint.d_x, d_pixelSize.d_width)); + const float deltaY = fabsf(local_cursor.y - CoordConverter::asAbsolute(d_dragPoint.d_y, d_pixelSize.d_height)); - // see if mouse has moved far enough to start dragging operation + // see if cursor has moved far enough to start dragging operation return (deltaX > d_dragThreshold || deltaY > d_dragThreshold) ? true : false; } @@ -219,14 +219,14 @@ namespace CEGUI notifyScreenAreaChanged(); // Now drag mode is set, change cursor as required - updateActiveMouseCursor(); + updateActiveCursor(); } } - void DragContainer::doDragging(const Vector2f& local_mouse) + void DragContainer::doDragging(const glm::vec2& local_cursor) { // calculate amount to move - UVector2 offset(cegui_absdim(local_mouse.d_x), cegui_absdim(local_mouse.d_y)); + UVector2 offset(cegui_absdim(local_cursor.x), cegui_absdim(local_cursor.y)); offset -= (d_usingFixedDragOffset) ? d_fixedDragOffset : d_dragPoint; // set new position setPosition(getPosition() + offset); @@ -236,40 +236,39 @@ namespace CEGUI onDragPositionChanged(args); } - void DragContainer::updateActiveMouseCursor(void) const + void DragContainer::updateActiveCursor(void) const { - getGUIContext().getMouseCursor(). - setImage(d_dragging ? getDragCursorImage() : getMouseCursor()); + getGUIContext().getCursor(). + setImage(d_dragging ? getDragIndicatorImage() : getCursor()); } - void DragContainer::onMouseButtonDown(MouseEventArgs& e) + void DragContainer::onCursorPressHold(CursorInputEventArgs& e) { - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { // ensure all inputs come to us for now if (captureInput()) { - // get position of mouse as co-ordinates local to this window. - Vector2f localPos = CoordConverter::screenToWindow(*this, e.position); + // get position of cursor as co-ordinates local to this window. + const glm::vec2 localPos = CoordConverter::screenToWindow(*this, e.position); // store drag point for possible sizing or moving operation. - d_dragPoint.d_x = cegui_absdim(localPos.d_x); - d_dragPoint.d_y = cegui_absdim(localPos.d_y); - d_leftMouseDown = true; + d_dragPoint.d_x = cegui_absdim(localPos.x); + d_dragPoint.d_y = cegui_absdim(localPos.y); + d_leftPointerHeld = true; } ++e.handled; } - } - void DragContainer::onMouseButtonUp(MouseEventArgs& e) + void DragContainer::onCursorActivate(CursorInputEventArgs& e) { - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { if (d_dragging) { @@ -296,25 +295,25 @@ namespace CEGUI } } - void DragContainer::onMouseMove(MouseEventArgs& e) + void DragContainer::onCursorMove(CursorInputEventArgs& e) { - Window::onMouseMove(e); + Window::onCursorMove(e); - // get position of mouse as co-ordinates local to this window. - Vector2f localMousePos = CoordConverter::screenToWindow(*this, e.position); + // get position of cursor as co-ordinates local to this window. + const glm::vec2 localPointerPos = CoordConverter::screenToWindow(*this, e.position); // handle dragging if (d_dragging) { - doDragging(localMousePos); - } + doDragging(localPointerPos); + } // not dragging else { - // if mouse button is down (but we're not yet being dragged) - if (d_leftMouseDown) + // if cursor is held pressed (but we're not yet being dragged) + if (d_leftPointerHeld) { - if (isDraggingThresholdExceeded(localMousePos)) + if (isDraggingThresholdExceeded(localPointerPos)) { // Trigger the event WindowEventArgs args(this); @@ -339,11 +338,11 @@ namespace CEGUI notifyScreenAreaChanged(); - // restore normal mouse cursor - updateActiveMouseCursor(); + // restore normal cursor + updateActiveCursor(); } - d_leftMouseDown = false; + d_leftPointerHeld = false; d_dropTarget = 0; ++e.handled; @@ -414,13 +413,13 @@ namespace CEGUI if (0 != (root = getGUIContext().getRootWindow())) { // this hack with the 'enabled' state is so that getChildAtPosition - // returns something useful instead of a pointer back to 'this'. + // returns something useful instead of a cursor back to 'this'. // This hack is only acceptable because I am CrazyEddie! bool wasEnabled = d_enabled; d_enabled = false; - // find out which child of root window has the mouse in it + // find out which child of root window has the cursor in it Window* eventWindow = root->getTargetChildAtPosition( - getGUIContext().getMouseCursor().getPosition()); + getGUIContext().getCursor().getPosition()); d_enabled = wasEnabled; // use root itself if no child was hit @@ -429,7 +428,7 @@ namespace CEGUI eventWindow = root; } - // if the window with the mouse is different to current drop target + // if the window with the cursor is different to current drop target if (eventWindow != d_dropTarget) { DragDropEventArgs args(eventWindow); @@ -461,11 +460,11 @@ namespace CEGUI } } - void DragContainer::onDragMouseCursorChanged(WindowEventArgs& e) + void DragContainer::onDragCursorChanged(WindowEventArgs& e) { - fireEvent(EventDragMouseCursorChanged, e, EventNamespace); + fireEvent(EventDragCursorChanged, e, EventNamespace); - updateActiveMouseCursor(); + updateActiveCursor(); } void DragContainer::onDragThresholdChanged(WindowEventArgs& e) @@ -507,8 +506,8 @@ void DragContainer::getRenderingContext_impl(RenderingContext& ctx) const // ensure root window is only used as owner if it really is. ctx.owner = root->getRenderingSurface() == ctx.surface ? root : 0; // ensure use of correct offset for the surface we're targetting - ctx.offset = ctx.owner ? ctx.owner->getOuterRectClipper().getPosition() : - Vector2f(0, 0); + ctx.offset = ctx.owner ? ctx.owner->getOuterRectClipper().getPositionGLM() : + glm::vec2(0, 0); // draw to overlay queue ctx.queue = RQ_OVERLAY; } @@ -553,10 +552,10 @@ bool DragContainer::pickUp(const bool force_sticky /*= false*/) // initialise the dragging state initialiseDragging(); - // get position of mouse as co-ordinates local to this window. - const Vector2f localMousePos(CoordConverter::screenToWindow(*this, - getGUIContext().getMouseCursor().getPosition())); - doDragging(localMousePos); + // get position of cursor as co-ordinates local to this window. + const glm::vec2 localPointerPos(CoordConverter::screenToWindow(*this, + getGUIContext().getCursor().getPosition())); + doDragging(localPointerPos); d_pickedUp = true; } diff --git a/cegui/src/widgets/Editbox.cpp b/cegui/src/widgets/Editbox.cpp index 4ef9b863a..b1db7aa98 100644 --- a/cegui/src/widgets/Editbox.cpp +++ b/cegui/src/widgets/Editbox.cpp @@ -32,6 +32,8 @@ #include "CEGUI/Font.h" #include "CEGUI/Clipboard.h" #include "CEGUI/BidiVisualMapping.h" +#include "CEGUI/UndoHandler.h" + #include // Start of CEGUI namespace section @@ -86,6 +88,8 @@ Editbox::Editbox(const String& type, const String& name) : // set copy of validation string to ".*" so getter returns something valid. else d_validationString = ".*"; + + d_undoHandler = new UndoHandler(this); } //----------------------------------------------------------------------------// @@ -93,6 +97,8 @@ Editbox::~Editbox(void) { if (d_weOwnValidator && d_validator) System::getSingleton().destroyRegexMatcher(d_validator); + + delete d_undoHandler; } //----------------------------------------------------------------------------// @@ -159,7 +165,7 @@ void Editbox::setValidationString(const String& validation_string) if (!d_validator) CEGUI_THROW(InvalidRequestException( - "Unable to set validation string on Editbox '" + getNamePath() + + "Unable to set validation string on Editbox '" + getNamePath() + "' because it does not currently have a RegexMatcher validator.")); d_validationString = validation_string; @@ -303,6 +309,12 @@ void Editbox::eraseSelectedText(bool modify_text) if (modify_text) { String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_DELETE; + undo.d_startIdx = getSelectionStartIndex(); + undo.d_text = newText.substr(getSelectionStartIndex(), getSelectionLength()); + d_undoHandler->addUndoHistory(undo); + newText.erase(getSelectionStartIndex(), getSelectionLength()); setText(newText); @@ -344,10 +356,10 @@ bool Editbox::performCopy(Clipboard& clipboard) { if (getSelectionLength() == 0) return false; - + const String selectedText = getText().substr( getSelectionStartIndex(), getSelectionLength()); - + clipboard.setText(selectedText); return true; } @@ -357,10 +369,10 @@ bool Editbox::performCut(Clipboard& clipboard) { if (isReadOnly()) return false; - + if (!performCopy(clipboard)) return false; - + handleDelete(); return true; } @@ -391,34 +403,48 @@ bool Editbox::performPaste(Clipboard& clipboard) { if (isReadOnly()) return false; - + String clipboardText = clipboard.getText(); - + if (clipboardText.empty()) return false; - + // backup current text String tmp(getText()); + + UndoHandler::UndoAction undoSelection; + undoSelection.d_type = UndoHandler::UAT_DELETE; + undoSelection.d_startIdx = getSelectionStartIndex(); + undoSelection.d_text = tmp.substr(getSelectionStartIndex(), getSelectionLength()); + tmp.erase(getSelectionStartIndex(), getSelectionLength()); - + // if there is room if (tmp.length() < d_maxTextLen) { + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_INSERT; + undo.d_startIdx = getCaretIndex(); + undo.d_text = clipboardText; + tmp.insert(getSelectionStartIndex(), clipboardText); - + if (handleValidityChangeForString(tmp)) { // erase selection using mode that does not modify getText() // (we just want to update state) eraseSelectedText(false); - + // advance caret (done first so we can "do stuff" in event // handlers!) d_caretPos += clipboardText.length(); - + // set text to the newly modified string setText(tmp); - + d_undoHandler->addUndoHistory(undo); + if (getSelectionLength() > 0) + d_undoHandler->addUndoHistory(undoSelection); + return true; } } @@ -427,17 +453,17 @@ bool Editbox::performPaste(Clipboard& clipboard) } //----------------------------------------------------------------------------// -void Editbox::onMouseButtonDown(MouseEventArgs& e) +void Editbox::onCursorPressHold(CursorInputEventArgs& e) { // base class handling - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { // grab inputs if (captureInput()) { - // handle mouse down + // handle cursor press clearSelection(); d_dragging = true; d_dragAnchorIdx = getTextIndexFromPosition(e.position); @@ -451,75 +477,26 @@ void Editbox::onMouseButtonDown(MouseEventArgs& e) ++e.handled; } - } //----------------------------------------------------------------------------// -void Editbox::onMouseButtonUp(MouseEventArgs& e) +void Editbox::onCursorActivate(CursorInputEventArgs& e) { // base class processing - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { releaseInput(); ++e.handled; } - -} - -//----------------------------------------------------------------------------// -void Editbox::onMouseDoubleClicked(MouseEventArgs& e) -{ - // base class processing - Window::onMouseDoubleClicked(e); - - if (e.button == LeftButton) - { - // if masked, set up to select all - if (isTextMasked()) - { - d_dragAnchorIdx = 0; - setCaretIndex(getText().length()); - } - // not masked, so select the word that was double-clicked. - else - { - d_dragAnchorIdx = TextUtils::getWordStartIdx(getText(), - (d_caretPos == getText().length()) ? d_caretPos : - d_caretPos + 1); - d_caretPos = TextUtils::getNextWordStartIdx(getText(), d_caretPos); - } - - // perform actual selection operation. - setSelection(d_dragAnchorIdx, d_caretPos); - - ++e.handled; - } - } //----------------------------------------------------------------------------// -void Editbox::onMouseTripleClicked(MouseEventArgs& e) +void Editbox::onCursorMove(CursorInputEventArgs& e) { // base class processing - Window::onMouseTripleClicked(e); - - if (e.button == LeftButton) - { - d_dragAnchorIdx = 0; - setCaretIndex(getText().length()); - setSelection(d_dragAnchorIdx, d_caretPos); - ++e.handled; - } - -} - -//----------------------------------------------------------------------------// -void Editbox::onMouseMove(MouseEventArgs& e) -{ - // base class processing - Window::onMouseMove(e); + Window::onCursorMove(e); if (d_dragging) { @@ -548,11 +525,11 @@ void Editbox::onCaptureLost(WindowEventArgs& e) } //----------------------------------------------------------------------------// -void Editbox::onCharacter(KeyEventArgs& e) +void Editbox::onCharacter(TextEventArgs& e) { - // NB: We are not calling the base class handler here because it propogates - // inputs back up the window hierarchy, whereas, as a consumer of key - // events, we want such propogation to cease with us regardless of whether + // NB: We are not calling the base class handler here because it propagates + // inputs back up the window hierarchy, whereas, as a consumer of input + // events, we want such propagation to cease with us regardless of whether // we actually handle the event. // fire event. @@ -560,16 +537,27 @@ void Editbox::onCharacter(KeyEventArgs& e) // only need to take notice if we have focus if (e.handled == 0 && hasInputFocus() && !isReadOnly() && - getFont()->isCodepointAvailable(e.codepoint)) + getFont()->isCodepointAvailable(e.character)) { // backup current text String tmp(getText()); + + UndoHandler::UndoAction undoSelection; + undoSelection.d_type = UndoHandler::UAT_DELETE; + undoSelection.d_startIdx = getSelectionStartIndex(); + undoSelection.d_text = tmp.substr(getSelectionStartIndex(), getSelectionLength()); + tmp.erase(getSelectionStartIndex(), getSelectionLength()); // if there is room if (tmp.length() < d_maxTextLen) { - tmp.insert(getSelectionStartIndex(), 1, e.codepoint); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_INSERT; + undo.d_startIdx = getSelectionStartIndex(); + undo.d_text = e.character; + + tmp.insert(getSelectionStartIndex(), 1, e.character); if (handleValidityChangeForString(tmp)) { @@ -586,6 +574,9 @@ void Editbox::onCharacter(KeyEventArgs& e) // char was accepted into the Editbox - mark event as handled. ++e.handled; + d_undoHandler->addUndoHistory(undo); + if (getSelectionLength() > 0) + d_undoHandler->addUndoHistory(undoSelection); } } else @@ -600,76 +591,6 @@ void Editbox::onCharacter(KeyEventArgs& e) // event was (possibly) not handled } -//----------------------------------------------------------------------------// -void Editbox::onKeyDown(KeyEventArgs& e) -{ - // fire event. - fireEvent(EventKeyDown, e, Window::EventNamespace); - - if (e.handled == 0 && hasInputFocus()) - { - if (isReadOnly()) - { - Window::onKeyDown(e); - return; - } - - WindowEventArgs args(this); - switch (e.scancode) - { - case Key::LeftShift: - case Key::RightShift: - if (getSelectionLength() == 0) - d_dragAnchorIdx = d_caretPos; - break; - - case Key::Backspace: - handleBackspace(); - break; - - case Key::Delete: - handleDelete(); - break; - - case Key::Tab: - case Key::Return: - case Key::NumpadEnter: - // Fire 'input accepted' event - onTextAcceptedEvent(args); - break; - - case Key::ArrowLeft: - if (e.sysKeys & Control) - handleWordLeft(e.sysKeys); - else - handleCharLeft(e.sysKeys); - break; - - case Key::ArrowRight: - if (e.sysKeys & Control) - handleWordRight(e.sysKeys); - else - handleCharRight(e.sysKeys); - break; - - case Key::Home: - handleHome(e.sysKeys); - break; - - case Key::End: - handleEnd(e.sysKeys); - break; - - default: - Window::onKeyDown(e); - return; - } - - ++e.handled; - } - -} - //----------------------------------------------------------------------------// void Editbox::handleBackspace(void) { @@ -679,6 +600,11 @@ void Editbox::handleBackspace(void) if (getSelectionLength() != 0) { + UndoHandler::UndoAction undoSelection; + undoSelection.d_type = UndoHandler::UAT_DELETE; + undoSelection.d_startIdx = getSelectionStartIndex(); + undoSelection.d_text = tmp.substr(getSelectionStartIndex(), getSelectionLength()); + tmp.erase(getSelectionStartIndex(), getSelectionLength()); if (handleValidityChangeForString(tmp)) @@ -689,10 +615,16 @@ void Editbox::handleBackspace(void) // set text to the newly modified string setText(tmp); + d_undoHandler->addUndoHistory(undoSelection); } } else if (getCaretIndex() > 0) { + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_DELETE; + undo.d_startIdx = d_caretPos - 1; + undo.d_text = tmp.substr(d_caretPos - 1, 1); + tmp.erase(d_caretPos - 1, 1); if (handleValidityChangeForString(tmp)) @@ -701,6 +633,7 @@ void Editbox::handleBackspace(void) // set text to the newly modified string setText(tmp); + d_undoHandler->addUndoHistory(undo); } } @@ -717,6 +650,11 @@ void Editbox::handleDelete(void) if (getSelectionLength() != 0) { + UndoHandler::UndoAction undoSelection; + undoSelection.d_type = UndoHandler::UAT_DELETE; + undoSelection.d_startIdx = getSelectionStartIndex(); + undoSelection.d_text = tmp.substr(getSelectionStartIndex(), getSelectionLength()); + tmp.erase(getSelectionStartIndex(), getSelectionLength()); if (handleValidityChangeForString(tmp)) @@ -727,16 +665,23 @@ void Editbox::handleDelete(void) // set text to the newly modified string setText(tmp); + d_undoHandler->addUndoHistory(undoSelection); } } else if (getCaretIndex() < tmp.length()) { + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_DELETE; + undo.d_startIdx = d_caretPos; + undo.d_text = tmp.substr(d_caretPos, 1); + tmp.erase(d_caretPos, 1); if (handleValidityChangeForString(tmp)) { // set text to the newly modified string setText(tmp); + d_undoHandler->addUndoHistory(undo); } } @@ -745,72 +690,72 @@ void Editbox::handleDelete(void) } //----------------------------------------------------------------------------// -void Editbox::handleCharLeft(uint sysKeys) +void Editbox::handleCharLeft(bool select) { if (d_caretPos > 0) setCaretIndex(d_caretPos - 1); - if (sysKeys & Shift) + if (select) setSelection(d_caretPos, d_dragAnchorIdx); else clearSelection(); } //----------------------------------------------------------------------------// -void Editbox::handleWordLeft(uint sysKeys) +void Editbox::handleWordLeft(bool select) { if (d_caretPos > 0) setCaretIndex(TextUtils::getWordStartIdx(getText(), d_caretPos)); - if (sysKeys & Shift) + if (select) setSelection(d_caretPos, d_dragAnchorIdx); else clearSelection(); } //----------------------------------------------------------------------------// -void Editbox::handleCharRight(uint sysKeys) +void Editbox::handleCharRight(bool select) { if (d_caretPos < getText().length()) setCaretIndex(d_caretPos + 1); - if (sysKeys & Shift) + if (select) setSelection(d_caretPos, d_dragAnchorIdx); else clearSelection(); } //----------------------------------------------------------------------------// -void Editbox::handleWordRight(uint sysKeys) +void Editbox::handleWordRight(bool select) { if (d_caretPos < getText().length()) setCaretIndex(TextUtils::getNextWordStartIdx(getText(), d_caretPos)); - if (sysKeys & Shift) + if (select) setSelection(d_caretPos, d_dragAnchorIdx); else clearSelection(); } //----------------------------------------------------------------------------// -void Editbox::handleHome(uint sysKeys) +void Editbox::handleHome(bool select) { if (d_caretPos > 0) setCaretIndex(0); - if (sysKeys & Shift) + if (select) setSelection(d_caretPos, d_dragAnchorIdx); else clearSelection(); } //----------------------------------------------------------------------------// -void Editbox::handleEnd(uint sysKeys) +void Editbox::handleEnd(bool select) { if (d_caretPos < getText().length()) setCaretIndex(getText().length()); - if (sysKeys & Shift) + if (select) setSelection(d_caretPos, d_dragAnchorIdx); else clearSelection(); @@ -910,43 +855,43 @@ void Editbox::onTextChanged(WindowEventArgs& e) void Editbox::addEditboxProperties(void) { const String& propertyOrigin = WidgetTypeName; - + CEGUI_DEFINE_PROPERTY(Editbox, bool, "ReadOnly","Property to get/set the read-only setting for the Editbox. Value is either \"true\" or \"false\".", &Editbox::setReadOnly, &Editbox::isReadOnly, false ); - + CEGUI_DEFINE_PROPERTY(Editbox, bool, "MaskText","Property to get/set the mask text setting for the Editbox. Value is either \"true\" or \"false\".", &Editbox::setTextMasked, &Editbox::isTextMasked, false /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(Editbox, String::value_type, "MaskCodepoint","Property to get/set the utf32 codepoint value used for masking text. " "Value is either \"[uint]\" (number = codepoint) if CEGUI is compiled with utf32 string or \"[char]\" (just the symbol) if CEGUI is compiled with std::string.", &Editbox::setMaskCodePoint, &Editbox::getMaskCodePoint, 42 ); - + CEGUI_DEFINE_PROPERTY(Editbox, String, "ValidationString","Property to get/set the validation string Editbox. Value is a text string.", &Editbox::setValidationString, &Editbox::getValidationString, ".*" ); - + CEGUI_DEFINE_PROPERTY(Editbox, size_t, "CaretIndex","Property to get/set the current caret index. Value is \"[uint]\".", &Editbox::setCaretIndex, &Editbox::getCaretIndex, 0 ); - + CEGUI_DEFINE_PROPERTY(Editbox, size_t, "SelectionStart","Property to get/set the zero based index of the selection start position within the text. Value is \"[uint]\".", &Editbox::setSelectionStart, &Editbox::getSelectionStartIndex, 0 /* TODO: getter inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(Editbox, size_t, "SelectionLength","Property to get/set the length of the selection (as a count of the number of code points selected). Value is \"[uint]\".", &Editbox::setSelectionLength, &Editbox::getSelectionLength, 0 ); - + CEGUI_DEFINE_PROPERTY(Editbox, size_t, "MaxTextLength","Property to get/set the the maximum allowed text length (as a count of code points). Value is \"[uint]\".", &Editbox::setMaxTextLength, &Editbox::getMaxTextLength, String().max_size() @@ -954,7 +899,7 @@ void Editbox::addEditboxProperties(void) } //----------------------------------------------------------------------------// -size_t Editbox::getTextIndexFromPosition(const Vector2f& pt) const +size_t Editbox::getTextIndexFromPosition(const glm::vec2& pt) const { if (d_windowRenderer != 0) { @@ -981,5 +926,160 @@ size_t Editbox::getCaretIndex(void) const } //----------------------------------------------------------------------------// +void Editbox::onSemanticInputEvent(SemanticEventArgs& e) +{ + if (isDisabled()) + return; + + if (e.d_semanticValue == SV_SelectAll && + e.d_payload.source == CIS_Left) + { + d_dragAnchorIdx = 0; + setCaretIndex(getText().length()); + setSelection(d_dragAnchorIdx, d_caretPos); + ++e.handled; + } + else if (e.d_semanticValue == SV_SelectWord && + e.d_payload.source == CIS_Left) + { + // if masked, set up to select all + if (isTextMasked()) + { + d_dragAnchorIdx = 0; + setCaretIndex(getText().length()); + } + // not masked, so select the word that was double-clicked. + else + { + d_dragAnchorIdx = TextUtils::getWordStartIdx(getText(), + (d_caretPos == getText().length()) ? d_caretPos : + d_caretPos + 1); + d_caretPos = TextUtils::getNextWordStartIdx(getText(), d_caretPos); + } + + // perform actual selection operation. + setSelection(d_dragAnchorIdx, d_caretPos); + + ++e.handled; + } + + // TODO: migrate common logic with MultiLineEditbox in a base class + if (e.handled == 0 && hasInputFocus()) + { + if (isReadOnly()) + { + Window::onSemanticInputEvent(e); + return; + } + + if (getSelectionLength() == 0 && isSelectionSemanticValue(e.d_semanticValue)) + d_dragAnchorIdx = d_caretPos; + + WindowEventArgs args(this); + switch (e.d_semanticValue) + { + case SV_DeletePreviousCharacter: + handleBackspace(); + break; + + case SV_DeleteNextCharacter: + handleDelete(); + break; + + case SV_Confirm: + // Fire 'input accepted' event + onTextAcceptedEvent(args); + break; + + case SV_GoToPreviousCharacter: + handleCharLeft(false); + break; + + case SV_GoToNextCharacter: + handleCharRight(false); + break; + + case SV_SelectPreviousCharacter: + handleCharLeft(true); + break; + + case SV_SelectNextCharacter: + handleCharRight(true); + break; + + case SV_GoToPreviousWord: + handleWordLeft(false); + break; + + case SV_GoToNextWord: + handleWordRight(false); + break; + + case SV_SelectPreviousWord: + handleWordLeft(true); + break; + + case SV_SelectNextWord: + handleWordRight(true); + break; + + case SV_GoToStartOfLine: + handleHome(false); + break; + + case SV_GoToEndOfLine: + handleEnd(false); + break; + + case SV_SelectToStartOfLine: + handleHome(true); + break; + + case SV_SelectToEndOfLine: + handleEnd(true); + break; + + default: + Window::onSemanticInputEvent(e); + return; + } + + ++e.handled; + } +} + +//----------------------------------------------------------------------------// + +/************************************************************************* + Undo/redo +*************************************************************************/ +bool Editbox::performUndo() +{ + bool result = false; + if (!isReadOnly()) + { + clearSelection(); + result = d_undoHandler->undo(d_caretPos); + WindowEventArgs args(this); + onTextChanged(args); + } + + return result; +} + +//----------------------------------------------------------------------------// +bool Editbox::performRedo() +{ + bool result = false; + if (!isReadOnly()) + { + clearSelection(); + result = d_undoHandler->redo(d_caretPos); + WindowEventArgs args(this); + onTextChanged(args); + } + + return result; +} } // End of CEGUI namespace section diff --git a/cegui/src/widgets/FrameWindow.cpp b/cegui/src/widgets/FrameWindow.cpp index b3aa79c56..3bb7858da 100644 --- a/cegui/src/widgets/FrameWindow.cpp +++ b/cegui/src/widgets/FrameWindow.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 13/4/2004 author: Paul D Turner - + purpose: Implementation of FrameWindow base class *************************************************************************/ /*************************************************************************** @@ -29,7 +29,7 @@ #include "CEGUI/widgets/FrameWindow.h" #include "CEGUI/widgets/Titlebar.h" #include "CEGUI/widgets/PushButton.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/WindowManager.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageManager.h" @@ -138,7 +138,7 @@ bool FrameWindow::isCloseButtonEnabled(void) const /************************************************************************* - Enables or disables sizing for this window. + Enables or disables sizing for this window. *************************************************************************/ void FrameWindow::setSizingEnabled(bool setting) { @@ -147,7 +147,7 @@ void FrameWindow::setSizingEnabled(bool setting) /************************************************************************* - Enables or disables the frame for this window. + Enables or disables the frame for this window. *************************************************************************/ void FrameWindow::setFrameEnabled(bool setting) { @@ -157,7 +157,7 @@ void FrameWindow::setFrameEnabled(bool setting) /************************************************************************* - Enables or disables the title bar for the frame window. + Enables or disables the title bar for the frame window. *************************************************************************/ void FrameWindow::setTitleBarEnabled(bool setting) { @@ -168,7 +168,7 @@ void FrameWindow::setTitleBarEnabled(bool setting) /************************************************************************* - Enables or disables the close button for the frame window. + Enables or disables the close button for the frame window. *************************************************************************/ void FrameWindow::setCloseButtonEnabled(bool setting) { @@ -179,7 +179,7 @@ void FrameWindow::setCloseButtonEnabled(bool setting) /************************************************************************* - Enables or disables roll-up (shading) for this window. + Enables or disables roll-up (shading) for this window. *************************************************************************/ void FrameWindow::setRollupEnabled(bool setting) { @@ -194,19 +194,19 @@ void FrameWindow::setRollupEnabled(bool setting) /************************************************************************* Toggles the state of the window between rolled-up (shaded) and normal - sizes. This requires roll-up to be enabled. + sizes. This requires roll-up to be enabled. *************************************************************************/ void FrameWindow::toggleRollup(void) { if (isRollupEnabled()) { d_rolledup ^= true; - + // event notification. WindowEventArgs args(this); onRollupToggled(args); - getGUIContext().updateWindowContainingMouse(); + getGUIContext().updateWindowContainingCursor(); } } @@ -220,23 +220,23 @@ void FrameWindow::setRolledup(bool val) } /************************************************************************* - Move the window by the pixel offsets specified in 'offset'. + Move the window by the pixel offsets specified in 'offset'. *************************************************************************/ -void FrameWindow::offsetPixelPosition(const Vector2f& offset) +void FrameWindow::offsetPixelPosition(const glm::vec2& offset) { - UVector2 uOffset(cegui_absdim(/*PixelAligned(*/offset.d_x/*)*/), - cegui_absdim(/*PixelAligned(*/offset.d_y/*)*/)); + UVector2 uOffset(cegui_absdim(/*PixelAligned(*/offset.x/*)*/), + cegui_absdim(/*PixelAligned(*/offset.y/*)*/)); setPosition(d_area.getPosition() + uOffset); } -/************************************************************************* +/************************************************************************* check local pixel co-ordinate point 'pt' and return one of the SizingLocation enumerated values depending where the point falls on the sizing border. *************************************************************************/ -FrameWindow::SizingLocation FrameWindow::getSizingBorderAtPoint(const Vector2f& pt) const +FrameWindow::SizingLocation FrameWindow::getSizingBorderAtPoint(const glm::vec2& pt) const { Rectf frame(getSizingRect()); @@ -253,10 +253,10 @@ FrameWindow::SizingLocation FrameWindow::getSizingBorderAtPoint(const Vector2f& frame.d_max.d_y -= d_borderSize; // detect which edges we are on - bool top = (pt.d_y < frame.d_min.d_y); - bool bottom = (pt.d_y >= frame.d_max.d_y); - bool left = (pt.d_x < frame.d_min.d_x); - bool right = (pt.d_x >= frame.d_max.d_x); + bool top = (pt.y < frame.d_min.d_y); + bool bottom = (pt.y >= frame.d_max.d_y); + bool left = (pt.x < frame.d_min.d_x); + bool right = (pt.x >= frame.d_max.d_x); // return appropriate 'SizingLocation' value if (top && left) @@ -291,19 +291,17 @@ FrameWindow::SizingLocation FrameWindow::getSizingBorderAtPoint(const Vector2f& { return SizingRight; } - } - } - // deafult: None. + // default: None. return SizingNone; } /************************************************************************* move the window's left edge by 'delta'. The rest of the window - does not move, thus this changes the size of the Window. + does not move, thus this changes the size of the Window. *************************************************************************/ bool FrameWindow::moveLeftEdge(float delta, URect& out_area) { @@ -381,8 +379,8 @@ bool FrameWindow::moveRightEdge(float delta, URect& out_area) out_area.d_min.d_x.d_offset += adjustment * 0.5f; } - // move the dragging point so mouse remains 'attached' to edge of window - d_dragPoint.d_x += adjustment; + // move the dragging point so cursor remains 'attached' to edge of window + d_dragPoint.x += adjustment; return d_horizontalAlignment == HA_RIGHT; } @@ -432,7 +430,7 @@ bool FrameWindow::moveTopEdge(float delta, URect& out_area) /************************************************************************* move the window's bottom edge by 'delta'. The rest of the window - does not move, thus this changes the size of the Window. + does not move, thus this changes the size of the Window. *************************************************************************/ bool FrameWindow::moveBottomEdge(float delta, URect& out_area) { @@ -469,8 +467,8 @@ bool FrameWindow::moveBottomEdge(float delta, URect& out_area) out_area.d_min.d_y.d_offset += adjustment * 0.5f; } - // move the dragging point so mouse remains 'attached' to edge of window - d_dragPoint.d_y += adjustment; + // move the dragging point so cursor remains 'attached' to edge of window + d_dragPoint.y += adjustment; return d_verticalAlignment == VA_BOTTOM; } @@ -489,43 +487,42 @@ bool FrameWindow::closeClickHandler(const EventArgs&) /************************************************************************* - Set the appropriate mouse cursor for the given window-relative pixel - point. + Set the appropriate cursor for the given window-relative pixel + point. *************************************************************************/ -void FrameWindow::setCursorForPoint(const Vector2f& pt) const +void FrameWindow::setIndicatorForPoint(const glm::vec2& pt) const { switch(getSizingBorderAtPoint(pt)) { case SizingTop: case SizingBottom: getGUIContext(). - getMouseCursor().setImage(d_nsSizingCursor); + getCursor().setImage(d_nsSizingCursor); break; case SizingLeft: case SizingRight: getGUIContext(). - getMouseCursor().setImage(d_ewSizingCursor); + getCursor().setImage(d_ewSizingCursor); break; case SizingTopLeft: case SizingBottomRight: getGUIContext(). - getMouseCursor().setImage(d_nwseSizingCursor); + getCursor().setImage(d_nwseSizingCursor); break; case SizingTopRight: case SizingBottomLeft: getGUIContext(). - getMouseCursor().setImage(d_neswSizingCursor); + getCursor().setImage(d_neswSizingCursor); break; default: getGUIContext(). - getMouseCursor().setImage(getMouseCursor()); + getCursor().setImage(getCursor()); break; } - } @@ -545,7 +542,7 @@ void FrameWindow::onRollupToggled(WindowEventArgs& e) /************************************************************************* - Event generated internally whenever the close button is clicked. + Event generated internally whenever the close button is clicked. *************************************************************************/ void FrameWindow::onCloseClicked(WindowEventArgs& e) { @@ -554,30 +551,30 @@ void FrameWindow::onCloseClicked(WindowEventArgs& e) /************************************************************************* - Handler for mouse move events + Handler for cursor move events *************************************************************************/ -void FrameWindow::onMouseMove(MouseEventArgs& e) +void FrameWindow::onCursorMove(CursorInputEventArgs& e) { // default processing (this is now essential as it controls event firing). - Window::onMouseMove(e); + Window::onCursorMove(e); - // if we are not the window containing the mouse, do NOT change the cursor - if (getGUIContext().getWindowContainingMouse() != this) + // if we are not the window containing the cursor, do NOT change the indicator + if (getGUIContext().getWindowContainingCursor() != this) { return; } if (isSizingEnabled()) { - Vector2f localMousePos(CoordConverter::screenToWindow(*this, e.position)); + const glm::vec2 local_cursor_pos(CoordConverter::screenToWindow(*this, e.position)); if (d_beingSized) { SizingLocation dragEdge = getSizingBorderAtPoint(d_dragPoint); // calculate sizing deltas... - float deltaX = localMousePos.d_x - d_dragPoint.d_x; - float deltaY = localMousePos.d_y - d_dragPoint.d_y; + const float deltaX = local_cursor_pos.x - d_dragPoint.x; + const float deltaY = local_cursor_pos.y - d_dragPoint.y; URect new_area(d_area); bool top_left_sizing = false; @@ -605,9 +602,8 @@ void FrameWindow::onMouseMove(MouseEventArgs& e) } else { - setCursorForPoint(localMousePos); + setIndicatorForPoint(local_cursor_pos); } - } // mark event as handled @@ -616,21 +612,21 @@ void FrameWindow::onMouseMove(MouseEventArgs& e) /************************************************************************* - Handler for mouse button down events + Handler for cursor press events *************************************************************************/ -void FrameWindow::onMouseButtonDown(MouseEventArgs& e) +void FrameWindow::onCursorPressHold(CursorInputEventArgs& e) { // default processing (this is now essential as it controls event firing). - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { if (isSizingEnabled()) { - // get position of mouse as co-ordinates local to this window. - Vector2f localPos(CoordConverter::screenToWindow(*this, e.position)); + // get position of cursor as co-ordinates local to this window. + const glm::vec2 localPos(CoordConverter::screenToWindow(*this, e.position)); - // if the mouse is on the sizing border + // if the cursor is on the sizing border if (getSizingBorderAtPoint(localPos) != SizingNone) { // ensure all inputs come to us for now @@ -646,36 +642,31 @@ void FrameWindow::onMouseButtonDown(MouseEventArgs& e) ++e.handled; } - } - } - } - } /************************************************************************* - Handler for mouse button up events + Handler for cursor activation events *************************************************************************/ -void FrameWindow::onMouseButtonUp(MouseEventArgs& e) +void FrameWindow::onCursorActivate(CursorInputEventArgs& e) { // default processing (this is now essential as it controls event firing). - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton && isCapturedByThis()) + if (e.source == CIS_Left && isCapturedByThis()) { // release our capture on the input data releaseInput(); ++e.handled; } - } /************************************************************************* - Handler for when mouse capture is lost + Handler for when cursor capture is lost *************************************************************************/ void FrameWindow::onCaptureLost(WindowEventArgs& e) { @@ -727,7 +718,7 @@ void FrameWindow::onDeactivated(ActivationEventArgs& e) /************************************************************************* - Set whether this FrameWindow can be moved by dragging the title bar. + Set whether this FrameWindow can be moved by dragging the title bar. *************************************************************************/ void FrameWindow::setDragMovingEnabled(bool setting) { @@ -790,29 +781,29 @@ void FrameWindow::addFrameWindowProperties(void) CEGUI_DEFINE_PROPERTY(FrameWindow, Image*, "NSSizingCursorImage", "Property to get/set the N-S (up-down) sizing cursor image for the FrameWindow. Value should be \"set:[imageset name] image:[image name]\".", - &FrameWindow::setNSSizingCursorImage, &FrameWindow::getNSSizingCursorImage, 0 + &FrameWindow::setNSSizingIndicatorImage, &FrameWindow::getNSSizingIndicatorImage, 0 ); CEGUI_DEFINE_PROPERTY(FrameWindow, Image*, "EWSizingCursorImage", "Property to get/set the E-W (left-right) sizing cursor image for the FrameWindow. Value should be \"set:[imageset name] image:[image name]\".", - &FrameWindow::setEWSizingCursorImage, &FrameWindow::getEWSizingCursorImage, 0 + &FrameWindow::setEWSizingIndicatorImage, &FrameWindow::getEWSizingIndicatorImage, 0 ); CEGUI_DEFINE_PROPERTY(FrameWindow, Image*, "NWSESizingCursorImage", "Property to get/set the NW-SE diagonal sizing cursor image for the FrameWindow. Value should be \"set:[imageset name] image:[image name]\".", - &FrameWindow::setNWSESizingCursorImage, &FrameWindow::getNWSESizingCursorImage, 0 + &FrameWindow::setNWSESizingIndicatorImage, &FrameWindow::getNWSESizingIndicatorImage, 0 ); CEGUI_DEFINE_PROPERTY(FrameWindow, Image*, "NESWSizingCursorImage", "Property to get/set the NE-SW diagonal sizing cursor image for the FramwWindow. Value should be \"set:[imageset name] image:[image name]\".", - &FrameWindow::setNESWSizingCursorImage, &FrameWindow::getNESWSizingCursorImage, 0 + &FrameWindow::setNESWSizingIndicatorImage, &FrameWindow::getNESWSizingIndicatorImage, 0 ); } /************************************************************************* return the image used for the north-south sizing cursor. *************************************************************************/ -const Image* FrameWindow::getNSSizingCursorImage() const +const Image* FrameWindow::getNSSizingIndicatorImage() const { return d_nsSizingCursor; } @@ -820,7 +811,7 @@ const Image* FrameWindow::getNSSizingCursorImage() const /************************************************************************* return the image used for the east-west sizing cursor. *************************************************************************/ -const Image* FrameWindow::getEWSizingCursorImage() const +const Image* FrameWindow::getEWSizingIndicatorImage() const { return d_ewSizingCursor; } @@ -828,7 +819,7 @@ const Image* FrameWindow::getEWSizingCursorImage() const /************************************************************************* return the image used for the northwest-southeast sizing cursor. *************************************************************************/ -const Image* FrameWindow::getNWSESizingCursorImage() const +const Image* FrameWindow::getNWSESizingIndicatorImage() const { return d_nwseSizingCursor; } @@ -836,7 +827,7 @@ const Image* FrameWindow::getNWSESizingCursorImage() const /************************************************************************* return the image used for the northeast-southwest sizing cursor. *************************************************************************/ -const Image* FrameWindow::getNESWSizingCursorImage() const +const Image* FrameWindow::getNESWSizingIndicatorImage() const { return d_neswSizingCursor; } @@ -844,7 +835,7 @@ const Image* FrameWindow::getNESWSizingCursorImage() const /************************************************************************* set the image used for the north-south sizing cursor. *************************************************************************/ -void FrameWindow::setNSSizingCursorImage(const Image* image) +void FrameWindow::setNSSizingIndicatorImage(const Image* image) { d_nsSizingCursor = image; } @@ -852,7 +843,7 @@ void FrameWindow::setNSSizingCursorImage(const Image* image) /************************************************************************* set the image used for the east-west sizing cursor. *************************************************************************/ -void FrameWindow::setEWSizingCursorImage(const Image* image) +void FrameWindow::setEWSizingIndicatorImage(const Image* image) { d_ewSizingCursor = image; } @@ -860,7 +851,7 @@ void FrameWindow::setEWSizingCursorImage(const Image* image) /************************************************************************* set the image used for the northwest-southeast sizing cursor. *************************************************************************/ -void FrameWindow::setNWSESizingCursorImage(const Image* image) +void FrameWindow::setNWSESizingIndicatorImage(const Image* image) { d_nwseSizingCursor = image; } @@ -868,7 +859,7 @@ void FrameWindow::setNWSESizingCursorImage(const Image* image) /************************************************************************* set the image used for the northeast-southwest sizing cursor. *************************************************************************/ -void FrameWindow::setNESWSizingCursorImage(const Image* image) +void FrameWindow::setNESWSizingIndicatorImage(const Image* image) { d_neswSizingCursor = image; } @@ -876,7 +867,7 @@ void FrameWindow::setNESWSizingCursorImage(const Image* image) /************************************************************************* set the image used for the north-south sizing cursor. *************************************************************************/ -void FrameWindow::setNSSizingCursorImage(const String& name) +void FrameWindow::setNSSizingIndicatorImage(const String& name) { d_nsSizingCursor = &ImageManager::getSingleton().get(name); } @@ -884,7 +875,7 @@ void FrameWindow::setNSSizingCursorImage(const String& name) /************************************************************************* set the image used for the east-west sizing cursor. *************************************************************************/ -void FrameWindow::setEWSizingCursorImage(const String& name) +void FrameWindow::setEWSizingIndicatorImage(const String& name) { d_ewSizingCursor = &ImageManager::getSingleton().get(name); } @@ -892,7 +883,7 @@ void FrameWindow::setEWSizingCursorImage(const String& name) /************************************************************************* set the image used for the northwest-southeast sizing cursor. *************************************************************************/ -void FrameWindow::setNWSESizingCursorImage(const String& name) +void FrameWindow::setNWSESizingIndicatorImage(const String& name) { d_nwseSizingCursor = &ImageManager::getSingleton().get(name); } @@ -900,11 +891,16 @@ void FrameWindow::setNWSESizingCursorImage(const String& name) /************************************************************************* set the image used for the northeast-southwest sizing cursor. *************************************************************************/ -void FrameWindow::setNESWSizingCursorImage(const String& name) +void FrameWindow::setNESWSizingIndicatorImage(const String& name) { d_neswSizingCursor = &ImageManager::getSingleton().get(name); } +bool FrameWindow::isHit(const glm::vec2& position, const bool /*allow_disabled*/) const +{ + return Window::isHit(position) && !d_rolledup; +} + /************************************************************************* Return a pointer to the Titlebar component widget for this FrameWindow. *************************************************************************/ diff --git a/cegui/src/widgets/GroupBox.cpp b/cegui/src/widgets/GroupBox.cpp index 03f4a8e86..d030d8f59 100644 --- a/cegui/src/widgets/GroupBox.cpp +++ b/cegui/src/widgets/GroupBox.cpp @@ -43,7 +43,7 @@ GroupBox::GroupBox(const String& type, const String& name) : { // When clicked, don't rise. Required because a Groupbox does not have an // actual parent child relation with the widgets which appear inside it. - d_riseOnClick = false; + d_riseOnPointerActivation = false; } //----------------------------------------------------------------------------// diff --git a/cegui/src/widgets/ItemEntry.cpp b/cegui/src/widgets/ItemEntry.cpp index 19a09bc3f..e5d47ea63 100644 --- a/cegui/src/widgets/ItemEntry.cpp +++ b/cegui/src/widgets/ItemEntry.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 31/3/2005 author: Tomas Lindquist Olsen (based on code by Paul D Turner) - + purpose: Implementation of ItemEntry widget base class *************************************************************************/ /*************************************************************************** @@ -86,7 +86,7 @@ void ItemEntry::setSelected_impl(bool setting, bool notify) { d_selected = setting; - // notify the ItemListbox if there is one that we just got selected + // notify the ItemListBase if there is one that we just got selected // to ensure selection scheme is not broken when setting selection from code if (d_ownerList && notify) { @@ -124,39 +124,39 @@ bool ItemEntry::validateWindowRenderer(const WindowRenderer* renderer) const return dynamic_cast(renderer) != 0; } -/************************************************************************* - Handle 'MouseClicked' event -*************************************************************************/ -void ItemEntry::onMouseClicked(MouseEventArgs& e) -{ - Window::onMouseClicked(e); - - if (d_selectable && e.button == LeftButton) - { - if (d_ownerList) - d_ownerList->notifyItemClicked(this); - else - setSelected(!isSelected()); - ++e.handled; - } -} - /************************************************************************* Add ItemEntry specific properties *************************************************************************/ void ItemEntry::addItemEntryProperties(void) { const String& propertyOrigin = WidgetTypeName; - + CEGUI_DEFINE_PROPERTY(ItemEntry, bool, "Selectable","Property to get/set the state of the selectable setting for the ItemEntry. Value is either \"true\" or \"false\".", &ItemEntry::setSelectable, &ItemEntry::isSelectable, false ); - + CEGUI_DEFINE_PROPERTY(ItemEntry, bool, "Selected","Property to get/set the state of the selected setting for the ItemEntry. Value is either \"true\" or \"false\".", &ItemEntry::setSelected, &ItemEntry::isSelected, false ); } +void ItemEntry::onSemanticInputEvent(SemanticEventArgs& e) +{ + bool range_selection = e.d_semanticValue == SV_SelectRange; + bool cumulative_selection = e.d_semanticValue == SV_SelectCumulative; + + if (d_selectable && + (e.d_semanticValue == SV_CursorActivate || range_selection || cumulative_selection) && + e.d_payload.source == CIS_Left) + { + if (d_ownerList) + d_ownerList->notifyItemActivated(this, cumulative_selection, range_selection); + else + setSelected(!isSelected()); + ++e.handled; + } +} + } // End of CEGUI namespace section diff --git a/cegui/src/widgets/ItemListbox.cpp b/cegui/src/widgets/ItemListbox.cpp deleted file mode 100644 index aa0af4851..000000000 --- a/cegui/src/widgets/ItemListbox.cpp +++ /dev/null @@ -1,444 +0,0 @@ -/************************************************************************ - created: Tue Sep 27 2005 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/widgets/ItemListbox.h" -#include "CEGUI/Exceptions.h" - -// begin CEGUI namespace -namespace CEGUI -{ - -/************************************************************************* - Constants -*************************************************************************/ -// event strings -const String ItemListbox::EventNamespace("ItemListbox"); -const String ItemListbox::WidgetTypeName("CEGUI/ItemListbox"); -const String ItemListbox::EventSelectionChanged("SelectionChanged"); -const String ItemListbox::EventMultiSelectModeChanged("MultiSelectModeChanged"); - -/************************************************************************ - Constructor -************************************************************************/ -ItemListbox::ItemListbox(const String& type, const String& name) : - ScrolledItemListBase(type, name), - d_multiSelect(false), - d_lastSelected(0), - d_nextSelectionIndex(0) -{ - addItemListboxProperties(); -} - -/************************************************************************ - Layout items -************************************************************************/ -void ItemListbox::layoutItemWidgets() -{ - float y = 0; - float widest = 0; - - ItemEntryList::iterator i = d_listItems.begin(); - ItemEntryList::iterator end = d_listItems.end(); - - while (i!=end) - { - ItemEntry* entry = *i; - const Sizef pxs = entry->getItemPixelSize(); - if (pxs.d_width > widest) - { - widest = pxs.d_width; - } - - entry->setArea(URect( - UVector2(cegui_absdim(0), cegui_absdim(y)), - UVector2(cegui_reldim(1), cegui_absdim(y + pxs.d_height)) - )); - - y += pxs.d_height; - - ++i; - } - - // reconfigure scrollbars - configureScrollbars(Sizef(widest, y)); -} - -/************************************************************************ - Get size of items -************************************************************************/ -Sizef ItemListbox::getContentSize() const -{ - float h = 0; - - ItemEntryList::const_iterator i = d_listItems.begin(); - ItemEntryList::const_iterator end = d_listItems.end(); - while (i!=end) - { - h += (*i)->getItemPixelSize().d_height; - ++i; - } - - return Sizef(getItemRenderArea().getWidth(), h); -} - -/************************************************************************ - Get the number of selected items -************************************************************************/ -size_t ItemListbox::getSelectedCount() const -{ - if (!d_multiSelect) - { - return d_lastSelected ? 1 : 0; - } - - size_t count = 0; - size_t max = d_listItems.size(); - for (size_t i=0; iisSelected()) - { - ++count; - } - } - - return count; -} - -/************************************************************************ - Get a pointer to the first selected item starting from the given index -************************************************************************/ -ItemEntry* ItemListbox::findSelectedItem(size_t start_index) const -{ - const size_t max = d_listItems.size(); - - for (size_t i = start_index; i < max; ++i) - { - ItemEntry* li = d_listItems[i]; - if (li->isSelected()) - { - d_nextSelectionIndex = i + 1; - return li; - } - } - - return 0; -} - -/************************************************************************ - Get a pointer to the first selected item -************************************************************************/ -ItemEntry* ItemListbox::getFirstSelectedItem(size_t start_index) const -{ - if (!d_multiSelect) - { - return d_lastSelected; - } - return findSelectedItem(start_index); -} - -/************************************************************************ - Get a pointer to the next selected item using internal counter -************************************************************************/ -ItemEntry* ItemListbox::getNextSelectedItem() const -{ - if (!d_multiSelect) - { - return 0; - } - return findSelectedItem(d_nextSelectionIndex); -} - -/************************************************************************ - Get a pointer to the next selected item after the given item -************************************************************************/ -ItemEntry* ItemListbox::getNextSelectedItemAfter(const ItemEntry* start_item) const -{ - if (start_item==0||!d_multiSelect) - { - return 0; - } - - size_t max = d_listItems.size(); - size_t i = getItemIndex(start_item); - - while (iisSelected()) - { - return li; - } - ++i; - } - - return 0; -} - -/************************************************************************ - Set whether multiple selections should be allowed -************************************************************************/ -void ItemListbox::setMultiSelectEnabled(bool state) -{ - if (state != d_multiSelect) - { - d_multiSelect = state; - WindowEventArgs e(this); - onMultiSelectModeChanged(e); - } -} - -/************************************************************************ - Notify item clicked -************************************************************************/ -void ItemListbox::notifyItemClicked(ItemEntry* li) -{ - bool sel_state = !(li->isSelected() && d_multiSelect); - bool skip = false; - - // multiselect enabled - if (d_multiSelect) - { - uint syskeys = getGUIContext().getSystemKeys().get(); - ItemEntry* last = d_lastSelected; - - // no Control? clear others - if (!(syskeys & Control)) - { - clearAllSelections(); - if (!sel_state) - { - sel_state=true; - } - } - - // select range if Shift if held, and we have a 'last selection' - if (last && (syskeys & Shift)) - { - selectRange(getItemIndex(last),getItemIndex(li)); - skip = true; - } - } - else - { - clearAllSelections(); - } - - if (!skip) - { - li->setSelected_impl(sel_state,false); - if (sel_state) - { - d_lastSelected = li; - } - else if (d_lastSelected == li) - { - d_lastSelected = 0; - } - } - - WindowEventArgs e(this); - onSelectionChanged(e); -} - -/************************************************************************ - Notify item select state change -************************************************************************/ -void ItemListbox::notifyItemSelectState(ItemEntry* li, bool state) -{ - // deselect - if (!state) - { - // clear last selection if this one was it - if (d_lastSelected == li) - { - d_lastSelected = 0; - } - } - // if we dont support multiselect, we must clear all the other selections - else if (!d_multiSelect) - { - clearAllSelections(); - li->setSelected_impl(true,false); - d_lastSelected = li; - } - - WindowEventArgs e(this); - onSelectionChanged(e); -} - -/************************************************************************* - Add ItemListbox specific properties -*************************************************************************/ -void ItemListbox::addItemListboxProperties() -{ - const String propertyOrigin("ItemListbox"); - CEGUI_DEFINE_PROPERTY(ItemListbox, bool, - "MultiSelect","Property to get/set the state of the multiselect enabled setting for the ItemListbox. Value is either \"true\" or \"false\".", - &ItemListbox::setMultiSelectEnabled, &ItemListbox::isMultiSelectEnabled, false - ); -} - -/************************************************************************* - Query item selection state -*************************************************************************/ -bool ItemListbox::isItemSelected(size_t index) const -{ - if (index >= d_listItems.size()) - { - CEGUI_THROW(InvalidRequestException( - "The index given is out of range for this ItemListbox")); - } - ItemEntry *li = d_listItems[index]; - return li->isSelected(); -} - -/************************************************************************* - Clear all selections -*************************************************************************/ -void ItemListbox::clearAllSelections() -{ - size_t max = d_listItems.size(); - for (size_t i=0; isetSelected_impl(false,false); - } - d_lastSelected = 0; - - WindowEventArgs e(this); - onSelectionChanged(e); -} - -/************************************************************************* - Select range of items -*************************************************************************/ -void ItemListbox::selectRange(size_t a, size_t z) -{ - // do nothing if the list is empty - if (d_listItems.empty()) - { - return; - } - - size_t max = d_listItems.size(); - if (a >= max) - { - a = 0; - } - if (z >= max) - { - z = max-1; - } - - if (a>z) - { - size_t tmp = a; - a = z; - z = tmp; - } - - for (size_t i=a; i<=z; ++i) - { - d_listItems[i]->setSelected_impl(true,false); - } - d_lastSelected = d_listItems[z]; - - - WindowEventArgs e(this); - onSelectionChanged(e); -} - -/************************************************************************ - Select all items if allowed -************************************************************************/ -void ItemListbox::selectAllItems() -{ - if (!d_multiSelect) - { - return; - } - - size_t max = d_listItems.size(); - for (size_t i=0; isetSelected_impl(true,false); - } - - WindowEventArgs e(this); - onSelectionChanged(e); -} - -/************************************************************************ - Handle selection changed -************************************************************************/ -void ItemListbox::onSelectionChanged(WindowEventArgs& e) -{ - fireEvent(EventSelectionChanged, e); -} - -/************************************************************************ - Handle multiselect mode changed -************************************************************************/ -void ItemListbox::onMultiSelectModeChanged(WindowEventArgs& e) -{ - fireEvent(EventMultiSelectModeChanged, e); -} - -/************************************************************************ - Handle key down event -************************************************************************/ -void ItemListbox::onKeyDown(KeyEventArgs& e) -{ - ScrolledItemListBase::onKeyDown(e); - - // select all (if allowed) on Ctrl+A - if (d_multiSelect) - { - uint sysKeys = getGUIContext().getSystemKeys().get(); - if (e.scancode == Key::A && (sysKeys&Control)) - { - selectAllItems(); - ++e.handled; - } - } -} - -//----------------------------------------------------------------------------// -bool ItemListbox::handle_PaneChildRemoved(const EventArgs& e) -{ - ItemListBase::handle_PaneChildRemoved(e); - - // get the window that's being removed - const Window* w = static_cast(e).window; - // Clear last selected pointer if that item was just removed. - if (w == d_lastSelected) - d_lastSelected = 0; - - return true; -} -//----------------------------------------------------------------------------// - -} // end CEGUI namespace diff --git a/cegui/src/widgets/LayoutCell.cpp b/cegui/src/widgets/LayoutCell.cpp deleted file mode 100644 index 7d7204548..000000000 --- a/cegui/src/widgets/LayoutCell.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/*********************************************************************** - created: 22/2/2011 - author: Martin Preisler - - purpose: Implements the LayoutCell class -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif - -#include "CEGUI/widgets/LayoutCell.h" - -#if defined(_MSC_VER) -# pragma warning(push) -# pragma warning(disable : 4355) -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ - -const String LayoutCell::EventNamespace("LayoutCell"); -const String LayoutCell::WidgetTypeName("LayoutCell"); - -//----------------------------------------------------------------------------// -LayoutCell::LayoutCell(const String& type, const String& name): - Window(type, name), - - d_clientChildContentArea(this, static_cast(&LayoutCell::getClientChildContentArea_impl)) -{ - // cell should take the whole window by default I think - setSize(USize(cegui_reldim(1), cegui_reldim(1))); - - subscribeEvent(Window::EventChildAdded, - Event::Subscriber(&LayoutCell::handleChildAdded, this)); - subscribeEvent(Window::EventChildRemoved, - Event::Subscriber(&LayoutCell::handleChildRemoved, this)); -} - -//----------------------------------------------------------------------------// -LayoutCell::~LayoutCell(void) -{} - -const Element::CachedRectf& LayoutCell::getClientChildContentArea() const -{ - if (!d_parent) - { - return Window::getClientChildContentArea(); - } - else - { - return d_clientChildContentArea; - } -} - -//----------------------------------------------------------------------------// -void LayoutCell::notifyScreenAreaChanged(bool recursive) -{ - d_clientChildContentArea.invalidateCache(); - - Window::notifyScreenAreaChanged(recursive); -} - -//----------------------------------------------------------------------------// -Rectf LayoutCell::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const -{ - return d_parent ? - (skipAllPixelAlignment ? d_parent->getUnclippedInnerRect().getFresh(true) : d_parent->getUnclippedInnerRect().get()) : - Window::getUnclippedInnerRect_impl(skipAllPixelAlignment); -} - -//----------------------------------------------------------------------------// -Rectf LayoutCell::getClientChildContentArea_impl(bool skipAllPixelAlignment) const -{ - if (!d_parent) - { - return skipAllPixelAlignment ? Window::getClientChildContentArea().getFresh(true) : Window::getClientChildContentArea().get(); - } - else - { - return skipAllPixelAlignment ? - Rectf(getUnclippedOuterRect().getFresh(true).getPosition(), d_parent->getUnclippedInnerRect().getFresh(true).getSize()) : - Rectf(getUnclippedOuterRect().get().getPosition(), d_parent->getUnclippedInnerRect().get().getSize()); - } -} - -//----------------------------------------------------------------------------// -void LayoutCell::addChild_impl(Element* element) -{ - Window* wnd = dynamic_cast(element); - - if (!wnd) - CEGUI_THROW(InvalidRequestException( - "LayoutCell can only have Elements of type Window added as children " - "(Window path: " + getNamePath() + ").")); - - Window::addChild_impl(wnd); - - // we have to subscribe to the EventSized for layout updates - d_eventConnections.insert(std::make_pair(wnd, - wnd->subscribeEvent(Window::EventSized, - Event::Subscriber(&LayoutCell::handleChildSized, this)))); -} - -//----------------------------------------------------------------------------// -void LayoutCell::removeChild_impl(Element* element) -{ - Window* wnd = static_cast(element); - - // we want to get rid of the subscription, because the child window could - // get removed and added somewhere else, we would be wastefully updating - // layouts if it was sized inside other Window - ConnectionTracker::iterator conn; - - while ((conn = d_eventConnections.find(wnd)) != d_eventConnections.end()) - { - conn->second->disconnect(); - d_eventConnections.erase(conn); - } - - Window::removeChild_impl(wnd); -} - -//----------------------------------------------------------------------------// -bool LayoutCell::handleChildSized(const EventArgs&) -{ - //markNeedsLayouting(); - - return true; -} - -//----------------------------------------------------------------------------// -bool LayoutCell::handleChildAdded(const EventArgs&) -{ - if (getChildCount() > 0) - { - CEGUI_THROW(InvalidRequestException( - "You can't add more than one widget to a layout cell!")); - } - - //markNeedsLayouting(); - - return true; -} - -//----------------------------------------------------------------------------// -bool LayoutCell::handleChildRemoved(const EventArgs&) -{ - //markNeedsLayouting(); - - return true; -} - -#if defined(_MSC_VER) -# pragma warning(pop) -#endif - - -} // End of CEGUI namespace section diff --git a/cegui/src/widgets/ListHeader.cpp b/cegui/src/widgets/ListHeader.cpp index dc2b61fec..8b1c872fe 100644 --- a/cegui/src/widgets/ListHeader.cpp +++ b/cegui/src/widgets/ListHeader.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 13/4/2004 author: Paul D Turner - + purpose: Implementation of ListHeader widget base class *************************************************************************/ /*************************************************************************** @@ -683,7 +683,7 @@ void ListHeader::setSegmentOffset(float offset) d_segmentOffset = offset; layoutSegments(); invalidate(); - + // Fire event. WindowEventArgs args(this); onSegmentOffsetChanged(args); @@ -905,14 +905,14 @@ bool ListHeader::segmentSizedHandler(const EventArgs& e) *************************************************************************/ bool ListHeader::segmentMovedHandler(const EventArgs& e) { - const Vector2f mousePos(getUnprojectedPosition( - getGUIContext().getMouseCursor().getPosition())); + const glm::vec2 cursor_pos(getUnprojectedPosition( + getGUIContext().getCursor().getPosition())); // segment must be dropped within the window - if (isHit(mousePos)) + if (isHit(cursor_pos)) { - // get mouse position as something local - Vector2f localMousePos(CoordConverter::screenToWindow(*this, mousePos)); + // get cursor position as something local + const glm::vec2 local_cursor_pos(CoordConverter::screenToWindow(*this, cursor_pos)); // set up to allow for current offsets float currwidth = -d_segmentOffset; @@ -923,7 +923,7 @@ bool ListHeader::segmentMovedHandler(const EventArgs& e) { currwidth += d_segments[col]->getPixelSize().d_width; - if (localMousePos.d_x < currwidth) + if (local_cursor_pos.x < currwidth) { // this is the column, exit loop early break; @@ -944,7 +944,7 @@ bool ListHeader::segmentMovedHandler(const EventArgs& e) /************************************************************************* - Hanlder for when a segment is clicked (to change sort segment / direction) + Handler for when a segment is clicked (to change sort segment / direction) *************************************************************************/ bool ListHeader::segmentClickedHandler(const EventArgs& e) { @@ -1004,19 +1004,19 @@ bool ListHeader::segmentDoubleClickHandler(const EventArgs& e) /************************************************************************* - Handler called whenever the mouse moves while dragging a segment + Handler called whenever the cursor moves while dragging a segment *************************************************************************/ bool ListHeader::segmentDragHandler(const EventArgs&) { - // what we do here is monitor the position and scroll if we can when mouse is outside area. + // what we do here is monitor the position and scroll if we can when cursor is outside area. - // get mouse position as something local - const Vector2f localMousePos(CoordConverter::screenToWindow(*this, + // get cursor position as something local + const glm::vec2 local_cursor_pos(CoordConverter::screenToWindow(*this, getUnprojectedPosition(getGUIContext(). - getMouseCursor().getPosition()))); + getCursor().getPosition()))); // scroll left? - if (localMousePos.d_x < 0.0f) + if (local_cursor_pos.x < 0.0f) { if (d_segmentOffset > 0.0f) { @@ -1024,7 +1024,7 @@ bool ListHeader::segmentDragHandler(const EventArgs&) } } // scroll right? - else if (localMousePos.d_x >= d_pixelSize.d_width) + else if (local_cursor_pos.x >= d_pixelSize.d_width) { float maxOffset = ceguimax(0.0f, getTotalSegmentsPixelExtent() - d_pixelSize.d_width); @@ -1034,7 +1034,6 @@ bool ListHeader::segmentDragHandler(const EventArgs&) // scroll, but never beyond the limit setSegmentOffset(ceguimin(maxOffset, d_segmentOffset + ScrollSpeed)); } - } return true; @@ -1052,22 +1051,22 @@ void ListHeader::addHeaderProperties(void) "SortSettingEnabled", "Property to get/set the setting for for user modification of the sort column & direction. Value is either \"true\" or \"false\".", &ListHeader::setSortingEnabled, &ListHeader::isSortingEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(ListHeader, bool, "ColumnsSizable", "Property to get/set the setting for user sizing of the column headers. Value is either \"true\" or \"false\".", &ListHeader::setColumnSizingEnabled, &ListHeader::isColumnSizingEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(ListHeader, bool, "ColumnsMovable", "Property to get/set the setting for user moving of the column headers. Value is either \"true\" or \"false\".", &ListHeader::setColumnDraggingEnabled, &ListHeader::isColumnDraggingEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(ListHeader, uint, "SortColumnID", "Property to get/set the current sort column (via ID code). Value is an unsigned integer number.", &ListHeader::setSortColumnFromID, &ListHeader::getSortSegmentID, 0 /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(ListHeader, ListHeaderSegment::SortDirection, "SortDirection", "Property to get/set the sort direction setting of the header. Value is the text of one of the SortDirection enumerated value names.", &ListHeader::setSortDirection, &ListHeader::getSortDirection, ListHeaderSegment::None diff --git a/cegui/src/widgets/ListHeaderSegment.cpp b/cegui/src/widgets/ListHeaderSegment.cpp index d005ea812..c2fc9eda8 100644 --- a/cegui/src/widgets/ListHeaderSegment.cpp +++ b/cegui/src/widgets/ListHeaderSegment.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 15/6/2004 author: Paul D Turner - + purpose: Implementation of List header segment widget. *************************************************************************/ /*************************************************************************** @@ -27,7 +27,7 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/widgets/ListHeaderSegment.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/CoordConverter.h" #include "CEGUI/ImageManager.h" @@ -58,12 +58,12 @@ const float ListHeaderSegment::SegmentMoveThreshold = 12.0f; /************************************************************************* - Constructor for list header segment base class + Constructor for list header segment base class *************************************************************************/ ListHeaderSegment::ListHeaderSegment(const String& type, const String& name) : Window(type, name), - d_sizingMouseCursor(0), - d_movingMouseCursor(0), + d_sizingCursor(0), + d_movingCursor(0), d_splitterSize(DefaultSizingArea), d_splitterHover(false), d_dragSizing(false), @@ -80,7 +80,7 @@ ListHeaderSegment::ListHeaderSegment(const String& type, const String& name) : /************************************************************************* - Destructor for list header segment base class. + Destructor for list header segment base class. *************************************************************************/ ListHeaderSegment::~ListHeaderSegment(void) { @@ -110,7 +110,7 @@ void ListHeaderSegment::setSizingEnabled(bool setting) /************************************************************************* - Set the current sort direction set for this segment. + Set the current sort direction set for this segment. *************************************************************************/ void ListHeaderSegment::setSortDirection(SortDirection sort_dir) { @@ -128,7 +128,7 @@ void ListHeaderSegment::setSortDirection(SortDirection sort_dir) /************************************************************************* - Set whether drag moving is allowed for this segment. + Set whether drag moving is allowed for this segment. *************************************************************************/ void ListHeaderSegment::setDragMovingEnabled(bool setting) { @@ -160,7 +160,7 @@ void ListHeaderSegment::setClickable(bool setting) /************************************************************************* - Handler called when segment is clicked. + Handler called when segment is clicked. *************************************************************************/ void ListHeaderSegment::onSegmentClicked(WindowEventArgs& e) { @@ -169,7 +169,7 @@ void ListHeaderSegment::onSegmentClicked(WindowEventArgs& e) /************************************************************************* - Handler called when the sizer/splitter is double-clicked. + Handler called when the sizer/splitter is double-clicked. *************************************************************************/ void ListHeaderSegment::onSplitterDoubleClicked(WindowEventArgs& e) { @@ -215,8 +215,8 @@ void ListHeaderSegment::onSegmentDragStart(WindowEventArgs& e) /************************************************************************* - Handler called when the user stops dragging the segment - (releases mouse button) + Handler called when the user stops dragging the segment + (releases pointer) *************************************************************************/ void ListHeaderSegment::onSegmentDragStop(WindowEventArgs& e) { @@ -256,34 +256,34 @@ void ListHeaderSegment::onClickableSettingChanged(WindowEventArgs& e) /************************************************************************* Processing for drag-sizing the segment *************************************************************************/ -void ListHeaderSegment::doDragSizing(const Vector2f& local_mouse) +void ListHeaderSegment::doDragSizing(const glm::vec2& local_cursor) { - float delta = local_mouse.d_x - d_dragPoint.d_x; + float delta = local_cursor.x - d_dragPoint.x; // store this so we can work out how much size actually changed - float orgWidth = d_pixelSize.d_width; + const float orgWidth = d_pixelSize.d_width; // ensure that we only size to the set constraints. // // NB: We are required to do this here due to our virtually unique sizing nature; the // normal system for limiting the window size is unable to supply the information we // require for updating our internal state used to manage the dragging, etc. - float maxWidth(CoordConverter::asAbsolute(d_maxSize.d_width, getRootContainerSize().d_width)); - float minWidth(CoordConverter::asAbsolute(d_minSize.d_width, getRootContainerSize().d_width)); - float newWidth = orgWidth + delta; + const float maxWidth(CoordConverter::asAbsolute(d_maxSize.d_width, getRootContainerSize().d_width)); + const float minWidth(CoordConverter::asAbsolute(d_minSize.d_width, getRootContainerSize().d_width)); + const float newWidth = orgWidth + delta; if (maxWidth != 0.0f && newWidth > maxWidth) delta = maxWidth - orgWidth; else if (newWidth < minWidth) delta = minWidth - orgWidth; - + // update segment area rect // URGENT FIXME: The pixel alignment will be done automatically again, right? Why is it done here? setArea_impl will do it! URect area(d_area.d_min.d_x, d_area.d_min.d_y, d_area.d_max.d_x + UDim(0,/*PixelAligned(*/delta/*)*/), d_area.d_max.d_y); setArea_impl(area.d_min, area.getSize()); - // move the dragging point so mouse remains 'attached' to edge of segment - d_dragPoint.d_x += d_pixelSize.d_width - orgWidth; + // move the dragging point so cursor remains 'attached' to edge of segment + d_dragPoint.x += d_pixelSize.d_width - orgWidth; WindowEventArgs args(this); onSegmentSized(args); @@ -291,21 +291,21 @@ void ListHeaderSegment::doDragSizing(const Vector2f& local_mouse) /************************************************************************* - Processing for drag-moving the segment + Processing for drag-moving the segment *************************************************************************/ -void ListHeaderSegment::doDragMoving(const Vector2f& local_mouse) +void ListHeaderSegment::doDragMoving(const glm::vec2& local_cursor) { - // calculate movement deltas. - float deltaX = local_mouse.d_x - d_dragPoint.d_x; - float deltaY = local_mouse.d_y - d_dragPoint.d_y; + // calculate movement deltas. + const float deltaX = local_cursor.x - d_dragPoint.x; + const float deltaY = local_cursor.y - d_dragPoint.y; // update 'ghost' position - d_dragPosition.d_x += deltaX; - d_dragPosition.d_y += deltaY; + d_dragPosition.x += deltaX; + d_dragPosition.y += deltaY; // update drag point. - d_dragPoint.d_x += deltaX; - d_dragPoint.d_y += deltaY; + d_dragPoint.x += deltaX; + d_dragPoint.y += deltaY; WindowEventArgs args(this); onSegmentDragPositionChanged(args); @@ -323,11 +323,10 @@ void ListHeaderSegment::initDragMoving(void) d_dragMoving = true; d_segmentPushed = false; d_segmentHover = false; - d_dragPosition.d_x = 0.0f; - d_dragPosition.d_y = 0.0f; + d_dragPosition = glm::vec2(0, 0); - // setup new cursor - getGUIContext().getMouseCursor().setImage(d_movingMouseCursor); + // setup new indicator + getGUIContext().getCursor().setImage(d_movingCursor); // Trigger the event WindowEventArgs args(this); @@ -347,8 +346,8 @@ void ListHeaderSegment::initSizingHoverState(void) { d_splitterHover = true; - // change the mouse cursor. - getGUIContext().getMouseCursor().setImage(d_sizingMouseCursor); + // change the cursor. + getGUIContext().getCursor().setImage(d_sizingCursor); // trigger redraw so 'sizing' area can be highlighted if needed. invalidate(); @@ -356,7 +355,7 @@ void ListHeaderSegment::initSizingHoverState(void) // reset segment hover as needed. if (d_segmentHover) - { + { d_segmentHover = false; invalidate(); } @@ -373,7 +372,7 @@ void ListHeaderSegment::initSegmentHoverState(void) if (d_splitterHover) { d_splitterHover = false; - getGUIContext().getMouseCursor().setImage(getMouseCursor()); + getGUIContext().getCursor().setImage(getCursor()); invalidate(); } @@ -390,12 +389,12 @@ void ListHeaderSegment::initSegmentHoverState(void) Return true if move threshold for initiating drag-moving has been exceeded. *************************************************************************/ -bool ListHeaderSegment::isDragMoveThresholdExceeded(const Vector2f& local_mouse) +bool ListHeaderSegment::isDragMoveThresholdExceeded(const glm::vec2& local_cursor) { - // see if mouse has moved far enough to start move operation - // calculate movement deltas. - float deltaX = local_mouse.d_x - d_dragPoint.d_x; - float deltaY = local_mouse.d_y - d_dragPoint.d_y; + // see if cursor has moved far enough to start move operation + // calculate movement deltas. + const float deltaX = local_cursor.x - d_dragPoint.x; + const float deltaY = local_cursor.y - d_dragPoint.y; if ((deltaX > SegmentMoveThreshold) || (deltaX < -SegmentMoveThreshold) || (deltaY > SegmentMoveThreshold) || (deltaY < -SegmentMoveThreshold)) @@ -406,42 +405,39 @@ bool ListHeaderSegment::isDragMoveThresholdExceeded(const Vector2f& local_mouse) { return false; } - } /************************************************************************* - Handler for when mouse position changes in widget area (or captured) + Handler for when cursor position changes in widget area (or captured) *************************************************************************/ -void ListHeaderSegment::onMouseMove(MouseEventArgs& e) +void ListHeaderSegment::onCursorMove(CursorInputEventArgs& e) { // base class processing - Window::onMouseMove(e); + Window::onCursorMove(e); - // - // convert mouse position to something local - // - Vector2f localMousePos(CoordConverter::screenToWindow(*this, e.position)); + // convert cursor position to something local + const glm::vec2 local_cursor_pos(CoordConverter::screenToWindow(*this, e.position)); // handle drag sizing if (d_dragSizing) { - doDragSizing(localMousePos); + doDragSizing(local_cursor_pos); } // handle drag moving else if (d_dragMoving) { - doDragMoving(localMousePos); - } - // not sizing, is mouse in the widget area? - else if (isHit(e.position)) - { - // mouse in sizing area & sizing is enabled - if ((localMousePos.d_x > (d_pixelSize.d_width - d_splitterSize)) && d_sizingEnabled) + doDragMoving(local_cursor_pos); + } + // not sizing, is cursor in the widget area? + else if (isHit(e.position)) + { + // cursor in sizing area & sizing is enabled + if ((local_cursor_pos.x > (d_pixelSize.d_width - d_splitterSize)) && d_sizingEnabled) { initSizingHoverState(); } - // mouse not in sizing area and/or sizing not enabled + // cursor not in sizing area and/or sizing not enabled else { initSegmentHoverState(); @@ -449,34 +445,30 @@ void ListHeaderSegment::onMouseMove(MouseEventArgs& e) // if we are pushed but not yet drag moving if (d_segmentPushed && !d_dragMoving) { - if (isDragMoveThresholdExceeded(localMousePos)) - { - initDragMoving(); - } - + if (isDragMoveThresholdExceeded(local_cursor_pos)) + { + initDragMoving(); + } } - } - } - // mouse is no longer within the widget area... + // cursor is no longer within the widget area... else { // only change settings if change is required if (d_splitterHover) { d_splitterHover = false; - getGUIContext().getMouseCursor().setImage(getMouseCursor()); + getGUIContext().getCursor().setImage(getCursor()); invalidate(); } // reset segment hover state if not already done. if (d_segmentHover) - { + { d_segmentHover = false; invalidate(); } - } ++e.handled; @@ -484,25 +476,25 @@ void ListHeaderSegment::onMouseMove(MouseEventArgs& e) /************************************************************************* - Handler for when mouse buttons are pushed + Handler for when cursor is pressed *************************************************************************/ -void ListHeaderSegment::onMouseButtonDown(MouseEventArgs& e) +void ListHeaderSegment::onCursorPressHold(CursorInputEventArgs& e) { // base class processing - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { // ensure all inputs come to us for now if (captureInput()) { - // get position of mouse as co-ordinates local to this window. - Vector2f localPos(CoordConverter::screenToWindow(*this, e.position)); + // get position of cursor as co-ordinates local to this window. + const glm::vec2 localPos(CoordConverter::screenToWindow(*this, e.position)); // store drag point for possible sizing or moving operation. d_dragPoint = localPos; - // if the mouse is in the sizing area + // if the cursor is in the sizing area if (d_splitterHover) { if (isSizingEnabled()) @@ -510,32 +502,28 @@ void ListHeaderSegment::onMouseButtonDown(MouseEventArgs& e) // setup the 'dragging' state variables d_dragSizing = true; } - } else { d_segmentPushed = true; } - } - ++e.handled; } - } /************************************************************************* - Handler for when mouse buttons area released + Handler for when the cursor is activated *************************************************************************/ -void ListHeaderSegment::onMouseButtonUp(MouseEventArgs& e) +void ListHeaderSegment::onCursorActivate(CursorInputEventArgs& e) { // base class processing - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { - // if we were pushed and mouse was released within our segment area + // if we were pushed and cursor was released (activated) within our segment area if (d_segmentPushed && d_segmentHover) { WindowEventArgs args(this); @@ -543,8 +531,8 @@ void ListHeaderSegment::onMouseButtonUp(MouseEventArgs& e) } else if (d_dragMoving) { - getGUIContext().getMouseCursor().setImage(getMouseCursor()); - + getGUIContext().getCursor().setImage(getCursor()); + WindowEventArgs args(this); onSegmentDragStop(args); } @@ -553,37 +541,15 @@ void ListHeaderSegment::onMouseButtonUp(MouseEventArgs& e) releaseInput(); ++e.handled; } - -} - - -/************************************************************************* - Handler for when a mouse button is double-clicked -*************************************************************************/ -void ListHeaderSegment::onMouseDoubleClicked(MouseEventArgs& e) -{ - // base class processing - Window::onMouseDoubleClicked(e); - - // if double-clicked on splitter / sizing area - if ((e.button == LeftButton) && d_splitterHover) - { - WindowEventArgs args(this); - onSplitterDoubleClicked(args); - - ++e.handled; - } - } - /************************************************************************* - Handler for when mouse leaves the widget area (uncaptured) + Handler for when cursor leaves the widget area (uncaptured) *************************************************************************/ -void ListHeaderSegment::onMouseLeaves(MouseEventArgs& e) +void ListHeaderSegment::onCursorLeaves(CursorInputEventArgs& e) { // base class processing - Window::onMouseLeaves(e); + Window::onCursorLeaves(e); d_splitterHover = false; d_dragSizing = false; @@ -591,9 +557,26 @@ void ListHeaderSegment::onMouseLeaves(MouseEventArgs& e) invalidate(); } +void ListHeaderSegment::onSemanticInputEvent(SemanticEventArgs& e) +{ + // base class processing + Window::onSemanticInputEvent(e); + + if (isDisabled()) + return; + + if (e.d_semanticValue == SV_SelectWord && e.d_payload.source == CIS_Left && + d_splitterHover) + { + WindowEventArgs args(this); + onSplitterDoubleClicked(args); + + ++e.handled; + } +} /************************************************************************* - Handler for when mouse input capture is lost + Handler for when cursor input capture is lost *************************************************************************/ void ListHeaderSegment::onCaptureLost(WindowEventArgs& e) { @@ -619,27 +602,27 @@ void ListHeaderSegment::addHeaderSegmentProperties(void) "Sizable", "Property to get/set the sizable setting of the header segment. Value is either \"true\" or \"false\".", &ListHeaderSegment::setSizingEnabled, &ListHeaderSegment::isSizingEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(ListHeaderSegment, bool, "Clickable", "Property to get/set the click-able setting of the header segment. Value is either \"true\" or \"false\".", &ListHeaderSegment::setClickable, &ListHeaderSegment::isClickable, true ); - + CEGUI_DEFINE_PROPERTY(ListHeaderSegment, bool, "Dragable", "Property to get/set the drag-able setting of the header segment. Value is either \"true\" or \"false\".", &ListHeaderSegment::setDragMovingEnabled, &ListHeaderSegment::isDragMovingEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(ListHeaderSegment, ListHeaderSegment::SortDirection, "SortDirection", "Property to get/set the sort direction setting of the header segment. Value is the text of one of the SortDirection enumerated value names.", &ListHeaderSegment::setSortDirection, &ListHeaderSegment::getSortDirection, ListHeaderSegment::None ); - + CEGUI_DEFINE_PROPERTY(ListHeaderSegment, Image*, "SizingCursorImage", "Property to get/set the sizing cursor image for the List Header Segment. Value should be \"set:[imageset name] image:[image name]\".", &ListHeaderSegment::setSizingCursorImage, &ListHeaderSegment::getSizingCursorImage, 0 ); - + CEGUI_DEFINE_PROPERTY(ListHeaderSegment, Image*, "MovingCursorImage", "Property to get/set the moving cursor image for the List Header Segment. Value should be \"set:[imageset name] image:[image name]\".", &ListHeaderSegment::setMovingCursorImage, &ListHeaderSegment::getMovingCursorImage, 0 @@ -648,32 +631,32 @@ void ListHeaderSegment::addHeaderSegmentProperties(void) const Image* ListHeaderSegment::getSizingCursorImage() const { - return d_sizingMouseCursor; + return d_sizingCursor; } void ListHeaderSegment::setSizingCursorImage(const Image* image) { - d_sizingMouseCursor = image; + d_sizingCursor = image; } void ListHeaderSegment::setSizingCursorImage(const String& name) { - d_sizingMouseCursor = &ImageManager::getSingleton().get(name); + d_sizingCursor = &ImageManager::getSingleton().get(name); } const Image* ListHeaderSegment::getMovingCursorImage() const { - return d_movingMouseCursor; + return d_movingCursor; } void ListHeaderSegment::setMovingCursorImage(const Image* image) { - d_movingMouseCursor = image; + d_movingCursor = image; } void ListHeaderSegment::setMovingCursorImage(const String& name) { - d_movingMouseCursor = &ImageManager::getSingleton().get(name); + d_movingCursor = &ImageManager::getSingleton().get(name); } } // End of CEGUI namespace section diff --git a/cegui/src/widgets/ListWidget.cpp b/cegui/src/widgets/ListWidget.cpp new file mode 100644 index 000000000..59dfbf0af --- /dev/null +++ b/cegui/src/widgets/ListWidget.cpp @@ -0,0 +1,230 @@ +/*********************************************************************** + created: Sat Jul 19 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/widgets/ListWidget.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +const String ListWidget::EventNamespace("ListWidget"); +const String ListWidget::WidgetTypeName("CEGUI/ListWidget"); + +//----------------------------------------------------------------------------// +ListWidget::ListWidget(const String& type, const String& name) : + ListView(type, name) +{ +} + +//----------------------------------------------------------------------------// +ListWidget::~ListWidget() +{ +} +//----------------------------------------------------------------------------// +void ListWidget::initialiseComponents() +{ + ListView::initialiseComponents(); + setModel(&d_itemModel); +} + +//----------------------------------------------------------------------------// +void ListWidget::setIndexSelectionState(size_t item_index, bool state) +{ + if (item_index > getItemCount()) + { + CEGUI_THROW(InvalidRequestException( + "the value passed in the 'item_index' parameter is out of range for this ListWidget.")); + } + + ListView::setIndexSelectionState( + d_itemModel.makeIndex(item_index, d_itemModel.getRootIndex()), state); +} + +//----------------------------------------------------------------------------// +void ListWidget::setIndexSelectionState(StandardItem* item, bool state) +{ + if (item == 0) + { + CEGUI_THROW(InvalidRequestException("the item passed was null.")); + } + + ListView::setSelectedIndex(d_itemModel.getIndexForItem(item)); +} +//----------------------------------------------------------------------------// +StandardItem* ListWidget::getFirstSelectedItem() +{ + return getNextSelectedItem(0); +} + +//----------------------------------------------------------------------------// +StandardItem* ListWidget::getNextSelectedItem(const StandardItem* start_item) +{ + if (d_indexSelectionStates.empty()) + return 0; + + int child_id = d_itemModel.getChildId(start_item); + if (start_item != 0 && child_id == -1) + return 0; + + size_t index = start_item == 0 ? 0 : (static_cast(child_id) + 1); + size_t list_size = getItemCount(); + + for (; index < list_size; ++index) + { + if (isIndexSelected(index)) + { + return getItemAtIndex(index); + } + } + + return 0; +} + +//----------------------------------------------------------------------------// +StandardItemModel* ListWidget::getModel() +{ + return static_cast(&d_itemModel); +} + +//----------------------------------------------------------------------------// +void ListWidget::addItem(const String& text) +{ + d_itemModel.addItem(text); +} + +//----------------------------------------------------------------------------// +void ListWidget::addItem(StandardItem* item) +{ + d_itemModel.addItem(item); +} + +//----------------------------------------------------------------------------// +void ListWidget::insertItem(StandardItem* item, const StandardItem* position) +{ + d_itemModel.insertItem(item, position); +} + +//----------------------------------------------------------------------------// +void ListWidget::removeItem(const StandardItem* item) +{ + d_itemModel.removeItem(item); +} + +//----------------------------------------------------------------------------// +size_t ListWidget::getItemCount() const +{ + return d_itemModel.getChildCount(d_itemModel.getRootIndex()); +} + +//----------------------------------------------------------------------------// +size_t ListWidget::getSelectedItemsCount() const +{ + return d_indexSelectionStates.size(); +} + +//----------------------------------------------------------------------------// +StandardItem* ListWidget::getItemAtIndex(size_t index) +{ + return d_itemModel.getItemForIndex( + d_itemModel.makeIndex(index, d_itemModel.getRootIndex())); +} + +//----------------------------------------------------------------------------// +StandardItem* ListWidget::findItemWithText(const String& text, const StandardItem* start_item) +{ + int child_id = d_itemModel.getChildId(start_item); + if (start_item != 0 && child_id == -1) + return 0; + + // if start_item is NULL begin search at beginning, else start at item after start_item + size_t index = start_item == 0 ? 0 : (static_cast(child_id) + 1); + size_t list_size = getItemCount(); + + while (index < list_size) + { + if (getItemAtIndex(index)->getText() == text) + { + return getItemAtIndex(index); + } + + index++; + } + + return 0; +} + +//----------------------------------------------------------------------------// +void ListWidget::clearList() +{ + d_itemModel.clear(true); + + WindowEventArgs args(this); + onViewContentsChanged(args); +} + +//----------------------------------------------------------------------------// +bool ListWidget::isItemInList(const StandardItem* item) +{ + //TODO: move this logic to the model? + size_t child_count = d_itemModel.getChildCount(d_itemModel.getRootIndex()); + for (size_t i = 0; i < child_count; ++i) + { + if (item == d_itemModel.getItemForIndex( + d_itemModel.makeIndex(i, d_itemModel.getRootIndex()))) + return true; + } + + return false; +} + +//----------------------------------------------------------------------------// +bool ListWidget::isItemSelected(const StandardItem* item) +{ + for (SelectionStatesVector::const_iterator itor = getIndexSelectionStates().begin(); + itor != getIndexSelectionStates().end(); ++itor) + { + if (item == d_itemModel.getItemForIndex(itor->d_selectedIndex)) + { + return true; + } + } + + return false; +} + +//----------------------------------------------------------------------------// +bool ListWidget::isIndexSelected(size_t index) +{ + //TODO: make a macro/inline function for lists that makes an index - since Root is always the parent + return ListView::isIndexSelected(d_itemModel.makeIndex(index, d_itemModel.getRootIndex())); +} + +//----------------------------------------------------------------------------// +void ListWidget::ensureIndexIsVisible(const StandardItem* item) +{ + ListView::ensureIndexIsVisible(d_itemModel.getIndexForItem(item)); +} +} diff --git a/cegui/src/widgets/Listbox.cpp b/cegui/src/widgets/Listbox.cpp deleted file mode 100644 index b8b49b3d1..000000000 --- a/cegui/src/widgets/Listbox.cpp +++ /dev/null @@ -1,1188 +0,0 @@ -/*********************************************************************** - created: 13/4/2004 - author: Paul D Turner - - purpose: Implementation of Listbox widget base class -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/Exceptions.h" -#include "CEGUI/WindowManager.h" -#include "CEGUI/widgets/Listbox.h" -#include "CEGUI/widgets/ListboxItem.h" -#include "CEGUI/widgets/Scrollbar.h" -#include "CEGUI/widgets/Tooltip.h" -#include "CEGUI/CoordConverter.h" -#include - -// Start of CEGUI namespace section -namespace CEGUI -{ -const String Listbox::EventNamespace("Listbox"); -const String Listbox::WidgetTypeName("CEGUI/Listbox"); - -/************************************************************************* - ListboxWindowRenderer -*************************************************************************/ -ListboxWindowRenderer::ListboxWindowRenderer(const String& name) : - WindowRenderer(name, Listbox::EventNamespace) -{ -} - -/************************************************************************* - Constants -*************************************************************************/ -// event names -const String Listbox::EventListContentsChanged( "ListContentsChanged" ); -const String Listbox::EventSelectionChanged( "SelectionChanged" ); -const String Listbox::EventSortModeChanged( "SortModeChanged" ); -const String Listbox::EventMultiselectModeChanged( "MultiselectModeChanged" ); -const String Listbox::EventVertScrollbarModeChanged( "VertScrollbarModeChanged" ); -const String Listbox::EventHorzScrollbarModeChanged( "HorzScrollbarModeChanged" ); - -/************************************************************************* - Child Widget name constants -*************************************************************************/ -const String Listbox::VertScrollbarName( "__auto_vscrollbar__" ); -const String Listbox::HorzScrollbarName( "__auto_hscrollbar__" ); - -/************************************************************************* - Constructor for Listbox base class. -*************************************************************************/ -Listbox::Listbox(const String& type, const String& name) - : Window(type, name), - d_sorted(false), - d_multiselect(false), - d_forceVertScroll(false), - d_forceHorzScroll(false), - d_itemTooltips(false), - d_lastSelected(0) -{ - addListboxProperties(); -} - - -/************************************************************************* - Destructor for Listbox base class. -*************************************************************************/ -Listbox::~Listbox(void) -{ - resetList_impl(); -} - - -/************************************************************************* - Initialise the Window based object ready for use. -*************************************************************************/ -void Listbox::initialiseComponents(void) -{ - // get the component sub-widgets - Scrollbar* vertScrollbar = getVertScrollbar(); - Scrollbar* horzScrollbar = getHorzScrollbar(); - - vertScrollbar->subscribeEvent(Scrollbar::EventScrollPositionChanged, Event::Subscriber(&Listbox::handle_scrollChange, this)); - horzScrollbar->subscribeEvent(Scrollbar::EventScrollPositionChanged, Event::Subscriber(&Listbox::handle_scrollChange, this)); - - configureScrollbars(); - performChildWindowLayout(); -} - - -/************************************************************************* - Return the number of selected items in the list box. -*************************************************************************/ -size_t Listbox::getSelectedCount(void) const -{ - size_t count = 0; - - for (size_t index = 0; index < d_listItems.size(); ++index) - { - if (d_listItems[index]->isSelected()) - { - count++; - } - - } - - return count; -} - - -/************************************************************************* - Return a pointer to the first selected item. -*************************************************************************/ -ListboxItem* Listbox::getFirstSelectedItem(void) const -{ - return getNextSelected(0); -} - - -/************************************************************************* - Return a pointer to the next selected item after item 'start_item' -*************************************************************************/ -ListboxItem* Listbox::getNextSelected(const ListboxItem* start_item) const -{ - // if start_item is NULL begin search at begining, else start at item after start_item - size_t index = (start_item == 0) ? 0 : (getItemIndex(start_item) + 1); - - while (index < d_listItems.size()) - { - // return pointer to this item if it's selected. - if (d_listItems[index]->isSelected()) - { - return d_listItems[index]; - } - // not selected, advance to next - else - { - index++; - } - - } - - // no more selected items. - return 0; -} - - -/************************************************************************* - Return the item at index position 'index'. -*************************************************************************/ -ListboxItem* Listbox::getListboxItemFromIndex(size_t index) const -{ - if (index < d_listItems.size()) - { - return d_listItems[index]; - } - else - { - CEGUI_THROW(InvalidRequestException( - "the specified index is out of range for this Listbox.")); - } -} - - -/************************************************************************* - Return the index of ListboxItem \a item -*************************************************************************/ -size_t Listbox::getItemIndex(const ListboxItem* item) const -{ - LBItemList::const_iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); - - if (pos != d_listItems.end()) - { - return std::distance(d_listItems.begin(), pos); - } - else - { - CEGUI_THROW(InvalidRequestException( - "the specified ListboxItem is not attached to this Listbox.")); - } - -} - - -/************************************************************************* - return whether the string at index position \a index is selected -*************************************************************************/ -bool Listbox::isItemSelected(size_t index) const -{ - if (index < d_listItems.size()) - { - return d_listItems[index]->isSelected(); - } - else - { - CEGUI_THROW(InvalidRequestException( - "the specified index is out of range for this Listbox.")); - } - -} - - -/************************************************************************* - Search the list for an item with the specified text -*************************************************************************/ -ListboxItem* Listbox::findItemWithText(const String& text, const ListboxItem* start_item) -{ - // if start_item is NULL begin search at begining, else start at item after start_item - size_t index = (!start_item) ? 0 : (getItemIndex(start_item) + 1); - - while (index < d_listItems.size()) - { - // return pointer to this item if it's text matches - if (d_listItems[index]->getText() == text) - { - return d_listItems[index]; - } - // no matching text, advance to next item - else - { - index++; - } - - } - - // no items matched. - return 0; -} - - -/************************************************************************* - Return whether the specified ListboxItem is in the List -*************************************************************************/ -bool Listbox::isListboxItemInList(const ListboxItem* item) const -{ - return std::find(d_listItems.begin(), d_listItems.end(), item) != d_listItems.end(); -} - - - -/************************************************************************* - Remove all items from the list. -*************************************************************************/ -void Listbox::resetList(void) -{ - if (resetList_impl()) - { - WindowEventArgs args(this); - onListContentsChanged(args); - } - -} - - -/************************************************************************* - Add the given ListboxItem to the list. -*************************************************************************/ -void Listbox::addItem(ListboxItem* item) -{ - if (item) - { - // establish ownership - item->setOwnerWindow(this); - - // if sorting is enabled, re-sort the list - if (isSortEnabled()) - { - d_listItems.insert(std::upper_bound(d_listItems.begin(), d_listItems.end(), item, &lbi_less), item); - - } - // not sorted, just stick it on the end. - else - { - d_listItems.push_back(item); - } - - WindowEventArgs args(this); - onListContentsChanged(args); - } - -} - - -/************************************************************************* - Insert an item into the list box after a specified item already in - the list. -*************************************************************************/ -void Listbox::insertItem(ListboxItem* item, const ListboxItem* position) -{ - // if the list is sorted, it's the same as a normal add operation - if (isSortEnabled()) - { - addItem(item); - } - else if (item) - { - // establish ownership - item->setOwnerWindow(this); - - // if position is NULL begin insert at begining, else insert after item 'position' - LBItemList::iterator ins_pos; - - if (!position) - { - ins_pos = d_listItems.begin(); - } - else - { - ins_pos = std::find(d_listItems.begin(), d_listItems.end(), position); - - // throw if item 'position' is not in the list - if (ins_pos == d_listItems.end()) - { - CEGUI_THROW(InvalidRequestException( - "the specified ListboxItem for parameter 'position' is not attached to this Listbox.")); - } - - } - - d_listItems.insert(ins_pos, item); - - WindowEventArgs args(this); - onListContentsChanged(args); - } - -} - - -/************************************************************************* - Removes the given item from the list box. -*************************************************************************/ -void Listbox::removeItem(const ListboxItem* item) -{ - if (item) - { - LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); - - // if item is in the list - if (pos != d_listItems.end()) - { - // disown item - (*pos)->setOwnerWindow(0); - - // remove item - d_listItems.erase(pos); - - // if item was the last selected item, reset that to NULL - if (item == d_lastSelected) - { - d_lastSelected = 0; - } - - // if item is supposed to be deleted by us - if (item->isAutoDeleted()) - { - // clean up this item. - CEGUI_DELETE_AO item; - } - - WindowEventArgs args(this); - onListContentsChanged(args); - } - - } - -} - - -/************************************************************************* - Clear the selected state for all items. -*************************************************************************/ -void Listbox::clearAllSelections(void) -{ - // only fire events and update if we actually made any changes - if (clearAllSelections_impl()) - { - WindowEventArgs args(this); - onSelectionChanged(args); - } - -} - - -/************************************************************************* - Set whether the list should be sorted. -*************************************************************************/ -void Listbox::setSortingEnabled(bool setting) -{ - // only react if the setting will change - if (d_sorted != setting) - { - d_sorted = setting; - - // if we are enabling sorting, we need to sort the list - if (d_sorted) - { - resortList(); - } - - WindowEventArgs args(this); - onSortModeChanged(args); - } - -} - - -/************************************************************************* - Set whether the list should allow multiple selections or just a - single selection -*************************************************************************/ -void Listbox::setMultiselectEnabled(bool setting) -{ - // only react if the setting is changed - if (d_multiselect != setting) - { - d_multiselect = setting; - - // if we change to single-select, deselect all except the first selected item. - WindowEventArgs args(this); - if ((!d_multiselect) && (getSelectedCount() > 1)) - { - ListboxItem* itm = getFirstSelectedItem(); - - while ((itm = getNextSelected(itm))) - { - itm->setSelected(false); - } - - onSelectionChanged(args); - - } - - onMultiselectModeChanged(args); - } - -} - -void Listbox::setItemTooltipsEnabled(bool setting) -{ - d_itemTooltips = setting; -} - - - -/************************************************************************* - Set whether the vertical scroll bar should always be shown. -*************************************************************************/ -void Listbox::setShowVertScrollbar(bool setting) -{ - if (d_forceVertScroll != setting) - { - d_forceVertScroll = setting; - - configureScrollbars(); - WindowEventArgs args(this); - onVertScrollbarModeChanged(args); - } - -} - - -/************************************************************************* - Set whether the horizontal scroll bar should always be shown. -*************************************************************************/ -void Listbox::setShowHorzScrollbar(bool setting) -{ - if (d_forceHorzScroll != setting) - { - d_forceHorzScroll = setting; - - configureScrollbars(); - WindowEventArgs args(this); - onHorzScrollbarModeChanged(args); - } - -} - - -/************************************************************************* - Set the select state of an attached ListboxItem. -*************************************************************************/ -void Listbox::setItemSelectState(ListboxItem* item, bool state) -{ - LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); - - if (pos != d_listItems.end()) - { - setItemSelectState(std::distance(d_listItems.begin(), pos), state); - } - else - { - CEGUI_THROW(InvalidRequestException( - "the specified ListboxItem is not attached to this Listbox.")); - } -} - - -/************************************************************************* - Set the select state of an attached ListboxItem. -*************************************************************************/ -void Listbox::setItemSelectState(size_t item_index, bool state) -{ - if (item_index < getItemCount()) - { - // only do this if the setting is changing - if (d_listItems[item_index]->isSelected() != state) - { - // conditions apply for single-select mode - if (state && !d_multiselect) - { - clearAllSelections_impl(); - } - - d_listItems[item_index]->setSelected(state); - WindowEventArgs args(this); - onSelectionChanged(args); - } - - } - else - { - CEGUI_THROW(InvalidRequestException( - "the value passed in the 'item_index' parameter is out of range for this Listbox.")); - } - -} - - -/************************************************************************* - Causes the list box to update it's internal state after changes have - been made to one or more attached ListboxItem objects. -*************************************************************************/ -void Listbox::handleUpdatedItemData(void) -{ - if (d_sorted) - resortList(); - - configureScrollbars(); - invalidate(); -} - - -/************************************************************************* - display required integrated scroll bars according to current state - of the list box and update their values. -*************************************************************************/ -void Listbox::configureScrollbars(void) -{ - Scrollbar* vertScrollbar = getVertScrollbar(); - Scrollbar* horzScrollbar = getHorzScrollbar(); - - float totalHeight = getTotalItemsHeight(); - float widestItem = getWidestItemWidth(); - - // - // First show or hide the scroll bars as needed (or requested) - // - // show or hide vertical scroll bar as required (or as specified by option) - if ((totalHeight > getListRenderArea().getHeight()) || d_forceVertScroll) - { - vertScrollbar->show(); - - // show or hide horizontal scroll bar as required (or as specified by option) - if ((widestItem > getListRenderArea().getWidth()) || d_forceHorzScroll) - { - horzScrollbar->show(); - } - else - { - horzScrollbar->hide(); - } - - } - else - { - // show or hide horizontal scroll bar as required (or as specified by option) - if ((widestItem > getListRenderArea().getWidth()) || d_forceHorzScroll) - { - horzScrollbar->show(); - - // show or hide vertical scroll bar as required (or as specified by option) - if ((totalHeight > getListRenderArea().getHeight()) || d_forceVertScroll) - { - vertScrollbar->show(); - } - else - { - vertScrollbar->hide(); - } - - } - else - { - vertScrollbar->hide(); - horzScrollbar->hide(); - } - - } - - // - // Set up scroll bar values - // - Rectf renderArea(getListRenderArea()); - - vertScrollbar->setDocumentSize(totalHeight); - vertScrollbar->setPageSize(renderArea.getHeight()); - vertScrollbar->setStepSize(ceguimax(1.0f, renderArea.getHeight() / 10.0f)); - vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition()); - - horzScrollbar->setDocumentSize(widestItem); - horzScrollbar->setPageSize(renderArea.getWidth()); - horzScrollbar->setStepSize(ceguimax(1.0f, renderArea.getWidth() / 10.0f)); - horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition()); -} - - -/************************************************************************* - select all strings between positions 'start' and 'end' (inclusive) -*************************************************************************/ -void Listbox::selectRange(size_t start, size_t end) -{ - // only continue if list has some items - if (!d_listItems.empty()) - { - // if start is out of range, start at begining. - if (start > d_listItems.size()) - { - start = 0; - } - - // if end is out of range end at the last item. - if (end >= d_listItems.size()) - { - end = d_listItems.size() - 1; - } - - // ensure start becomes before the end. - if (start > end) - { - size_t tmp; - tmp = start; - start = end; - end = tmp; - } - - // perform selections - for( ; start <= end; ++start) - { - d_listItems[start]->setSelected(true); - } - - } - -} - - -/************************************************************************* - Return the sum of all item heights -*************************************************************************/ -float Listbox::getTotalItemsHeight(void) const -{ - float height = 0; - - for (size_t i = 0; i < getItemCount(); ++i) - { - height += d_listItems[i]->getPixelSize().d_height; - } - - return height; -} - - -/************************************************************************* - Return the width of the widest item -*************************************************************************/ -float Listbox::getWidestItemWidth(void) const -{ - float widest = 0; - - for (size_t i = 0; i < getItemCount(); ++i) - { - float thisWidth = d_listItems[i]->getPixelSize().d_width; - - if (thisWidth > widest) - { - widest = thisWidth; - } - - } - - return widest; -} - - -/************************************************************************* - Clear the selected state for all items (implementation) -*************************************************************************/ -bool Listbox::clearAllSelections_impl(void) -{ - // flag used so we can track if we did anything. - bool modified = false; - - for (size_t index = 0; index < d_listItems.size(); ++index) - { - if (d_listItems[index]->isSelected()) - { - d_listItems[index]->setSelected(false); - modified = true; - } - - } - - return modified; -} - - -/************************************************************************* - Return the ListboxItem under the given screen pixel co-ordinate. -*************************************************************************/ -ListboxItem* Listbox::getItemAtPoint(const Vector2f& pt) const -{ - const Vector2f local_pos(CoordConverter::screenToWindow(*this, pt)); - const Rectf renderArea(getListRenderArea()); - - // point must be within the rendering area of the Listbox. - if (renderArea.isPointInRect(local_pos)) - { - float y = renderArea.d_min.d_x - getVertScrollbar()->getScrollPosition(); - - // test if point is above first item - if (local_pos.d_y >= y) - { - for (size_t i = 0; i < getItemCount(); ++i) - { - y += d_listItems[i]->getPixelSize().d_height; - - if (local_pos.d_y < y) - { - return d_listItems[i]; - } - - } - } - } - - return 0; -} - - -/************************************************************************* - Handler called internally when the list contents are changed -*************************************************************************/ -void Listbox::onListContentsChanged(WindowEventArgs& e) -{ - configureScrollbars(); - invalidate(); - fireEvent(EventListContentsChanged, e, EventNamespace); -} - - -/************************************************************************* - Handler called internally when the currently selected item or items - changes. -*************************************************************************/ -void Listbox::onSelectionChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventSelectionChanged, e, EventNamespace); -} - - -/************************************************************************* - Handler called internally when the sort mode setting changes. -*************************************************************************/ -void Listbox::onSortModeChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventSortModeChanged, e, EventNamespace); -} - - -/************************************************************************* - Handler called internally when the multi-select mode setting changes. -*************************************************************************/ -void Listbox::onMultiselectModeChanged(WindowEventArgs& e) -{ - fireEvent(EventMultiselectModeChanged, e, EventNamespace); -} - - -/************************************************************************* - Handler called internally when the forced display of the vertical - scroll bar setting changes. -*************************************************************************/ -void Listbox::onVertScrollbarModeChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventVertScrollbarModeChanged, e, EventNamespace); -} - - -/************************************************************************* - Handler called internally when the forced display of the horizontal - scroll bar setting changes. -*************************************************************************/ -void Listbox::onHorzScrollbarModeChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventHorzScrollbarModeChanged, e, EventNamespace); -} - - -/************************************************************************* - Handler for when we are sized -*************************************************************************/ -void Listbox::onSized(ElementEventArgs& e) -{ - // base class handling - Window::onSized(e); - - configureScrollbars(); - - ++e.handled; -} - - -/************************************************************************* - Handler for when mouse button is pressed -*************************************************************************/ -void Listbox::onMouseButtonDown(MouseEventArgs& e) -{ - // base class processing - Window::onMouseButtonDown(e); - - if (e.button == LeftButton) - { - bool modified = false; - - // clear old selections if no control key is pressed or if multi-select is off - if (!(e.sysKeys & Control) || !d_multiselect) - { - modified = clearAllSelections_impl(); - } - - ListboxItem* item = getItemAtPoint(e.position); - - if (item) - { - modified = true; - - // select range or item, depending upon keys and last selected item - if (((e.sysKeys & Shift) && (d_lastSelected != 0)) && d_multiselect) - { - selectRange(getItemIndex(item), getItemIndex(d_lastSelected)); - } - else - { - item->setSelected(item->isSelected() ^ true); - } - - // update last selected item - d_lastSelected = item->isSelected() ? item : 0; - } - - // fire event if needed - if (modified) - { - WindowEventArgs args(this); - onSelectionChanged(args); - } - - ++e.handled; - } - -} - - -/************************************************************************* - Handler for mouse wheel changes -*************************************************************************/ -void Listbox::onMouseWheel(MouseEventArgs& e) -{ - // base class processing. - Window::onMouseWheel(e); - - Scrollbar* vertScrollbar = getVertScrollbar(); - Scrollbar* horzScrollbar = getHorzScrollbar(); - - if (vertScrollbar->isEffectiveVisible() && (vertScrollbar->getDocumentSize() > vertScrollbar->getPageSize())) - { - vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.wheelChange); - } - else if (horzScrollbar->isEffectiveVisible() && (horzScrollbar->getDocumentSize() > horzScrollbar->getPageSize())) - { - horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.wheelChange); - } - - ++e.handled; -} - -/************************************************************************* - Handler for mouse movement -*************************************************************************/ -void Listbox::onMouseMove(MouseEventArgs& e) -{ - if (d_itemTooltips) - { - static ListboxItem* lastItem = 0; - - ListboxItem* item = getItemAtPoint(e.position); - if (item != lastItem) - { - if (item) - { - setTooltipText(item->getTooltipText()); - } - else - { - setTooltipText(""); - } - lastItem = item; - } - - // must check the result from getTooltip(), as the tooltip object could - // be 0 at any time for various reasons. - Tooltip* tooltip = getTooltip(); - - if (tooltip) - { - if (tooltip->getTargetWindow() != this) - tooltip->setTargetWindow(this); - else - tooltip->positionSelf(); - } - } - - Window::onMouseMove(e); -} - - -/************************************************************************* - Ensure the item at the specified index is visible within the list box. -*************************************************************************/ -void Listbox::ensureItemIsVisible(size_t item_index) -{ - Scrollbar* vertScrollbar = getVertScrollbar(); - - // handle simple "scroll to the bottom" case - if (item_index >= getItemCount()) - { - vertScrollbar->setScrollPosition(vertScrollbar->getDocumentSize() - vertScrollbar->getPageSize()); - } - else - { - float bottom; - float listHeight = getListRenderArea().getHeight(); - float top = 0; - - // get height to top of item - size_t i; - for (i = 0; i < item_index; ++i) - { - top += d_listItems[i]->getPixelSize().d_height; - } - - // calculate height to bottom of item - bottom = top + d_listItems[i]->getPixelSize().d_height; - - // account for current scrollbar value - float currPos = vertScrollbar->getScrollPosition(); - top -= currPos; - bottom -= currPos; - - // if top is above the view area, or if item is too big to fit - if ((top < 0.0f) || ((bottom - top) > listHeight)) - { - // scroll top of item to top of box. - vertScrollbar->setScrollPosition(currPos + top); - } - // if bottom is below the view area - else if (bottom >= listHeight) - { - // position bottom of item at the bottom of the list - vertScrollbar->setScrollPosition(currPos + bottom - listHeight); - } - - // Item is already fully visible - nothing more to do. - } - -} - - -/************************************************************************* - Ensure the item at the specified index is visible within the list box. -*************************************************************************/ -void Listbox::ensureItemIsVisible(const ListboxItem* item) -{ - ensureItemIsVisible(getItemIndex(item)); -} - - -/************************************************************************* - Return whether the vertical scroll bar is always shown. -*************************************************************************/ -bool Listbox::isVertScrollbarAlwaysShown(void) const -{ - return d_forceVertScroll; -} - - -/************************************************************************* - Return whether the horizontal scroll bar is always shown. -*************************************************************************/ -bool Listbox::isHorzScrollbarAlwaysShown(void) const -{ - return d_forceHorzScroll; -} - -/************************************************************************* - Add properties for this class -*************************************************************************/ -void Listbox::addListboxProperties(void) -{ - const String& propertyOrigin = WidgetTypeName; - - CEGUI_DEFINE_PROPERTY(Listbox, bool, - "Sort","Property to get/set the sort setting of the list box. Value is either \"true\" or \"false\".", - &Listbox::setSortingEnabled, &Listbox::isSortEnabled, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Listbox, bool, - "MultiSelect","Property to get/set the multi-select setting of the list box. Value is either \"true\" or \"false\".", - &Listbox::setMultiselectEnabled, &Listbox::isMultiselectEnabled, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Listbox, bool, - "ForceVertScrollbar","Property to get/set the 'always show' setting for the vertical scroll bar of the list box. Value is either \"true\" or \"false\".", - &Listbox::setShowVertScrollbar, &Listbox::isVertScrollbarAlwaysShown, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Listbox, bool, - "ForceHorzScrollbar","Property to get/set the 'always show' setting for the horizontal scroll bar of the list box. Value is either \"true\" or \"false\".", - &Listbox::setShowHorzScrollbar, &Listbox::isHorzScrollbarAlwaysShown, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Listbox, bool, - "ItemTooltips","Property to access the show item tooltips setting of the list box. Value is either \"true\" or \"false\".", - &Listbox::setItemTooltipsEnabled, &Listbox::isItemTooltipsEnabled, false /* TODO: Inconsistency */ - ); -} - - -/************************************************************************* - Remove all items from the list. -*************************************************************************/ -bool Listbox::resetList_impl(void) -{ - // just return false if the list is already empty - if (getItemCount() == 0) - { - return false; - } - // we have items to be removed and possible deleted - else - { - // delete any items we are supposed to - for (size_t i = 0; i < getItemCount(); ++i) - { - // if item is supposed to be deleted by us - if (d_listItems[i]->isAutoDeleted()) - { - // clean up this item. - CEGUI_DELETE_AO d_listItems[i]; - } - - } - - // clear out the list. - d_listItems.clear(); - - d_lastSelected = 0; - - return true; - } - -} - -/************************************************************************* - Handler for scroll position changes. -*************************************************************************/ -bool Listbox::handle_scrollChange(const EventArgs&) -{ - // simply trigger a redraw of the Listbox. - invalidate(); - return true; -} - -/************************************************************************* - Return a pointer to the vertical scrollbar component widget for this - Listbox. -*************************************************************************/ -Scrollbar* Listbox::getVertScrollbar() const -{ - return static_cast(getChild(VertScrollbarName)); -} - -/************************************************************************* - Return a pointer to the horizontal scrollbar component widget for this - Listbox. -*************************************************************************/ -Scrollbar* Listbox::getHorzScrollbar() const -{ - return static_cast(getChild(HorzScrollbarName)); -} - -/************************************************************************* - Return a Rect object describing, in un-clipped pixels, the window - relative area that is to be used for rendering list items. -*************************************************************************/ -Rectf Listbox::getListRenderArea() const -{ - if (d_windowRenderer != 0) - { - ListboxWindowRenderer* wr = (ListboxWindowRenderer*)d_windowRenderer; - return wr->getListRenderArea(); - } - else - { - CEGUI_THROW(InvalidRequestException( - "This function must be implemented by the window renderer module")); - } -} - -bool Listbox::validateWindowRenderer(const WindowRenderer* renderer) const -{ - return dynamic_cast(renderer) != 0; -} - -/************************************************************************* - Function to resort the list data. -*************************************************************************/ -void Listbox::resortList() -{ - std::sort(d_listItems.begin(), d_listItems.end(), &lbi_less); -} - -////////////////////////////////////////////////////////////////////////// -/************************************************************************* - Functions used for predicates in std algorithms -*************************************************************************/ -////////////////////////////////////////////////////////////////////////// -/************************************************************************* - used for < comparisons between ListboxItem pointers -*************************************************************************/ -bool lbi_less(const ListboxItem* a, const ListboxItem* b) -{ - return *a < *b; -} - -/************************************************************************* - used for > comparisons between ListboxItem pointers -*************************************************************************/ -bool lbi_greater(const ListboxItem* a, const ListboxItem* b) -{ - return *a > *b; -} - -} // End of CEGUI namespace section diff --git a/cegui/src/widgets/ListboxItem.cpp b/cegui/src/widgets/ListboxItem.cpp index 1b430fdd1..bb868a03e 100644 --- a/cegui/src/widgets/ListboxItem.cpp +++ b/cegui/src/widgets/ListboxItem.cpp @@ -57,9 +57,9 @@ ListboxItem::ListboxItem(const String& text, uint item_id, void* item_data, bool #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), + d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), + d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif @@ -78,7 +78,7 @@ ListboxItem::ListboxItem(const String& text, uint item_id, void* item_data, bool //----------------------------------------------------------------------------// ListboxItem::~ListboxItem(void) { - CEGUI_DELETE_AO d_bidiVisualMapping; + delete d_bidiVisualMapping; } /************************************************************************* @@ -89,23 +89,6 @@ void ListboxItem::setSelectionBrushImage(const String& name) setSelectionBrushImage(&ImageManager::getSingleton().get(name)); } - -/************************************************************************* - Return a ColourRect object describing the colours in 'cols' after - having their alpha component modulated by the value 'alpha'. -*************************************************************************/ -ColourRect ListboxItem::getModulateAlphaColourRect(const ColourRect& cols, float alpha) const -{ - return ColourRect - ( - calculateModulatedAlphaColour(cols.d_top_left, alpha), - calculateModulatedAlphaColour(cols.d_top_right, alpha), - calculateModulatedAlphaColour(cols.d_bottom_left, alpha), - calculateModulatedAlphaColour(cols.d_bottom_right, alpha) - ); -} - - /************************************************************************* Return a colour value describing the colour specified by 'col' after having its alpha component modulated by the value 'alpha'. diff --git a/cegui/src/widgets/ListboxTextItem.cpp b/cegui/src/widgets/ListboxTextItem.cpp index 9b6c69801..0f56f9d0e 100644 --- a/cegui/src/widgets/ListboxTextItem.cpp +++ b/cegui/src/widgets/ListboxTextItem.cpp @@ -32,6 +32,7 @@ #include "CEGUI/Window.h" #include "CEGUI/Image.h" #include "CEGUI/CoordConverter.h" +#include "CEGUI/GeometryBuffer.h" // Start of CEGUI namespace section namespace CEGUI @@ -131,33 +132,34 @@ Sizef ListboxTextItem::getPixelSize(void) const /************************************************************************* Draw the list box item in its current state. *************************************************************************/ -void ListboxTextItem::draw(GeometryBuffer& buffer, const Rectf& targetRect, +void ListboxTextItem::draw(std::vector& geometry_buffers, const Rectf& targetRect, float alpha, const Rectf* clipper) const { if (d_selected && d_selectBrush != 0) - d_selectBrush->render(buffer, targetRect, clipper, - getModulateAlphaColourRect(d_selectCols, alpha)); + { + d_selectBrush->render(geometry_buffers, targetRect, clipper, true, + d_selectCols, alpha); + } const Font* font = getFont(); if (!font) return; - Vector2f draw_pos(targetRect.getPosition()); + glm::vec2 draw_pos(targetRect.getPositionGLM()); - draw_pos.d_y += CoordConverter::alignToPixels( + draw_pos.y += CoordConverter::alignToPixels( (font->getLineSpacing() - font->getFontHeight()) * 0.5f); if (!d_renderedStringValid) parseTextString(); - const ColourRect final_colours( - getModulateAlphaColourRect(ColourRect(0xFFFFFFFF), alpha)); + const ColourRect final_colours(ColourRect(0xFFFFFFFF)); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { - d_renderedString.draw(d_owner, i, buffer, draw_pos, &final_colours, clipper, 0.0f); - draw_pos.d_y += d_renderedString.getPixelSize(d_owner, i).d_height; + d_renderedString.draw(d_owner, i, geometry_buffers, draw_pos, &final_colours, clipper, 0.0f); + draw_pos.y += d_renderedString.getPixelSize(d_owner, i).d_height; } } diff --git a/cegui/src/widgets/MenuItem.cpp b/cegui/src/widgets/MenuItem.cpp index b16dcdced..09806bd57 100644 --- a/cegui/src/widgets/MenuItem.cpp +++ b/cegui/src/widgets/MenuItem.cpp @@ -59,8 +59,6 @@ MenuItem::MenuItem(const String& type, const String& name) d_autoPopupTimeElapsed(0.0f), d_popup(0) { - // menuitems dont want multi-click events - setWantsMultiClickEvents(false); // add the new properties addMenuItemProperties(); d_popupOffset.d_x = cegui_absdim(0); @@ -79,7 +77,7 @@ MenuItem::~MenuItem(void) /************************************************************************* Update the internal state of the Widget *************************************************************************/ -void MenuItem::updateInternalState(const Vector2f& mouse_pos) +void MenuItem::updateInternalState(const glm::vec2& cursor_pos) { bool oldstate = d_hovering; @@ -90,9 +88,9 @@ void MenuItem::updateInternalState(const Vector2f& mouse_pos) const Window* capture_wnd = getCaptureWindow(); if (capture_wnd == 0) - d_hovering = (getGUIContext().getWindowContainingMouse() == this && isHit(mouse_pos)); + d_hovering = (getGUIContext().getWindowContainingCursor() == this && isHit(cursor_pos)); else - d_hovering = (capture_wnd == this && isHit(mouse_pos)); + d_hovering = (capture_wnd == this && isHit(cursor_pos)); // if state has changed, trigger a re-draw // and possible make the parent menu open another popup @@ -325,7 +323,7 @@ void MenuItem::closeAllMenuItemPopups() // are we attached to a PopupMenu? if (!d_ownerList) return; - + if (dynamic_cast(d_ownerList)) { closePopupMenu(); @@ -338,7 +336,7 @@ void MenuItem::closeAllMenuItemPopups() // is this parent popup attached to a menu item? Window* popParent = pop->getParent(); MenuItem* mi = dynamic_cast(popParent); - + if (mi) { // recurse @@ -370,18 +368,18 @@ void MenuItem::onClicked(WindowEventArgs& e) /************************************************************************* - Handler for when the mouse moves + Handler for when the cursor moves *************************************************************************/ -void MenuItem::onMouseMove(MouseEventArgs& e) +void MenuItem::onCursorMove(CursorInputEventArgs& e) { - // this is needed to discover whether mouse is in the widget area or not. + // this is needed to discover whether cursor is in the widget area or not. // The same thing used to be done each frame in the rendering method, // but in this version the rendering method may not be called every frame // so we must discover the internal widget state here - which is actually // more efficient anyway. // base class processing - ItemEntry::onMouseMove(e); + ItemEntry::onCursorMove(e); updateInternalState(e.position); ++e.handled; @@ -389,14 +387,14 @@ void MenuItem::onMouseMove(MouseEventArgs& e) /************************************************************************* - Handler for mouse button pressed events + Handler for cursor pressed events *************************************************************************/ -void MenuItem::onMouseButtonDown(MouseEventArgs& e) +void MenuItem::onCursorPressHold(CursorInputEventArgs& e) { // default processing - ItemEntry::onMouseButtonDown(e); + ItemEntry::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { d_popupWasClosed = false; @@ -411,27 +409,26 @@ void MenuItem::onMouseButtonDown(MouseEventArgs& e) // event was handled by us. ++e.handled; } - } /************************************************************************* - Handler for mouse button release events + Handler for cursor activation events *************************************************************************/ -void MenuItem::onMouseButtonUp(MouseEventArgs& e) +void MenuItem::onCursorActivate(CursorInputEventArgs& e) { // default processing - ItemEntry::onMouseButtonUp(e); + ItemEntry::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { releaseInput(); // was the button released over this window? - // (use mouse position, as e.position in args has been unprojected) + // (use cursor position, as e.position in args has been unprojected) if (!d_popupWasClosed && getGUIContext().getRootWindow()->getTargetChildAtPosition( - getGUIContext().getMouseCursor().getPosition()) == this) + getGUIContext().getCursor().getPosition()) == this) { WindowEventArgs we(this); onClicked(we); @@ -440,11 +437,10 @@ void MenuItem::onMouseButtonUp(MouseEventArgs& e) // event was handled by us. ++e.handled; } - } /************************************************************************* - Handler for when mouse capture is lost + Handler for when cursor capture is lost *************************************************************************/ void MenuItem::onCaptureLost(WindowEventArgs& e) { @@ -453,7 +449,7 @@ void MenuItem::onCaptureLost(WindowEventArgs& e) d_pushed = false; updateInternalState(getUnprojectedPosition( - getGUIContext().getMouseCursor().getPosition())); + getGUIContext().getCursor().getPosition())); invalidate(); // event was handled by us. @@ -462,12 +458,12 @@ void MenuItem::onCaptureLost(WindowEventArgs& e) /************************************************************************* - Handler for when mouse leaves the widget + Handler for when cursor leaves the widget *************************************************************************/ -void MenuItem::onMouseLeaves(MouseEventArgs& e) +void MenuItem::onCursorLeaves(CursorInputEventArgs& e) { - // deafult processing - ItemEntry::onMouseLeaves(e); + // default processing + ItemEntry::onCursorLeaves(e); d_hovering = false; invalidate(); @@ -486,7 +482,7 @@ void MenuItem::onTextChanged(WindowEventArgs& e) // if we are attached to a ItemListBase, we make it update as necessary Window* parent = getParent(); ItemListBase* ilb = dynamic_cast(parent); - + if (ilb) { ilb->handleUpdatedItemData(); @@ -502,7 +498,7 @@ void MenuItem::updateSelf(float elapsed) { ItemEntry::updateSelf(elapsed); - //handle delayed popup closing/opening when hovering with the mouse + //handle delayed popup closing/opening when hovering with the cursor if (d_autoPopupTimeout != 0.0f && (d_popupOpening || d_popupClosing)) { // stop timer if the hovering state isn't set appropriately anymore @@ -540,12 +536,12 @@ void MenuItem::updateSelf(float elapsed) void MenuItem::addChild_impl(Element* element) { Window* wnd = dynamic_cast(element); - + if (!wnd) CEGUI_THROW(InvalidRequestException( "MenuItem can only have Elements of type Window added as children " "(Window path: " + getNamePath() + ").")); - + ItemEntry::addChild_impl(wnd); PopupMenu* pop = dynamic_cast(wnd); @@ -562,12 +558,12 @@ Add MenuItem specific properties void MenuItem::addMenuItemProperties(void) { const String& propertyOrigin = WidgetTypeName; - + CEGUI_DEFINE_PROPERTY(MenuItem, UVector2, "PopupOffset","Property to specify an offset for the popup menu position. Value is a UVector2 property value.", &MenuItem::setPopupOffset, &MenuItem::getPopupOffset, UVector2::zero() ); - + CEGUI_DEFINE_PROPERTY(MenuItem, float, "AutoPopupTimeout","Property to specify the time, which has to elapse before the popup window is opened/closed if the hovering state changes. Value is a float property value.", &MenuItem::setAutoPopupTimeout, &MenuItem::getAutoPopupTimeout, 0.0f diff --git a/cegui/src/widgets/MultiColumnList.cpp b/cegui/src/widgets/MultiColumnList.cpp index 676a9c5c7..1ed44c5ea 100644 --- a/cegui/src/widgets/MultiColumnList.cpp +++ b/cegui/src/widgets/MultiColumnList.cpp @@ -799,7 +799,7 @@ void MultiColumnList::removeColumn(uint col_idx) // delete the ListboxItem as needed. if ((item != 0) && item->isAutoDeleted()) { - CEGUI_DELETE_AO item; + delete item; } } @@ -974,7 +974,7 @@ void MultiColumnList::removeRow(uint row_idx) if ((item != 0) && item->isAutoDeleted()) { - CEGUI_DELETE_AO item; + delete item; } } @@ -1019,7 +1019,7 @@ void MultiColumnList::setItem(ListboxItem* item, const MCLGridRef& position) if ((oldItem != 0) && oldItem->isAutoDeleted()) { - CEGUI_DELETE_AO oldItem; + delete oldItem; } // set new item. @@ -1595,10 +1595,10 @@ bool MultiColumnList::clearAllSelections_impl(void) /************************************************************************* Return the ListboxItem under the given window local pixel co-ordinate. *************************************************************************/ -ListboxItem* MultiColumnList::getItemAtPoint(const Vector2f& pt) const +ListboxItem* MultiColumnList::getItemAtPoint(const glm::vec2& pt) const { const ListHeader* header = getListHeader(); - Rectf listArea(getListRenderArea()); + const Rectf listArea(getListRenderArea()); float y = listArea.d_min.d_y - getVertScrollbar()->getScrollPosition(); float x = listArea.d_min.d_x - getHorzScrollbar()->getScrollPosition(); @@ -1608,7 +1608,7 @@ ListboxItem* MultiColumnList::getItemAtPoint(const Vector2f& pt) const y += getHighestRowItemHeight(i); // have we located the row? - if (pt.d_y < y) + if (pt.y < y) { // scan across to find column that was clicked for (uint j = 0; j < getColumnCount(); ++j) @@ -1617,7 +1617,7 @@ ListboxItem* MultiColumnList::getItemAtPoint(const Vector2f& pt) const x += CoordConverter::asAbsolute(seg.getWidth(), header->getPixelSize().d_width); // was this the column? - if (pt.d_x < x) + if (pt.x < x) { // return contents of grid element that was clicked. return d_grid[i][j]; @@ -1918,80 +1918,97 @@ void MultiColumnList::onSized(ElementEventArgs& e) /************************************************************************* - Handler for when mouse button is pressed + Handler for when cursor is pressed *************************************************************************/ -void MultiColumnList::onMouseButtonDown(MouseEventArgs& e) +void MultiColumnList::onCursorPressHold(CursorInputEventArgs& e) { - // base class processing - Window::onMouseButtonDown(e); + // base class processing + Window::onCursorPressHold(e); - if (e.button == LeftButton) - { - bool modified = false; - - Vector2f localPos(CoordConverter::screenToWindow(*this, e.position)); - ListboxItem* item = getItemAtPoint(localPos); - - if (item) - { - // clear old selections if no control key is pressed or if multi-select is off - if (!(e.sysKeys & Control) || !d_multiSelect) - { - modified = clearAllSelections_impl(); - } - - modified = true; - - // select range or item, depending upon keys and last selected item - if (((e.sysKeys & Shift) && (d_lastSelected != 0)) && d_multiSelect) - { - modified |= selectRange(getItemGridReference(item), getItemGridReference(d_lastSelected)); - } - else - { - modified |= setItemSelectState_impl(getItemGridReference(item), item->isSelected() ^ true); - } + if (e.source == CIS_Left) + { + const glm::vec2 local_point = CoordConverter::screenToWindow(*this, e.position); + handleSelection(local_point, false, false); - // update last selected item - d_lastSelected = item->isSelected() ? item : 0; - } + ++e.handled; + } +} - // fire event if needed - if (modified) - { - WindowEventArgs args(this); - onSelectionChanged(args); - } +void MultiColumnList::onSemanticInputEvent(SemanticEventArgs& e) +{ + bool cumulative = e.d_semanticValue == SV_SelectCumulative; + bool range = e.d_semanticValue == SV_SelectRange; - ++e.handled; - } + if (cumulative || range) + { + const glm::vec2 local_point = CoordConverter::screenToWindow(*this, + getGUIContext().getCursor().getPosition()); + handleSelection(local_point, cumulative, range); + ++ e.handled; + } } - /************************************************************************* - Handler for mouse wheel changes + Handler for scroll actions *************************************************************************/ -void MultiColumnList::onMouseWheel(MouseEventArgs& e) +void MultiColumnList::onScroll(CursorInputEventArgs& e) { // base class processing. - Window::onMouseWheel(e); + Window::onScroll(e); Scrollbar* vertScrollbar = getVertScrollbar(); Scrollbar* horzScrollbar = getHorzScrollbar(); if (vertScrollbar->isEffectiveVisible() && (vertScrollbar->getDocumentSize() > vertScrollbar->getPageSize())) { - vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.wheelChange); + vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.scroll); } else if (horzScrollbar->isEffectiveVisible() && (horzScrollbar->getDocumentSize() > horzScrollbar->getPageSize())) { - horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.wheelChange); + horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.scroll); } ++e.handled; } +void MultiColumnList::handleSelection(const glm::vec2& position, bool cumulative, bool range) +{ + bool modified = false; + + ListboxItem* item = getItemAtPoint(position); + + if (item) + { + // clear old selections if not a cumulative selection or if multi-select is off + if (!cumulative || !d_multiSelect) + { + modified = clearAllSelections_impl(); + } + + modified = true; + + // select range or item, depending upon state and last selected item + if (range && (d_lastSelected != 0) && d_multiSelect) + { + modified |= selectRange(getItemGridReference(item), getItemGridReference(d_lastSelected)); + } + else + { + modified |= setItemSelectState_impl(getItemGridReference(item), item->isSelected() ^ true); + } + + // update last selected item + d_lastSelected = item->isSelected() ? item : 0; + } + + // fire event if needed + if (modified) + { + WindowEventArgs args(this); + onSelectionChanged(args); + } +} /************************************************************************* Event handler for header offset changes (scrolling) @@ -2225,7 +2242,7 @@ void MultiColumnList::addMultiColumnListProperties(void) "ColumnsMovable", "Property to get/set the setting for user moving of the column headers. Value is either \"true\" or \"false\".", &MultiColumnList::setUserColumnDraggingEnabled, &MultiColumnList::isUserColumnDraggingEnabled, true /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(MultiColumnList, bool, "SortSettingEnabled", "Property to get/set the setting for for user modification of the sort column & direction." " Value is either \"true\" or \"false\".", @@ -2243,7 +2260,7 @@ void MultiColumnList::addMultiColumnListProperties(void) " Value is either \"true\" or \"false\".", &MultiColumnList::setShowVertScrollbar, &MultiColumnList::isVertScrollbarAlwaysShown, false /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(MultiColumnList, bool, "ForceHorzScrollbar", "Property to get/set the 'always show' setting for the horizontal scroll bar of the list box." " Value is either \"true\" or \"false\".", @@ -2262,7 +2279,7 @@ void MultiColumnList::addMultiColumnListProperties(void) CEGUI_DEFINE_PROPERTY_NO_XML(MultiColumnList, uint, "RowCount", "Property to access the number of rows in the list (read only)", - 0, &MultiColumnList::getRowCount, 0 + 0, &MultiColumnList::getRowCount, 0 ); CEGUI_DEFINE_PROPERTY(MultiColumnList, MultiColumnList::SelectionMode, @@ -2306,7 +2323,7 @@ bool MultiColumnList::resetList_impl(void) // delete item as needed. if ((item != 0) && item->isAutoDeleted()) { - CEGUI_DELETE_AO item; + delete item; } } @@ -2692,7 +2709,6 @@ void MultiColumnList::resortList() // else no (or invalid) direction, so do not sort. } - ////////////////////////////////////////////////////////////////////////// /************************************************************************* Operators for MCLGridRef diff --git a/cegui/src/widgets/MultiLineEditbox.cpp b/cegui/src/widgets/MultiLineEditbox.cpp index 940abf3cc..9edce607c 100644 --- a/cegui/src/widgets/MultiLineEditbox.cpp +++ b/cegui/src/widgets/MultiLineEditbox.cpp @@ -34,6 +34,7 @@ #include "CEGUI/CoordConverter.h" #include "CEGUI/WindowManager.h" #include "CEGUI/Clipboard.h" +#include "CEGUI/UndoHandler.h" // Start of CEGUI namespace section namespace CEGUI @@ -64,12 +65,6 @@ void MultiLineEditboxWindowRenderer::onLookNFeelAssigned() } } -/************************************************************************* - TODO: - - Clipboard support - Undo support -*************************************************************************/ /************************************************************************* Constants *************************************************************************/ @@ -108,9 +103,12 @@ MultiLineEditbox::MultiLineEditbox(const String& type, const String& name) : d_widestExtent(0.0f), d_forceVertScroll(false), d_forceHorzScroll(false), - d_selectionBrush(0) + d_selectionBrush(0), + d_lastRenderWidth(0.0) { addMultiLineEditboxProperties(); + // create undo handler + d_undoHandler = new UndoHandler(this); // override default and disable text parsing d_textParsingEnabled = false; @@ -124,6 +122,7 @@ MultiLineEditbox::MultiLineEditbox(const String& type, const String& name) : *************************************************************************/ MultiLineEditbox::~MultiLineEditbox(void) { + delete d_undoHandler; } @@ -299,6 +298,7 @@ void MultiLineEditbox::setMaxTextLength(size_t max_len) String newText = getText(); newText.resize(d_maxTextLen); setText(newText); + d_undoHandler->clearUndoHistory(); onTextChanged(args); } @@ -432,21 +432,9 @@ void MultiLineEditbox::configureScrollbars(void) horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition()); } - -/************************************************************************* - Format the text into lines as needed by the current formatting options. -*************************************************************************/ -void MultiLineEditbox::formatText(void) -{ - formatText(true); -} - //----------------------------------------------------------------------------// void MultiLineEditbox::formatText(const bool update_scrollbars) { - // TODO: ASSAF - todo - // clear old formatting data - d_lines.clear(); d_widestExtent = 0.0f; String paraText; @@ -456,10 +444,30 @@ void MultiLineEditbox::formatText(const bool update_scrollbars) if (fnt) { float areaWidth = getTextRenderArea().getWidth(); + String::size_type currPos = 0; + String::size_type paraLen; + LineInfo line; - String::size_type currPos = 0; - String::size_type paraLen; - LineInfo line; + // now we will check if our width changed, if not we'll just update text from last cursor + if (areaWidth != d_lastRenderWidth || !d_undoHandler->canUndo()) + { + d_lines.clear(); + } + else + { + // ok there's no need to update whole text + size_t lastuUndoPos = d_undoHandler->getLastAction().d_startIdx; + // ok now delete all formatting data before lastuUndoPos + int countToRemove = getLineNumberFromIndex(lastuUndoPos) - 1; + if (countToRemove >= 0) + { + d_lines.erase(d_lines.begin() + countToRemove, d_lines.end()); + if (d_lines.size() > 0) + currPos = d_lines.back().d_startIdx + d_lines.back().d_length; + } + else + d_lines.clear(); + } while (currPos < getText().length()) { @@ -550,6 +558,7 @@ void MultiLineEditbox::formatText(const bool update_scrollbars) currPos += paraLen; } + d_lastRenderWidth = areaWidth; } if (update_scrollbars) @@ -589,32 +598,32 @@ size_t MultiLineEditbox::getNextTokenLength(const String& text, size_t start_idx Return the text code point index that is rendered closest to screen position 'pt'. *************************************************************************/ -size_t MultiLineEditbox::getTextIndexFromPosition(const Vector2f& pt) const +size_t MultiLineEditbox::getTextIndexFromPosition(const glm::vec2& pt) const { // // calculate final window position to be checked // - Vector2f wndPt = CoordConverter::screenToWindow(*this, pt); + glm::vec2 wndPt = CoordConverter::screenToWindow(*this, pt); Rectf textArea(getTextRenderArea()); - wndPt -= textArea.d_min; + wndPt -= glm::vec2(textArea.d_min.d_x, textArea.d_min.d_y); // factor in scroll bar values - wndPt.d_x += getHorzScrollbar()->getScrollPosition(); - wndPt.d_y += getVertScrollbar()->getScrollPosition(); + wndPt.x += getHorzScrollbar()->getScrollPosition(); + wndPt.y += getVertScrollbar()->getScrollPosition(); size_t lineNumber = static_cast( - ceguimax(0.0f, wndPt.d_y) / getFont()->getLineSpacing()); + ceguimax(0.0f, wndPt.y) / getFont()->getLineSpacing()); if (lineNumber >= d_lines.size()) { lineNumber = d_lines.size() - 1; } - String lineText(getText().substr(d_lines[lineNumber].d_startIdx, d_lines[lineNumber].d_length)); + const String lineText(getText().substr(d_lines[lineNumber].d_startIdx, d_lines[lineNumber].d_length)); - size_t lineIdx = getFont()->getCharAtPixel(lineText, wndPt.d_x); + size_t lineIdx = getFont()->getCharAtPixel(lineText, wndPt.x); if (lineIdx >= lineText.length() - 1) { @@ -693,6 +702,11 @@ void MultiLineEditbox::eraseSelectedText(bool modify_text) if (modify_text) { String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_DELETE; + undo.d_startIdx = getSelectionStartIndex(); + undo.d_text = newText.substr(getSelectionStartIndex(), getSelectionLength()); + d_undoHandler->addUndoHistory(undo); newText.erase(getSelectionStartIndex(), getSelectionLength()); setText(newText); @@ -711,10 +725,10 @@ bool MultiLineEditbox::performCopy(Clipboard& clipboard) { if (getSelectionLength() == 0) return false; - + const String selectedText = getText().substr( getSelectionStartIndex(), getSelectionLength()); - + clipboard.setText(selectedText); return true; } @@ -724,10 +738,10 @@ bool MultiLineEditbox::performCut(Clipboard& clipboard) { if (isReadOnly()) return false; - + if (!performCopy(clipboard)) return false; - + handleDelete(); return true; } @@ -737,28 +751,33 @@ bool MultiLineEditbox::performPaste(Clipboard& clipboard) { if (isReadOnly()) return false; - + String clipboardText = clipboard.getText(); - + if (clipboardText.empty()) return false; - + // backup current text String tmp(getText()); tmp.erase(getSelectionStartIndex(), getSelectionLength()); - + // erase selected text eraseSelectedText(); - + // if there is room if (getText().length() - clipboardText.length() < d_maxTextLen) { String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_INSERT; + undo.d_startIdx = getCaretIndex(); + undo.d_text = clipboardText; + d_undoHandler->addUndoHistory(undo); newText.insert(getCaretIndex(), clipboardText); setText(newText); - + d_caretPos += clipboardText.length(); - + WindowEventArgs args(this); onTextChanged(args); @@ -788,6 +807,11 @@ void MultiLineEditbox::handleBackspace(void) else if (d_caretPos > 0) { String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_DELETE; + undo.d_startIdx = d_caretPos - 1; + undo.d_text = newText.substr(d_caretPos - 1, 1); + d_undoHandler->addUndoHistory(undo); newText.erase(d_caretPos - 1, 1); setCaretIndex(d_caretPos - 1); setText(newText); @@ -814,6 +838,11 @@ void MultiLineEditbox::handleDelete(void) else if (getCaretIndex() < getText().length() - 1) { String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_DELETE; + undo.d_startIdx = d_caretPos; + undo.d_text = newText.substr(d_caretPos, 1); + d_undoHandler->addUndoHistory(undo); newText.erase(d_caretPos, 1); setText(newText); @@ -829,16 +858,16 @@ void MultiLineEditbox::handleDelete(void) /************************************************************************* - Processing to move caret one character left + Processing to move caret one character left (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleCharLeft(uint sysKeys) +void MultiLineEditbox::handleCharLeft(bool select) { if (d_caretPos > 0) { setCaretIndex(d_caretPos - 1); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -846,21 +875,20 @@ void MultiLineEditbox::handleCharLeft(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret one word left + Processing to move caret one word left (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleWordLeft(uint sysKeys) +void MultiLineEditbox::handleWordLeft(bool select) { if (d_caretPos > 0) { setCaretIndex(TextUtils::getWordStartIdx(getText(), getCaretIndex())); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -868,21 +896,20 @@ void MultiLineEditbox::handleWordLeft(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret one character right + Processing to move caret one character right (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleCharRight(uint sysKeys) +void MultiLineEditbox::handleCharRight(bool select) { if (d_caretPos < getText().length() - 1) { setCaretIndex(d_caretPos + 1); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -890,21 +917,20 @@ void MultiLineEditbox::handleCharRight(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret one word right + Processing to move caret one word right (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleWordRight(uint sysKeys) +void MultiLineEditbox::handleWordRight(bool select) { if (d_caretPos < getText().length() - 1) { setCaretIndex(TextUtils::getNextWordStartIdx(getText(), getCaretIndex())); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -912,21 +938,20 @@ void MultiLineEditbox::handleWordRight(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret to the start of the text. + Processing to move caret to the start of the text (and optionally select the text) *************************************************************************/ -void MultiLineEditbox::handleDocHome(uint sysKeys) +void MultiLineEditbox::handleDocHome(bool select) { if (d_caretPos > 0) { setCaretIndex(0); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -934,21 +959,20 @@ void MultiLineEditbox::handleDocHome(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret to the end of the text + Processing to move caret to the end of the text (and optionally select the text) *************************************************************************/ -void MultiLineEditbox::handleDocEnd(uint sysKeys) +void MultiLineEditbox::handleDocEnd(bool select) { if (d_caretPos < getText().length() - 1) { setCaretIndex(getText().length() - 1); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -956,14 +980,14 @@ void MultiLineEditbox::handleDocEnd(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret to the start of the current line. + Processing to move caret to the start of the current line + (and optionally select the text) *************************************************************************/ -void MultiLineEditbox::handleLineHome(uint sysKeys) +void MultiLineEditbox::handleLineHome(bool select) { size_t line = getLineNumberFromIndex(d_caretPos); @@ -976,7 +1000,7 @@ void MultiLineEditbox::handleLineHome(uint sysKeys) setCaretIndex(lineStartIdx); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -984,16 +1008,14 @@ void MultiLineEditbox::handleLineHome(uint sysKeys) { clearSelection(); } - } - } /************************************************************************* - Processing to move caret to the end of the current line + Processing to move caret to the end of the current line (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleLineEnd(uint sysKeys) +void MultiLineEditbox::handleLineEnd(bool select) { size_t line = getLineNumberFromIndex(d_caretPos); @@ -1006,7 +1028,7 @@ void MultiLineEditbox::handleLineEnd(uint sysKeys) setCaretIndex(lineEndIdx); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -1014,16 +1036,14 @@ void MultiLineEditbox::handleLineEnd(uint sysKeys) { clearSelection(); } - } - } /************************************************************************* - Processing to move caret up a line. + Processing to move caret up a line (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleLineUp(uint sysKeys) +void MultiLineEditbox::handleLineUp(bool select) { size_t caretLine = getLineNumberFromIndex(d_caretPos); @@ -1038,7 +1058,7 @@ void MultiLineEditbox::handleLineUp(uint sysKeys) setCaretIndex(d_lines[caretLine].d_startIdx + newLineIndex); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -1046,14 +1066,13 @@ void MultiLineEditbox::handleLineUp(uint sysKeys) { clearSelection(); } - } /************************************************************************* - Processing to move caret down a line. + Processing to move caret down a line (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handleLineDown(uint sysKeys) +void MultiLineEditbox::handleLineDown(bool select) { size_t caretLine = getLineNumberFromIndex(d_caretPos); @@ -1068,7 +1087,7 @@ void MultiLineEditbox::handleLineDown(uint sysKeys) setCaretIndex(d_lines[caretLine].d_startIdx + newLineIndex); } - if (sysKeys & Shift) + if (select) { setSelection(d_caretPos, d_dragAnchorIdx); } @@ -1076,14 +1095,13 @@ void MultiLineEditbox::handleLineDown(uint sysKeys) { clearSelection(); } - } /************************************************************************* Processing to insert a new line / paragraph. *************************************************************************/ -void MultiLineEditbox::handleNewLine(uint /*sysKeys*/) +void MultiLineEditbox::handleNewLine() { if (!isReadOnly()) { @@ -1094,6 +1112,11 @@ void MultiLineEditbox::handleNewLine(uint /*sysKeys*/) if (getText().length() - 1 < d_maxTextLen) { String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_INSERT; + undo.d_startIdx = getCaretIndex(); + undo.d_text = "\x0a"; + d_undoHandler->addUndoHistory(undo); newText.insert(getCaretIndex(), 1, 0x0a); setText(newText); @@ -1102,16 +1125,14 @@ void MultiLineEditbox::handleNewLine(uint /*sysKeys*/) WindowEventArgs args(this); onTextChanged(args); } - } - } /************************************************************************* - Processing to move caret one page up + Processing to move caret one page up (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handlePageUp(uint sysKeys) +void MultiLineEditbox::handlePageUp(bool select) { size_t caretLine = getLineNumberFromIndex(d_caretPos); size_t nbLine = static_cast(getTextRenderArea().getHeight() / getFont()->getLineSpacing()); @@ -1120,8 +1141,10 @@ void MultiLineEditbox::handlePageUp(uint sysKeys) { newline = caretLine - nbLine; } + setCaretIndex(d_lines[newline].d_startIdx); - if (sysKeys & Shift) + + if (select) { setSelection(d_caretPos, d_selectionEnd); } @@ -1129,14 +1152,15 @@ void MultiLineEditbox::handlePageUp(uint sysKeys) { clearSelection(); } + ensureCaretIsVisible(); } /************************************************************************* - Processing to move caret one page down + Processing to move caret one page down (and optionally select it) *************************************************************************/ -void MultiLineEditbox::handlePageDown(uint sysKeys) +void MultiLineEditbox::handlePageDown(bool select) { size_t caretLine = getLineNumberFromIndex(d_caretPos); size_t nbLine = static_cast(getTextRenderArea().getHeight() / getFont()->getLineSpacing()); @@ -1146,7 +1170,7 @@ void MultiLineEditbox::handlePageDown(uint sysKeys) newline = std::min(newline,d_lines.size() - 1); } setCaretIndex(d_lines[newline].d_startIdx + d_lines[newline].d_length - 1); - if (sysKeys & Shift) + if (select) { setSelection(d_selectionStart, d_caretPos); } @@ -1159,19 +1183,19 @@ void MultiLineEditbox::handlePageDown(uint sysKeys) /************************************************************************* - Handler for when a mouse button is pushed + Handler for when a cursor is pressed *************************************************************************/ -void MultiLineEditbox::onMouseButtonDown(MouseEventArgs& e) +void MultiLineEditbox::onCursorPressHold(CursorInputEventArgs& e) { // base class handling - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { // grab inputs if (captureInput()) { - // handle mouse down + // handle cursor press clearSelection(); d_dragging = true; d_dragAnchorIdx = getTextIndexFromPosition(e.position); @@ -1180,102 +1204,31 @@ void MultiLineEditbox::onMouseButtonDown(MouseEventArgs& e) ++e.handled; } - } /************************************************************************* - Handler for when mouse button is released + Handler for when cursor is activated *************************************************************************/ -void MultiLineEditbox::onMouseButtonUp(MouseEventArgs& e) +void MultiLineEditbox::onCursorActivate(CursorInputEventArgs& e) { // base class processing - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { releaseInput(); ++e.handled; } - -} - - -/************************************************************************* - Handler for when mouse button is double-clicked -*************************************************************************/ -void MultiLineEditbox::onMouseDoubleClicked(MouseEventArgs& e) -{ - // base class processing - Window::onMouseDoubleClicked(e); - - if (e.button == LeftButton) - { - d_dragAnchorIdx = TextUtils::getWordStartIdx(getText(), (d_caretPos == getText().length()) ? d_caretPos : d_caretPos + 1); - d_caretPos = TextUtils::getNextWordStartIdx(getText(), d_caretPos); - - // perform actual selection operation. - setSelection(d_dragAnchorIdx, d_caretPos); - - ++e.handled; - } - -} - - -/************************************************************************* - Handler for when mouse button is triple-clicked. -*************************************************************************/ -void MultiLineEditbox::onMouseTripleClicked(MouseEventArgs& e) -{ - // base class processing - Window::onMouseTripleClicked(e); - - if (e.button == LeftButton) - { - size_t caretLine = getLineNumberFromIndex(d_caretPos); - size_t lineStart = d_lines[caretLine].d_startIdx; - - // find end of last paragraph - String::size_type paraStart = getText().find_last_of(d_lineBreakChars, lineStart); - - // if no previous paragraph, selection will start at the beginning. - if (paraStart == String::npos) - { - paraStart = 0; - } - - // find end of this paragraph - String::size_type paraEnd = getText().find_first_of(d_lineBreakChars, lineStart); - - // if paragraph has no end, which actually should never happen, fix the - // erroneous situation and select up to end at end of text. - if (paraEnd == String::npos) - { - String newText = getText(); - newText.append(1, '\n'); - setText(newText); - - paraEnd = getText().length() - 1; - } - - // set up selection using new values. - d_dragAnchorIdx = paraStart; - setCaretIndex(paraEnd); - setSelection(d_dragAnchorIdx, d_caretPos); - ++e.handled; - } - } - /************************************************************************* - Handler for when mouse moves in the window. + Handler for when cursor moves in the window. *************************************************************************/ -void MultiLineEditbox::onMouseMove(MouseEventArgs& e) +void MultiLineEditbox::onCursorMove(CursorInputEventArgs& e) { // base class processing - Window::onMouseMove(e); + Window::onCursorMove(e); if (d_dragging) { @@ -1304,11 +1257,11 @@ void MultiLineEditbox::onCaptureLost(WindowEventArgs& e) /************************************************************************* Handler for when character (printable keys) are typed *************************************************************************/ -void MultiLineEditbox::onCharacter(KeyEventArgs& e) +void MultiLineEditbox::onCharacter(TextEventArgs& e) { - // NB: We are not calling the base class handler here because it propogates - // inputs back up the window hierarchy, whereas, as a consumer of key - // events, we want such propogation to cease with us regardless of whether + // NB: We are not calling the base class handler here because it propagates + // inputs back up the window hierarchy, whereas, as a consumer of input + // events, we want such propagation to cease with us regardless of whether // we actually handle the event. // fire event. @@ -1316,17 +1269,22 @@ void MultiLineEditbox::onCharacter(KeyEventArgs& e) // only need to take notice if we have focus if (e.handled == 0 && hasInputFocus() && !isReadOnly() && - getFont()->isCodepointAvailable(e.codepoint)) + getFont()->isCodepointAvailable(e.character)) { // erase selected text eraseSelectedText(); // if there is room if (getText().length() - 1 < d_maxTextLen) - { - String newText = getText(); - newText.insert(getCaretIndex(), 1, e.codepoint); - setText(newText); + { + String newText = getText(); + UndoHandler::UndoAction undo; + undo.d_type = UndoHandler::UAT_INSERT; + undo.d_startIdx = getCaretIndex(); + undo.d_text = e.character; + d_undoHandler->addUndoHistory(undo); + newText.insert(getCaretIndex(), 1, e.character); + setText(newText); d_caretPos++; @@ -1346,118 +1304,6 @@ void MultiLineEditbox::onCharacter(KeyEventArgs& e) } - -/************************************************************************* - Handler for when non-printable keys are typed. -*************************************************************************/ -void MultiLineEditbox::onKeyDown(KeyEventArgs& e) -{ - // fire event. - fireEvent(EventKeyDown, e, Window::EventNamespace); - - if (e.handled == 0 && hasInputFocus()) - { - if (isReadOnly()) - { - Window::onKeyDown(e); - return; - } - - WindowEventArgs args(this); - switch (e.scancode) - { - case Key::LeftShift: - case Key::RightShift: - if (getSelectionLength() == 0) - { - d_dragAnchorIdx = getCaretIndex(); - } - break; - - case Key::Backspace: - handleBackspace(); - break; - - case Key::Delete: - handleDelete(); - break; - - case Key::Return: - case Key::NumpadEnter: - handleNewLine(e.sysKeys); - break; - - case Key::ArrowLeft: - if (e.sysKeys & Control) - { - handleWordLeft(e.sysKeys); - } - else - { - handleCharLeft(e.sysKeys); - } - break; - - case Key::ArrowRight: - if (e.sysKeys & Control) - { - handleWordRight(e.sysKeys); - } - else - { - handleCharRight(e.sysKeys); - } - break; - - case Key::ArrowUp: - handleLineUp(e.sysKeys); - break; - - case Key::ArrowDown: - handleLineDown(e.sysKeys); - break; - - case Key::Home: - if (e.sysKeys & Control) - { - handleDocHome(e.sysKeys); - } - else - { - handleLineHome(e.sysKeys); - } - break; - - case Key::End: - if (e.sysKeys & Control) - { - handleDocEnd(e.sysKeys); - } - else - { - handleLineEnd(e.sysKeys); - } - break; - - case Key::PageUp: - handlePageUp(e.sysKeys); - break; - - case Key::PageDown: - handlePageDown(e.sysKeys); - break; - - default: - Window::onKeyDown(e); - return; - } - - ++e.handled; - } - -} - - /************************************************************************* Handler for when text is programmatically changed. *************************************************************************/ @@ -1507,23 +1353,23 @@ void MultiLineEditbox::onSized(ElementEventArgs& e) /************************************************************************* - Handler for mouse wheel changes + Handler for scroll actions *************************************************************************/ -void MultiLineEditbox::onMouseWheel(MouseEventArgs& e) +void MultiLineEditbox::onScroll(CursorInputEventArgs& e) { // base class processing. - Window::onMouseWheel(e); + Window::onScroll(e); Scrollbar* vertScrollbar = getVertScrollbar(); Scrollbar* horzScrollbar = getHorzScrollbar(); if (vertScrollbar->isEffectiveVisible() && (vertScrollbar->getDocumentSize() > vertScrollbar->getPageSize())) { - vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.wheelChange); + vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + vertScrollbar->getStepSize() * -e.scroll); } else if (horzScrollbar->isEffectiveVisible() && (horzScrollbar->getDocumentSize() > horzScrollbar->getPageSize())) { - horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.wheelChange); + horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + horzScrollbar->getStepSize() * -e.scroll); } ++e.handled; @@ -1634,17 +1480,17 @@ bool MultiLineEditbox::isWordWrapped(void) const void MultiLineEditbox::addMultiLineEditboxProperties(void) { const String& propertyOrigin = WidgetTypeName; - + CEGUI_DEFINE_PROPERTY(MultiLineEditbox, bool, "ReadOnly","Property to get/set the read-only setting for the Editbox. Value is either \"true\" or \"false\".", &MultiLineEditbox::setReadOnly, &MultiLineEditbox::isReadOnly, false ); - + CEGUI_DEFINE_PROPERTY(MultiLineEditbox, size_t, "CaretIndex","Property to get/set the current caret index. Value is \"[uint]\".", &MultiLineEditbox::setCaretIndex, &MultiLineEditbox::getCaretIndex, 0 ); - + CEGUI_DEFINE_PROPERTY(MultiLineEditbox, size_t, "SelectionStart","Property to get/set the zero based index of the selection start position within the text. Value is \"[uint]\".", &MultiLineEditbox::setSelectionStart, &MultiLineEditbox::getSelectionStartIndex, 0 @@ -1653,7 +1499,7 @@ void MultiLineEditbox::addMultiLineEditboxProperties(void) "SelectionLength","Property to get/set the length of the selection (as a count of the number of code points selected). Value is \"[uint]\".", &MultiLineEditbox::setSelectionLength, &MultiLineEditbox::getSelectionLength, 0 ); - + CEGUI_DEFINE_PROPERTY(MultiLineEditbox, size_t, "MaxTextLength","Property to get/set the the maximum allowed text length (as a count of code points). Value is \"[uint]\".", &MultiLineEditbox::setMaxTextLength, &MultiLineEditbox::getMaxTextLength, String().max_size() @@ -1681,7 +1527,7 @@ void MultiLineEditbox::addMultiLineEditboxProperties(void) *************************************************************************/ bool MultiLineEditbox::handle_scrollChange(const EventArgs&) { - // simply trigger a redraw of the Listbox. + // simply trigger a redraw of the MultiLineEditbox invalidate(); return true; } @@ -1763,5 +1609,213 @@ bool MultiLineEditbox::handle_vertScrollbarVisibilityChanged(const EventArgs&) return true; } +/************************************************************************* + Undo/redo +*************************************************************************/ +bool MultiLineEditbox::performUndo() +{ + bool result = false; + if (!isReadOnly()) + { + clearSelection(); + + result = d_undoHandler->undo(d_caretPos); + WindowEventArgs args(this); + onTextChanged(args); + } + + return result; +} + +//----------------------------------------------------------------------------// +bool MultiLineEditbox::performRedo() +{ + bool result = false; + if (!isReadOnly()) + { + clearSelection(); + result = d_undoHandler->redo(d_caretPos); + WindowEventArgs args(this); + onTextChanged(args); + } + return result; +} + +//----------------------------------------------------------------------------// +void MultiLineEditbox::onSemanticInputEvent(SemanticEventArgs& e) +{ + // base class processing + Window::onSemanticInputEvent(e); + + if (isDisabled()) + return; + + if (e.d_semanticValue == SV_SelectAll && e.d_payload.source == CIS_Left) + { + handleSelectAllText(e); + + ++e.handled; + } + else if (e.d_semanticValue == SV_SelectWord && e.d_payload.source == CIS_Left) + { + d_dragAnchorIdx = TextUtils::getWordStartIdx(getText(), + (d_caretPos == getText().length()) ? d_caretPos : d_caretPos + 1); + d_caretPos = TextUtils::getNextWordStartIdx(getText(), d_caretPos); + + // perform actual selection operation. + setSelection(d_dragAnchorIdx, d_caretPos); + + ++e.handled; + } + + if (e.handled == 0 && hasInputFocus()) + { + if (isReadOnly()) + { + Window::onSemanticInputEvent(e); + return; + } + + if (getSelectionLength() == 0 && isSelectionSemanticValue(e.d_semanticValue)) + d_dragAnchorIdx = d_caretPos; + + switch (e.d_semanticValue) + { + case SV_DeletePreviousCharacter: + handleBackspace(); + break; + + case SV_DeleteNextCharacter: + handleDelete(); + break; + + case SV_Confirm: + handleNewLine(); + break; + + case SV_GoToPreviousCharacter: + handleCharLeft(false); + break; + + case SV_GoToNextCharacter: + handleCharRight(false); + break; + + case SV_SelectPreviousCharacter: + handleCharLeft(true); + break; + + case SV_SelectNextCharacter: + handleCharRight(true); + break; + + case SV_GoToPreviousWord: + handleWordLeft(false); + break; + + case SV_GoToNextWord: + handleWordRight(false); + break; + + case SV_SelectPreviousWord: + handleWordLeft(true); + break; + + case SV_SelectNextWord: + handleWordRight(true); + break; + + case SV_GoUp: + handleLineUp(false); + break; + + case SV_SelectUp: + handleLineUp(true); + break; + + case SV_GoDown: + handleLineDown(false); + break; + + case SV_SelectDown: + handleLineDown(true); + break; + + case SV_GoToStartOfLine: + handleLineHome(false); + break; + + case SV_GoToEndOfLine: + handleLineEnd(false); + break; + + case SV_GoToStartOfDocument: + handleDocHome(false); + break; + + case SV_SelectToStartOfLine: + handleLineHome(true); + break; + + case SV_SelectToEndOfLine: + handleLineEnd(true); + break; + + case SV_SelectToStartOfDocument: + handleDocHome(true); + break; + + case SV_SelectToEndOfDocument: + handleDocHome(true); + + case SV_GoToPreviousPage: + handlePageUp(false); + break; + + case SV_GoToNextPage: + handlePageDown(false); + break; + + default: + Window::onSemanticInputEvent(e); + return; + } + + ++e.handled; + } +} + +//----------------------------------------------------------------------------// +void MultiLineEditbox::handleSelectAllText(SemanticEventArgs& e) +{ + size_t caretLine = getLineNumberFromIndex(d_caretPos); + size_t lineStart = d_lines[caretLine].d_startIdx; + + // find end of last paragraph + String::size_type paraStart = getText().find_last_of(d_lineBreakChars, lineStart); + + // if no previous paragraph, selection will start at the beginning. + if (paraStart == String::npos) + paraStart = 0; + // find end of this paragraph + String::size_type paraEnd = getText().find_first_of(d_lineBreakChars, lineStart); + + // if paragraph has no end, which actually should never happen, fix the + // erroneous situation and select up to end at end of text. + if (paraEnd == String::npos) + { + String newText = getText(); + newText.append(1, '\n'); + setText(newText); + + paraEnd = getText().length() - 1; + } + + // set up selection using new values. + d_dragAnchorIdx = paraStart; + setCaretIndex(paraEnd); + setSelection(d_dragAnchorIdx, d_caretPos); + ++e.handled; +} } // End of CEGUI namespace section diff --git a/cegui/src/widgets/PopupMenu.cpp b/cegui/src/widgets/PopupMenu.cpp index 36d7e7127..88b2fa583 100644 --- a/cegui/src/widgets/PopupMenu.cpp +++ b/cegui/src/widgets/PopupMenu.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 1/4/2005 author: Tomas Lindquist Olsen (based on code by Paul D Turner) - + purpose: Implementation of PopupMenu widget base class *************************************************************************/ /*************************************************************************** @@ -127,7 +127,7 @@ void PopupMenu::openPopupMenu(bool notify) d_fading = false; setAlpha(d_origAlpha); } - + show(); moveToFront(); } @@ -277,7 +277,7 @@ Sizef PopupMenu::getContentSize() const // find the content sizes float widest = 0; float total_height = 0; - + size_t i = 0; size_t max = d_listItems.size(); while (i < max) @@ -289,7 +289,7 @@ Sizef PopupMenu::getContentSize() const i++; } - + const float count = float(i); // vert item spacing @@ -309,7 +309,7 @@ Sizef PopupMenu::getContentSize() const void PopupMenu::onAlphaChanged(WindowEventArgs& e) { MenuBase::onAlphaChanged(e); - + // if we are not fading, this is a real alpha change request and we save a copy of the value if (!d_fading) { @@ -354,23 +354,23 @@ void PopupMenu::onHidden(WindowEventArgs& e) /************************************************************************ - Handler for mouse button down events + Handler for cursor press events ************************************************************************/ -void PopupMenu::onMouseButtonDown(MouseEventArgs& e) +void PopupMenu::onCursorPressHold(CursorInputEventArgs& e) { - MenuBase::onMouseButtonDown(e); - // dont reach our parent + MenuBase::onCursorPressHold(e); + // don't reach our parent ++e.handled; } /************************************************************************ - Handler for mouse button up events + Handler for cursor activation events ************************************************************************/ -void PopupMenu::onMouseButtonUp(MouseEventArgs& e) +void PopupMenu::onCursorActivate(CursorInputEventArgs& e) { - MenuBase::onMouseButtonUp(e); - // dont reach our parent + MenuBase::onCursorActivate(e); + // don't reach our parent ++e.handled; } @@ -386,7 +386,7 @@ void PopupMenu::addPopupMenuProperties(void) "FadeInTime", "Property to get/set the fade in time in seconds of the popup menu. Value is a float.", &PopupMenu::setFadeInTime, &PopupMenu::getFadeInTime, 0.0f ); - + CEGUI_DEFINE_PROPERTY(PopupMenu, float, "FadeOutTime", "Property to get/set the fade out time in seconds of the popup menu. Value is a float.", &PopupMenu::setFadeOutTime, &PopupMenu::getFadeOutTime, 0.0f diff --git a/cegui/src/widgets/PushButton.cpp b/cegui/src/widgets/PushButton.cpp index 143270da1..0fb8cfc35 100644 --- a/cegui/src/widgets/PushButton.cpp +++ b/cegui/src/widgets/PushButton.cpp @@ -68,33 +68,44 @@ void PushButton::onClicked(WindowEventArgs& e) /************************************************************************* - Handler for mouse button release events + Handler for cursor activation events *************************************************************************/ -void PushButton::onMouseButtonUp(MouseEventArgs& e) +void PushButton::onCursorActivate(CursorInputEventArgs& e) { - if ((e.button == LeftButton) && isPushed()) + if ((e.source == CIS_Left) && isPushed()) { Window* sheet = getGUIContext().getRootWindow(); if (sheet) { - // if mouse was released over this widget - // (use position from mouse, as e.position has been unprojected) - if (this == sheet->getTargetChildAtPosition( - getGUIContext().getMouseCursor().getPosition())) + // if cursor was released over this widget + // (use position from cursor, as e.position has been unprojected) + if (this == sheet->getTargetChildAtPosition( + getGUIContext().getCursor().getPosition())) { // fire event WindowEventArgs args(this); onClicked(args); } - } - ++e.handled; } // default handling - ButtonBase::onMouseButtonUp(e); + ButtonBase::onCursorActivate(e); +} + +void PushButton::onSemanticInputEvent(SemanticEventArgs& e) +{ + if (isDisabled()) + return; + + if (e.d_semanticValue == SV_Confirm) + { + onClicked(e); + + ++e.handled; + } } } // End of CEGUI namespace section diff --git a/cegui/src/widgets/ScrollablePane.cpp b/cegui/src/widgets/ScrollablePane.cpp index 772d91a25..5418a977e 100644 --- a/cegui/src/widgets/ScrollablePane.cpp +++ b/cegui/src/widgets/ScrollablePane.cpp @@ -485,10 +485,10 @@ void ScrollablePane::onSized(ElementEventArgs& e) } //----------------------------------------------------------------------------// -void ScrollablePane::onMouseWheel(MouseEventArgs& e) +void ScrollablePane::onScroll(CursorInputEventArgs& e) { // base class processing. - Window::onMouseWheel(e); + Window::onScroll(e); Scrollbar* vertScrollbar = getVertScrollbar(); Scrollbar* horzScrollbar = getHorzScrollbar(); @@ -497,13 +497,13 @@ void ScrollablePane::onMouseWheel(MouseEventArgs& e) (vertScrollbar->getDocumentSize() > vertScrollbar->getPageSize())) { vertScrollbar->setScrollPosition(vertScrollbar->getScrollPosition() + - vertScrollbar->getStepSize() * -e.wheelChange); + vertScrollbar->getStepSize() * -e.scroll); } else if (horzScrollbar->isEffectiveVisible() && (horzScrollbar->getDocumentSize() > horzScrollbar->getPageSize())) { horzScrollbar->setScrollPosition(horzScrollbar->getScrollPosition() + - horzScrollbar->getStepSize() * -e.wheelChange); + horzScrollbar->getStepSize() * -e.scroll); } ++e.handled; @@ -516,13 +516,13 @@ void ScrollablePane::addScrollablePaneProperties(void) CEGUI_DEFINE_PROPERTY(ScrollablePane, bool, "ForceVertScrollbar", "Property to get/set the 'always show' setting for the vertical scroll " - "bar of the tree. Value is either \"true\" or \"false\".", + "bar of the pane. Value is either \"true\" or \"false\".", &ScrollablePane::setShowVertScrollbar, &ScrollablePane::isVertScrollbarAlwaysShown, false /* TODO: Inconsistency */ ); CEGUI_DEFINE_PROPERTY(ScrollablePane, bool, "ForceHorzScrollbar", "Property to get/set the 'always show' setting for the horizontal " - "scroll bar of the tree. Value is either \"true\" or \"false\".", + "scroll bar of the pane. Value is either \"true\" or \"false\".", &ScrollablePane::setShowHorzScrollbar, &ScrollablePane::isHorzScrollbarAlwaysShown, false /* TODO: Inconsistency */ ); diff --git a/cegui/src/widgets/Scrollbar.cpp b/cegui/src/widgets/Scrollbar.cpp index 173ac7a4a..afc3a2e0a 100644 --- a/cegui/src/widgets/Scrollbar.cpp +++ b/cegui/src/widgets/Scrollbar.cpp @@ -90,13 +90,13 @@ void Scrollbar::initialiseComponents(void) // set up Increase button getIncreaseButton()-> - subscribeEvent(PushButton::EventMouseButtonDown, + subscribeEvent(PushButton::EventCursorPressHold, Event::Subscriber(&CEGUI::Scrollbar::handleIncreaseClicked, this)); // set up Decrease button getDecreaseButton()-> - subscribeEvent(PushButton::EventMouseButtonDown, + subscribeEvent(PushButton::EventCursorPressHold, Event::Subscriber(&CEGUI::Scrollbar::handleDecreaseClicked, this)); @@ -212,12 +212,12 @@ void Scrollbar::onScrollConfigChanged(WindowEventArgs& e) } //----------------------------------------------------------------------------// -void Scrollbar::onMouseButtonDown(MouseEventArgs& e) +void Scrollbar::onCursorPressHold(CursorInputEventArgs& e) { // base class processing - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button != LeftButton) + if (e.source != CIS_Left) return; const float adj = getAdjustDirectionFromPoint(e.position); @@ -231,13 +231,13 @@ void Scrollbar::onMouseButtonDown(MouseEventArgs& e) } //----------------------------------------------------------------------------// -void Scrollbar::onMouseWheel(MouseEventArgs& e) +void Scrollbar::onScroll(CursorInputEventArgs& e) { // base class processing - Window::onMouseWheel(e); + Window::onScroll(e); - // scroll by e.wheelChange * stepSize - setScrollPosition(d_position + d_stepSize * -e.wheelChange); + // scroll by vertical scroll * stepSize + setScrollPosition(d_position + d_stepSize * -e.scroll); // ensure the message does not go to our parent. ++e.handled; @@ -255,7 +255,7 @@ bool Scrollbar::handleThumbMoved(const EventArgs&) //----------------------------------------------------------------------------// bool Scrollbar::handleIncreaseClicked(const EventArgs& e) { - if (((const MouseEventArgs&)e).button != LeftButton) + if (((const CursorInputEventArgs&)e).source != CIS_Left) return false; scrollForwardsByStep(); @@ -265,7 +265,7 @@ bool Scrollbar::handleIncreaseClicked(const EventArgs& e) //----------------------------------------------------------------------------// bool Scrollbar::handleDecreaseClicked(const EventArgs& e) { - if (((const MouseEventArgs&)e).button != LeftButton) + if (((const CursorInputEventArgs&)e).source != CIS_Left) return false; scrollBackwardsByStep(); @@ -392,7 +392,7 @@ float Scrollbar::getValueFromThumb(void) const } //----------------------------------------------------------------------------// -float Scrollbar::getAdjustDirectionFromPoint(const Vector2f& pt) const +float Scrollbar::getAdjustDirectionFromPoint(const glm::vec2& pt) const { if (!d_windowRenderer) CEGUI_THROW(InvalidRequestException( diff --git a/cegui/src/widgets/ScrolledContainer.cpp b/cegui/src/widgets/ScrolledContainer.cpp index 7fdab0677..4c56c63de 100644 --- a/cegui/src/widgets/ScrolledContainer.cpp +++ b/cegui/src/widgets/ScrolledContainer.cpp @@ -47,11 +47,11 @@ ScrolledContainer::ScrolledContainer(const String& type, const String& name) : Window(type, name), d_contentArea(0, 0, 0, 0), d_autosizePane(true), - + d_clientChildContentArea(this, static_cast(&ScrolledContainer::getClientChildContentArea_impl)) { addScrolledContainerProperties(); - setMouseInputPropagationEnabled(true); + setCursorInputPropagationEnabled(true); } //----------------------------------------------------------------------------// @@ -90,7 +90,7 @@ void ScrolledContainer::setContentArea(const Rectf& area) if (!d_autosizePane) { d_contentArea = area; - + // Fire event WindowEventArgs args(this); onContentChanged(args); @@ -135,9 +135,9 @@ Rectf ScrolledContainer::getChildExtentsArea(void) const wnd->getPixelSize()); if (wnd->getHorizontalAlignment() == HA_CENTRE) - area.setPosition(area.getPosition() - CEGUI::Vector2f(area.getWidth() * 0.5f - d_pixelSize.d_width * 0.5f, 0.0f)); + area.setPosition(area.getPosition() - Vector2(area.getWidth() * 0.5f - d_pixelSize.d_width * 0.5f, 0.0f)); if (wnd->getVerticalAlignment() == VA_CENTRE) - area.setPosition(area.getPosition() - CEGUI::Vector2f(0.0f, area.getHeight() * 0.5f - d_pixelSize.d_height * 0.5f)); + area.setPosition(area.getPosition() - Vector2(0.0f, area.getHeight() * 0.5f - d_pixelSize.d_height * 0.5f)); if (area.d_min.d_x < extents.d_min.d_x) extents.d_min.d_x = area.d_min.d_x; @@ -303,13 +303,13 @@ void ScrolledContainer::addScrolledContainerProperties(void) " Value is either \"true\" or \"false\".", &ScrolledContainer::setContentPaneAutoSized, &ScrolledContainer::isContentPaneAutoSized, true ); - + CEGUI_DEFINE_PROPERTY(ScrolledContainer, Rectf, "ContentArea", "Property to get/set the current content area rectangle of the content pane." " Value is \"l:[float] t:[float] r:[float] b:[float]\" (where l is left, t is top, r is right, and b is bottom).", &ScrolledContainer::setContentArea, &ScrolledContainer::getContentArea, Rectf::zero() ); - + CEGUI_DEFINE_PROPERTY(ScrolledContainer, Rectf, "ChildExtentsArea", "Property to get the current content extents rectangle." " Value is \"l:[float] t:[float] r:[float] b:[float]\" (where l is left, t is top, r is right, and b is bottom).", diff --git a/cegui/src/widgets/ScrolledItemListBase.cpp b/cegui/src/widgets/ScrolledItemListBase.cpp deleted file mode 100644 index b635acd54..000000000 --- a/cegui/src/widgets/ScrolledItemListBase.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/************************************************************************ - created: Sat Oct 29 2005 - author: Tomas Lindquist Olsen -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/widgets/ScrolledItemListBase.h" -#include "CEGUI/widgets/ClippedContainer.h" -#include "CEGUI/WindowManager.h" -#include "CEGUI/Logger.h" -#include "CEGUI/PropertyHelper.h" -#include "CEGUI/CoordConverter.h" - -// begin CEGUI namespace -namespace CEGUI -{ - -/************************************************************************* - Constants -*************************************************************************/ -// event strings -const String ScrolledItemListBase::EventNamespace("ScrolledItemListBase"); -const String ScrolledItemListBase::EventVertScrollbarModeChanged("VertScrollbarModeChanged"); -const String ScrolledItemListBase::EventHorzScrollbarModeChanged("HorzScrollbarModeChanged"); - -// component widget name suffixes -const String ScrolledItemListBase::VertScrollbarName( "__auto_vscrollbar__" ); -const String ScrolledItemListBase::HorzScrollbarName( "__auto_hscrollbar__" ); -const String ScrolledItemListBase::ContentPaneName("__auto_content_pane__"); - -/************************************************************************ - Constructor -************************************************************************/ -ScrolledItemListBase::ScrolledItemListBase(const String& type, const String& name) : - ItemListBase(type, name), - d_forceVScroll(false), - d_forceHScroll(false) -{ - d_pane = WindowManager::getSingletonPtr()-> - createWindow("ClippedContainer", ContentPaneName); - - d_pane->setAutoWindow(true); - static_cast(d_pane)->setClipperWindow(this); - d_pane->setMouseInputPropagationEnabled(true); - - addChild(d_pane); - - // add properties for this class - addScrolledItemListBaseProperties(); -} - -/************************************************************************ - Destructor -************************************************************************/ -ScrolledItemListBase::~ScrolledItemListBase() -{ - if (d_pane && d_pane != this) - WindowManager::getSingletonPtr()->destroyWindow(d_pane); -} - -/************************************************************************ - Initialise -************************************************************************/ -void ScrolledItemListBase::initialiseComponents() -{ - // base class handling - ItemListBase::initialiseComponents(); - - // init scrollbars - Scrollbar* v = getVertScrollbar(); - Scrollbar* h = getHorzScrollbar(); - - v->setAlwaysOnTop(true); - h->setAlwaysOnTop(true); - - v->subscribeEvent(Scrollbar::EventScrollPositionChanged, - Event::Subscriber(&ScrolledItemListBase::handle_VScroll,this)); - h->subscribeEvent(Scrollbar::EventScrollPositionChanged, - Event::Subscriber(&ScrolledItemListBase::handle_HScroll,this)); - - v->hide(); - h->hide(); -} - -/************************************************************************ - Get vertical scroll bar -************************************************************************/ -Scrollbar* ScrolledItemListBase::getVertScrollbar() const -{ - return static_cast(getChild(VertScrollbarName)); -} - -/************************************************************************ - Get horizontal scroll bar -************************************************************************/ -Scrollbar* ScrolledItemListBase::getHorzScrollbar() const -{ - return static_cast(getChild(HorzScrollbarName)); -} - -/************************************************************************ - Configure scroll bars -************************************************************************/ -void ScrolledItemListBase::configureScrollbars(const Sizef& doc_size) -{ - Scrollbar* v = getVertScrollbar(); - Scrollbar* h = getHorzScrollbar(); - - const bool old_vert_visible = v->isVisible(); - const bool old_horz_visible = h->isVisible(); - - Sizef render_area_size = getItemRenderArea().getSize(); - - // setup the pane size - float pane_size_w = ceguimax(doc_size.d_width, render_area_size.d_width); - USize pane_size(cegui_absdim(pane_size_w), cegui_absdim(doc_size.d_height)); - - d_pane->setMinSize(pane_size); - d_pane->setMaxSize(pane_size); - //d_pane->setWindowSize(pane_size); - - // "fix" scrollbar visibility - if (d_forceVScroll || doc_size.d_height > render_area_size.d_height) - { - v->show(); - } - else - { - v->hide(); - } - - //render_area_size = getItemRenderArea().getSize(); - - if (d_forceHScroll || doc_size.d_width > render_area_size.d_width) - { - h->show(); - } - else - { - h->hide(); - } - - // if some change occurred, invalidate the inner rect area caches. - if ((old_vert_visible != v->isVisible()) || - (old_horz_visible != h->isVisible())) - { - d_unclippedInnerRect.invalidateCache(); - d_innerRectClipperValid = false; - } - - // get a fresh item render area - Rectf render_area = getItemRenderArea(); - render_area_size = render_area.getSize(); - - // update the pane clipper area - static_cast(d_pane)->setClipArea(render_area); - - // setup vertical scrollbar - v->setDocumentSize(doc_size.d_height); - v->setPageSize(render_area_size.d_height); - v->setStepSize(ceguimax(1.0f, render_area_size.d_height / 10.0f)); - v->setScrollPosition(v->getScrollPosition()); - - // setup horizontal scrollbar - h->setDocumentSize(doc_size.d_width); - h->setPageSize(render_area_size.d_width); - h->setStepSize(ceguimax(1.0f, render_area_size.d_width / 10.0f)); - h->setScrollPosition(h->getScrollPosition()); -} - -/************************************************************************ - Handle mouse wheel event -************************************************************************/ -void ScrolledItemListBase::onMouseWheel(MouseEventArgs& e) -{ - ItemListBase::onMouseWheel(e); - - size_t count = getItemCount(); - Scrollbar* v = getVertScrollbar(); - - // dont do anything if we are no using scrollbars - // or have'nt got any items - if (!v->isVisible() || !count) - { - return; - } - - const float pixH = d_pane->getUnclippedOuterRect().get().getHeight(); - const float delta = (pixH/float(count)) * -e.wheelChange; - v->setScrollPosition(v->getScrollPosition() + delta); - ++e.handled; -} - -/************************************************************************ - Event subscribers for scrolling -************************************************************************/ -bool ScrolledItemListBase::handle_VScroll(const EventArgs& e) -{ - const WindowEventArgs& we = static_cast(e); - Scrollbar* v = static_cast(we.window); - float newpos = -v->getScrollPosition(); - d_pane->setYPosition(cegui_absdim(newpos)); - return true; -} - -bool ScrolledItemListBase::handle_HScroll(const EventArgs& e) -{ - const WindowEventArgs& we = static_cast(e); - Scrollbar* h = static_cast(we.window); - float newpos = -h->getScrollPosition(); - d_pane->setXPosition(cegui_absdim(newpos)); - return true; -} - -/************************************************************************ - Set vertical scrollbar mode -************************************************************************/ -void ScrolledItemListBase::setShowVertScrollbar(bool mode) -{ - if (mode != d_forceVScroll) - { - d_forceVScroll = mode; - WindowEventArgs e(this); - onVertScrollbarModeChanged(e); - } -} - -/************************************************************************ - Set horizontal scrollbar mode -************************************************************************/ -void ScrolledItemListBase::setShowHorzScrollbar(bool mode) -{ - if (mode != d_forceHScroll) - { - d_forceHScroll = mode; - WindowEventArgs e(this); - onHorzScrollbarModeChanged(e); - } -} - -/************************************************************************ - Handle vertical scrollbar mode change -************************************************************************/ -void ScrolledItemListBase::onVertScrollbarModeChanged(WindowEventArgs& e) -{ - fireEvent(EventVertScrollbarModeChanged, e); -} - -/************************************************************************ - Handle horizontal scrollbar mode change -************************************************************************/ -void ScrolledItemListBase::onHorzScrollbarModeChanged(WindowEventArgs& e) -{ - fireEvent(EventHorzScrollbarModeChanged, e); -} - -/************************************************************************* - Add ItemListbox specific properties -*************************************************************************/ -void ScrolledItemListBase::addScrolledItemListBaseProperties() -{ - const String propertyOrigin = "CEGUI/ScrolledItemListBase"; - - CEGUI_DEFINE_PROPERTY(ScrolledItemListBase, bool, - "ForceVertScrollbar", "Property to get/set the state of the force vertical scrollbar setting for the ScrolledItemListBase. Value is either \"true\" or \"false\".", - &ScrolledItemListBase::setShowVertScrollbar, &ScrolledItemListBase::isVertScrollbarAlwaysShown, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(ScrolledItemListBase, bool, - "ForceHorzScrollbar", "Property to get/set the state of the force horizontal scrollbar setting for the ScrolledItemListBase. Value is either \"true\" or \"false\".", - &ScrolledItemListBase::setShowHorzScrollbar, &ScrolledItemListBase::isHorzScrollbarAlwaysShown, false /* TODO: Inconsistency */ - ); -} - -//----------------------------------------------------------------------------// -void ScrolledItemListBase::ensureItemIsVisibleVert(const ItemEntry& item) -{ - const Rectf render_area = getItemRenderArea(); - Scrollbar* const v = getVertScrollbar(); - const float currPos = v->getScrollPosition(); - - const float top = - CoordConverter::asAbsolute(item.getYPosition(), getPixelSize().d_height) - currPos; - const float bottom = top + item.getItemPixelSize().d_height; - - // if top is above the view area, or if item is too big, scroll item to top - if ((top < render_area.d_min.d_y) || ((bottom - top) > render_area.getHeight())) - v->setScrollPosition(currPos + top); - // if bottom is below the view area, scroll item to bottom of list - else if (bottom >= render_area.d_max.d_y) - v->setScrollPosition(currPos + bottom - render_area.getHeight()); -} - -//----------------------------------------------------------------------------// -void ScrolledItemListBase::ensureItemIsVisibleHorz(const ItemEntry& item) -{ - const Rectf render_area = getItemRenderArea(); - Scrollbar* const h = getHorzScrollbar(); - const float currPos = h->getScrollPosition(); - - const float left = - CoordConverter::asAbsolute(item.getXPosition(), getPixelSize().d_width) - currPos; - const float right = left + item.getItemPixelSize().d_width; - - // if left is left of the view area, or if item too big, scroll item to left - if ((left < render_area.d_min.d_x) || ((right - left) > render_area.getWidth())) - h->setScrollPosition(currPos + left); - // if right is right of the view area, scroll item to right of list - else if (right >= render_area.d_max.d_x) - h->setScrollPosition(currPos + right - render_area.getWidth()); -} - -//----------------------------------------------------------------------------// - -} // end CEGUI namespace diff --git a/cegui/src/widgets/Slider.cpp b/cegui/src/widgets/Slider.cpp index 7a3c32951..4bc0fe0b0 100644 --- a/cegui/src/widgets/Slider.cpp +++ b/cegui/src/widgets/Slider.cpp @@ -176,14 +176,14 @@ void Slider::onThumbTrackEnded(WindowEventArgs& e) /************************************************************************* - Handler for when a mouse button is pressed + Handler for when a cursor is pressed *************************************************************************/ -void Slider::onMouseButtonDown(MouseEventArgs& e) +void Slider::onCursorPressHold(CursorInputEventArgs& e) { // base class processing - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { float adj = getAdjustDirectionFromPoint(e.position); @@ -195,20 +195,19 @@ void Slider::onMouseButtonDown(MouseEventArgs& e) ++e.handled; } - } /************************************************************************* Handler for scroll wheel changes *************************************************************************/ -void Slider::onMouseWheel(MouseEventArgs& e) +void Slider::onScroll(CursorInputEventArgs& e) { // base class processing - Window::onMouseWheel(e); + Window::onScroll(e); - // scroll by e.wheelChange * stepSize - setCurrentValue(d_value + d_step * e.wheelChange); + // scroll by vertical scroll * stepSize + setCurrentValue(d_value + d_step * e.scroll); // ensure the message does not go to our parent. ++e.handled; @@ -263,12 +262,12 @@ void Slider::addSliderProperties(void) "CurrentValue", "Property to get/set the current value of the slider. Value is a float.", &Slider::setCurrentValue, &Slider::getCurrentValue, 0.0f ); - + CEGUI_DEFINE_PROPERTY(Slider, float, "MaximumValue", "Property to get/set the maximum value of the slider. Value is a float.", &Slider::setMaxValue, &Slider::getMaxValue, 1.0f /* TODO: Inconsistency */ ); - + CEGUI_DEFINE_PROPERTY(Slider, float, "ClickStepSize", "Property to get/set the click-step size for the slider. Value is a float.", &Slider::setClickStep, &Slider::getClickStep, 0.01f /* TODO: Inconsistency */ @@ -325,7 +324,7 @@ float Slider::getValueFromThumb(void) const Given window location 'pt', return a value indicating what change should be made to the scroll bar. *************************************************************************/ -float Slider::getAdjustDirectionFromPoint(const Vector2f& pt) const +float Slider::getAdjustDirectionFromPoint(const glm::vec2& pt) const { if (d_windowRenderer != 0) { diff --git a/cegui/src/widgets/Spinner.cpp b/cegui/src/widgets/Spinner.cpp index 4d6958d89..7ddf133ba 100644 --- a/cegui/src/widgets/Spinner.cpp +++ b/cegui/src/widgets/Spinner.cpp @@ -82,14 +82,12 @@ namespace CEGUI Editbox* editbox = getEditbox(); // setup component controls - increaseButton->setWantsMultiClickEvents(false); - increaseButton->setMouseAutoRepeatEnabled(true); - decreaseButton->setWantsMultiClickEvents(false); - decreaseButton->setMouseAutoRepeatEnabled(true); + increaseButton->setCursorAutoRepeatEnabled(true); + decreaseButton->setCursorAutoRepeatEnabled(true); // perform event subscriptions. - increaseButton->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&Spinner::handleIncreaseButton, this)); - decreaseButton->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&Spinner::handleDecreaseButton, this)); + increaseButton->subscribeEvent(Window::EventCursorPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this)); + decreaseButton->subscribeEvent(Window::EventCursorPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this)); editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this)); // final initialisation @@ -208,22 +206,22 @@ namespace CEGUI "CurrentValue", "Property to get/set the current value of the spinner. Value is a float.", &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f ); - + CEGUI_DEFINE_PROPERTY(Spinner, double, "StepSize", "Property to get/set the step size of the spinner. Value is a float.", &Spinner::setStepSize, &Spinner::getStepSize, 1.0f ); - + CEGUI_DEFINE_PROPERTY(Spinner, double, "MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.", &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f ); - + CEGUI_DEFINE_PROPERTY(Spinner, double, "MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.", &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f ); - + CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode, "TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".", &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer @@ -406,7 +404,7 @@ namespace CEGUI bool Spinner::handleIncreaseButton(const EventArgs& e) { - if (((const MouseEventArgs&)e).button == LeftButton) + if (((const CursorInputEventArgs&)e).source == CIS_Left) { setCurrentValue(d_currentValue + d_stepSize); return true; @@ -417,7 +415,7 @@ namespace CEGUI bool Spinner::handleDecreaseButton(const EventArgs& e) { - if (((const MouseEventArgs&)e).button == LeftButton) + if (((const CursorInputEventArgs&)e).source == CIS_Left) { setCurrentValue(d_currentValue - d_stepSize); return true; diff --git a/cegui/src/widgets/TabButton.cpp b/cegui/src/widgets/TabButton.cpp index d27d72f3f..9e4d35260 100644 --- a/cegui/src/widgets/TabButton.cpp +++ b/cegui/src/widgets/TabButton.cpp @@ -84,11 +84,11 @@ void TabButton::onClicked(WindowEventArgs& e) /************************************************************************* - Handler for mouse button release events + Handler for cursor press events *************************************************************************/ -void TabButton::onMouseButtonDown(MouseEventArgs& e) +void TabButton::onCursorPressHold(CursorInputEventArgs& e) { - if (e.button == MiddleButton) + if (e.source == CIS_Middle) { captureInput (); ++e.handled; @@ -98,21 +98,21 @@ void TabButton::onMouseButtonDown(MouseEventArgs& e) } // default handling - ButtonBase::onMouseButtonDown(e); + ButtonBase::onCursorPressHold(e); } -void TabButton::onMouseButtonUp(MouseEventArgs& e) +void TabButton::onCursorActivate(CursorInputEventArgs& e) { - if ((e.button == LeftButton) && isPushed()) + if ((e.source == CIS_Left) && isPushed()) { Window* sheet = getGUIContext().getRootWindow(); if (sheet) { - // if mouse was released over this widget - // (use mouse position, as e.position has been unprojected) + // if cursor was released over this widget + // (use cursor position, as e.position has been unprojected) if (this == sheet->getTargetChildAtPosition( - getGUIContext().getMouseCursor().getPosition())) + getGUIContext().getCursor().getPosition())) { // fire event WindowEventArgs args(this); @@ -122,7 +122,7 @@ void TabButton::onMouseButtonUp(MouseEventArgs& e) ++e.handled; } - else if (e.button == MiddleButton) + else if (e.source == CIS_Middle) { d_dragging = false; releaseInput (); @@ -130,10 +130,10 @@ void TabButton::onMouseButtonUp(MouseEventArgs& e) } // default handling - ButtonBase::onMouseButtonUp(e); + ButtonBase::onCursorActivate(e); } -void TabButton::onMouseMove(MouseEventArgs& e) +void TabButton::onCursorMove(CursorInputEventArgs& e) { if (d_dragging) { @@ -142,15 +142,15 @@ void TabButton::onMouseMove(MouseEventArgs& e) } // default handling - ButtonBase::onMouseMove(e); + ButtonBase::onCursorMove(e); } -void TabButton::onMouseWheel(MouseEventArgs& e) +void TabButton::onScroll(CursorInputEventArgs& e) { fireEvent(EventScrolled, e, EventNamespace); // default handling - ButtonBase::onMouseMove(e); + ButtonBase::onCursorMove(e); } } // End of CEGUI namespace section diff --git a/cegui/src/widgets/TabControl.cpp b/cegui/src/widgets/TabControl.cpp index 80540031e..7d58ddd49 100644 --- a/cegui/src/widgets/TabControl.cpp +++ b/cegui/src/widgets/TabControl.cpp @@ -406,14 +406,12 @@ void TabControl::makeTabVisible_impl(Window* wnd) { scrollLeftBtn = getChild(ButtonScrollLeft); lx = CoordConverter::asAbsolute(scrollLeftBtn->getArea().d_max.d_x, ww); - scrollLeftBtn->setWantsMultiClickEvents(false); } if (isChild(ButtonScrollRight)) { scrollRightBtn = getChild(ButtonScrollRight); rx = CoordConverter::asAbsolute(scrollRightBtn->getPosition().d_x, ww); - scrollRightBtn->setWantsMultiClickEvents(false); } if (x < lx) @@ -439,12 +437,12 @@ void TabControl::addTabControlProperties(void) "TabHeight", "Property to get/set the height of the tabs.", &TabControl::setTabHeight, &TabControl::getTabHeight, UDim(0.05f,0.0f) ); - + CEGUI_DEFINE_PROPERTY(TabControl, UDim, "TabTextPadding", "Property to get/set the padding either side of the tab buttons.", &TabControl::setTabTextPadding, &TabControl::getTabTextPadding, UDim(0.0f,0.5f) ); - + CEGUI_DEFINE_PROPERTY(TabControl, TabPanePosition, "TabPanePosition", "Property to get/set the position of the buttons pane.", &TabControl::setTabPanePosition, &TabControl::getTabPanePosition, TabControl::Top @@ -456,12 +454,12 @@ Internal version of adding a child window void TabControl::addChild_impl(Element* element) { Window* wnd = dynamic_cast(element); - + if (!wnd) CEGUI_THROW(InvalidRequestException( "TabControl can only have Elements of type Window added as " "children (Window path: " + getNamePath() + ").")); - + if (wnd->isAutoWindow()) { // perform normal addChild @@ -479,7 +477,7 @@ Internal version of removing a child window void TabControl::removeChild_impl(Element* element) { Window* wnd = static_cast(element); - + // protect against possible null pointers if (!wnd) return; @@ -521,7 +519,7 @@ void TabControl::calculateTabButtonSizePosition(size_t index) // panel of the correct height already UVector2 position(cegui_absdim(0.0f), cegui_absdim(0.0f)); USize size(cegui_absdim(0.0f), cegui_reldim(1.0f)); - + // x position is based on previous button if (!index) { @@ -535,11 +533,11 @@ void TabControl::calculateTabButtonSizePosition(size_t index) // position is prev pos + width position.d_x = prevButton->getArea().d_max.d_x; } - - size.d_width = + + size.d_width = cegui_absdim(btn->getRenderedString().getHorizontalExtent(btn)) + getTabTextPadding() + getTabTextPadding(); - + btn->setPosition(position); btn->setSize(size); @@ -753,21 +751,21 @@ bool TabControl::handleScrollPane(const EventArgs& e) bool TabControl::handleDraggedPane(const EventArgs& e) { - const MouseEventArgs& me = static_cast(e); + const CursorInputEventArgs& pe = static_cast(e); - if (me.button == MiddleButton) + if (pe.source == CIS_Middle) { - // This is the middle-mouse-click event, remember initial drag position + // This is the middle cursor source activate event, remember initial drag position Window *but_pane = getTabButtonPane(); - d_btGrabPos = (me.position.d_x - + d_btGrabPos = (pe.position.x - but_pane->getOuterRectClipper().d_min.d_x) - d_firstTabOffset; } - else if (me.button == NoButton) + else if (pe.source == CIS_None) { - // Regular mouse move event + // Regular cursor move event Window *but_pane = getTabButtonPane(); - float new_to = (me.position.d_x - + float new_to = (pe.position.x - but_pane->getOuterRectClipper().d_min.d_x) - d_btGrabPos; if ((new_to < d_firstTabOffset - 0.9) || @@ -783,12 +781,12 @@ bool TabControl::handleDraggedPane(const EventArgs& e) bool TabControl::handleWheeledPane(const EventArgs& e) { - const MouseEventArgs& me = static_cast(e); + const CursorInputEventArgs& me = static_cast(e); Window *but_pane = getTabButtonPane(); float delta = but_pane->getOuterRectClipper().getWidth () / 20; - d_firstTabOffset += me.wheelChange * delta; + d_firstTabOffset += me.scroll * delta; performChildWindowLayout(); return true; diff --git a/cegui/src/widgets/Thumb.cpp b/cegui/src/widgets/Thumb.cpp index 767e4193d..97ba0abe2 100644 --- a/cegui/src/widgets/Thumb.cpp +++ b/cegui/src/widgets/Thumb.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 25/4/2004 author: Paul D Turner - + purpose: Implements common parts of the Thumb base class widget *************************************************************************/ /*************************************************************************** @@ -63,7 +63,7 @@ Thumb::Thumb(const String& type, const String& name) : /************************************************************************* - Destructor for Thumb objects + Destructor for Thumb objects *************************************************************************/ Thumb::~Thumb(void) { @@ -71,7 +71,7 @@ Thumb::~Thumb(void) /************************************************************************* - set the movement range of the thumb for the vertical axis. + set the movement range of the thumb for the vertical axis. *************************************************************************/ void Thumb::setVertRange(float min, float max) { @@ -101,7 +101,7 @@ void Thumb::setVertRange(float min, float max) } /************************************************************************* - set the movement range of the thumb for the vertical axis. + set the movement range of the thumb for the vertical axis. *************************************************************************/ void Thumb::setVertRange(const std::pair &range) { @@ -148,7 +148,7 @@ void Thumb::setHorzRange(const std::pair &range) /************************************************************************* - event triggered internally when the position of the thumb + event triggered internally when the position of the thumb *************************************************************************/ void Thumb::onThumbPositionChanged(WindowEventArgs& e) { @@ -157,7 +157,7 @@ void Thumb::onThumbPositionChanged(WindowEventArgs& e) /************************************************************************* - Handler triggered when the user begins to drag the thumb. + Handler triggered when the user begins to drag the thumb. *************************************************************************/ void Thumb::onThumbTrackStarted(WindowEventArgs& e) { @@ -175,32 +175,29 @@ void Thumb::onThumbTrackEnded(WindowEventArgs& e) /************************************************************************* - Handler for mouse movement events + Handler for cursor movement events *************************************************************************/ -void Thumb::onMouseMove(MouseEventArgs& e) +void Thumb::onCursorMove(CursorInputEventArgs& e) { // default processing - PushButton::onMouseMove(e); + PushButton::onCursorMove(e); // only react if we are being dragged if (d_beingDragged) { - Sizef parentSize(getParentPixelSize()); - - Vector2f delta; - float hmin, hmax, vmin, vmax; + const Sizef parentSize(getParentPixelSize()); - delta = CoordConverter::screenToWindow(*this, e.position); + const float hmin = d_horzMin; + const float hmax = d_horzMax; + const float vmin = d_vertMin; + const float vmax = d_vertMax; - hmin = d_horzMin; - hmax = d_horzMax; - vmin = d_vertMin; - vmax = d_vertMax; + glm::vec2 delta = CoordConverter::screenToWindow(*this, e.position); - // calculate amount of movement + // calculate amount of movement delta -= d_dragPoint; - delta.d_x /= parentSize.d_width; - delta.d_y /= parentSize.d_height; + delta.x /= parentSize.d_width; + delta.y /= parentSize.d_height; // // Calculate new (pixel) position for thumb @@ -209,7 +206,7 @@ void Thumb::onMouseMove(MouseEventArgs& e) if (d_horzFree) { - newPos.d_x.d_scale += delta.d_x; + newPos.d_x.d_scale += delta.x; // limit value to within currently set range newPos.d_x.d_scale = (newPos.d_x.d_scale < hmin) ? hmin : (newPos.d_x.d_scale > hmax) ? hmax : newPos.d_x.d_scale; @@ -217,7 +214,7 @@ void Thumb::onMouseMove(MouseEventArgs& e) if (d_vertFree) { - newPos.d_y.d_scale += delta.d_y; + newPos.d_y.d_scale += delta.y; // limit new position to within currently set range newPos.d_y.d_scale = (newPos.d_y.d_scale < vmin) ? vmin : (newPos.d_y.d_scale > vmax) ? vmax : newPos.d_y.d_scale; @@ -234,9 +231,7 @@ void Thumb::onMouseMove(MouseEventArgs& e) WindowEventArgs args(this); onThumbPositionChanged(args); } - } - } ++e.handled; @@ -244,14 +239,14 @@ void Thumb::onMouseMove(MouseEventArgs& e) /************************************************************************* - Handler for mouse button down events + Handler for cursor press events *************************************************************************/ -void Thumb::onMouseButtonDown(MouseEventArgs& e) +void Thumb::onCursorPressHold(CursorInputEventArgs& e) { // default processing - PushButton::onMouseButtonDown(e); + PushButton::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { // initialise the dragging state d_beingDragged = true; @@ -263,12 +258,11 @@ void Thumb::onMouseButtonDown(MouseEventArgs& e) ++e.handled; } - } /************************************************************************* - Handler for event triggered when we lose capture of mouse input + Handler for event triggered when we lose capture of cursor input *************************************************************************/ void Thumb::onCaptureLost(WindowEventArgs& e) { @@ -288,7 +282,7 @@ void Thumb::onCaptureLost(WindowEventArgs& e) /************************************************************************* Return a std::pair that describes the current range set for the - vertical movement. + vertical movement. *************************************************************************/ std::pair Thumb::getVertRange(void) const { @@ -298,7 +292,7 @@ std::pair Thumb::getVertRange(void) const /************************************************************************* Return a std::pair that describes the current range set for the - horizontal movement. + horizontal movement. *************************************************************************/ std::pair Thumb::getHorzRange(void) const { @@ -312,15 +306,15 @@ std::pair Thumb::getHorzRange(void) const void Thumb::addThumbProperties(void) { const String& propertyOrigin = WidgetTypeName; - + CEGUI_DEFINE_PROPERTY(Thumb, bool, "HotTracked", "Property to get/set the state of the state of the 'hot-tracked' setting for the thumb." " Value is either \"true\" or \"false\".", &Thumb::setHotTracked, &Thumb::isHotTracked, true ); - + typedef std::pair range; - + CEGUI_DEFINE_PROPERTY(Thumb, range, "VertRange", "Property to get/set the vertical movement range for the thumb. Value is \"min:[float] max:[float]\".", &Thumb::setVertRange, &Thumb::getVertRange, range(0.0f, 1.0f) @@ -335,7 +329,7 @@ void Thumb::addThumbProperties(void) "VertFree", "Property to get/set the state the setting to free the thumb vertically. Value is either \"true\" or \"false\".", &Thumb::setVertFree, &Thumb::isVertFree, false ); - + CEGUI_DEFINE_PROPERTY(Thumb, bool, "HorzFree", "Property to get/set the state the setting to free the thumb horizontally. Value is either \"true\" or \"false\".", &Thumb::setHorzFree, &Thumb::isHorzFree, false diff --git a/cegui/src/widgets/Titlebar.cpp b/cegui/src/widgets/Titlebar.cpp index 8765ced45..3bc72f1ff 100644 --- a/cegui/src/widgets/Titlebar.cpp +++ b/cegui/src/widgets/Titlebar.cpp @@ -1,7 +1,7 @@ /*********************************************************************** created: 25/4/2004 author: Paul D Turner - + purpose: Implementation of common Titlebar parts. *************************************************************************/ /*************************************************************************** @@ -28,7 +28,7 @@ ***************************************************************************/ #include "CEGUI/widgets/Titlebar.h" #include "CEGUI/widgets/FrameWindow.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" #include "CEGUI/CoordConverter.h" // Start of CEGUI namespace section @@ -95,25 +95,23 @@ bool Titlebar::isDragged() const return d_dragging; } -const Vector2f& Titlebar::getDragPoint() const +const glm::vec2& Titlebar::getDragPoint() const { return d_dragPoint; } /************************************************************************* - Handler for mouse movement events + Handler for cursor movement events *************************************************************************/ -void Titlebar::onMouseMove(MouseEventArgs& e) +void Titlebar::onCursorMove(CursorInputEventArgs& e) { // Base class processing. - Window::onMouseMove(e); + Window::onCursorMove(e); if (d_dragging && (d_parent != 0)) { - Vector2f delta(CoordConverter::screenToWindow(*this, e.position)); - - // calculate amount that window has been moved - delta -= d_dragPoint; + // calculate amount that window has been moved + const glm::vec2 delta(CoordConverter::screenToWindow(*this, e.position) - d_dragPoint); // move the window. *** Again: Titlebar objects should only be attached to FrameWindow derived classes. *** ((FrameWindow*)d_parent)->offsetPixelPosition(delta); @@ -124,18 +122,18 @@ void Titlebar::onMouseMove(MouseEventArgs& e) /************************************************************************* - Handler for mouse button press events + Handler for cursor press events *************************************************************************/ -void Titlebar::onMouseButtonDown(MouseEventArgs& e) +void Titlebar::onCursorPressHold(CursorInputEventArgs& e) { // Base class processing - Window::onMouseButtonDown(e); + Window::onCursorPressHold(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { if ((d_parent != 0) && d_dragEnabled) { - // we want all mouse inputs from now on + // we want all cursor inputs from now on if (captureInput()) { // initialise the dragging state @@ -144,22 +142,22 @@ void Titlebar::onMouseButtonDown(MouseEventArgs& e) // store old constraint area d_oldCursorArea = getGUIContext(). - getMouseCursor().getConstraintArea(); + getCursor().getConstraintArea(); // setup new constraint area to be the intersection of the old area and our grand-parent's clipped inner-area Rectf constrainArea; if ((d_parent == 0) || (getParent()->getParent() == 0)) { - Rectf screen(Vector2f(0, 0), getRootContainerSize()); + const Rectf screen(glm::vec2(0, 0), getRootContainerSize()); constrainArea = screen.getIntersection(d_oldCursorArea); } - else + else { constrainArea = getParent()->getParent()->getInnerRectClipper().getIntersection(d_oldCursorArea); } - getGUIContext().getMouseCursor(). + getGUIContext().getCursor(). setConstraintArea(&constrainArea); } } @@ -170,59 +168,56 @@ void Titlebar::onMouseButtonDown(MouseEventArgs& e) /************************************************************************* - Handler for mouse button release events + Handler for cursor activation events *************************************************************************/ -void Titlebar::onMouseButtonUp(MouseEventArgs& e) +void Titlebar::onCursorActivate(CursorInputEventArgs& e) { // Base class processing - Window::onMouseButtonUp(e); + Window::onCursorActivate(e); - if (e.button == LeftButton) + if (e.source == CIS_Left) { releaseInput(); ++e.handled; } - } - -/************************************************************************* - Handler for mouse button double-click events -*************************************************************************/ -void Titlebar::onMouseDoubleClicked(MouseEventArgs& e) +void Titlebar::onSemanticInputEvent(SemanticEventArgs& e) { - // Base class processing - Window::onMouseDoubleClicked(e); + // Base class processing + Window::onSemanticInputEvent(e); - if (e.button == LeftButton) - { - // if we do not have a parent window, then obviously nothing should happen. - if (d_parent) - { - // we should only ever be attached to a FrameWindow (or derived) class - ((FrameWindow*)d_parent)->toggleRollup(); - } + if (isDisabled()) + return; - ++e.handled; - } + if (e.d_semanticValue == SV_SelectWord && e.d_payload.source == CIS_Left) + { -} + // if we do not have a parent window, then obviously nothing should happen. + if (d_parent) + { + // we should only ever be attached to a FrameWindow (or derived) class + ((FrameWindow*)d_parent)->toggleRollup(); + } + ++e.handled; + } +} /************************************************************************* - Handler for if the window loses capture of the mouse. + Handler for if the window loses capture of the cursor. *************************************************************************/ void Titlebar::onCaptureLost(WindowEventArgs& e) { // Base class processing Window::onCaptureLost(e); - // when we lose out hold on the mouse inputs, we are no longer dragging. + // when we lose out hold on the cursor inputs, we are no longer dragging. d_dragging = false; // restore old constraint area getGUIContext(). - getMouseCursor().setConstraintArea(&d_oldCursorArea); + getCursor().setConstraintArea(&d_oldCursorArea); } @@ -253,5 +248,4 @@ void Titlebar::addTitlebarProperties(void) ); } - } // End of CEGUI namespace section diff --git a/cegui/src/widgets/ToggleButton.cpp b/cegui/src/widgets/ToggleButton.cpp index 3448552a7..9fcff26c7 100644 --- a/cegui/src/widgets/ToggleButton.cpp +++ b/cegui/src/widgets/ToggleButton.cpp @@ -45,7 +45,7 @@ ToggleButton::ToggleButton(const String& type, const String& name) : void ToggleButton::addToggleButtonProperties() { const String& propertyOrigin(WidgetTypeName); - + CEGUI_DEFINE_PROPERTY(ToggleButton, bool, "Selected", "Property to access the selected state of the ToggleButton. " @@ -74,16 +74,16 @@ void ToggleButton::onSelectStateChange(WindowEventArgs& e) } //----------------------------------------------------------------------------// -void ToggleButton::onMouseButtonUp(MouseEventArgs& e) +void ToggleButton::onCursorActivate(CursorInputEventArgs& e) { - if (e.button == LeftButton && isPushed()) + if (e.source == CIS_Left && isPushed()) { if (const Window* const sheet = getGUIContext().getRootWindow()) { - // was mouse released over this widget - // (use mouse position, as e.position is already unprojected) + // was cursor released over this widget + // (use cursor position, as e.position is already unprojected) if (this == sheet->getTargetChildAtPosition( - getGUIContext().getMouseCursor().getPosition())) + getGUIContext().getCursor().getPosition())) { setSelected(getPostClickSelectState()); } @@ -92,7 +92,7 @@ void ToggleButton::onMouseButtonUp(MouseEventArgs& e) ++e.handled; } - ButtonBase::onMouseButtonUp(e); + ButtonBase::onCursorActivate(e); } //----------------------------------------------------------------------------// @@ -101,6 +101,20 @@ bool ToggleButton::getPostClickSelectState() const return d_selected ^ true; } +//----------------------------------------------------------------------------// +void ToggleButton::onSemanticInputEvent(SemanticEventArgs& e) +{ + if (isDisabled()) + return; + + if (e.d_semanticValue == SV_Confirm) + { + setSelected(getPostClickSelectState()); + + ++e.handled; + } +} + //----------------------------------------------------------------------------// } diff --git a/cegui/src/widgets/Tooltip.cpp b/cegui/src/widgets/Tooltip.cpp index 676112975..ff3b5aee9 100644 --- a/cegui/src/widgets/Tooltip.cpp +++ b/cegui/src/widgets/Tooltip.cpp @@ -66,7 +66,7 @@ namespace CEGUI setClippedByParent(false); setDestroyedByParent(false); setAlwaysOnTop(true); - + // we need updates even when not visible setUpdateMode(WUM_ALWAYS); @@ -79,46 +79,46 @@ namespace CEGUI void Tooltip::positionSelf(void) { - // no recusion allowed for this function! + // no recursion allowed for this function! if (d_inPositionSelf) return; d_inPositionSelf = true; - MouseCursor& cursor = getGUIContext().getMouseCursor(); - Rectf screen(Vector2f(0, 0), getRootContainerSize()); + const Cursor& indicator = getGUIContext().getCursor(); + const Rectf screen(glm::vec2(0, 0), getRootContainerSize()); Rectf tipRect(getUnclippedOuterRect().get()); - const Image* mouseImage = cursor.getImage(); + const Image* cursor_image = indicator.getImage(); - Vector2f mousePos(cursor.getPosition()); - Sizef mouseSz(0,0); + const glm::vec2 cursor_pos(indicator.getPosition()); + Sizef cursor_size(0,0); - if (mouseImage) + if (cursor_image) { - mouseSz = mouseImage->getRenderedSize(); + cursor_size = cursor_image->getRenderedSize(); } - Vector2f tmpPos(mousePos.d_x + mouseSz.d_width, mousePos.d_y + mouseSz.d_height); + glm::vec2 tmpPos(cursor_pos.x + cursor_size.d_width, cursor_pos.y + cursor_size.d_height); tipRect.setPosition(tmpPos); // if tooltip would be off the right of the screen, - // reposition to the other side of the mouse cursor. + // reposition to the other side of the cursor. if (screen.right() < tipRect.right()) { - tmpPos.d_x = mousePos.d_x - tipRect.getWidth() - 5; + tmpPos.x = cursor_pos.x - tipRect.getWidth() - 5; } // if tooltip would be off the bottom of the screen, - // reposition to the other side of the mouse cursor. + // reposition to the other side of the cursor. if (screen.bottom() < tipRect.bottom()) { - tmpPos.d_y = mousePos.d_y - tipRect.getHeight() - 5; + tmpPos.y = cursor_pos.y - tipRect.getHeight() - 5; } // set final position of tooltip window. setPosition( - UVector2(cegui_absdim(tmpPos.d_x), - cegui_absdim(tmpPos.d_y))); + UVector2(cegui_absdim(tmpPos.x), + cegui_absdim(tmpPos.y))); d_inPositionSelf = false; } @@ -338,11 +338,11 @@ namespace CEGUI } } - void Tooltip::onMouseEnters(MouseEventArgs& e) + void Tooltip::onCursorEnters(CursorInputEventArgs& e) { positionSelf(); - Window::onMouseEnters(e); + Window::onCursorEnters(e); } void Tooltip::onTextChanged(WindowEventArgs& e) diff --git a/cegui/src/widgets/Tree.cpp b/cegui/src/widgets/Tree.cpp deleted file mode 100644 index f4943f586..000000000 --- a/cegui/src/widgets/Tree.cpp +++ /dev/null @@ -1,1404 +0,0 @@ -/*********************************************************************** - created: 5-13-07 - author: Jonathan Welch (Based on Code by David Durant) - *************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUI/Exceptions.h" -#include "CEGUI/WindowManager.h" -#include "CEGUI/CoordConverter.h" -#include "CEGUI/WindowManager.h" -#include "CEGUI/falagard/WidgetLookManager.h" -#include "CEGUI/falagard/WidgetLookFeel.h" -#include "CEGUI/widgets/TreeItem.h" -#include "CEGUI/widgets/Tree.h" -#include "CEGUI/widgets/Scrollbar.h" -#include "CEGUI/widgets/Tooltip.h" - -#include - -// Start of CEGUI namespace section -namespace CEGUI -{ -const String Tree::EventNamespace("Tree"); -const String Tree::WidgetTypeName("CEGUI/Tree"); -/************************************************************************* - Constants -*************************************************************************/ -// event names -const String Tree::EventListContentsChanged( "ListContentsChanged" ); -const String Tree::EventSelectionChanged( "SelectionChanged" ); -const String Tree::EventSortModeChanged( "SortModeChanged" ); -const String Tree::EventMultiselectModeChanged( "MultiselectModeChanged" ); -const String Tree::EventVertScrollbarModeChanged( "VertScrollbarModeChanged" ); -const String Tree::EventHorzScrollbarModeChanged( "HorzScrollbarModeChanged" ); -const String Tree::EventBranchOpened( "BranchOpened" ); -const String Tree::EventBranchClosed( "BranchClosed" ); - -/************************************************************************* - Constructor for Tree base class. -*************************************************************************/ -Tree::Tree(const String& type, const String& name) : - Window(type, name), - d_sorted(false), - d_multiselect(false), - d_forceVertScroll(false), - d_forceHorzScroll(false), - d_itemTooltips(false), - d_vertScrollbar(0), - d_horzScrollbar(0), - d_lastSelected(0), - d_openButtonImagery(0), - d_closeButtonImagery(0), - d_itemArea(0, 0, 0, 0) -{ - // add new events specific to tree. - addTreeEvents(); - - addTreeProperties(); -} - -void Tree::setLookNFeel(const String& look) -{ - Window::setLookNFeel( look ); - initialise(); -} - -/************************************************************************* - Destructor for Tree base class. -*************************************************************************/ -Tree::~Tree(void) -{ - resetList_impl(); -} - -/************************************************************************* - Initialise the Window based object ready for use. -*************************************************************************/ -void Tree::initialise(void) -{ - // get WidgetLookFeel for the assigned look. - const WidgetLookFeel &wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName); - const ImagerySection &tempOpenImagery = wlf.getImagerySection("OpenTreeButton"); - const ImagerySection &tempCloseImagery = wlf.getImagerySection("CloseTreeButton"); - d_openButtonImagery = &tempOpenImagery; - d_closeButtonImagery = &tempCloseImagery; - - // create the component sub-widgets - d_vertScrollbar = createVertScrollbar("__auto_vscrollbar__"); - d_horzScrollbar = createHorzScrollbar("__auto_hscrollbar__"); - - addChild(d_vertScrollbar); - addChild(d_horzScrollbar); - - d_vertScrollbar->subscribeEvent(Scrollbar::EventScrollPositionChanged, Event::Subscriber(&Tree::handle_scrollChange, this)); - d_horzScrollbar->subscribeEvent(Scrollbar::EventScrollPositionChanged, Event::Subscriber(&Tree::handle_scrollChange, this)); - - configureScrollbars(); - performChildWindowLayout(); -} - -/************************************************************************* - Return the number of selected items in the tree. -*************************************************************************/ -size_t Tree::getSelectedCount(void) const -{ - size_t count = 0; - - for (size_t index = 0; index < d_listItems.size(); ++index) - { - if (d_listItems[index]->isSelected()) - count++; - } - - return count; -} - -/************************************************************************* - Return a pointer to the first selected item. -*************************************************************************/ -TreeItem* Tree::getFirstSelectedItem(void) const -{ - bool found_first = true; - return getNextSelectedItemFromList(d_listItems, 0, found_first); -} - -/************************************************************************* - Return a pointer to the next selected item after item 'start_item' -*************************************************************************/ -TreeItem* Tree::getNextSelected(const TreeItem* start_item) const -{ - bool found_first = (start_item == 0); - return getNextSelectedItemFromList(d_listItems, start_item, found_first); -} - -// Recursive! -TreeItem* Tree::getNextSelectedItemFromList(const LBItemList &itemList, - const TreeItem* startItem, - bool& foundStartItem) const -{ - size_t itemCount = itemList.size(); - - for (size_t index = 0; index < itemCount; ++index) - { - if (foundStartItem == true) - { - // Already found the startItem, now looking for next selected item. - if (itemList[index]->isSelected()) - return itemList[index]; - } - else - { - // Still looking for startItem. Is this it? - if (itemList[index] == startItem) - foundStartItem = true; - } - - if (itemList[index]->getItemCount() > 0) - { - if (itemList[index]->getIsOpen()) - { - TreeItem *foundSelectedTree; - foundSelectedTree = getNextSelectedItemFromList(itemList[index]->getItemList(), startItem, foundStartItem); - if (foundSelectedTree != 0) - return foundSelectedTree; - } - } - } - - return 0; -} - -// Recursive! -TreeItem* Tree::findItemWithTextFromList(const LBItemList &itemList, const String& text, const TreeItem* startItem, bool foundStartItem) -{ - size_t itemCount = itemList.size(); - - for (size_t index = 0; index < itemCount; ++index) - { - if (foundStartItem == true) - { - // Already found the startItem, now looking for the actual text. - if (itemList[index]->getText() == text) - return itemList[index]; - } - else - { - // Still looking for startItem. Is this it? - if (itemList[index] == startItem) - foundStartItem = true; - } - - if (itemList[index]->getItemCount() > 0) - { - // Search the current item's itemList regardless if it's open or not. - TreeItem *foundSelectedTree; - foundSelectedTree = findItemWithTextFromList(itemList[index]->getItemList(), text, startItem, foundStartItem); - if (foundSelectedTree != 0) - return foundSelectedTree; - } - } - - return 0; -} - -/************************************************************************* - Search the list for an item with the specified text -*************************************************************************/ -TreeItem* Tree::findNextItemWithText(const String& text, const TreeItem* start_item) -{ - if (start_item == 0) - return findItemWithTextFromList(d_listItems, text, 0, true); - else - return findItemWithTextFromList(d_listItems, text, start_item, false); -} - - -TreeItem* Tree::findFirstItemWithText(const String& text) -{ - return findItemWithTextFromList(d_listItems, text, 0, true); -} - -// Recursive! -TreeItem* Tree::findItemWithIDFromList(const LBItemList &itemList, uint searchID, const TreeItem* startItem, bool foundStartItem) -{ - size_t itemCount = itemList.size(); - - for (size_t index = 0; index < itemCount; ++index) - { - if (foundStartItem == true) - { - // Already found the startItem, now looking for the actual text. - if (itemList[index]->getID() == searchID) - return itemList[index]; - } - else - { - // Still looking for startItem. Is this it? - if (itemList[index] == startItem) - foundStartItem = true; - } - - if (itemList[index]->getItemCount() > 0) - { - // Search the current item's itemList regardless if it's open or not. - TreeItem *foundSelectedTree; - foundSelectedTree = findItemWithIDFromList(itemList[index]->getItemList(), searchID, startItem, foundStartItem); - if (foundSelectedTree != 0) - return foundSelectedTree; - } - } - - return 0; -} - -TreeItem* Tree::findNextItemWithID(uint searchID, const TreeItem* start_item) -{ - if (start_item == 0) - return findItemWithIDFromList(d_listItems, searchID, 0, true); - else - return findItemWithIDFromList(d_listItems, searchID, start_item, false); -} - -TreeItem* Tree::findFirstItemWithID(uint searchID) -{ - return findItemWithIDFromList(d_listItems, searchID, 0, true); -} - -/************************************************************************* - Return whether the specified TreeItem is in the List -*************************************************************************/ -bool Tree::isTreeItemInList(const TreeItem* item) const -{ - return std::find(d_listItems.begin(), d_listItems.end(), item) != d_listItems.end(); -} - -/************************************************************************* - Remove all items from the list. -*************************************************************************/ -void Tree::resetList(void) -{ - if (resetList_impl()) - { - WindowEventArgs args(this); - onListContentsChanged(args); - } -} - -/************************************************************************* - Add the given TreeItem to the list. -*************************************************************************/ -void Tree::addItem(TreeItem* item) -{ - if (item != 0) - { - // establish ownership - item->setOwnerWindow(this); - - // if sorting is enabled, re-sort the list - if (isSortEnabled()) - { - d_listItems.insert(std::upper_bound(d_listItems.begin(), d_listItems.end(), item, &lbi_less), item); - } - // not sorted, just stick it on the end. - else - { - d_listItems.push_back(item); - } - - WindowEventArgs args(this); - onListContentsChanged(args); - } -} - -/************************************************************************* - Insert an item into the tree after a specified item already in - the list. -*************************************************************************/ -void Tree::insertItem(TreeItem* item, const TreeItem* position) -{ - // if the list is sorted, it's the same as a normal add operation - if (isSortEnabled()) - { - addItem(item); - } - else if (item != 0) - { - // establish ownership - item->setOwnerWindow(this); - - // if position is NULL begin insert at begining, else insert after item 'position' - LBItemList::iterator ins_pos; - - if (position == 0) - { - ins_pos = d_listItems.begin(); - } - else - { - ins_pos = std::find(d_listItems.begin(), d_listItems.end(), position); - - // throw if item 'position' is not in the list - if (ins_pos == d_listItems.end()) - { - CEGUI_THROW(InvalidRequestException( - "the specified TreeItem for parameter 'position' is not attached to this Tree.")); - } - } - - d_listItems.insert(ins_pos, item); - - WindowEventArgs args(this); - onListContentsChanged(args); - } -} - -/************************************************************************* - Removes the given item from the tree. -*************************************************************************/ -void Tree::removeItem(const TreeItem* item) -{ - if (item != 0) - { - LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); - - // if item is in the list - if (pos != d_listItems.end()) - { - // disown item - (*pos)->setOwnerWindow(0); - - // remove item - d_listItems.erase(pos); - - // if item was the last selected item, reset that to NULL - if (item == d_lastSelected) - { - d_lastSelected = 0; - } - - // if item is supposed to be deleted by us - if (item->isAutoDeleted()) - { - // clean up this item. - CEGUI_DELETE_AO item; - } - - WindowEventArgs args(this); - onListContentsChanged(args); - } - } -} - -/************************************************************************* - Clear the selected state for all items. -*************************************************************************/ -void Tree::clearAllSelections(void) -{ - // only fire events and update if we actually made any changes - if (clearAllSelections_impl()) - { - TreeEventArgs args(this); - onSelectionChanged(args); - } -} - -/************************************************************************* - Set whether the list should be sorted. -*************************************************************************/ -void Tree::setSortingEnabled(bool setting) -{ - // only react if the setting will change - if (d_sorted != setting) - { - d_sorted = setting; - - // if we are enabling sorting, we need to sort the list - if (d_sorted) - { - std::sort(d_listItems.begin(), d_listItems.end(), &lbi_less); - } - - WindowEventArgs args(this); - onSortModeChanged(args); - } -} - -/************************************************************************* - Set whether the list should allow multiple selections or just a - single selection -*************************************************************************/ -void Tree::setMultiselectEnabled(bool setting) -{ - // only react if the setting is changed - if (d_multiselect != setting) - { - d_multiselect = setting; - - // if we change to single-select, deselect all except the first selected item. - TreeEventArgs args(this); - if ((!d_multiselect) && (getSelectedCount() > 1)) - { - TreeItem* itm = getFirstSelectedItem(); - - while ((itm = getNextSelected(itm))) - { - itm->setSelected(false); - } - - onSelectionChanged(args); - } - - onMultiselectModeChanged(args); - } -} - - -void Tree::setItemTooltipsEnabled(bool setting) -{ - d_itemTooltips = setting; -} - -/************************************************************************* - Set whether the vertical scroll bar should always be shown. -*************************************************************************/ -void Tree::setShowVertScrollbar(bool setting) -{ - if (d_forceVertScroll != setting) - { - d_forceVertScroll = setting; - - configureScrollbars(); - WindowEventArgs args(this); - onVertScrollbarModeChanged(args); - } -} - -/************************************************************************* - Set whether the horizontal scroll bar should always be shown. -*************************************************************************/ -void Tree::setShowHorzScrollbar(bool setting) -{ - if (d_forceHorzScroll != setting) - { - d_forceHorzScroll = setting; - - configureScrollbars(); - WindowEventArgs args(this); - onHorzScrollbarModeChanged(args); - } -} - -/************************************************************************* - Set the select state of an attached TreeItem. -*************************************************************************/ -void Tree::setItemSelectState(TreeItem* item, bool state) -{ - if (containsOpenItemRecursive(d_listItems, item)) - { - TreeEventArgs args(this); - args.treeItem = item; - - if (state && !d_multiselect) - clearAllSelections_impl(); - - item->setSelected(state); - d_lastSelected = item->isSelected() ? item : 0; - onSelectionChanged(args); - } - else - { - CEGUI_THROW(InvalidRequestException("the specified TreeItem is not " - "attached to this Tree or not visible.")); - } - } - -//----------------------------------------------------------------------------// -bool Tree::containsOpenItemRecursive(const LBItemList& itemList, TreeItem* item) -{ - size_t itemCount = itemList.size(); - for (size_t index = 0; index < itemCount; ++index) - { - if (itemList[index] == item) - return true; - - if (itemList[index]->getItemCount() > 0) - { - if (itemList[index]->getIsOpen()) - { - if (containsOpenItemRecursive(itemList[index]->getItemList(), item)) - return true; - } - } - } - - return false; -} - -/************************************************************************* - Set the select state of an attached TreeItem. -*************************************************************************/ -void Tree::setItemSelectState(size_t item_index, bool state) -{ - if (item_index < getItemCount()) - { - // only do this if the setting is changing - if (d_listItems[item_index]->isSelected() != state) - { - // conditions apply for single-select mode - if (state && !d_multiselect) - { - clearAllSelections_impl(); - } - - d_listItems[item_index]->setSelected(state); - TreeEventArgs args(this); - args.treeItem = d_listItems[item_index]; - onSelectionChanged(args); - } - } - else - { - CEGUI_THROW(InvalidRequestException( - "the value passed in the 'item_index' parameter is out of range for this Tree.")); - } - -} - -/************************************************************************* - Causes the tree to update it's internal state after changes have - been made to one or more attached TreeItem objects. -*************************************************************************/ -void Tree::handleUpdatedItemData(void) -{ - configureScrollbars(); - invalidate(); -} - -/************************************************************************* - Perform the actual rendering for this Window. -*************************************************************************/ -void Tree::populateGeometryBuffer() -{ - // get the derived class to render general stuff before we handle the items - cacheTreeBaseImagery(); - - // Render list items - Vector2f itemPos; - float widest = getWidestItemWidth(); - - // calculate position of area we have to render into - //Rect itemsArea(getTreeRenderArea()); - //Rect itemsArea(0,0,500,500); - - // set up some initial positional details for items - itemPos.d_x = d_itemArea.left() - d_horzScrollbar->getScrollPosition(); - itemPos.d_y = d_itemArea.top() - d_vertScrollbar->getScrollPosition(); - - drawItemList(d_listItems, d_itemArea, widest, itemPos, *d_geometry, - getEffectiveAlpha()); -} - -// Recursive! -void Tree::drawItemList(LBItemList& itemList, Rectf& itemsArea, float widest, - Vector2f& itemPos, GeometryBuffer& geometry, float alpha) -{ - if (itemList.empty()) - return; - - // loop through the items - Sizef itemSize; - Rectf itemClipper, itemRect; - size_t itemCount = itemList.size(); - bool itemIsVisible; - for (size_t i = 0; i < itemCount; ++i) - { - itemSize.d_height = itemList[i]->getPixelSize().d_height; - - // allow item to have full width of box if this is wider than items - itemSize.d_width = ceguimax(itemsArea.getWidth(), widest); - - // calculate destination area for this item. - itemRect.left(itemPos.d_x); - itemRect.top(itemPos.d_y); - itemRect.setSize(itemSize); - itemClipper = itemRect.getIntersection(itemsArea); - itemRect.d_min.d_x += 20; // start text past open/close buttons - - if (itemClipper.getHeight() > 0) - { - itemIsVisible = true; - itemList[i]->draw(geometry, itemRect, alpha, &itemClipper); - } - else - { - itemIsVisible = false; - } - - // Process this item's list if it has items in it. - if (itemList[i]->getItemCount() > 0) - { - Rectf buttonRenderRect; - buttonRenderRect.left(itemPos.d_x); - buttonRenderRect.right(buttonRenderRect.left() + 10); - buttonRenderRect.top(itemPos.d_y); - buttonRenderRect.bottom(buttonRenderRect.top() + 10); - itemList[i]->setButtonLocation(buttonRenderRect); - - if (itemList[i]->getIsOpen()) - { - // Draw the Close button - if (itemIsVisible) - d_closeButtonImagery->render(*this, buttonRenderRect, 0, &itemClipper); - - // update position ready for next item - itemPos.d_y += itemSize.d_height; - - itemPos.d_x += 20; - drawItemList(itemList[i]->getItemList(), itemsArea, widest, - itemPos, geometry, alpha); - itemPos.d_x -= 20; - } - else - { - // Draw the Open button - if (itemIsVisible) - d_openButtonImagery->render(*this, buttonRenderRect, 0, &itemClipper); - - // update position ready for next item - itemPos.d_y += itemSize.d_height; - } - } - else - { - // update position ready for next item - itemPos.d_y += itemSize.d_height; - } - } - - // Successfully drew all items, so vertical scrollbar not needed. - // setShowVertScrollbar(false); -} - -#define HORIZONTAL_STEP_SIZE_DIVISOR 20.0f - -/************************************************************************* - display required integrated scroll bars according to current state - of the tree and update their values. -*************************************************************************/ -void Tree::configureScrollbars(void) -{ - Rectf renderArea(getTreeRenderArea()); - - //This is becuase CEGUI IS GAY! and fires events before the item is initialized - if(!d_vertScrollbar) - d_vertScrollbar = createVertScrollbar("__auto_vscrollbar__"); - if(!d_horzScrollbar) - d_horzScrollbar = createHorzScrollbar("__auto_hscrollbar__"); - - float totalHeight = getTotalItemsHeight(); - float widestItem = getWidestItemWidth() + 20; - - // - // First show or hide the scroll bars as needed (or requested) - // - // show or hide vertical scroll bar as required (or as specified by option) - if ((totalHeight > renderArea.getHeight()) || d_forceVertScroll) - { - d_vertScrollbar->show(); - renderArea.d_max.d_x -= d_vertScrollbar->getWidth().d_offset + d_vertScrollbar->getXPosition().d_offset; - // show or hide horizontal scroll bar as required (or as specified by option) - if ((widestItem > renderArea.getWidth()) || d_forceHorzScroll) - { - d_horzScrollbar->show(); - renderArea.d_max.d_y -= d_horzScrollbar->getHeight().d_offset; - } - else - { - d_horzScrollbar->hide(); - d_horzScrollbar->setScrollPosition(0); - } - } - else - { - // show or hide horizontal scroll bar as required (or as specified by option) - if ((widestItem > renderArea.getWidth()) || d_forceHorzScroll) - { - d_horzScrollbar->show(); - renderArea.d_max.d_y -= d_vertScrollbar->getHeight().d_offset; - - // show or hide vertical scroll bar as required (or as specified by option) - if ((totalHeight > renderArea.getHeight()) || d_forceVertScroll) - { - d_vertScrollbar->show(); - // renderArea.d_right -= d_vertScrollbar->getAbsoluteWidth(); - renderArea.d_max.d_x -= d_vertScrollbar->getWidth().d_offset; - } - else - { - d_vertScrollbar->hide(); - d_vertScrollbar->setScrollPosition(0); - } - } - else - { - d_vertScrollbar->hide(); - d_vertScrollbar->setScrollPosition(0); - d_horzScrollbar->hide(); - d_horzScrollbar->setScrollPosition(0); - } - } - - // - // Set up scroll bar values - // - - float itemHeight; - if (!d_listItems.empty()) - itemHeight = d_listItems[0]->getPixelSize().d_height; - else - itemHeight = 10; - - d_vertScrollbar->setDocumentSize(totalHeight); - d_vertScrollbar->setPageSize(renderArea.getHeight()); - d_vertScrollbar->setStepSize(ceguimax(1.0f, renderArea.getHeight() / itemHeight)); - d_vertScrollbar->setScrollPosition(d_vertScrollbar->getScrollPosition()); - - d_horzScrollbar->setDocumentSize(widestItem + d_vertScrollbar->getWidth().d_offset); - // d_horzScrollbar->setDocumentSize(widestItem + d_vertScrollbar->getAbsoluteWidth()); - d_horzScrollbar->setPageSize(renderArea.getWidth()); - d_horzScrollbar->setStepSize(ceguimax(1.0f, renderArea.getWidth() / HORIZONTAL_STEP_SIZE_DIVISOR)); - d_horzScrollbar->setScrollPosition(d_horzScrollbar->getScrollPosition()); -} - -/************************************************************************* - select all strings between positions 'start' and 'end' (inclusive) -*************************************************************************/ -void Tree::selectRange(size_t start, size_t end) -{ - // only continue if list has some items - if (!d_listItems.empty()) - { - // if start is out of range, start at begining. - if (start > d_listItems.size()) - { - start = 0; - } - - // if end is out of range end at the last item. - if (end >= d_listItems.size()) - { - end = d_listItems.size() - 1; - } - - // ensure start becomes before the end. - if (start > end) - { - size_t tmp; - tmp = start; - start = end; - end = tmp; - } - - // perform selections - for( ; start <= end; ++start) - { - d_listItems[start]->setSelected(true); - } - } -} - -/************************************************************************* - Return the sum of all item heights -*************************************************************************/ -float Tree::getTotalItemsHeight(void) const -{ - float heightSum = 0; - - getTotalItemsInListHeight(d_listItems, &heightSum); - return heightSum; -} - -// Recursive! -void Tree::getTotalItemsInListHeight(const LBItemList &itemList, float *heightSum) const -{ - size_t itemCount = itemList.size(); - for (size_t index = 0; index < itemCount; ++index) - { - *heightSum += itemList[index]->getPixelSize().d_height; - if (itemList[index]->getIsOpen() && (itemList[index]->getItemCount() > 0)) - getTotalItemsInListHeight(itemList[index]->getItemList(), heightSum); - } -} - -/************************************************************************* - Return the width of the widest item, including any white space to the left - due to indenting. -*************************************************************************/ -float Tree::getWidestItemWidth(void) const -{ - float widest = 0; - - getWidestItemWidthInList(d_listItems, 0, &widest); - return widest; -} - -// Recursive! -void Tree::getWidestItemWidthInList(const LBItemList &itemList, int itemDepth, float *widest) const -{ - size_t itemCount = itemList.size(); - for (size_t index = 0; index < itemCount; ++index) - { - Rectf buttonLocation = itemList[index]->getButtonLocation(); - float thisWidth = itemList[index]->getPixelSize().d_width + - buttonLocation.getWidth() + - (d_horzScrollbar->getScrollPosition() / HORIZONTAL_STEP_SIZE_DIVISOR) + - (itemDepth * 20); - - if (thisWidth > *widest) - *widest = thisWidth; - - if (itemList[index]->getIsOpen() && (itemList[index]->getItemCount() > 0)) - getWidestItemWidthInList(itemList[index]->getItemList(), itemDepth + 1, widest); - } -} - -/************************************************************************* - Clear the selected state for all items (implementation) -*************************************************************************/ -bool Tree::clearAllSelections_impl(void) -{ - return clearAllSelectionsFromList(d_listItems); -} - -// Recursive! -bool Tree::clearAllSelectionsFromList(const LBItemList &itemList) -{ - // flag used so we can track if we did anything. - bool modified = false; - - for (size_t index = 0; index < itemList.size(); ++index) - { - if (itemList[index]->isSelected()) - { - itemList[index]->setSelected(false); - modified = true; - } - - if (itemList[index]->getItemCount() > 0) - { - bool modifiedSubList = clearAllSelectionsFromList(itemList[index]->getItemList()); - if (modifiedSubList) - modified = true; - } - } - - return modified; -} - -/************************************************************************* - Return the TreeItem under the given window local pixel co-ordinate. -*************************************************************************/ -TreeItem* Tree::getItemAtPoint(const Vector2f& pt) const -{ - Rectf renderArea(getTreeRenderArea()); - - // point must be within the rendering area of the Tree. - if (renderArea.isPointInRect(pt)) - { - float y = renderArea.top() - d_vertScrollbar->getScrollPosition(); - - // test if point is above first item - if (pt.d_y >= y) - return getItemFromListAtPoint(d_listItems, &y, pt); - } - - return 0; -} - -// Recursive! -TreeItem* Tree::getItemFromListAtPoint(const LBItemList &itemList, float *bottomY, const Vector2f& pt) const -{ - size_t itemCount = itemList.size(); - - for (size_t i = 0; i < itemCount; ++i) - { - *bottomY += itemList[i]->getPixelSize().d_height; - if (pt.d_y < *bottomY) - return itemList[i]; - - if (itemList[i]->getItemCount() > 0) - { - if (itemList[i]->getIsOpen()) - { - TreeItem *foundPointedAtTree; - foundPointedAtTree = getItemFromListAtPoint(itemList[i]->getItemList(), bottomY, pt); - if (foundPointedAtTree != 0) - return foundPointedAtTree; - } - } - } - - return 0; -} - -/************************************************************************* - Add tree specific events -*************************************************************************/ -void Tree::addTreeEvents(void) -{ - addEvent(EventListContentsChanged); - addEvent(EventSelectionChanged); - addEvent(EventSortModeChanged); - addEvent(EventMultiselectModeChanged); - addEvent(EventVertScrollbarModeChanged); - addEvent(EventHorzScrollbarModeChanged); - addEvent(EventBranchOpened); - addEvent(EventBranchClosed); -} - -/************************************************************************* - Handler called internally when the list contents are changed -*************************************************************************/ -void Tree::onListContentsChanged(WindowEventArgs& e) -{ - configureScrollbars(); - invalidate(); - fireEvent(EventListContentsChanged, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the currently selected item or items - changes. -*************************************************************************/ -void Tree::onSelectionChanged(TreeEventArgs& e) -{ - invalidate(); - fireEvent(EventSelectionChanged, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the sort mode setting changes. -*************************************************************************/ -void Tree::onSortModeChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventSortModeChanged, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the multi-select mode setting changes. -*************************************************************************/ -void Tree::onMultiselectModeChanged(WindowEventArgs& e) -{ - fireEvent(EventMultiselectModeChanged, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the forced display of the vertical - scroll bar setting changes. -*************************************************************************/ -void Tree::onVertScrollbarModeChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventVertScrollbarModeChanged, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the forced display of the horizontal - scroll bar setting changes. -*************************************************************************/ -void Tree::onHorzScrollbarModeChanged(WindowEventArgs& e) -{ - invalidate(); - fireEvent(EventHorzScrollbarModeChanged, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the forced display of the horizontal - scroll bar setting changes. -*************************************************************************/ -void Tree::onBranchOpened(TreeEventArgs& e) -{ - invalidate(); - fireEvent(EventBranchOpened, e, EventNamespace); -} - -/************************************************************************* - Handler called internally when the forced display of the horizontal - scroll bar setting changes. -*************************************************************************/ -void Tree::onBranchClosed(TreeEventArgs& e) -{ - invalidate(); - fireEvent(EventBranchClosed, e, EventNamespace); -} - -/************************************************************************* - Handler for when we are sized -*************************************************************************/ -void Tree::onSized(ElementEventArgs& e) -{ - // base class handling - Window::onSized(e); - - configureScrollbars(); - - ++e.handled; -} - -/************************************************************************* - Handler for when mouse button is pressed -*************************************************************************/ -void Tree::onMouseButtonDown(MouseEventArgs& e) -{ - // base class processing - // populateGeometryBuffer(); - Window::onMouseButtonDown(e); - - if (e.button == LeftButton) - { - //bool modified = false; - - Vector2f localPos(CoordConverter::screenToWindow(*this, e.position)); - // Point localPos(screenToWindow(e.position)); - - TreeItem* item = getItemAtPoint(localPos); - - if (item != 0) - { - //modified = true; - TreeEventArgs args(this); - args.treeItem = item; - populateGeometryBuffer(); - Rectf buttonLocation = item->getButtonLocation(); - if ((localPos.d_x >= buttonLocation.left()) && (localPos.d_x <= buttonLocation.right()) && - (localPos.d_y >= buttonLocation.top()) && (localPos.d_y <= buttonLocation.bottom())) - { - item->toggleIsOpen(); - if (item->getIsOpen()) - { - TreeItem *lastItemInList = item->getTreeItemFromIndex(item->getItemCount() - 1); - ensureItemIsVisible(lastItemInList); - ensureItemIsVisible(item); - onBranchOpened(args); - } - else - { - onBranchClosed(args); - } - - // Update the item screen locations, needed to update the scrollbars. - // populateGeometryBuffer(); - - // Opened or closed a tree branch, so must update scrollbars. - configureScrollbars(); - } - else - { - // clear old selections if no control key is pressed or if multi-select is off - if (!(e.sysKeys & Control) || !d_multiselect) - clearAllSelections_impl(); - - // select range or item, depending upon keys and last selected item -#if 0 // TODO: fix this - if (((e.sysKeys & Shift) && (d_lastSelected != 0)) && d_multiselect) - selectRange(getItemIndex(item), getItemIndex(d_lastSelected)); - else -#endif - item->setSelected(item->isSelected() ^ true); - - // update last selected item - d_lastSelected = item->isSelected() ? item : 0; - onSelectionChanged(args); - } - } - else - { - // clear old selections if no control key is pressed or if multi-select is off - if (!(e.sysKeys & Control) || !d_multiselect) - { - if (clearAllSelections_impl()) - { - // Changes to the selections were actually made - TreeEventArgs args(this); - args.treeItem = item; - onSelectionChanged(args); - } - } - } - - - ++e.handled; - } -} - -/************************************************************************* - Handler for mouse wheel changes -*************************************************************************/ -void Tree::onMouseWheel(MouseEventArgs& e) -{ - // base class processing. - Window::onMouseWheel(e); - - if (d_vertScrollbar->isEffectiveVisible() && (d_vertScrollbar->getDocumentSize() > d_vertScrollbar->getPageSize())) - d_vertScrollbar->setScrollPosition(d_vertScrollbar->getScrollPosition() + d_vertScrollbar->getStepSize() * -e.wheelChange); - else if (d_horzScrollbar->isEffectiveVisible() && (d_horzScrollbar->getDocumentSize() > d_horzScrollbar->getPageSize())) - d_horzScrollbar->setScrollPosition(d_horzScrollbar->getScrollPosition() + d_horzScrollbar->getStepSize() * -e.wheelChange); - - ++e.handled; -} - -/************************************************************************* - Handler for mouse movement -*************************************************************************/ -void Tree::onMouseMove(MouseEventArgs& e) -{ - if (d_itemTooltips) - { - static TreeItem* lastItem = 0; - - Vector2f posi(CoordConverter::screenToWindow(*this, e.position)); - // Point posi = relativeToAbsolute(CoordConverter::screenToWindow(*this, e.position)); - TreeItem* item = getItemAtPoint(posi); - if (item != lastItem) - { - if (item != 0) - { - setTooltipText(item->getTooltipText()); - } - else - { - setTooltipText(""); - } - lastItem = item; - } - - // must check the result from getTooltip(), as the tooltip object could - // be 0 at any time for various reasons. - Tooltip* tooltip = getTooltip(); - - if (tooltip) - { - if (tooltip->getTargetWindow() != this) - tooltip->setTargetWindow(this); - else - tooltip->positionSelf(); - } - } - - Window::onMouseMove(e); -} - -// Recursive! -bool Tree::getHeightToItemInList(const LBItemList &itemList, const TreeItem *treeItem, int itemDepth, float *height) const -{ - size_t itemCount = itemList.size(); - for (size_t index = 0; index < itemCount; ++index) - { - if (treeItem == itemList[index]) - return true; - - *height += itemList[index]->getPixelSize().d_height; - - if (itemList[index]->getIsOpen() && (itemList[index]->getItemCount() > 0)) - { - if (getHeightToItemInList(itemList[index]->getItemList(), treeItem, itemDepth + 1, height)) - return true; - } - } - - return false; -} - -/************************************************************************* - Ensure the specified item is visible within the tree. -*************************************************************************/ -void Tree::ensureItemIsVisible(const TreeItem *treeItem) -{ - if (!treeItem) - return; - - float top = 0; - if (!getHeightToItemInList(d_listItems, treeItem, 0, &top)) - return; // treeItem wasn't found by getHeightToItemInList - - // calculate height to bottom of item - float bottom = top + treeItem->getPixelSize().d_height; - - // account for current scrollbar value - const float currPos = d_vertScrollbar->getScrollPosition(); - top -= currPos; - bottom -= currPos; - - const float listHeight = getTreeRenderArea().getHeight(); - - // if top is above the view area, or if item is too big to fit - if ((top < 0.0f) || ((bottom - top) > listHeight)) - { - // scroll top of item to top of box. - d_vertScrollbar->setScrollPosition(currPos + top); - } - // if bottom is below the view area - else if (bottom >= listHeight) - { - // position bottom of item at the bottom of the list - d_vertScrollbar->setScrollPosition(currPos + bottom - listHeight); - } -} - -/************************************************************************* - Return whether the vertical scroll bar is always shown. -*************************************************************************/ -bool Tree::isVertScrollbarAlwaysShown(void) const -{ - return d_forceVertScroll; -} - -/************************************************************************* - Return whether the horizontal scroll bar is always shown. -*************************************************************************/ -bool Tree::isHorzScrollbarAlwaysShown(void) const -{ - return d_forceHorzScroll; -} - -/************************************************************************* - Add properties for this class -*************************************************************************/ -void Tree::addTreeProperties(void) -{ - const String& propertyOrigin = WidgetTypeName; - - CEGUI_DEFINE_PROPERTY(Tree, bool, - "Sort", "Property to get/set the sort setting of the tree. " - "Value is either \"true\" or \"false\".", - &Tree::setSortingEnabled, &Tree::isSortEnabled, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Tree, bool, - "MultiSelect", "Property to get/set the multi-select setting of the tree. " - "Value is either \"true\" or \"false\".", - &Tree::setMultiselectEnabled, &Tree::isMultiselectEnabled, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Tree, bool, - "ForceVertScrollbar", "Property to get/set the 'always show' setting for the vertical scroll " - "bar of the tree. Value is either \"true\" or \"false\".", - &Tree::setShowVertScrollbar, &Tree::isVertScrollbarAlwaysShown, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Tree, bool, - "ForceHorzScrollbar", "Property to get/set the 'always show' setting for the horizontal " - "scroll bar of the tree. Value is either \"true\" or \"false\".", - &Tree::setShowHorzScrollbar, &Tree::isHorzScrollbarAlwaysShown, false /* TODO: Inconsistency */ - ); - - CEGUI_DEFINE_PROPERTY(Tree, bool, - "ItemTooltips", "Property to access the show item tooltips setting of the tree. " - "Value is either \"true\" or \"false\".", - &Tree::setItemTooltipsEnabled, &Tree::isItemTooltipsEnabled, false /* TODO: Inconsistency */ - ); -} - -/************************************************************************* - Remove all items from the list. -*************************************************************************/ -bool Tree::resetList_impl(void) -{ - // just return false if the list is already empty - if (getItemCount() == 0) - { - return false; - } - // we have items to be removed and possible deleted - else - { - // delete any items we are supposed to - for (size_t i = 0; i < getItemCount(); ++i) - { - // if item is supposed to be deleted by us - if (d_listItems[i]->isAutoDeleted()) - { - // clean up this item. - CEGUI_DELETE_AO d_listItems[i]; - } - } - - // clear out the list. - d_listItems.clear(); - d_lastSelected = 0; - return true; - } -} - -/************************************************************************* - Handler for scroll position changes. -*************************************************************************/ -bool Tree::handle_scrollChange(const EventArgs&) -{ - // simply trigger a redraw of the Tree. - invalidate(); - return true; -} - -bool Tree::handleFontRenderSizeChange(const EventArgs& args) -{ - bool res = Window::handleFontRenderSizeChange(args); - - if (!res) - { - const Font* const font = static_cast(args).font; - - for (size_t i = 0; i < getItemCount(); ++i) - res |= d_listItems[i]->handleFontRenderSizeChange(font); - - if (res) - invalidate(); - } - - return res; -} - -////////////////////////////////////////////////////////////////////////// -/************************************************************************* - Functions used for predicates in std algorithms -*************************************************************************/ -////////////////////////////////////////////////////////////////////////// -/************************************************************************* - used for < comparisons between TreeItem pointers -*************************************************************************/ -bool lbi_less(const TreeItem* a, const TreeItem* b) -{ - return *a < *b; -} - -/************************************************************************* - used for > comparisons between TreeItem pointers -*************************************************************************/ -bool lbi_greater(const TreeItem* a, const TreeItem* b) -{ - return *a > *b; -} - -} // End of CEGUI namespace section diff --git a/cegui/src/widgets/TreeItem.cpp b/cegui/src/widgets/TreeItem.cpp deleted file mode 100644 index adf433efb..000000000 --- a/cegui/src/widgets/TreeItem.cpp +++ /dev/null @@ -1,401 +0,0 @@ -/*********************************************************************** - created: 5-13-07 - author: Jonathan Welch (Based on Code by David Durant) - *************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif - -#include "CEGUI/widgets/Tree.h" -#include "CEGUI/widgets/TreeItem.h" -#include "CEGUI/System.h" -#include "CEGUI/ImageManager.h" -#include "CEGUI/Image.h" -#include "CEGUI/FontManager.h" -#include "CEGUI/Font.h" -#include "CEGUI/Window.h" -#include - -#if defined (CEGUI_USE_FRIBIDI) - #include "CEGUI/FribidiVisualMapping.h" -#elif defined (CEGUI_USE_MINIBIDI) - #include "CEGUI/MinibidiVisualMapping.h" -#else - #include "CEGUI/BidiVisualMapping.h" -#endif - -// Start of CEGUI namespace section -namespace CEGUI -{ -//----------------------------------------------------------------------------// -BasicRenderedStringParser TreeItem::d_stringParser; - -/************************************************************************* - Constants -*************************************************************************/ -const Colour TreeItem::DefaultSelectionColour = 0xFF4444AA; -const Colour TreeItem::DefaultTextColour = 0xFFFFFFFF; - -/************************************************************************* - Base class constructor -*************************************************************************/ -TreeItem::TreeItem(const String& text, uint item_id, void* item_data, - bool disabled, bool auto_delete) : -#ifndef CEGUI_BIDI_SUPPORT - d_bidiVisualMapping(0), -#elif defined (CEGUI_USE_FRIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), -#elif defined (CEGUI_USE_MINIBIDI) - d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), -#else - #error "BIDI Configuration is inconsistant, check your config!" -#endif - d_bidiDataValid(false), - d_itemID(item_id), - d_itemData(item_data), - d_selected(false), - d_disabled(disabled), - d_autoDelete(auto_delete), - d_buttonLocation(Rectf(0, 0, 0, 0)), - d_owner(0), - d_selectCols(DefaultSelectionColour, DefaultSelectionColour, - DefaultSelectionColour, DefaultSelectionColour), - d_selectBrush(0), - d_textCols(DefaultTextColour, DefaultTextColour, - DefaultTextColour, DefaultTextColour), - d_font(0), - d_iconImage(0), - d_isOpen(false), - d_renderedStringValid(false) -{ - setText(text); -} - -//----------------------------------------------------------------------------// -TreeItem::~TreeItem(void) -{ - // delete any items we are supposed to - for (size_t i = 0; i < getItemCount(); ++i) - { - // if item is supposed to be deleted by us - if (d_listItems[i]->isAutoDeleted()) - { - // clean up this item. - CEGUI_DELETE_AO d_listItems[i]; - } - } - - CEGUI_DELETE_AO d_bidiVisualMapping; -} - -/************************************************************************* - Set the selection highlighting brush image. -*************************************************************************/ -void TreeItem::setSelectionBrushImage(const String& name) -{ - setSelectionBrushImage( - &ImageManager::getSingleton().get(name)); -} - -/************************************************************************* - Return a ColourRect object describing the colours in 'cols' after - having their alpha component modulated by the value 'alpha'. -*************************************************************************/ -ColourRect TreeItem::getModulateAlphaColourRect(const ColourRect& cols, - float alpha) const -{ - return ColourRect - ( - calculateModulatedAlphaColour(cols.d_top_left, alpha), - calculateModulatedAlphaColour(cols.d_top_right, alpha), - calculateModulatedAlphaColour(cols.d_bottom_left, alpha), - calculateModulatedAlphaColour(cols.d_bottom_right, alpha) - ); -} - -/************************************************************************* - Return a colour value describing the colour specified by 'col' after - having its alpha component modulated by the value 'alpha'. -*************************************************************************/ -Colour TreeItem::calculateModulatedAlphaColour(Colour col, float alpha) const -{ - Colour temp(col); - temp.setAlpha(temp.getAlpha() * alpha); - return temp; -} - -/************************************************************************* - Return a pointer to the font being used by this TreeItem -*************************************************************************/ -const Font* TreeItem::getFont(void) const -{ - // prefer out own font - if (d_font != 0) - return d_font; - // try our owner window's font setting - // (may be null if owner uses non existant default font) - else if (d_owner != 0) - return d_owner->getFont(); - // no owner, just use the default (which may be NULL anyway) - else - return System::getSingleton().getDefaultGUIContext().getDefaultFont(); -} - -/************************************************************************* - Set the font to be used by this TreeItem -*************************************************************************/ -void TreeItem::setFont(const String& font_name) -{ - setFont(&FontManager::getSingleton().get(font_name)); -} - -//----------------------------------------------------------------------------// -void TreeItem::setFont(const Font* font) -{ - d_font = font; - - d_renderedStringValid = false; -} - -//----------------------------------------------------------------------------// - -/************************************************************************* - Return the rendered pixel size of this tree item. -*************************************************************************/ -Sizef TreeItem::getPixelSize(void) const -{ - const Font* fnt = getFont(); - - if (!fnt) - return Sizef(0, 0); - - if (!d_renderedStringValid) - parseTextString(); - - Sizef sz(0.0f, 0.0f); - - for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) - { - const Sizef line_sz(d_renderedString.getPixelSize(d_owner, i)); - sz.d_height += line_sz.d_height; - - if (line_sz.d_width > sz.d_width) - sz.d_width = line_sz.d_width; - } - - return sz; -} - -/************************************************************************* - Add the given TreeItem to this item's list. -*************************************************************************/ -void TreeItem::addItem(TreeItem* item) -{ - if (item != 0) - { - Tree* parentWindow = (Tree*)getOwnerWindow(); - - // establish ownership - item->setOwnerWindow(parentWindow); - - // if sorting is enabled, re-sort the tree - if (parentWindow->isSortEnabled()) - { - d_listItems.insert( - std::upper_bound(d_listItems.begin(), - d_listItems.end(), item, &lbi_less), - item); - } - // not sorted, just stick it on the end. - else - { - d_listItems.push_back(item); - } - - WindowEventArgs args(parentWindow); - parentWindow->onListContentsChanged(args); - } -} - -/************************************************************************* - Remove the given TreeItem from this item's list. -*************************************************************************/ -void TreeItem::removeItem(const TreeItem* item) -{ - if (item) - { - Tree* parentWindow = (Tree*)getOwnerWindow(); - - LBItemList::iterator pos = std::find(d_listItems.begin(), - d_listItems.end(), - item); - if (pos != d_listItems.end()) - { - (*pos)->setOwnerWindow(0); - d_listItems.erase(pos); - - if (item == parentWindow->d_lastSelected) - parentWindow->d_lastSelected = 0; - - if (item->isAutoDeleted()) - CEGUI_DELETE_AO item; - - WindowEventArgs args(parentWindow); - parentWindow->onListContentsChanged(args); - } - } -} - -TreeItem *TreeItem::getTreeItemFromIndex(size_t itemIndex) -{ - if (itemIndex > d_listItems.size()) - return 0; - - return d_listItems[itemIndex]; -} - -/************************************************************************* - Draw the tree item in its current state. -*************************************************************************/ -void TreeItem::draw(GeometryBuffer& buffer, const Rectf& targetRect, - float alpha, const Rectf* clipper) const -{ - Rectf finalRect(targetRect); - - if (d_iconImage != 0) - { - Rectf finalPos(finalRect); - finalPos.setWidth(targetRect.getHeight()); - finalPos.setHeight(targetRect.getHeight()); - d_iconImage->render(buffer, finalPos, clipper, - ColourRect(Colour(1,1,1,alpha))); - finalRect.d_min.d_x += targetRect.getHeight(); - } - - if (d_selected && d_selectBrush != 0) - d_selectBrush->render(buffer, finalRect, clipper, - getModulateAlphaColourRect(d_selectCols, alpha)); - - const Font* font = getFont(); - - if (!font) - return; - - Vector2f draw_pos(finalRect.getPosition()); - draw_pos.d_y -= (font->getLineSpacing() - font->getBaseline()) * 0.5f; - - if (!d_renderedStringValid) - parseTextString(); - - const ColourRect final_colours( - getModulateAlphaColourRect(ColourRect(0xFFFFFFFF), alpha)); - - for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) - { - d_renderedString.draw(d_owner, i, buffer, draw_pos, &final_colours, clipper, 0.0f); - draw_pos.d_y += d_renderedString.getPixelSize(d_owner, i).d_height; - } -} - -/************************************************************************* - Set the colours used for selection highlighting. -*************************************************************************/ -void TreeItem::setSelectionColours(Colour top_left_colour, - Colour top_right_colour, - Colour bottom_left_colour, - Colour bottom_right_colour) -{ - d_selectCols.d_top_left = top_left_colour; - d_selectCols.d_top_right = top_right_colour; - d_selectCols.d_bottom_left = bottom_left_colour; - d_selectCols.d_bottom_right = bottom_right_colour; -} - -/************************************************************************* - Set the colours used for text rendering. -*************************************************************************/ -void TreeItem::setTextColours(Colour top_left_colour, - Colour top_right_colour, - Colour bottom_left_colour, - Colour bottom_right_colour) -{ - d_textCols.d_top_left = top_left_colour; - d_textCols.d_top_right = top_right_colour; - d_textCols.d_bottom_left = bottom_left_colour; - d_textCols.d_bottom_right = bottom_right_colour; - - d_renderedStringValid = false; -} - -//----------------------------------------------------------------------------// -void TreeItem::setText( const String& text ) -{ - d_textLogical = text; - d_bidiDataValid = false; - d_renderedStringValid = false; -} - -//----------------------------------------------------------------------------// -void TreeItem::parseTextString() const -{ - d_renderedString = - d_stringParser.parse(getTextVisual(), const_cast(getFont()), &d_textCols); - d_renderedStringValid = true; -} - -//----------------------------------------------------------------------------// -const String& TreeItem::getTextVisual() const -{ - // no bidi support - if (!d_bidiVisualMapping) - return d_textLogical; - - if (!d_bidiDataValid) - { - d_bidiVisualMapping->updateVisual(d_textLogical); - d_bidiDataValid = true; - } - - return d_bidiVisualMapping->getTextVisual(); -} - -//----------------------------------------------------------------------------// -bool TreeItem::handleFontRenderSizeChange(const Font* const font) -{ - if (getFont() == font) - return true; - - for (size_t i = 0; i < getItemCount(); ++i) - { - if (d_listItems[i]->handleFontRenderSizeChange(font)) - return true; - } - - return false; -} - -//----------------------------------------------------------------------------// - -} // End of CEGUI namespace section diff --git a/cegui/src/widgets/TreeWidget.cpp b/cegui/src/widgets/TreeWidget.cpp new file mode 100644 index 000000000..67965d5c5 --- /dev/null +++ b/cegui/src/widgets/TreeWidget.cpp @@ -0,0 +1,65 @@ +/*********************************************************************** + created: Wed Aug 07 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CEGUI/widgets/TreeWidget.h" + +namespace CEGUI +{ + +//----------------------------------------------------------------------------// +const String TreeWidget::EventNamespace("TreeWidget"); +const String TreeWidget::WidgetTypeName("CEGUI/TreeWidget"); + +//----------------------------------------------------------------------------// +TreeWidget::TreeWidget(const String& type, const String& name) : + TreeView(type, name) +{ +} + +//----------------------------------------------------------------------------// +TreeWidget::~TreeWidget() +{ +} + +//----------------------------------------------------------------------------// +void TreeWidget::initialiseComponents() +{ + TreeView::initialiseComponents(); + setModel(&d_itemModel); +} + +//----------------------------------------------------------------------------// +StandardItemModel* TreeWidget::getModel() +{ + return &d_itemModel; +} + +//----------------------------------------------------------------------------// +void TreeWidget::addItem(StandardItem* item) +{ + d_itemModel.addItem(item); +} +} diff --git a/cmake/CEGUIAndroid.cmake b/cmake/CEGUIAndroid.cmake new file mode 100644 index 000000000..ccb328459 --- /dev/null +++ b/cmake/CEGUIAndroid.cmake @@ -0,0 +1,98 @@ +#/******************************************************************************* +# Filename: CEGUIAndroid.cmake +# Created: 28/9/2014 +# Author: David Reepmeyer +#*******************************************************************************/ +#/*************************************************************************** +# * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team +# * +# * Permission is hereby granted, free of charge, to any person obtaining +# * a copy of this software and associated documentation files (the +# * "Software"), to deal in the Software without restriction, including +# * without limitation the rights to use, copy, modify, merge, publish, +# * distribute, sublicense, and/or sell copies of the Software, and to +# * permit persons to whom the Software is furnished to do so, subject to +# * the following conditions: +# * +# * The above copyright notice and this permission notice shall be +# * included in all copies or substantial portions of the Software. +# * +# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +# * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +# * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# * OTHER DEALINGS IN THE SOFTWARE. +# ***************************************************************************/ + +macro(create_android_proj ANDROID_PROJECT_TARGET) + if (ANDROID) + if(APPLE OR WIN32) + SET(ANDROID_EXECUTABLE "android") + SET(NDK_BUILD_EXECUTABLE "ndk-build") + else() + SET(ANDROID_EXECUTABLE "$ENV{ANDROID_SDK}/tools/android") + SET(NDK_BUILD_EXECUTABLE "$ENV{ANDROID_NDK}/ndk-build") + endif() + + SET(ANT_EXECUTABLE "ant") + if(${ANDROID_NATIVE_API_LEVEL} LESS 14) + MATH(EXPR ANDROID_SDK_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}+1") + else() + SET(ANDROID_SDK_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}") + SET(SCREEN_SIZE "|screenSize") + endif() + + SET(ANDROID_TARGET "android-${ANDROID_SDK_API_LEVEL}") + + SET(NDKOUT "${CMAKE_BINARY_DIR}/SampleBrowserNDK") + file(MAKE_DIRECTORY "${NDKOUT}") + file(MAKE_DIRECTORY "${NDKOUT}/jni") + file(MAKE_DIRECTORY "${NDKOUT}/assets") + file(MAKE_DIRECTORY "${NDKOUT}/res") + file(WRITE "${NDKOUT}/default.properties" "target=${ANDROID_TARGET}") + file(WRITE "${NDKOUT}/jni/Application.mk" + "APP_ABI := ${ANDROID_ABI}\nAPP_STL := gnustl_static\nAPP_CPPFLAGS := -fexceptions -frtti \nNDK_TOOLCHAIN_VERSION := ${ANDROID_COMPILER_VERSION}") + SET(ANDROID_MOD_NAME "${CEGUI_TARGET_NAME}") + SET(JNI_PATH "${CMAKE_SOURCE_DIR}/samples/browser") + foreach(COMBINED_SOURCE_FILE ${COMBINED_SOURCE_FILES}) + set(COMBINED_SOURCE_FILES_STRING "${COMBINED_SOURCE_FILES_STRING} ${COMBINED_SOURCE_FILE}") + endforeach() + SET(JNI_SRC_FILES "${COMBINED_SOURCE_FILES_STRING}") + SET(PKG_NAME "cegui.org.uk.browser") + SET(ANDROID_SHARED_LIB "${CEGUI_TARGET_NAME}") + file(COPY "${CMAKE_SOURCE_DIR}/datafiles/imagesets/ic_launcher.png" DESTINATION "${NDKOUT}/res/drawable") + file(COPY "${CMAKE_SOURCE_DIR}/datafiles" DESTINATION "${NDKOUT}/assets") + if (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) + SET(ANDROID_GLES_VERSION "0x00020000") + configure_file("${OGRE_TEMPLATES_DIR}/Android.OgreGLES2.mk.in" "${NDKOUT}/jni/Android.mk" @ONLY) + elseif (CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE) + if (CEGUI_BUILD_RENDERER_OPENGLES2_WITH_GLES3_SUPPORT) + SET(ANDROID_GLES_VERSION "0x00030000") + configure_file("${OGRE_TEMPLATES_DIR}/Android.GLES3.mk.in" "${NDKOUT}/jni/Android.mk" @ONLY) + else() + SET(ANDROID_GLES_VERSION "0x00020000") + configure_file("${OGRE_TEMPLATES_DIR}/Android.GLES2.mk.in" "${NDKOUT}/jni/Android.mk" @ONLY) + endif() + endif() + configure_file("${OGRE_TEMPLATES_DIR}/AndroidManifest.xml.in" "${NDKOUT}/AndroidManifest.xml" @ONLY) + + add_custom_command( + TARGET ${ANDROID_PROJECT_TARGET} POST_BUILD COMMAND ${ANDROID_EXECUTABLE} + update project --name ${ANDROID_PROJECT_TARGET} --subprojects --target ${ANDROID_TARGET} --path "${NDKOUT}" WORKING_DIRECTORY ${NDKOUT}) + + if(DEBUG) + add_custom_command( TARGET ${ANDROID_PROJECT_TARGET} POST_BUILD COMMAND + ${NDK_BUILD_EXECUTABLE} all -j2 V=1 NDK_DEBUG=1 WORKING_DIRECTORY ${NDKOUT}) + else() + add_custom_command( TARGET ${ANDROID_PROJECT_TARGET} POST_BUILD COMMAND + ${NDK_BUILD_EXECUTABLE} all -j2 V=1 WORKING_DIRECTORY ${NDKOUT}) + endif() + + add_custom_command( TARGET ${ANDROID_PROJECT_TARGET} POST_BUILD + COMMAND ${ANT_EXECUTABLE} debug WORKING_DIRECTORY ${NDKOUT}) + endif() +endmacro(create_android_proj) + + diff --git a/cmake/CEGUIMacros.cmake b/cmake/CEGUIMacros.cmake index 09bd74c32..9a9e654fb 100644 --- a/cmake/CEGUIMacros.cmake +++ b/cmake/CEGUIMacros.cmake @@ -49,7 +49,9 @@ endmacro() # Add libs to a target, and correctly handles static versions of libs built by the project # macro (cegui_target_link_libraries _TARGET_NAME) - target_link_libraries(${_TARGET_NAME} ${ARGN}) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + target_link_libraries(${_TARGET_NAME} ${ARGN}) + endif() get_target_property(_TARGET_EXISTS ${_TARGET_NAME}_Static TYPE) if (_TARGET_EXISTS) @@ -203,49 +205,51 @@ macro (cegui_add_library_impl _LIB_NAME _IS_MODULE _SOURCE_FILES_VAR _HEADER_FIL ########################################################################### # SHARED LIBRARY SET UP ########################################################################### - add_library(${_LIB_NAME} ${_LIB_TYPE} ${${_SOURCE_FILES_VAR}} ${${_HEADER_FILES_VAR}}) - set_target_properties(${_LIB_NAME} PROPERTIES DEFINE_SYMBOL ${_CEGUI_EXPORT_DEFINE}) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + add_library(${_LIB_NAME} ${_LIB_TYPE} ${${_SOURCE_FILES_VAR}} ${${_HEADER_FILES_VAR}}) + set_target_properties(${_LIB_NAME} PROPERTIES DEFINE_SYMBOL ${_CEGUI_EXPORT_DEFINE}) - if (NOT CEGUI_BUILD_SHARED_LIBS_WITH_STATIC_DEPENDENCIES) - # Starting with CMake 2.8.12 LINK_INTERFACE_LIBRARIES was renamed to INTERFACE_LINK_LIBRARIES - if (${CMAKE_VERSION} VERSION_GREATER 2.8.12 OR ${CMAKE_VERSION} VERSION_EQUAL 2.8.12) - set_target_properties(${_LIB_NAME} PROPERTIES - INTERFACE_LINK_LIBRARIES "" - ) - else() - set_target_properties(${_LIB_NAME} PROPERTIES - LINK_INTERFACE_LIBRARIES "" - ) + if (NOT CEGUI_BUILD_SHARED_LIBS_WITH_STATIC_DEPENDENCIES) + # Starting with CMake 2.8.12 LINK_INTERFACE_LIBRARIES was renamed to INTERFACE_LINK_LIBRARIES + if (${CMAKE_VERSION} VERSION_GREATER 2.8.12 OR ${CMAKE_VERSION} VERSION_EQUAL 2.8.12) + set_target_properties(${_LIB_NAME} PROPERTIES + INTERFACE_LINK_LIBRARIES "" + ) + else() + set_target_properties(${_LIB_NAME} PROPERTIES + LINK_INTERFACE_LIBRARIES "" + ) + endif() endif() - endif() - if (APPLE) - set_target_properties(${_LIB_NAME} PROPERTIES - INSTALL_NAME_DIR ${CEGUI_APPLE_DYLIB_INSTALL_PATH} - BUILD_WITH_INSTALL_RPATH TRUE - ) + if (APPLE) + set_target_properties(${_LIB_NAME} PROPERTIES + INSTALL_NAME_DIR ${CEGUI_APPLE_DYLIB_INSTALL_PATH} + BUILD_WITH_INSTALL_RPATH TRUE + ) + + # Force the somewhat standard .dylib extension for modules over the use of + # the .so extension + if (${_IS_MODULE}) + set_target_properties(${_LIB_NAME} PROPERTIES SUFFIX ".dylib") + endif() - # Force the somewhat standard .dylib extension for modules over the use of - # the .so extension - if (${_IS_MODULE}) - set_target_properties(${_LIB_NAME} PROPERTIES SUFFIX ".dylib") + elseif(CEGUI_INSTALL_WITH_RPATH) + set_target_properties(${_LIB_NAME} PROPERTIES + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CEGUI_LIB_INSTALL_DIR}" + ) endif() - elseif(CEGUI_INSTALL_WITH_RPATH) - set_target_properties(${_LIB_NAME} PROPERTIES - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CEGUI_LIB_INSTALL_DIR}" - ) - endif() - - # Do not version modules, since we dlopen these directly and need to know - # the name is what we think it will be (and not rely on symlinks which will - # not be installed always, but usually only as part of *-dev packages). - if (NOT ${_IS_MODULE}) - if (NOT APPLE OR CEGUI_APPLE_DYLIB_SET_VERSION_INFO) - set_target_properties(${_LIB_NAME} PROPERTIES - VERSION ${CEGUI_ABI_VERSION} - SOVERSION ${CEGUI_SOVERSION} - ) + # Do not version modules, since we dlopen these directly and need to know + # the name is what we think it will be (and not rely on symlinks which will + # not be installed always, but usually only as part of *-dev packages). + if (NOT ${_IS_MODULE}) + if (NOT APPLE OR CEGUI_APPLE_DYLIB_SET_VERSION_INFO) + set_target_properties(${_LIB_NAME} PROPERTIES + VERSION ${CEGUI_ABI_VERSION} + SOVERSION ${CEGUI_SOVERSION} + ) + endif() endif() endif() @@ -259,11 +263,13 @@ macro (cegui_add_library_impl _LIB_NAME _IS_MODULE _SOURCE_FILES_VAR _HEADER_FIL set(_CEGUI_LIB_DEST ${CEGUI_LIB_INSTALL_DIR}) endif() - install(TARGETS ${_LIB_NAME} - RUNTIME DESTINATION bin - LIBRARY DESTINATION ${_CEGUI_LIB_DEST} - ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} - ) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + install(TARGETS ${_LIB_NAME} + RUNTIME DESTINATION bin + LIBRARY DESTINATION ${_CEGUI_LIB_DEST} + ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} + ) + endif() if (CEGUI_BUILD_STATIC_CONFIGURATION) install(TARGETS ${_LIB_NAME}_Static @@ -360,27 +366,30 @@ macro (cegui_apple_app_setup _TARGET_NAME _STATIC) endmacro() # -# Define a CEGUI sample module +# Define a CEGUI sample module using some extra header and source files # -macro (cegui_add_sample _NAME) +macro (cegui_add_sample_with_extra_files _NAME _EXTRA_HEADER_FILES _EXTRA_SOURCE_FILES) set (CEGUI_TARGET_NAME ${_NAME}) - cegui_gather_files() - set(CORE_HEADER_FILES ${CORE_HEADER_FILES} - ${CMAKE_SOURCE_DIR}/samples/common/include/Sample.h - ${CMAKE_SOURCE_DIR}/samples/common/include/SampleBase.h - ) - + set(CORE_HEADER_FILES ${CORE_HEADER_FILES} ${_EXTRA_HEADER_FILES} + ${CMAKE_SOURCE_DIR}/samples/common/include/Sample.h + ${CMAKE_SOURCE_DIR}/samples/common/include/SampleBase.h + ) + + set(CORE_SOURCE_FILES ${CORE_SOURCE_FILES} ${_EXTRA_SOURCE_FILES}) + # Each demo will become a dynamically linked library as plugin (module) cegui_add_library_impl(${CEGUI_TARGET_NAME} TRUE CORE_SOURCE_FILES CORE_HEADER_FILES FALSE FALSE) # Setup custom install location - install(TARGETS ${CEGUI_TARGET_NAME} - RUNTIME DESTINATION bin - LIBRARY DESTINATION ${CEGUI_SAMPLE_INSTALL_DIR} - ARCHIVE DESTINATION ${CEGUI_SAMPLE_INSTALL_DIR} - ) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + install(TARGETS ${CEGUI_TARGET_NAME} + RUNTIME DESTINATION bin + LIBRARY DESTINATION ${CEGUI_SAMPLE_INSTALL_DIR} + ARCHIVE DESTINATION ${CEGUI_SAMPLE_INSTALL_DIR} + ) + endif() if (CEGUI_BUILD_STATIC_CONFIGURATION) install(TARGETS ${CEGUI_TARGET_NAME}_Static @@ -402,8 +411,13 @@ macro (cegui_add_sample _NAME) # Add the MetaData chunk of the sample to the final xml file(READ ${CMAKE_CURRENT_SOURCE_DIR}/SampleMetaData.xml DEMO_META_DATA) file(APPEND ${CMAKE_BINARY_DIR}/datafiles/samples/samples.xml "${DEMO_META_DATA}") + +endmacro() +macro (cegui_add_sample _NAME) + cegui_add_sample_with_extra_files(${_NAME} "" "") endmacro() + # # Define a PyCEGUI* extension module # @@ -437,12 +451,20 @@ endmacro() # Define a CEGUI test executable # macro (cegui_add_test_executable _NAME) + cegui_add_test_executable_with_extra_files(${_NAME} "" "") +endmacro() + +macro (cegui_add_test_executable_with_extra_files _NAME _EXTRA_HEADER_FILES _EXTRA_SOURCE_FILES) set (CEGUI_TARGET_NAME ${_NAME}-${CEGUI_VERSION_MAJOR}.${CEGUI_VERSION_MINOR}) cegui_gather_files() include_directories(${Boost_INCLUDE_DIR}) + # add the extra header/source files + set(CORE_HEADER_FILES ${CORE_HEADER_FILES} ${_EXTRA_HEADER_FILES}) + set(CORE_SOURCE_FILES ${CORE_SOURCE_FILES} ${_EXTRA_SOURCE_FILES}) + ########################################################################### # Statically Linked Executable ########################################################################### @@ -465,41 +487,45 @@ macro (cegui_add_test_executable _NAME) ########################################################################### # Dynamically Linked Executable ########################################################################### - add_executable(${CEGUI_TARGET_NAME} ${CORE_SOURCE_FILES} ${CORE_HEADER_FILES}) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + add_executable(${CEGUI_TARGET_NAME} ${CORE_SOURCE_FILES} ${CORE_HEADER_FILES}) - # append the _d (or whatever) for debug builds as needed. - if (CEGUI_HAS_BUILD_SUFFIX AND CEGUI_BUILD_SUFFIX) - set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES - OUTPUT_NAME_DEBUG "${CEGUI_TARGET_NAME}${CEGUI_BUILD_SUFFIX}" - ) - endif() + # append the _d (or whatever) for debug builds as needed. + if (CEGUI_HAS_BUILD_SUFFIX AND CEGUI_BUILD_SUFFIX) + set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES + OUTPUT_NAME_DEBUG "${CEGUI_TARGET_NAME}${CEGUI_BUILD_SUFFIX}" + ) + endif() - add_definitions(-DBOOST_ALL_NO_LIB) - # set boost to use dynamic linking - if (NOT CEGUI_BUILD_STATIC_CONFIGURATION) - add_definitions( -DBOOST_TEST_DYN_LINK ) - endif() + add_definitions(-DBOOST_ALL_NO_LIB) + # set boost to use dynamic linking + if (NOT CEGUI_BUILD_STATIC_CONFIGURATION) + add_definitions( -DBOOST_TEST_DYN_LINK ) + endif() - if (NOT APPLE AND CEGUI_INSTALL_WITH_RPATH) - set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CEGUI_LIB_INSTALL_DIR}" - ) + if (NOT APPLE AND CEGUI_INSTALL_WITH_RPATH) + set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CEGUI_LIB_INSTALL_DIR}" + ) + endif() endif() ########################################################################### # LIBRARY LINK SETUP ########################################################################### - cegui_target_link_libraries(${CEGUI_TARGET_NAME} - ${CEGUI_BASE_LIBNAME} - ${CEGUI_NULL_RENDERER_LIBNAME} - ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} - ) - - if (CEGUI_BUILD_PERFORMANCE_TESTS) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) cegui_target_link_libraries(${CEGUI_TARGET_NAME} - ${Boost_TIMER_LIBRARY} - ${Boost_SYSTEM_LIBRARY} - ) + ${CEGUI_BASE_LIBNAME} + ${CEGUI_NULL_RENDERER_LIBNAME} + ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} + ) + + if (CEGUI_BUILD_PERFORMANCE_TESTS) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} + ${Boost_TIMER_LIBRARY} + ${Boost_SYSTEM_LIBRARY} + ) + endif() endif() if (CEGUI_BUILD_STATIC_CONFIGURATION) @@ -514,11 +540,13 @@ macro (cegui_add_test_executable _NAME) ########################################################################### # INSTALLATION ########################################################################### - install(TARGETS ${CEGUI_TARGET_NAME} - RUNTIME DESTINATION bin - LIBRARY DESTINATION ${CEGUI_LIB_INSTALL_DIR} - ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} - ) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + install(TARGETS ${CEGUI_TARGET_NAME} + RUNTIME DESTINATION bin + LIBRARY DESTINATION ${CEGUI_LIB_INSTALL_DIR} + ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} + ) + endif() if (CEGUI_BUILD_STATIC_CONFIGURATION) install(TARGETS ${CEGUI_TARGET_NAME}_Static @@ -605,11 +633,13 @@ macro (cegui_find_package_handle_standard_args _PKGNAME _LIBBASENAMEVAR) list(APPEND _FPHSA_LIBS ${_LIBBASENAMEVAR}_STATIC_DBG) endif() else() - if (_WANT_REL_LIBS) - list(APPEND _FPHSA_LIBS ${_LIBBASENAMEVAR}) - endif() - if (_WANT_DBG_LIBS) - list(APPEND _FPHSA_LIBS ${_LIBBASENAMEVAR}_DBG) + if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + if (_WANT_REL_LIBS) + list(APPEND _FPHSA_LIBS ${_LIBBASENAMEVAR}) + endif() + if (_WANT_DBG_LIBS) + list(APPEND _FPHSA_LIBS ${_LIBBASENAMEVAR}_DBG) + endif() endif() if (CEGUI_BUILD_STATIC_CONFIGURATION) if (_WANT_REL_LIBS) diff --git a/cmake/FindD3DX11Effects.cmake b/cmake/FindD3DX11Effects.cmake deleted file mode 100644 index 5c2fcd91e..000000000 --- a/cmake/FindD3DX11Effects.cmake +++ /dev/null @@ -1,40 +0,0 @@ -################################################################################ -# Custom cmake module for CEGUI to find the D3D 11 Effects lib. -################################################################################ -include(FindPackageHandleStandardArgs) - -find_path(D3DX11EFFECTS_H_PATH NAMES d3dx11effect.h) -find_library(D3DX11EFFECTS_LIB NAMES D3DX11Effects PATH_SUFFIXES dynamic) -find_library(D3DX11EFFECTS_LIB_DBG NAMES D3DX11EffectsD D3DX11Effects_d PATH_SUFFIXES dynamic) -mark_as_advanced(D3DX11EFFECTS_H_PATH D3DX11EFFECTS_LIB D3DX11EFFECTS_LIB_DBG) - -if (WIN32) - find_library(D3DX11EFFECTS_LIB_STATIC NAMES D3DX11Effects PATH_SUFFIXES static) - find_library(D3DX11EFFECTS_LIB_STATIC_DBG NAMES D3DX11EffectsD PATH_SUFFIXES static) - mark_as_advanced(D3DX11EFFECTS_LIB_STATIC D3DX11EFFECTS_LIB_STATIC_DBG) -endif() - -cegui_find_package_handle_standard_args(D3DX11EFFECTS D3DX11EFFECTS_LIB D3DX11EFFECTS_H_PATH) - - -# set up output vars -if (D3DX11EFFECTS_FOUND) - set (D3DX11EFFECTS_INCLUDE_DIR ${D3DX11EFFECTS_H_PATH}) - set (D3DX11EFFECTS_LIBRARIES ${D3DX11EFFECTS_LIB}) - if (D3DX11EFFECTS_LIB_DBG) - set (D3DX11EFFECTS_LIBRARIES_DBG ${D3DX11EFFECTS_LIB_DBG}) - endif() - if (D3DX11EFFECTS_LIB_STATIC) - set (D3DX11EFFECTS_LIBRARIES_STATIC ${D3DX11EFFECTS_LIB_STATIC}) - endif() - if (D3DX11EFFECTS_LIB_DBG) - set (D3DX11EFFECTS_LIBRARIES_STATIC_DBG ${D3DX11EFFECTS_LIB_STATIC_DBG}) - endif() -else() - set (D3DX11EFFECTS_INCLUDE_DIR) - set (D3DX11EFFECTS_LIBRARIES) - set (D3DX11EFFECTS_LIBRARIES_DBG) - set (D3DX11EFFECTS_LIBRARIES_STATIC) - set (D3DX11EFFECTS_LIBRARIES_STATIC_DBG) -endif() - diff --git a/cmake/FindDevIL.cmake b/cmake/FindDevIL.cmake index 45f2f2eb0..e767a32e4 100644 --- a/cmake/FindDevIL.cmake +++ b/cmake/FindDevIL.cmake @@ -24,7 +24,7 @@ if (WIN32 OR APPLE) endif() cegui_find_package_handle_standard_args(IL IL_LIB IL_H_PATH) -cegui_find_package_handle_standard_args(ILU ILU_LIB) +cegui_find_package_handle_standard_args(ILU ILU_LIB IL_H_PATH) # set up output vars if (IL_FOUND AND ILU_FOUND) diff --git a/cmake/FindDirectXSDK.cmake b/cmake/FindDirectXSDK.cmake index 35b36c79e..def671133 100644 --- a/cmake/FindDirectXSDK.cmake +++ b/cmake/FindDirectXSDK.cmake @@ -9,14 +9,12 @@ else() set (DIRECTXSDK_ARCH x64) endif() -find_path(DIRECTXSDK_H_PATH NAMES d3d10.h PATHS ENV DXSDK_DIR PATH_SUFFIXES Include NO_DEFAULT_PATH) -find_path(DIRECTXSDK_LIB_PATH NAMES d3dx10d.lib PATHS ENV DXSDK_DIR PATH_SUFFIXES "Lib/${DIRECTXSDK_ARCH}") +find_path(DIRECTXSDK_H_PATH NAMES d3d11.h PATHS ENV DXSDK_DIR PATH_SUFFIXES Include NO_DEFAULT_PATH) +find_path(DIRECTXSDK_LIB_PATH NAMES d3d11.lib PATHS ENV DXSDK_DIR PATH_SUFFIXES "Lib/${DIRECTXSDK_ARCH}") # now test for the specific d3d lib versions and set MAX_D3D accordingly if (EXISTS "${DIRECTXSDK_LIB_PATH}/d3d11.lib") set (DIRECTXSDK_MAX_D3D 11) -elseif (EXISTS "${DIRECTXSDK_LIB_PATH}/d3d10.lib") - set (DIRECTXSDK_MAX_D3D 10) elseif (EXISTS "${DIRECTXSDK_LIB_PATH}/d39.lib") set (DIRECTXSDK_MAX_D3D 9) else() diff --git a/cmake/FindOgre.cmake b/cmake/FindOgre.cmake index 93b0b522a..80b4ffcfc 100644 --- a/cmake/FindOgre.cmake +++ b/cmake/FindOgre.cmake @@ -202,6 +202,7 @@ if (OGRE_FOUND) find_package(Freetype QUIET) find_package(OpenGL QUIET) find_package(OpenGLES QUIET) + find_package(OpenGLES2 QUIET) find_package(ZLIB QUIET) find_package(ZZip QUIET) if (UNIX AND NOT APPLE) @@ -224,7 +225,7 @@ if (OGRE_FOUND) if (NOT FREETYPE_FOUND) set(OGRE_DEPS_FOUND FALSE) endif () - if (UNIX AND NOT APPLE) + if (UNIX AND NOT APPLE AND NOT ANDROID) if (NOT X11_FOUND) set(OGRE_DEPS_FOUND FALSE) endif () @@ -244,6 +245,11 @@ if (OGRE_FOUND) set (CEGUI_FOUND_OGRE_VERSION_${ver} "${CMAKE_MATCH_1}") endif() endforeach() + + get_filename_component(OGRE_LIBRARY_DIR_REL "${OGRE_LIB}" PATH) + get_filename_component(OGRE_LIBRARY_DIR_DBG "${OGRE_LIB_DBG}" PATH) + set(OGRE_LIBRARY_DIRS ${OGRE_LIBRARY_DIR_REL} ${OGRE_LIBRARY_DIR_DBG}) + else() set (OGRE_INCLUDE_DIR) set (OGRE_LIBRARIES) diff --git a/cmake/FindOpenGLES.cmake b/cmake/FindOpenGLES.cmake index e6fd9dbc6..6b149fec5 100644 --- a/cmake/FindOpenGLES.cmake +++ b/cmake/FindOpenGLES.cmake @@ -7,7 +7,7 @@ include(FindPackageHandleStandardArgs) find_path(OPENGLES_H_PATH NAMES GLES/gl.h) -find_library(OPENGLES_LIB NAMES GLES_CM) +find_library(OPENGLES_LIB NAMES GLES_CM GLESv1_CM) mark_as_advanced(OPENGLES_H_PATH OPENGLES_LIB OPENGLES_LIB_DBG) find_package_handle_standard_args(OPENGLES DEFAULT_MSG OPENGLES_LIB OPENGLES_H_PATH) diff --git a/cmake/FindOpenGLES2.cmake b/cmake/FindOpenGLES2.cmake new file mode 100644 index 000000000..5451b9b94 --- /dev/null +++ b/cmake/FindOpenGLES2.cmake @@ -0,0 +1,27 @@ +################################################################################ +# Custom cmake module for CEGUI to find OpenGL ES (2.0) +# +# Placeholder module to create some vars we can manually set. +# Later will create a proper tests (or steal them, anyway) +################################################################################ +include(FindPackageHandleStandardArgs) + +find_path(OPENGLES2_H_PATH NAMES GLES2/gl2.h) +find_library(OPENGLES2_LIB NAMES GLESv2) +mark_as_advanced(OPENGLES2_H_PATH OPENGLES2_LIB OPENGLES2_LIB_DBG) + +find_package_handle_standard_args(OPENGLES2 DEFAULT_MSG OPENGLES2_LIB OPENGLES2_H_PATH) + +# set up output vars +if (OPENGLES2_FOUND) + set (OPENGLES2_INCLUDE_DIR ${OPENGLES2_H_PATH}) + set (OPENGLES2_LIBRARIES ${OPENGLES2_LIB}) + if (OPENGLES2_LIB_DBG) + set (OPENGLES2_LIBRARIES_DBG ${OPENGLES2_LIB_DBG}) + endif() +else() + set (OPENGLES2_INCLUDE_DIR) + set (OPENGLES2_LIBRARIES) + set (OPENGLES2_LIBRARIES_DBG) +endif() + diff --git a/cmake/FindOpenGLES3.cmake b/cmake/FindOpenGLES3.cmake new file mode 100644 index 000000000..842b6d5ce --- /dev/null +++ b/cmake/FindOpenGLES3.cmake @@ -0,0 +1,27 @@ +################################################################################ +# Custom cmake module for CEGUI to find OpenGL ES (3.0) +# +# Placeholder module to create some vars we can manually set. +# Later will create a proper tests (or steal them, anyway) +################################################################################ +include(FindPackageHandleStandardArgs) + +find_path(OPENGLES3_H_PATH NAMES GLES3/gl3.h) +find_library(OPENGLES3_LIB NAMES GLESv3) +mark_as_advanced(OPENGLES3_H_PATH OPENGLES3_LIB OPENGLES3_LIB_DBG) + +find_package_handle_standard_args(OPENGLES3 DEFAULT_MSG OPENGLES3_LIB OPENGLES3_H_PATH) + +# set up output vars +if (OPENGLES3_FOUND) + set (OPENGLES3_INCLUDE_DIR ${OPENGLES3_H_PATH}) + set (OPENGLES3_LIBRARIES ${OPENGLES3_LIB}) + if (OPENGLES3_LIB_DBG) + set (OPENGLES3_LIBRARIES_DBG ${OPENGLES3_LIB_DBG}) + endif() +else() + set (OPENGLES3_INCLUDE_DIR) + set (OPENGLES3_LIBRARIES) + set (OPENGLES3_LIBRARIES_DBG) +endif() + diff --git a/cmake/templates/Android.GLES2.mk.in b/cmake/templates/Android.GLES2.mk.in new file mode 100644 index 000000000..91679d57e --- /dev/null +++ b/cmake/templates/Android.GLES2.mk.in @@ -0,0 +1,42 @@ + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := iconv +LOCAL_CFLAGS += -std=c99 +LOCAL_C_INCLUDES := @ANDROID_NDK@/sources/android/support/include +LOCAL_C_INCLUDES += @ANDROID_NDK@/sources/android/support/src/musl-multibyte +LOCAL_SRC_FILES := @ANDROID_NDK@/sources/android/support/src/musl-locale/iconv.c +LOCAL_SRC_FILES += @ANDROID_NDK@/sources/android/support/src/musl-multibyte/wctomb.c +include $(BUILD_STATIC_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_MODULE := @ANDROID_MOD_NAME@ +LOCAL_LDLIBS := -landroid -lz -lc -lm -ldl -llog -lEGL -lGLESv2 +LOCAL_LDLIBS += -L@CMAKE_BINARY_DIR@/lib +LOCAL_LDLIBS += -L@CEGUI_DEPENDENCIES_DIR@/lib/@ANDROID_ABI@ -L@CEGUI_DEPENDENCIES_DIR@/lib/ +LOCAL_LDLIBS += -lCEGUIOpenGLRenderer-@CEGUI_VERSION_MAJOR@_Static -lCEGUIBase-@CEGUI_VERSION_MAJOR@_Static -lCEGUICommonDialogs-@CEGUI_VERSION_MAJOR@_Static -lCEGUICoreWindowRendererSet_Static -lCEGUIFreeImageImageCodec_Static -lCEGUITinyXMLParser_Static -lCEGUISampleBrowser-@CEGUI_VERSION_MAJOR@.@CEGUI_VERSION_MINOR@_Static +LOCAL_LDLIBS += -lfreeimage -lfreetype -ltinyxml -lzzip -lpcre +LOCAL_LDLIBS += @NDKOUT@/obj/local/@ANDROID_ABI@/libiconv.a +LOCAL_LDLIBS += @ANDROID_NDK@/sources/cxx-stl/gnu-libstdc++/@ANDROID_COMPILER_VERSION@/libs/@ANDROID_ABI@/libgnustl_static.a +LOCAL_STATIC_LIBRARIES := @SAMPLE_LDLIBS@ android_native_app_glue iconv +LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES=1 +LOCAL_CFLAGS += -fexceptions -frtti -D___ANDROID___ -DANDROID -DZZIP_OMIT_CONFIG_H +LOCAL_CFLAGS += -DCEGUI_SAMPLES_ANDROID_GLES2=1 + +LOCAL_C_INCLUDES := @CMAKE_SOURCE_DIR@/samples/browser/include +LOCAL_C_INCLUDES += @CMAKE_SOURCE_DIR@/cegui/include +LOCAL_C_INCLUDES += @CMAKE_SOURCE_DIR@/samples/common/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/samples/browswer/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/cegui/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/samples/common/include +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include +LOCAL_C_INCLUDES += @ANDROID_NDK@/sources/cpufeatures + +LOCAL_PATH := @JNI_PATH@ +LOCAL_SRC_FILES := @JNI_SRC_FILES@ + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,android/cpufeatures) +$(call import-module,android/native_app_glue) diff --git a/cmake/templates/Android.GLES3.mk.in b/cmake/templates/Android.GLES3.mk.in new file mode 100644 index 000000000..c61e3499a --- /dev/null +++ b/cmake/templates/Android.GLES3.mk.in @@ -0,0 +1,42 @@ + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := iconv +LOCAL_CFLAGS += -std=c99 +LOCAL_C_INCLUDES := @ANDROID_NDK@/sources/android/support/include +LOCAL_C_INCLUDES += @ANDROID_NDK@/sources/android/support/src/musl-multibyte +LOCAL_SRC_FILES := @ANDROID_NDK@/sources/android/support/src/musl-locale/iconv.c +LOCAL_SRC_FILES += @ANDROID_NDK@/sources/android/support/src/musl-multibyte/wctomb.c +include $(BUILD_STATIC_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_MODULE := @ANDROID_MOD_NAME@ +LOCAL_LDLIBS := -landroid -lz -lc -lm -ldl -llog -lEGL -lGLESv3 +LOCAL_LDLIBS += -L@CMAKE_BINARY_DIR@/lib +LOCAL_LDLIBS += -L@CEGUI_DEPENDENCIES_DIR@/lib/@ANDROID_ABI@ -L@CEGUI_DEPENDENCIES_DIR@/lib/ +LOCAL_LDLIBS += -lCEGUIOpenGLRenderer-@CEGUI_VERSION_MAJOR@_Static -lCEGUIBase-@CEGUI_VERSION_MAJOR@_Static -lCEGUICommonDialogs-@CEGUI_VERSION_MAJOR@_Static -lCEGUICoreWindowRendererSet_Static -lCEGUIFreeImageImageCodec_Static -lCEGUITinyXMLParser_Static -lCEGUISampleBrowser-@CEGUI_VERSION_MAJOR@.@CEGUI_VERSION_MINOR@_Static +LOCAL_LDLIBS += -lfreeimage -lfreetype -ltinyxml -lzzip -lpcre +LOCAL_LDLIBS += @NDKOUT@/obj/local/@ANDROID_ABI@/libiconv.a +LOCAL_LDLIBS += @ANDROID_NDK@/sources/cxx-stl/gnu-libstdc++/@ANDROID_COMPILER_VERSION@/libs/@ANDROID_ABI@/libgnustl_static.a +LOCAL_STATIC_LIBRARIES := @SAMPLE_LDLIBS@ android_native_app_glue iconv +LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES=1 +LOCAL_CFLAGS += -fexceptions -frtti -D___ANDROID___ -DANDROID -DZZIP_OMIT_CONFIG_H +LOCAL_CFLAGS += -DCEGUI_SAMPLES_ANDROID_GLES2=1 -DCEGUI_GLES3_SUPPORT + +LOCAL_C_INCLUDES := @CMAKE_SOURCE_DIR@/samples/browser/include +LOCAL_C_INCLUDES += @CMAKE_SOURCE_DIR@/cegui/include +LOCAL_C_INCLUDES += @CMAKE_SOURCE_DIR@/samples/common/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/samples/browswer/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/cegui/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/samples/common/include +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include +LOCAL_C_INCLUDES += @ANDROID_NDK@/sources/cpufeatures + +LOCAL_PATH := @JNI_PATH@ +LOCAL_SRC_FILES := @JNI_SRC_FILES@ + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,android/cpufeatures) +$(call import-module,android/native_app_glue) diff --git a/cmake/templates/Android.OgreGLES2.mk.in b/cmake/templates/Android.OgreGLES2.mk.in new file mode 100644 index 000000000..d9510475d --- /dev/null +++ b/cmake/templates/Android.OgreGLES2.mk.in @@ -0,0 +1,48 @@ + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := iconv +LOCAL_CFLAGS += -std=c99 +LOCAL_C_INCLUDES := @ANDROID_NDK@/sources/android/support/include +LOCAL_C_INCLUDES += @ANDROID_NDK@/sources/android/support/src/musl-multibyte +LOCAL_SRC_FILES := @ANDROID_NDK@/sources/android/support/src/musl-locale/iconv.c +LOCAL_SRC_FILES += @ANDROID_NDK@/sources/android/support/src/musl-multibyte/wctomb.c +include $(BUILD_STATIC_LIBRARY) + +include $(CLEAR_VARS) +LOCAL_MODULE := @ANDROID_MOD_NAME@ +LOCAL_LDLIBS := -landroid -lz -lc -lm -ldl -llog -lEGL -lGLESv2 +LOCAL_LDLIBS += -L@CMAKE_BINARY_DIR@/lib +LOCAL_LDLIBS += -L@CEGUI_DEPENDENCIES_DIR@/lib/@ANDROID_ABI@ -L@CEGUI_DEPENDENCIES_DIR@/lib/ +LOCAL_LDLIBS += -L@CEGUI_DEPENDENCIES_DIR@/lib/@ANDROID_ABI@/OGRE -L@CEGUI_DEPENDENCIES_DIR@/lib/OGRE +LOCAL_LDLIBS += -lCEGUIOgreRenderer-@CEGUI_VERSION_MAJOR@_Static -lCEGUIBase-@CEGUI_VERSION_MAJOR@_Static -lCEGUICommonDialogs-@CEGUI_VERSION_MAJOR@_Static -lCEGUICoreWindowRendererSet_Static -lCEGUIFreeImageImageCodec_Static -lCEGUITinyXMLParser_Static -lCEGUISampleBrowser-@CEGUI_VERSION_MAJOR@.@CEGUI_VERSION_MINOR@_Static +LOCAL_LDLIBS += -lRenderSystem_GLES2Static -lOgreMainStatic +LOCAL_LDLIBS += -lfreeimage -lfreetype -ltinyxml -lzzip -lOIS -lpcre +LOCAL_LDLIBS += @NDKOUT@/obj/local/@ANDROID_ABI@/libcpufeatures.a @NDKOUT@/obj/local/@ANDROID_ABI@/libiconv.a +LOCAL_LDLIBS += @ANDROID_NDK@/sources/cxx-stl/gnu-libstdc++/@ANDROID_COMPILER_VERSION@/libs/@ANDROID_ABI@/libgnustl_static.a +LOCAL_STATIC_LIBRARIES := @SAMPLE_LDLIBS@ android_native_app_glue cpufeatures iconv +LOCAL_CFLAGS += -fexceptions -frtti -D___ANDROID___ -DANDROID -DZZIP_OMIT_CONFIG_H +LOCAL_CFLAGS += -DCEGUI_SAMPLES_ANDROID_OGRE=1 + +LOCAL_C_INCLUDES := @CMAKE_SOURCE_DIR@/samples/browser/include +LOCAL_C_INCLUDES += @CMAKE_SOURCE_DIR@/cegui/include +LOCAL_C_INCLUDES += @CMAKE_SOURCE_DIR@/samples/common/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/samples/browswer/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/cegui/include +LOCAL_C_INCLUDES += @CMAKE_BINARY_DIR@/samples/common/include +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include/OIS +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include/OGRE +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include/OGRE/RenderSystems/GLES2 +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include/OGRE/RenderSystems/GLES2/include +LOCAL_C_INCLUDES += @CEGUI_DEPENDENCIES_DIR@/include/OGRE/RenderSystems/GLES2/include/EGL +LOCAL_C_INCLUDES += @ANDROID_NDK@/sources/cpufeatures + +LOCAL_PATH := @JNI_PATH@ +LOCAL_SRC_FILES := @JNI_SRC_FILES@ + +include $(BUILD_SHARED_LIBRARY) + +$(call import-module,android/cpufeatures) +$(call import-module,android/native_app_glue) diff --git a/cmake/templates/AndroidManifest.xml.in b/cmake/templates/AndroidManifest.xml.in new file mode 100644 index 000000000..e9b103207 --- /dev/null +++ b/cmake/templates/AndroidManifest.xml.in @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + diff --git a/cmake/toolchain/android.toolchain.cmake b/cmake/toolchain/android.toolchain.cmake new file mode 100644 index 000000000..437341e16 --- /dev/null +++ b/cmake/toolchain/android.toolchain.cmake @@ -0,0 +1,1780 @@ +# Copyright (c) 2010-2011, Ethan Rublee +# Copyright (c) 2011-2014, Andrey Kamaev +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +# ------------------------------------------------------------------------------ +# Android CMake toolchain file, for use with the Android NDK r5-r9 +# Requires cmake 2.6.3 or newer (2.8.5 or newer is recommended). +# See home page: https://github.com/taka-no-me/android-cmake +# +# The file is mantained by the OpenCV project. The latest version can be get at +# http://code.opencv.org/projects/opencv/repository/revisions/master/changes/android/android.toolchain.cmake +# +# Usage Linux: +# $ export ANDROID_NDK=/absolute/path/to/the/android-ndk +# $ mkdir build && cd build +# $ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake .. +# $ make -j8 +# +# Usage Linux (using standalone toolchain): +# $ export ANDROID_STANDALONE_TOOLCHAIN=/absolute/path/to/android-toolchain +# $ mkdir build && cd build +# $ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake .. +# $ make -j8 +# +# Usage Windows: +# You need native port of make to build your project. +# Android NDK r7 (or newer) already has make.exe on board. +# For older NDK you have to install it separately. +# For example, this one: http://gnuwin32.sourceforge.net/packages/make.htm +# +# $ SET ANDROID_NDK=C:\absolute\path\to\the\android-ndk +# $ mkdir build && cd build +# $ cmake.exe -G"MinGW Makefiles" +# -DCMAKE_TOOLCHAIN_FILE=path\to\the\android.toolchain.cmake +# -DCMAKE_MAKE_PROGRAM="%ANDROID_NDK%\prebuilt\windows\bin\make.exe" .. +# $ cmake.exe --build . +# +# +# Options (can be set as cmake parameters: -D=): +# ANDROID_NDK=/opt/android-ndk - path to the NDK root. +# Can be set as environment variable. Can be set only at first cmake run. +# +# ANDROID_STANDALONE_TOOLCHAIN=/opt/android-toolchain - path to the +# standalone toolchain. This option is not used if full NDK is found +# (ignored if ANDROID_NDK is set). +# Can be set as environment variable. Can be set only at first cmake run. +# +# ANDROID_ABI=armeabi-v7a - specifies the target Application Binary +# Interface (ABI). This option nearly matches to the APP_ABI variable +# used by ndk-build tool from Android NDK. +# +# Possible targets are: +# "armeabi" - matches to the NDK ABI with the same name. +# See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation. +# "armeabi-v7a" - matches to the NDK ABI with the same name. +# See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation. +# "armeabi-v7a with NEON" - same as armeabi-v7a, but +# sets NEON as floating-point unit +# "armeabi-v7a with VFPV3" - same as armeabi-v7a, but +# sets VFPV3 as floating-point unit (has 32 registers instead of 16). +# "armeabi-v6 with VFP" - tuned for ARMv6 processors having VFP. +# "x86" - matches to the NDK ABI with the same name. +# See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation. +# "mips" - matches to the NDK ABI with the same name. +# See ${ANDROID_NDK}/docs/CPU-ARCH-ABIS.html for the documentation. +# +# ANDROID_NATIVE_API_LEVEL=android-8 - level of Android API compile for. +# Option is read-only when standalone toolchain is used. +# +# ANDROID_TOOLCHAIN_NAME=arm-linux-androideabi-4.6 - the name of compiler +# toolchain to be used. The list of possible values depends on the NDK +# version. For NDK r8c the possible values are: +# +# * arm-linux-androideabi-4.4.3 +# * arm-linux-androideabi-4.6 +# * arm-linux-androideabi-clang3.1 +# * mipsel-linux-android-4.4.3 +# * mipsel-linux-android-4.6 +# * mipsel-linux-android-clang3.1 +# * x86-4.4.3 +# * x86-4.6 +# * x86-clang3.1 +# +# ANDROID_FORCE_ARM_BUILD=OFF - set ON to generate 32-bit ARM instructions +# instead of Thumb. Is not available for "x86" (inapplicable) and +# "armeabi-v6 with VFP" (is forced to be ON) ABIs. +# +# ANDROID_NO_UNDEFINED=ON - set ON to show all undefined symbols as linker +# errors even if they are not used. +# +# ANDROID_SO_UNDEFINED=OFF - set ON to allow undefined symbols in shared +# libraries. Automatically turned for NDK r5x and r6x due to GLESv2 +# problems. +# +# LIBRARY_OUTPUT_PATH_ROOT=${CMAKE_SOURCE_DIR} - where to output binary +# files. See additional details below. +# +# ANDROID_SET_OBSOLETE_VARIABLES=ON - if set, then toolchain defines some +# obsolete variables which were used by previous versions of this file for +# backward compatibility. +# +# ANDROID_STL=gnustl_static - specify the runtime to use. +# +# Possible values are: +# none -> Do not configure the runtime. +# system -> Use the default minimal system C++ runtime library. +# Implies -fno-rtti -fno-exceptions. +# Is not available for standalone toolchain. +# system_re -> Use the default minimal system C++ runtime library. +# Implies -frtti -fexceptions. +# Is not available for standalone toolchain. +# gabi++_static -> Use the GAbi++ runtime as a static library. +# Implies -frtti -fno-exceptions. +# Available for NDK r7 and newer. +# Is not available for standalone toolchain. +# gabi++_shared -> Use the GAbi++ runtime as a shared library. +# Implies -frtti -fno-exceptions. +# Available for NDK r7 and newer. +# Is not available for standalone toolchain. +# stlport_static -> Use the STLport runtime as a static library. +# Implies -fno-rtti -fno-exceptions for NDK before r7. +# Implies -frtti -fno-exceptions for NDK r7 and newer. +# Is not available for standalone toolchain. +# stlport_shared -> Use the STLport runtime as a shared library. +# Implies -fno-rtti -fno-exceptions for NDK before r7. +# Implies -frtti -fno-exceptions for NDK r7 and newer. +# Is not available for standalone toolchain. +# gnustl_static -> Use the GNU STL as a static library. +# Implies -frtti -fexceptions. +# gnustl_shared -> Use the GNU STL as a shared library. +# Implies -frtti -fno-exceptions. +# Available for NDK r7b and newer. +# Silently degrades to gnustl_static if not available. +# +# ANDROID_STL_FORCE_FEATURES=ON - turn rtti and exceptions support based on +# chosen runtime. If disabled, then the user is responsible for settings +# these options. +# +# What?: +# android-cmake toolchain searches for NDK/toolchain in the following order: +# ANDROID_NDK - cmake parameter +# ANDROID_NDK - environment variable +# ANDROID_STANDALONE_TOOLCHAIN - cmake parameter +# ANDROID_STANDALONE_TOOLCHAIN - environment variable +# ANDROID_NDK - default locations +# ANDROID_STANDALONE_TOOLCHAIN - default locations +# +# Make sure to do the following in your scripts: +# SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${my_cxx_flags}" ) +# SET( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${my_cxx_flags}" ) +# The flags will be prepopulated with critical flags, so don't loose them. +# Also be aware that toolchain also sets configuration-specific compiler +# flags and linker flags. +# +# ANDROID and BUILD_ANDROID will be set to true, you may test any of these +# variables to make necessary Android-specific configuration changes. +# +# Also ARMEABI or ARMEABI_V7A or X86 or MIPS will be set true, mutually +# exclusive. NEON option will be set true if VFP is set to NEON. +# +# LIBRARY_OUTPUT_PATH_ROOT should be set in cache to determine where Android +# libraries will be installed. +# Default is ${CMAKE_SOURCE_DIR}, and the android libs will always be +# under the ${LIBRARY_OUTPUT_PATH_ROOT}/libs/${ANDROID_NDK_ABI_NAME} +# (depending on the target ABI). This is convenient for Android packaging. +# +# Change Log: +# - initial version December 2010 +# - April 2011 +# [+] added possibility to build with NDK (without standalone toolchain) +# [+] support cross-compilation on Windows (native, no cygwin support) +# [+] added compiler option to force "char" type to be signed +# [+] added toolchain option to compile to 32-bit ARM instructions +# [+] added toolchain option to disable SWIG search +# [+] added platform "armeabi-v7a with VFPV3" +# [~] ARM_TARGETS renamed to ARM_TARGET +# [+] EXECUTABLE_OUTPUT_PATH is set by toolchain (required on Windows) +# [~] Fixed bug with ANDROID_API_LEVEL variable +# [~] turn off SWIG search if it is not found first time +# - May 2011 +# [~] ANDROID_LEVEL is renamed to ANDROID_API_LEVEL +# [+] ANDROID_API_LEVEL is detected by toolchain if not specified +# [~] added guard to prevent changing of output directories on the first +# cmake pass +# [~] toolchain exits with error if ARM_TARGET is not recognized +# - June 2011 +# [~] default NDK path is updated for version r5c +# [+] variable CMAKE_SYSTEM_PROCESSOR is set based on ARM_TARGET +# [~] toolchain install directory is added to linker paths +# [-] removed SWIG-related stuff from toolchain +# [+] added macro find_host_package, find_host_program to search +# packages/programs on the host system +# [~] fixed path to STL library +# - July 2011 +# [~] fixed options caching +# [~] search for all supported NDK versions +# [~] allowed spaces in NDK path +# - September 2011 +# [~] updated for NDK r6b +# - November 2011 +# [*] rewritten for NDK r7 +# [+] x86 toolchain support (experimental) +# [+] added "armeabi-v6 with VFP" ABI for ARMv6 processors. +# [~] improved compiler and linker flags management +# [+] support different build flags for Release and Debug configurations +# [~] by default compiler flags the same as used by ndk-build (but only +# where reasonable) +# [~] ANDROID_NDK_TOOLCHAIN_ROOT is splitted to ANDROID_STANDALONE_TOOLCHAIN +# and ANDROID_TOOLCHAIN_ROOT +# [~] ARM_TARGET is renamed to ANDROID_ABI +# [~] ARMEABI_NDK_NAME is renamed to ANDROID_NDK_ABI_NAME +# [~] ANDROID_API_LEVEL is renamed to ANDROID_NATIVE_API_LEVEL +# - January 2012 +# [+] added stlport_static support (experimental) +# [+] added special check for cygwin +# [+] filtered out hidden files (starting with .) while globbing inside NDK +# [+] automatically applied GLESv2 linkage fix for NDK revisions 5-6 +# [+] added ANDROID_GET_ABI_RAWNAME to get NDK ABI names by CMake flags +# - February 2012 +# [+] updated for NDK r7b +# [~] fixed cmake try_compile() command +# [~] Fix for missing install_name_tool on OS X +# - March 2012 +# [~] fixed incorrect C compiler flags +# [~] fixed CMAKE_SYSTEM_PROCESSOR change on ANDROID_ABI change +# [+] improved toolchain loading speed +# [+] added assembler language support (.S) +# [+] allowed preset search paths and extra search suffixes +# - April 2012 +# [+] updated for NDK r7c +# [~] fixed most of problems with compiler/linker flags and caching +# [+] added option ANDROID_FUNCTION_LEVEL_LINKING +# - May 2012 +# [+] updated for NDK r8 +# [+] added mips architecture support +# - August 2012 +# [+] updated for NDK r8b +# [~] all intermediate files generated by toolchain are moved to CMakeFiles +# [~] libstdc++ and libsupc are removed from explicit link libraries +# [+] added CCache support (via NDK_CCACHE environment or cmake variable) +# [+] added gold linker support for NDK r8b +# [~] fixed mips linker flags for NDK r8b +# - September 2012 +# [+] added NDK release name detection (see ANDROID_NDK_RELEASE) +# [+] added support for all C++ runtimes from NDK +# (system, gabi++, stlport, gnustl) +# [+] improved warnings on known issues of NDKs +# [~] use gold linker as default if available (NDK r8b) +# [~] globally turned off rpath +# [~] compiler options are aligned with NDK r8b +# - October 2012 +# [~] fixed C++ linking: explicitly link with math library (OpenCV #2426) +# - November 2012 +# [+] updated for NDK r8c +# [+] added support for clang compiler +# - December 2012 +# [+] suppress warning about unused CMAKE_TOOLCHAIN_FILE variable +# [+] adjust API level to closest compatible as NDK does +# [~] fixed ccache full path search +# [+] updated for NDK r8d +# [~] compiler options are aligned with NDK r8d +# - March 2013 +# [+] updated for NDK r8e (x86 version) +# [+] support x86_64 version of NDK +# - April 2013 +# [+] support non-release NDK layouts (from Linaro git and Android git) +# [~] automatically detect if explicit link to crtbegin_*.o is needed +# - June 2013 +# [~] fixed stl include path for standalone toolchain made by NDK >= r8c +# - July 2013 +# [+] updated for NDK r9 +# - November 2013 +# [+] updated for NDK r9b +# - December 2013 +# [+] updated for NDK r9c +# - January 2014 +# [~] fix copying of shared STL +# ------------------------------------------------------------------------------ + +cmake_minimum_required( VERSION 2.6.3 ) + +if( DEFINED CMAKE_CROSSCOMPILING ) + # subsequent toolchain loading is not really needed + return() +endif() + +if( CMAKE_TOOLCHAIN_FILE ) + # touch toolchain variable only to suppress "unused variable" warning +endif() + +get_property( _CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE ) +if( _CMAKE_IN_TRY_COMPILE ) + include( "${CMAKE_CURRENT_SOURCE_DIR}/../android.toolchain.config.cmake" OPTIONAL ) +endif() + +# this one is important +set( CMAKE_SYSTEM_NAME Linux ) +# this one not so much +set( CMAKE_SYSTEM_VERSION 1 ) + +# rpath makes low sence for Android +set( CMAKE_SKIP_RPATH TRUE CACHE BOOL "If set, runtime paths are not added when using shared libraries." ) + +set( ANDROID_SUPPORTED_NDK_VERSIONS ${ANDROID_EXTRA_NDK_VERSIONS} -r9c -r9b -r9 -r8e -r8d -r8c -r8b -r8 -r7c -r7b -r7 -r6b -r6 -r5c -r5b -r5 "" ) +if(NOT DEFINED ANDROID_NDK_SEARCH_PATHS) + if( CMAKE_HOST_WIN32 ) + file( TO_CMAKE_PATH "$ENV{PROGRAMFILES}" ANDROID_NDK_SEARCH_PATHS ) + set( ANDROID_NDK_SEARCH_PATHS "${ANDROID_NDK_SEARCH_PATHS}/android-ndk" "$ENV{SystemDrive}/NVPACK/android-ndk" ) + else() + file( TO_CMAKE_PATH "$ENV{HOME}" ANDROID_NDK_SEARCH_PATHS ) + set( ANDROID_NDK_SEARCH_PATHS /opt/android-ndk "${ANDROID_NDK_SEARCH_PATHS}/NVPACK/android-ndk" ) + endif() +endif() +if(NOT DEFINED ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH) + set( ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH /opt/android-toolchain ) +endif() + +set( ANDROID_SUPPORTED_ABIS_arm "armeabi-v7a;armeabi;armeabi-v7a with NEON;armeabi-v7a with VFPV3;armeabi-v6 with VFP" ) +set( ANDROID_SUPPORTED_ABIS_x86 "x86" ) +set( ANDROID_SUPPORTED_ABIS_mipsel "mips" ) + +set( ANDROID_DEFAULT_NDK_API_LEVEL 8 ) +set( ANDROID_DEFAULT_NDK_API_LEVEL_x86 9 ) +set( ANDROID_DEFAULT_NDK_API_LEVEL_mips 9 ) + + +macro( __LIST_FILTER listvar regex ) + if( ${listvar} ) + foreach( __val ${${listvar}} ) + if( __val MATCHES "${regex}" ) + list( REMOVE_ITEM ${listvar} "${__val}" ) + endif() + endforeach() + endif() +endmacro() + +macro( __INIT_VARIABLE var_name ) + set( __test_path 0 ) + foreach( __var ${ARGN} ) + if( __var STREQUAL "PATH" ) + set( __test_path 1 ) + break() + endif() + endforeach() + if( __test_path AND NOT EXISTS "${${var_name}}" ) + unset( ${var_name} CACHE ) + endif() + if( "${${var_name}}" STREQUAL "" ) + set( __values 0 ) + foreach( __var ${ARGN} ) + if( __var STREQUAL "VALUES" ) + set( __values 1 ) + elseif( NOT __var STREQUAL "PATH" ) + set( __obsolete 0 ) + if( __var MATCHES "^OBSOLETE_.*$" ) + string( REPLACE "OBSOLETE_" "" __var "${__var}" ) + set( __obsolete 1 ) + endif() + if( __var MATCHES "^ENV_.*$" ) + string( REPLACE "ENV_" "" __var "${__var}" ) + set( __value "$ENV{${__var}}" ) + elseif( DEFINED ${__var} ) + set( __value "${${__var}}" ) + else() + if( __values ) + set( __value "${__var}" ) + else() + set( __value "" ) + endif() + endif() + if( NOT "${__value}" STREQUAL "" ) + if( __test_path ) + if( EXISTS "${__value}" ) + file( TO_CMAKE_PATH "${__value}" ${var_name} ) + if( __obsolete AND NOT _CMAKE_IN_TRY_COMPILE ) + message( WARNING "Using value of obsolete variable ${__var} as initial value for ${var_name}. Please note, that ${__var} can be completely removed in future versions of the toolchain." ) + endif() + break() + endif() + else() + set( ${var_name} "${__value}" ) + if( __obsolete AND NOT _CMAKE_IN_TRY_COMPILE ) + message( WARNING "Using value of obsolete variable ${__var} as initial value for ${var_name}. Please note, that ${__var} can be completely removed in future versions of the toolchain." ) + endif() + break() + endif() + endif() + endif() + endforeach() + unset( __value ) + unset( __values ) + unset( __obsolete ) + elseif( __test_path ) + file( TO_CMAKE_PATH "${${var_name}}" ${var_name} ) + endif() + unset( __test_path ) +endmacro() + +macro( __DETECT_NATIVE_API_LEVEL _var _path ) + SET( __ndkApiLevelRegex "^[\t ]*#define[\t ]+__ANDROID_API__[\t ]+([0-9]+)[\t ]*$" ) + FILE( STRINGS ${_path} __apiFileContent REGEX "${__ndkApiLevelRegex}" ) + if( NOT __apiFileContent ) + message( SEND_ERROR "Could not get Android native API level. Probably you have specified invalid level value, or your copy of NDK/toolchain is broken." ) + endif() + string( REGEX REPLACE "${__ndkApiLevelRegex}" "\\1" ${_var} "${__apiFileContent}" ) + unset( __apiFileContent ) + unset( __ndkApiLevelRegex ) +endmacro() + +macro( __DETECT_TOOLCHAIN_MACHINE_NAME _var _root ) + if( EXISTS "${_root}" ) + file( GLOB __gccExePath RELATIVE "${_root}/bin/" "${_root}/bin/*-gcc${TOOL_OS_SUFFIX}" ) + __LIST_FILTER( __gccExePath "^[.].*" ) + list( LENGTH __gccExePath __gccExePathsCount ) + if( NOT __gccExePathsCount EQUAL 1 AND NOT _CMAKE_IN_TRY_COMPILE ) + message( WARNING "Could not determine machine name for compiler from ${_root}" ) + set( ${_var} "" ) + else() + get_filename_component( __gccExeName "${__gccExePath}" NAME_WE ) + string( REPLACE "-gcc" "" ${_var} "${__gccExeName}" ) + endif() + unset( __gccExePath ) + unset( __gccExePathsCount ) + unset( __gccExeName ) + else() + set( ${_var} "" ) + endif() +endmacro() + + +# fight against cygwin +set( ANDROID_FORBID_SYGWIN TRUE CACHE BOOL "Prevent cmake from working under cygwin and using cygwin tools") +mark_as_advanced( ANDROID_FORBID_SYGWIN ) +if( ANDROID_FORBID_SYGWIN ) + if( CYGWIN ) + message( FATAL_ERROR "Android NDK and android-cmake toolchain are not welcome Cygwin. It is unlikely that this cmake toolchain will work under cygwin. But if you want to try then you can set cmake variable ANDROID_FORBID_SYGWIN to FALSE and rerun cmake." ) + endif() + + if( CMAKE_HOST_WIN32 ) + # remove cygwin from PATH + set( __new_path "$ENV{PATH}") + __LIST_FILTER( __new_path "cygwin" ) + set(ENV{PATH} "${__new_path}") + unset(__new_path) + endif() +endif() + + +# detect current host platform +if( NOT DEFINED ANDROID_NDK_HOST_X64 AND (CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "amd64|x86_64|AMD64" OR CMAKE_HOST_APPLE) ) + set( ANDROID_NDK_HOST_X64 1 CACHE BOOL "Try to use 64-bit compiler toolchain" ) + mark_as_advanced( ANDROID_NDK_HOST_X64 ) +endif() + +set( TOOL_OS_SUFFIX "" ) +if( CMAKE_HOST_APPLE ) + set( ANDROID_NDK_HOST_SYSTEM_NAME "darwin-x86_64" ) + set( ANDROID_NDK_HOST_SYSTEM_NAME2 "darwin-x86" ) +elseif( CMAKE_HOST_WIN32 ) + set( ANDROID_NDK_HOST_SYSTEM_NAME "windows-x86_64" ) + set( ANDROID_NDK_HOST_SYSTEM_NAME2 "windows" ) + set( TOOL_OS_SUFFIX ".exe" ) +elseif( CMAKE_HOST_UNIX ) + set( ANDROID_NDK_HOST_SYSTEM_NAME "linux-x86_64" ) + set( ANDROID_NDK_HOST_SYSTEM_NAME2 "linux-x86" ) +else() + message( FATAL_ERROR "Cross-compilation on your platform is not supported by this cmake toolchain" ) +endif() + +if( NOT ANDROID_NDK_HOST_X64 ) + set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) +endif() + +# see if we have path to Android NDK +__INIT_VARIABLE( ANDROID_NDK PATH ENV_ANDROID_NDK ) +if( NOT ANDROID_NDK ) + # see if we have path to Android standalone toolchain + __INIT_VARIABLE( ANDROID_STANDALONE_TOOLCHAIN PATH ENV_ANDROID_STANDALONE_TOOLCHAIN OBSOLETE_ANDROID_NDK_TOOLCHAIN_ROOT OBSOLETE_ENV_ANDROID_NDK_TOOLCHAIN_ROOT ) + + if( NOT ANDROID_STANDALONE_TOOLCHAIN ) + #try to find Android NDK in one of the the default locations + set( __ndkSearchPaths ) + foreach( __ndkSearchPath ${ANDROID_NDK_SEARCH_PATHS} ) + foreach( suffix ${ANDROID_SUPPORTED_NDK_VERSIONS} ) + list( APPEND __ndkSearchPaths "${__ndkSearchPath}${suffix}" ) + endforeach() + endforeach() + __INIT_VARIABLE( ANDROID_NDK PATH VALUES ${__ndkSearchPaths} ) + unset( __ndkSearchPaths ) + + if( ANDROID_NDK ) + message( STATUS "Using default path for Android NDK: ${ANDROID_NDK}" ) + message( STATUS " If you prefer to use a different location, please define a cmake or environment variable: ANDROID_NDK" ) + else() + #try to find Android standalone toolchain in one of the the default locations + __INIT_VARIABLE( ANDROID_STANDALONE_TOOLCHAIN PATH ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH ) + + if( ANDROID_STANDALONE_TOOLCHAIN ) + message( STATUS "Using default path for standalone toolchain ${ANDROID_STANDALONE_TOOLCHAIN}" ) + message( STATUS " If you prefer to use a different location, please define the variable: ANDROID_STANDALONE_TOOLCHAIN" ) + endif( ANDROID_STANDALONE_TOOLCHAIN ) + endif( ANDROID_NDK ) + endif( NOT ANDROID_STANDALONE_TOOLCHAIN ) +endif( NOT ANDROID_NDK ) + +# remember found paths +if( ANDROID_NDK ) + get_filename_component( ANDROID_NDK "${ANDROID_NDK}" ABSOLUTE ) + set( ANDROID_NDK "${ANDROID_NDK}" CACHE INTERNAL "Path of the Android NDK" FORCE ) + set( BUILD_WITH_ANDROID_NDK True ) + if( EXISTS "${ANDROID_NDK}/RELEASE.TXT" ) + file( STRINGS "${ANDROID_NDK}/RELEASE.TXT" ANDROID_NDK_RELEASE_FULL LIMIT_COUNT 1 REGEX r[0-9]+[a-z]? ) + string( REGEX MATCH r[0-9]+[a-z]? ANDROID_NDK_RELEASE "${ANDROID_NDK_RELEASE_FULL}" ) + else() + set( ANDROID_NDK_RELEASE "r1x" ) + set( ANDROID_NDK_RELEASE_FULL "unreleased" ) + endif() +elseif( ANDROID_STANDALONE_TOOLCHAIN ) + get_filename_component( ANDROID_STANDALONE_TOOLCHAIN "${ANDROID_STANDALONE_TOOLCHAIN}" ABSOLUTE ) + # try to detect change + if( CMAKE_AR ) + string( LENGTH "${ANDROID_STANDALONE_TOOLCHAIN}" __length ) + string( SUBSTRING "${CMAKE_AR}" 0 ${__length} __androidStandaloneToolchainPreviousPath ) + if( NOT __androidStandaloneToolchainPreviousPath STREQUAL ANDROID_STANDALONE_TOOLCHAIN ) + message( FATAL_ERROR "It is not possible to change path to the Android standalone toolchain on subsequent run." ) + endif() + unset( __androidStandaloneToolchainPreviousPath ) + unset( __length ) + endif() + set( ANDROID_STANDALONE_TOOLCHAIN "${ANDROID_STANDALONE_TOOLCHAIN}" CACHE INTERNAL "Path of the Android standalone toolchain" FORCE ) + set( BUILD_WITH_STANDALONE_TOOLCHAIN True ) +else() + list(GET ANDROID_NDK_SEARCH_PATHS 0 ANDROID_NDK_SEARCH_PATH) + message( FATAL_ERROR "Could not find neither Android NDK nor Android standalone toolchain. + You should either set an environment variable: + export ANDROID_NDK=~/my-android-ndk + or + export ANDROID_STANDALONE_TOOLCHAIN=~/my-android-toolchain + or put the toolchain or NDK in the default path: + sudo ln -s ~/my-android-ndk ${ANDROID_NDK_SEARCH_PATH} + sudo ln -s ~/my-android-toolchain ${ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH}" ) +endif() + +# android NDK layout +if( BUILD_WITH_ANDROID_NDK ) + if( NOT DEFINED ANDROID_NDK_LAYOUT ) + # try to automatically detect the layout + if( EXISTS "${ANDROID_NDK}/RELEASE.TXT") + set( ANDROID_NDK_LAYOUT "RELEASE" ) + elseif( EXISTS "${ANDROID_NDK}/../../linux-x86/toolchain/" ) + set( ANDROID_NDK_LAYOUT "LINARO" ) + elseif( EXISTS "${ANDROID_NDK}/../../gcc/" ) + set( ANDROID_NDK_LAYOUT "ANDROID" ) + endif() + endif() + set( ANDROID_NDK_LAYOUT "${ANDROID_NDK_LAYOUT}" CACHE STRING "The inner layout of NDK" ) + mark_as_advanced( ANDROID_NDK_LAYOUT ) + if( ANDROID_NDK_LAYOUT STREQUAL "LINARO" ) + set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) # only 32-bit at the moment + set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/../../${ANDROID_NDK_HOST_SYSTEM_NAME}/toolchain" ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH "" ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "" ) + elseif( ANDROID_NDK_LAYOUT STREQUAL "ANDROID" ) + set( ANDROID_NDK_HOST_SYSTEM_NAME ${ANDROID_NDK_HOST_SYSTEM_NAME2} ) # only 32-bit at the moment + set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/../../gcc/${ANDROID_NDK_HOST_SYSTEM_NAME}/arm" ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH "" ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "" ) + else() # ANDROID_NDK_LAYOUT STREQUAL "RELEASE" + set( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK}/toolchains" ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH "/prebuilt/${ANDROID_NDK_HOST_SYSTEM_NAME}" ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH2 "/prebuilt/${ANDROID_NDK_HOST_SYSTEM_NAME2}" ) + endif() + get_filename_component( ANDROID_NDK_TOOLCHAINS_PATH "${ANDROID_NDK_TOOLCHAINS_PATH}" ABSOLUTE ) + + # try to detect change of NDK + if( CMAKE_AR ) + string( LENGTH "${ANDROID_NDK_TOOLCHAINS_PATH}" __length ) + string( SUBSTRING "${CMAKE_AR}" 0 ${__length} __androidNdkPreviousPath ) + if( NOT __androidNdkPreviousPath STREQUAL ANDROID_NDK_TOOLCHAINS_PATH ) + message( FATAL_ERROR "It is not possible to change the path to the NDK on subsequent CMake run. You must remove all generated files from your build folder first. + " ) + endif() + unset( __androidNdkPreviousPath ) + unset( __length ) + endif() +endif() + + +# get all the details about standalone toolchain +if( BUILD_WITH_STANDALONE_TOOLCHAIN ) + __DETECT_NATIVE_API_LEVEL( ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot/usr/include/android/api-level.h" ) + set( ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} ) + set( __availableToolchains "standalone" ) + __DETECT_TOOLCHAIN_MACHINE_NAME( __availableToolchainMachines "${ANDROID_STANDALONE_TOOLCHAIN}" ) + if( NOT __availableToolchainMachines ) + message( FATAL_ERROR "Could not determine machine name of your toolchain. Probably your Android standalone toolchain is broken." ) + endif() + if( __availableToolchainMachines MATCHES i686 ) + set( __availableToolchainArchs "x86" ) + elseif( __availableToolchainMachines MATCHES arm ) + set( __availableToolchainArchs "arm" ) + elseif( __availableToolchainMachines MATCHES mipsel ) + set( __availableToolchainArchs "mipsel" ) + endif() + execute_process( COMMAND "${ANDROID_STANDALONE_TOOLCHAIN}/bin/${__availableToolchainMachines}-gcc${TOOL_OS_SUFFIX}" -dumpversion + OUTPUT_VARIABLE __availableToolchainCompilerVersions OUTPUT_STRIP_TRAILING_WHITESPACE ) + string( REGEX MATCH "[0-9]+[.][0-9]+([.][0-9]+)?" __availableToolchainCompilerVersions "${__availableToolchainCompilerVersions}" ) + if( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/bin/clang${TOOL_OS_SUFFIX}" ) + list( APPEND __availableToolchains "standalone-clang" ) + list( APPEND __availableToolchainMachines ${__availableToolchainMachines} ) + list( APPEND __availableToolchainArchs ${__availableToolchainArchs} ) + list( APPEND __availableToolchainCompilerVersions ${__availableToolchainCompilerVersions} ) + endif() +endif() + +macro( __GLOB_NDK_TOOLCHAINS __availableToolchainsVar __availableToolchainsLst __toolchain_subpath ) + foreach( __toolchain ${${__availableToolchainsLst}} ) + if( "${__toolchain}" MATCHES "-clang3[.][0-9]$" AND NOT EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/${__toolchain}${__toolchain_subpath}" ) + string( REGEX REPLACE "-clang3[.][0-9]$" "-4.6" __gcc_toolchain "${__toolchain}" ) + else() + set( __gcc_toolchain "${__toolchain}" ) + endif() + __DETECT_TOOLCHAIN_MACHINE_NAME( __machine "${ANDROID_NDK_TOOLCHAINS_PATH}/${__gcc_toolchain}${__toolchain_subpath}" ) + if( __machine ) + string( REGEX MATCH "[0-9]+[.][0-9]+([.][0-9x]+)?$" __version "${__gcc_toolchain}" ) + if( __machine MATCHES i686 ) + set( __arch "x86" ) + elseif( __machine MATCHES arm ) + set( __arch "arm" ) + elseif( __machine MATCHES mipsel ) + set( __arch "mipsel" ) + endif() + list( APPEND __availableToolchainMachines "${__machine}" ) + list( APPEND __availableToolchainArchs "${__arch}" ) + list( APPEND __availableToolchainCompilerVersions "${__version}" ) + list( APPEND ${__availableToolchainsVar} "${__toolchain}" ) + endif() + unset( __gcc_toolchain ) + endforeach() +endmacro() + +# get all the details about NDK +if( BUILD_WITH_ANDROID_NDK ) + file( GLOB ANDROID_SUPPORTED_NATIVE_API_LEVELS RELATIVE "${ANDROID_NDK}/platforms" "${ANDROID_NDK}/platforms/android-*" ) + string( REPLACE "android-" "" ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_SUPPORTED_NATIVE_API_LEVELS}" ) + set( __availableToolchains "" ) + set( __availableToolchainMachines "" ) + set( __availableToolchainArchs "" ) + set( __availableToolchainCompilerVersions "" ) + if( ANDROID_TOOLCHAIN_NAME AND EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_TOOLCHAIN_NAME}/" ) + # do not go through all toolchains if we know the name + set( __availableToolchainsLst "${ANDROID_TOOLCHAIN_NAME}" ) + __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) + if( NOT __availableToolchains AND NOT ANDROID_NDK_TOOLCHAINS_SUBPATH STREQUAL ANDROID_NDK_TOOLCHAINS_SUBPATH2 ) + __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH2}" ) + if( __availableToolchains ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH ${ANDROID_NDK_TOOLCHAINS_SUBPATH2} ) + endif() + endif() + endif() + if( NOT __availableToolchains ) + file( GLOB __availableToolchainsLst RELATIVE "${ANDROID_NDK_TOOLCHAINS_PATH}" "${ANDROID_NDK_TOOLCHAINS_PATH}/*" ) + if( __availableToolchains ) + list(SORT __availableToolchainsLst) # we need clang to go after gcc + endif() + __LIST_FILTER( __availableToolchainsLst "^[.]" ) + __LIST_FILTER( __availableToolchainsLst "llvm" ) + __LIST_FILTER( __availableToolchainsLst "renderscript" ) + __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) + if( NOT __availableToolchains AND NOT ANDROID_NDK_TOOLCHAINS_SUBPATH STREQUAL ANDROID_NDK_TOOLCHAINS_SUBPATH2 ) + __GLOB_NDK_TOOLCHAINS( __availableToolchains __availableToolchainsLst "${ANDROID_NDK_TOOLCHAINS_SUBPATH2}" ) + if( __availableToolchains ) + set( ANDROID_NDK_TOOLCHAINS_SUBPATH ${ANDROID_NDK_TOOLCHAINS_SUBPATH2} ) + endif() + endif() + endif() + if( NOT __availableToolchains ) + message( FATAL_ERROR "Could not find any working toolchain in the NDK. Probably your Android NDK is broken." ) + endif() +endif() + +# build list of available ABIs +set( ANDROID_SUPPORTED_ABIS "" ) +set( __uniqToolchainArchNames ${__availableToolchainArchs} ) +list( REMOVE_DUPLICATES __uniqToolchainArchNames ) +list( SORT __uniqToolchainArchNames ) +foreach( __arch ${__uniqToolchainArchNames} ) + list( APPEND ANDROID_SUPPORTED_ABIS ${ANDROID_SUPPORTED_ABIS_${__arch}} ) +endforeach() +unset( __uniqToolchainArchNames ) +if( NOT ANDROID_SUPPORTED_ABIS ) + message( FATAL_ERROR "No one of known Android ABIs is supported by this cmake toolchain." ) +endif() + +# choose target ABI +__INIT_VARIABLE( ANDROID_ABI OBSOLETE_ARM_TARGET OBSOLETE_ARM_TARGETS VALUES ${ANDROID_SUPPORTED_ABIS} ) +# verify that target ABI is supported +list( FIND ANDROID_SUPPORTED_ABIS "${ANDROID_ABI}" __androidAbiIdx ) +if( __androidAbiIdx EQUAL -1 ) + string( REPLACE ";" "\", \"" PRINTABLE_ANDROID_SUPPORTED_ABIS "${ANDROID_SUPPORTED_ABIS}" ) + message( FATAL_ERROR "Specified ANDROID_ABI = \"${ANDROID_ABI}\" is not supported by this cmake toolchain or your NDK/toolchain. + Supported values are: \"${PRINTABLE_ANDROID_SUPPORTED_ABIS}\" + " ) +endif() +unset( __androidAbiIdx ) + +# set target ABI options +if( ANDROID_ABI STREQUAL "x86" ) + set( X86 true ) + set( ANDROID_NDK_ABI_NAME "x86" ) + set( ANDROID_ARCH_NAME "x86" ) + set( ANDROID_ARCH_FULLNAME "x86" ) + set( ANDROID_LLVM_TRIPLE "i686-none-linux-android" ) + set( CMAKE_SYSTEM_PROCESSOR "i686" ) +elseif( ANDROID_ABI STREQUAL "mips" ) + set( MIPS true ) + set( ANDROID_NDK_ABI_NAME "mips" ) + set( ANDROID_ARCH_NAME "mips" ) + set( ANDROID_ARCH_FULLNAME "mipsel" ) + set( ANDROID_LLVM_TRIPLE "mipsel-none-linux-android" ) + set( CMAKE_SYSTEM_PROCESSOR "mips" ) +elseif( ANDROID_ABI STREQUAL "armeabi" ) + set( ARMEABI true ) + set( ANDROID_NDK_ABI_NAME "armeabi" ) + set( ANDROID_ARCH_NAME "arm" ) + set( ANDROID_ARCH_FULLNAME "arm" ) + set( ANDROID_LLVM_TRIPLE "armv5te-none-linux-androideabi" ) + set( CMAKE_SYSTEM_PROCESSOR "armv5te" ) +elseif( ANDROID_ABI STREQUAL "armeabi-v6 with VFP" ) + set( ARMEABI_V6 true ) + set( ANDROID_NDK_ABI_NAME "armeabi" ) + set( ANDROID_ARCH_NAME "arm" ) + set( ANDROID_ARCH_FULLNAME "arm" ) + set( ANDROID_LLVM_TRIPLE "armv5te-none-linux-androideabi" ) + set( CMAKE_SYSTEM_PROCESSOR "armv6" ) + # need always fallback to older platform + set( ARMEABI true ) +elseif( ANDROID_ABI STREQUAL "armeabi-v7a") + set( ARMEABI_V7A true ) + set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) + set( ANDROID_ARCH_NAME "arm" ) + set( ANDROID_ARCH_FULLNAME "arm" ) + set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" ) + set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) +elseif( ANDROID_ABI STREQUAL "armeabi-v7a with VFPV3" ) + set( ARMEABI_V7A true ) + set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) + set( ANDROID_ARCH_NAME "arm" ) + set( ANDROID_ARCH_FULLNAME "arm" ) + set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" ) + set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) + set( VFPV3 true ) +elseif( ANDROID_ABI STREQUAL "armeabi-v7a with NEON" ) + set( ARMEABI_V7A true ) + set( ANDROID_NDK_ABI_NAME "armeabi-v7a" ) + set( ANDROID_ARCH_NAME "arm" ) + set( ANDROID_ARCH_FULLNAME "arm" ) + set( ANDROID_LLVM_TRIPLE "armv7-none-linux-androideabi" ) + set( CMAKE_SYSTEM_PROCESSOR "armv7-a" ) + set( VFPV3 true ) + set( NEON true ) +else() + message( SEND_ERROR "Unknown ANDROID_ABI=\"${ANDROID_ABI}\" is specified." ) +endif() + +if( CMAKE_BINARY_DIR AND EXISTS "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" ) + # really dirty hack + # it is not possible to change CMAKE_SYSTEM_PROCESSOR after the first run... + file( APPEND "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeSystem.cmake" "SET(CMAKE_SYSTEM_PROCESSOR \"${CMAKE_SYSTEM_PROCESSOR}\")\n" ) +endif() + +if( ANDROID_ARCH_NAME STREQUAL "arm" AND NOT ARMEABI_V6 ) + __INIT_VARIABLE( ANDROID_FORCE_ARM_BUILD OBSOLETE_FORCE_ARM VALUES OFF ) + set( ANDROID_FORCE_ARM_BUILD ${ANDROID_FORCE_ARM_BUILD} CACHE BOOL "Use 32-bit ARM instructions instead of Thumb-1" FORCE ) + mark_as_advanced( ANDROID_FORCE_ARM_BUILD ) +else() + unset( ANDROID_FORCE_ARM_BUILD CACHE ) +endif() + +# choose toolchain +if( ANDROID_TOOLCHAIN_NAME ) + list( FIND __availableToolchains "${ANDROID_TOOLCHAIN_NAME}" __toolchainIdx ) + if( __toolchainIdx EQUAL -1 ) + list( SORT __availableToolchains ) + string( REPLACE ";" "\n * " toolchains_list "${__availableToolchains}" ) + set( toolchains_list " * ${toolchains_list}") + message( FATAL_ERROR "Specified toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is missing in your NDK or broken. Please verify that your NDK is working or select another compiler toolchain. +To configure the toolchain set CMake variable ANDROID_TOOLCHAIN_NAME to one of the following values:\n${toolchains_list}\n" ) + endif() + list( GET __availableToolchainArchs ${__toolchainIdx} __toolchainArch ) + if( NOT __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME ) + message( SEND_ERROR "Selected toolchain \"${ANDROID_TOOLCHAIN_NAME}\" is not able to compile binaries for the \"${ANDROID_ARCH_NAME}\" platform." ) + endif() +else() + set( __toolchainIdx -1 ) + set( __applicableToolchains "" ) + set( __toolchainMaxVersion "0.0.0" ) + list( LENGTH __availableToolchains __availableToolchainsCount ) + math( EXPR __availableToolchainsCount "${__availableToolchainsCount}-1" ) + foreach( __idx RANGE ${__availableToolchainsCount} ) + list( GET __availableToolchainArchs ${__idx} __toolchainArch ) + if( __toolchainArch STREQUAL ANDROID_ARCH_FULLNAME ) + list( GET __availableToolchainCompilerVersions ${__idx} __toolchainVersion ) + string( REPLACE "x" "99" __toolchainVersion "${__toolchainVersion}") + if( __toolchainVersion VERSION_GREATER __toolchainMaxVersion ) + set( __toolchainMaxVersion "${__toolchainVersion}" ) + set( __toolchainIdx ${__idx} ) + endif() + endif() + endforeach() + unset( __availableToolchainsCount ) + unset( __toolchainMaxVersion ) + unset( __toolchainVersion ) +endif() +unset( __toolchainArch ) +if( __toolchainIdx EQUAL -1 ) + message( FATAL_ERROR "No one of available compiler toolchains is able to compile for ${ANDROID_ARCH_NAME} platform." ) +endif() +list( GET __availableToolchains ${__toolchainIdx} ANDROID_TOOLCHAIN_NAME ) +list( GET __availableToolchainMachines ${__toolchainIdx} ANDROID_TOOLCHAIN_MACHINE_NAME ) +list( GET __availableToolchainCompilerVersions ${__toolchainIdx} ANDROID_COMPILER_VERSION ) + +unset( __toolchainIdx ) +unset( __availableToolchains ) +unset( __availableToolchainMachines ) +unset( __availableToolchainArchs ) +unset( __availableToolchainCompilerVersions ) + +# choose native API level +__INIT_VARIABLE( ANDROID_NATIVE_API_LEVEL ENV_ANDROID_NATIVE_API_LEVEL ANDROID_API_LEVEL ENV_ANDROID_API_LEVEL ANDROID_STANDALONE_TOOLCHAIN_API_LEVEL ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME} ANDROID_DEFAULT_NDK_API_LEVEL ) +string( REGEX MATCH "[0-9]+" ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" ) +# adjust API level +set( __real_api_level ${ANDROID_DEFAULT_NDK_API_LEVEL_${ANDROID_ARCH_NAME}} ) +foreach( __level ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} ) + if( NOT __level GREATER ANDROID_NATIVE_API_LEVEL AND NOT __level LESS __real_api_level ) + set( __real_api_level ${__level} ) + endif() +endforeach() +if( __real_api_level AND NOT ANDROID_NATIVE_API_LEVEL EQUAL __real_api_level ) + message( STATUS "Adjusting Android API level 'android-${ANDROID_NATIVE_API_LEVEL}' to 'android-${__real_api_level}'") + set( ANDROID_NATIVE_API_LEVEL ${__real_api_level} ) +endif() +unset(__real_api_level) +# validate +list( FIND ANDROID_SUPPORTED_NATIVE_API_LEVELS "${ANDROID_NATIVE_API_LEVEL}" __levelIdx ) +if( __levelIdx EQUAL -1 ) + message( SEND_ERROR "Specified Android native API level 'android-${ANDROID_NATIVE_API_LEVEL}' is not supported by your NDK/toolchain." ) +else() + if( BUILD_WITH_ANDROID_NDK ) + __DETECT_NATIVE_API_LEVEL( __realApiLevel "${ANDROID_NDK}/platforms/android-${ANDROID_NATIVE_API_LEVEL}/arch-${ANDROID_ARCH_NAME}/usr/include/android/api-level.h" ) + if( NOT __realApiLevel EQUAL ANDROID_NATIVE_API_LEVEL ) + message( SEND_ERROR "Specified Android API level (${ANDROID_NATIVE_API_LEVEL}) does not match to the level found (${__realApiLevel}). Probably your copy of NDK is broken." ) + endif() + unset( __realApiLevel ) + endif() + set( ANDROID_NATIVE_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}" CACHE STRING "Android API level for native code" FORCE ) + if( CMAKE_VERSION VERSION_GREATER "2.8" ) + list( SORT ANDROID_SUPPORTED_NATIVE_API_LEVELS ) + set_property( CACHE ANDROID_NATIVE_API_LEVEL PROPERTY STRINGS ${ANDROID_SUPPORTED_NATIVE_API_LEVELS} ) + endif() +endif() +unset( __levelIdx ) + + +# remember target ABI +set( ANDROID_ABI "${ANDROID_ABI}" CACHE STRING "The target ABI for Android. If arm, then armeabi-v7a is recommended for hardware floating point." FORCE ) +if( CMAKE_VERSION VERSION_GREATER "2.8" ) + list( SORT ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME} ) + set_property( CACHE ANDROID_ABI PROPERTY STRINGS ${ANDROID_SUPPORTED_ABIS_${ANDROID_ARCH_FULLNAME}} ) +endif() + + +# runtime choice (STL, rtti, exceptions) +if( NOT ANDROID_STL ) + # honor legacy ANDROID_USE_STLPORT + if( DEFINED ANDROID_USE_STLPORT ) + if( ANDROID_USE_STLPORT ) + set( ANDROID_STL stlport_static ) + endif() + message( WARNING "You are using an obsolete variable ANDROID_USE_STLPORT to select the STL variant. Use -DANDROID_STL=stlport_static instead." ) + endif() + if( NOT ANDROID_STL ) + set( ANDROID_STL gnustl_static ) + endif() +endif() +set( ANDROID_STL "${ANDROID_STL}" CACHE STRING "C++ runtime" ) +set( ANDROID_STL_FORCE_FEATURES ON CACHE BOOL "automatically configure rtti and exceptions support based on C++ runtime" ) +mark_as_advanced( ANDROID_STL ANDROID_STL_FORCE_FEATURES ) + +if( BUILD_WITH_ANDROID_NDK ) + if( NOT "${ANDROID_STL}" MATCHES "^(none|system|system_re|gabi\\+\\+_static|gabi\\+\\+_shared|stlport_static|stlport_shared|gnustl_static|gnustl_shared)$") + message( FATAL_ERROR "ANDROID_STL is set to invalid value \"${ANDROID_STL}\". +The possible values are: + none -> Do not configure the runtime. + system -> Use the default minimal system C++ runtime library. + system_re -> Same as system but with rtti and exceptions. + gabi++_static -> Use the GAbi++ runtime as a static library. + gabi++_shared -> Use the GAbi++ runtime as a shared library. + stlport_static -> Use the STLport runtime as a static library. + stlport_shared -> Use the STLport runtime as a shared library. + gnustl_static -> (default) Use the GNU STL as a static library. + gnustl_shared -> Use the GNU STL as a shared library. +" ) + endif() +elseif( BUILD_WITH_STANDALONE_TOOLCHAIN ) + if( NOT "${ANDROID_STL}" MATCHES "^(none|gnustl_static|gnustl_shared)$") + message( FATAL_ERROR "ANDROID_STL is set to invalid value \"${ANDROID_STL}\". +The possible values are: + none -> Do not configure the runtime. + gnustl_static -> (default) Use the GNU STL as a static library. + gnustl_shared -> Use the GNU STL as a shared library. +" ) + endif() +endif() + +unset( ANDROID_RTTI ) +unset( ANDROID_EXCEPTIONS ) +unset( ANDROID_STL_INCLUDE_DIRS ) +unset( __libstl ) +unset( __libsupcxx ) + +if( NOT _CMAKE_IN_TRY_COMPILE AND ANDROID_NDK_RELEASE STREQUAL "r7b" AND ARMEABI_V7A AND NOT VFPV3 AND ANDROID_STL MATCHES "gnustl" ) + message( WARNING "The GNU STL armeabi-v7a binaries from NDK r7b can crash non-NEON devices. The files provided with NDK r7b were not configured properly, resulting in crashes on Tegra2-based devices and others when trying to use certain floating-point functions (e.g., cosf, sinf, expf). +You are strongly recommended to switch to another NDK release. +" ) +endif() + +if( NOT _CMAKE_IN_TRY_COMPILE AND X86 AND ANDROID_STL MATCHES "gnustl" AND ANDROID_NDK_RELEASE STREQUAL "r6" ) + message( WARNING "The x86 system header file from NDK r6 has incorrect definition for ptrdiff_t. You are recommended to upgrade to a newer NDK release or manually patch the header: +See https://android.googlesource.com/platform/development.git f907f4f9d4e56ccc8093df6fee54454b8bcab6c2 + diff --git a/ndk/platforms/android-9/arch-x86/include/machine/_types.h b/ndk/platforms/android-9/arch-x86/include/machine/_types.h + index 5e28c64..65892a1 100644 + --- a/ndk/platforms/android-9/arch-x86/include/machine/_types.h + +++ b/ndk/platforms/android-9/arch-x86/include/machine/_types.h + @@ -51,7 +51,11 @@ typedef long int ssize_t; + #endif + #ifndef _PTRDIFF_T + #define _PTRDIFF_T + -typedef long ptrdiff_t; + +# ifdef __ANDROID__ + + typedef int ptrdiff_t; + +# else + + typedef long ptrdiff_t; + +# endif + #endif +" ) +endif() + + +# setup paths and STL for standalone toolchain +if( BUILD_WITH_STANDALONE_TOOLCHAIN ) + set( ANDROID_TOOLCHAIN_ROOT "${ANDROID_STANDALONE_TOOLCHAIN}" ) + set( ANDROID_CLANG_TOOLCHAIN_ROOT "${ANDROID_STANDALONE_TOOLCHAIN}" ) + set( ANDROID_SYSROOT "${ANDROID_STANDALONE_TOOLCHAIN}/sysroot" ) + + if( NOT ANDROID_STL STREQUAL "none" ) + set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_STANDALONE_TOOLCHAIN}/include/c++/${ANDROID_COMPILER_VERSION}" ) + if( NOT EXISTS "${ANDROID_STL_INCLUDE_DIRS}" ) + # old location ( pre r8c ) + set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/include/c++/${ANDROID_COMPILER_VERSION}" ) + endif() + if( ARMEABI_V7A AND EXISTS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/${CMAKE_SYSTEM_PROCESSOR}/bits" ) + list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/${CMAKE_SYSTEM_PROCESSOR}" ) + elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/thumb/bits" ) + list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/thumb" ) + else() + list( APPEND ANDROID_STL_INCLUDE_DIRS "${ANDROID_STL_INCLUDE_DIRS}/${ANDROID_TOOLCHAIN_MACHINE_NAME}" ) + endif() + # always search static GNU STL to get the location of libsupc++.a + if( ARMEABI_V7A AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb/libstdc++.a" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb" ) + elseif( ARMEABI_V7A AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libstdc++.a" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}" ) + elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libstdc++.a" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb" ) + elseif( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libstdc++.a" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib" ) + endif() + if( __libstl ) + set( __libsupcxx "${__libstl}/libsupc++.a" ) + set( __libstl "${__libstl}/libstdc++.a" ) + endif() + if( NOT EXISTS "${__libsupcxx}" ) + message( FATAL_ERROR "The required libstdsupc++.a is missing in your standalone toolchain. + Usually it happens because of bug in make-standalone-toolchain.sh script from NDK r7, r7b and r7c. + You need to either upgrade to newer NDK or manually copy + $ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a + to + ${__libsupcxx} + " ) + endif() + if( ANDROID_STL STREQUAL "gnustl_shared" ) + if( ARMEABI_V7A AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libgnustl_shared.so" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libgnustl_shared.so" ) + elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD AND EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libgnustl_shared.so" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libgnustl_shared.so" ) + elseif( EXISTS "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libgnustl_shared.so" ) + set( __libstl "${ANDROID_STANDALONE_TOOLCHAIN}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libgnustl_shared.so" ) + endif() + endif() + endif() +endif() + +# clang +if( "${ANDROID_TOOLCHAIN_NAME}" STREQUAL "standalone-clang" ) + set( ANDROID_COMPILER_IS_CLANG 1 ) + execute_process( COMMAND "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/clang${TOOL_OS_SUFFIX}" --version OUTPUT_VARIABLE ANDROID_CLANG_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE ) + string( REGEX MATCH "[0-9]+[.][0-9]+" ANDROID_CLANG_VERSION "${ANDROID_CLANG_VERSION}") +elseif( "${ANDROID_TOOLCHAIN_NAME}" MATCHES "-clang3[.][0-9]?$" ) + string( REGEX MATCH "3[.][0-9]$" ANDROID_CLANG_VERSION "${ANDROID_TOOLCHAIN_NAME}") + string( REGEX REPLACE "-clang${ANDROID_CLANG_VERSION}$" "-4.6" ANDROID_GCC_TOOLCHAIN_NAME "${ANDROID_TOOLCHAIN_NAME}" ) + if( NOT EXISTS "${ANDROID_NDK_TOOLCHAINS_PATH}/llvm-${ANDROID_CLANG_VERSION}${ANDROID_NDK_TOOLCHAINS_SUBPATH}/bin/clang${TOOL_OS_SUFFIX}" ) + message( FATAL_ERROR "Could not find the Clang compiler driver" ) + endif() + set( ANDROID_COMPILER_IS_CLANG 1 ) + set( ANDROID_CLANG_TOOLCHAIN_ROOT "${ANDROID_NDK_TOOLCHAINS_PATH}/llvm-${ANDROID_CLANG_VERSION}${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) +else() + set( ANDROID_GCC_TOOLCHAIN_NAME "${ANDROID_TOOLCHAIN_NAME}" ) + unset( ANDROID_COMPILER_IS_CLANG CACHE ) +endif() + +string( REPLACE "." "" _clang_name "clang${ANDROID_CLANG_VERSION}" ) +if( NOT EXISTS "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" ) + set( _clang_name "clang" ) +endif() + + +# setup paths and STL for NDK +if( BUILD_WITH_ANDROID_NDK ) + set( ANDROID_TOOLCHAIN_ROOT "${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}${ANDROID_NDK_TOOLCHAINS_SUBPATH}" ) + set( ANDROID_SYSROOT "${ANDROID_NDK}/platforms/android-${ANDROID_NATIVE_API_LEVEL}/arch-${ANDROID_ARCH_NAME}" ) + + if( ANDROID_STL STREQUAL "none" ) + # do nothing + elseif( ANDROID_STL STREQUAL "system" ) + set( ANDROID_RTTI OFF ) + set( ANDROID_EXCEPTIONS OFF ) + set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/system/include" ) + elseif( ANDROID_STL STREQUAL "system_re" ) + set( ANDROID_RTTI ON ) + set( ANDROID_EXCEPTIONS ON ) + set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/system/include" ) + elseif( ANDROID_STL MATCHES "gabi" ) + if( ANDROID_NDK_RELEASE STRLESS "r7" ) + message( FATAL_ERROR "gabi++ is not awailable in your NDK. You have to upgrade to NDK r7 or newer to use gabi++.") + endif() + set( ANDROID_RTTI ON ) + set( ANDROID_EXCEPTIONS OFF ) + set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/gabi++/include" ) + set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gabi++/libs/${ANDROID_NDK_ABI_NAME}/libgabi++_static.a" ) + elseif( ANDROID_STL MATCHES "stlport" ) + if( NOT ANDROID_NDK_RELEASE STRLESS "r8d" ) + set( ANDROID_EXCEPTIONS ON ) + else() + set( ANDROID_EXCEPTIONS OFF ) + endif() + if( ANDROID_NDK_RELEASE STRLESS "r7" ) + set( ANDROID_RTTI OFF ) + else() + set( ANDROID_RTTI ON ) + endif() + set( ANDROID_STL_INCLUDE_DIRS "${ANDROID_NDK}/sources/cxx-stl/stlport/stlport" ) + set( __libstl "${ANDROID_NDK}/sources/cxx-stl/stlport/libs/${ANDROID_NDK_ABI_NAME}/libstlport_static.a" ) + elseif( ANDROID_STL MATCHES "gnustl" ) + set( ANDROID_EXCEPTIONS ON ) + set( ANDROID_RTTI ON ) + if( EXISTS "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}" ) + if( ARMEABI_V7A AND ANDROID_COMPILER_VERSION VERSION_EQUAL "4.7" AND ANDROID_NDK_RELEASE STREQUAL "r8d" ) + # gnustl binary for 4.7 compiler is buggy :( + # TODO: look for right fix + set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/4.6" ) + else() + set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}" ) + endif() + else() + set( __libstl "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++" ) + endif() + set( ANDROID_STL_INCLUDE_DIRS "${__libstl}/include" "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/include" ) + if( EXISTS "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libgnustl_static.a" ) + set( __libstl "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libgnustl_static.a" ) + else() + set( __libstl "${__libstl}/libs/${ANDROID_NDK_ABI_NAME}/libstdc++.a" ) + endif() + else() + message( FATAL_ERROR "Unknown runtime: ${ANDROID_STL}" ) + endif() + # find libsupc++.a - rtti & exceptions + if( ANDROID_STL STREQUAL "system_re" OR ANDROID_STL MATCHES "gnustl" ) + set( __libsupcxx "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/${ANDROID_COMPILER_VERSION}/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a" ) # r8b or newer + if( NOT EXISTS "${__libsupcxx}" ) + set( __libsupcxx "${ANDROID_NDK}/sources/cxx-stl/gnu-libstdc++/libs/${ANDROID_NDK_ABI_NAME}/libsupc++.a" ) # r7-r8 + endif() + if( NOT EXISTS "${__libsupcxx}" ) # before r7 + if( ARMEABI_V7A ) + if( ANDROID_FORCE_ARM_BUILD ) + set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/libsupc++.a" ) + else() + set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/${CMAKE_SYSTEM_PROCESSOR}/thumb/libsupc++.a" ) + endif() + elseif( ARMEABI AND NOT ANDROID_FORCE_ARM_BUILD ) + set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/thumb/libsupc++.a" ) + else() + set( __libsupcxx "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}/lib/libsupc++.a" ) + endif() + endif() + if( NOT EXISTS "${__libsupcxx}") + message( ERROR "Could not find libsupc++.a for a chosen platform. Either your NDK is not supported or is broken.") + endif() + endif() +endif() + + +# case of shared STL linkage +if( ANDROID_STL MATCHES "shared" AND DEFINED __libstl ) + string( REPLACE "_static.a" "_shared.so" __libstl "${__libstl}" ) + # TODO: check if .so file exists before the renaming +endif() + + +# ccache support +__INIT_VARIABLE( _ndk_ccache NDK_CCACHE ENV_NDK_CCACHE ) +if( _ndk_ccache ) + if( DEFINED NDK_CCACHE AND NOT EXISTS NDK_CCACHE ) + unset( NDK_CCACHE CACHE ) + endif() + find_program( NDK_CCACHE "${_ndk_ccache}" DOC "The path to ccache binary") +else() + unset( NDK_CCACHE CACHE ) +endif() +unset( _ndk_ccache ) + + +# setup the cross-compiler +if( NOT CMAKE_C_COMPILER ) + if( NDK_CCACHE AND NOT ANDROID_SYSROOT MATCHES "[ ;\"]" ) + set( CMAKE_C_COMPILER "${NDK_CCACHE}" CACHE PATH "ccache as C compiler" ) + set( CMAKE_CXX_COMPILER "${NDK_CCACHE}" CACHE PATH "ccache as C++ compiler" ) + if( ANDROID_COMPILER_IS_CLANG ) + set( CMAKE_C_COMPILER_ARG1 "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" CACHE PATH "C compiler") + set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler") + else() + set( CMAKE_C_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "C compiler") + set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler") + endif() + else() + if( ANDROID_COMPILER_IS_CLANG ) + set( CMAKE_C_COMPILER "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}${TOOL_OS_SUFFIX}" CACHE PATH "C compiler") + set( CMAKE_CXX_COMPILER "${ANDROID_CLANG_TOOLCHAIN_ROOT}/bin/${_clang_name}++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler") + else() + set( CMAKE_C_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "C compiler" ) + set( CMAKE_CXX_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}" CACHE PATH "C++ compiler" ) + endif() + endif() + set( CMAKE_ASM_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}" CACHE PATH "assembler" ) + set( CMAKE_STRIP "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-strip${TOOL_OS_SUFFIX}" CACHE PATH "strip" ) + set( CMAKE_AR "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ar${TOOL_OS_SUFFIX}" CACHE PATH "archive" ) + set( CMAKE_LINKER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ld${TOOL_OS_SUFFIX}" CACHE PATH "linker" ) + set( CMAKE_NM "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-nm${TOOL_OS_SUFFIX}" CACHE PATH "nm" ) + set( CMAKE_OBJCOPY "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-objcopy${TOOL_OS_SUFFIX}" CACHE PATH "objcopy" ) + set( CMAKE_OBJDUMP "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-objdump${TOOL_OS_SUFFIX}" CACHE PATH "objdump" ) + set( CMAKE_RANLIB "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-ranlib${TOOL_OS_SUFFIX}" CACHE PATH "ranlib" ) +endif() + +set( _CMAKE_TOOLCHAIN_PREFIX "${ANDROID_TOOLCHAIN_MACHINE_NAME}-" ) +if( CMAKE_VERSION VERSION_LESS 2.8.5 ) + set( CMAKE_ASM_COMPILER_ARG1 "-c" ) +endif() +if( APPLE ) + find_program( CMAKE_INSTALL_NAME_TOOL NAMES install_name_tool ) + if( NOT CMAKE_INSTALL_NAME_TOOL ) + message( FATAL_ERROR "Could not find install_name_tool, please check your installation." ) + endif() + mark_as_advanced( CMAKE_INSTALL_NAME_TOOL ) +endif() + +# Force set compilers because standard identification works badly for us +include( CMakeForceCompiler ) +CMAKE_FORCE_C_COMPILER( "${CMAKE_C_COMPILER}" GNU ) +if( ANDROID_COMPILER_IS_CLANG ) + set( CMAKE_C_COMPILER_ID Clang) +endif() +set( CMAKE_C_PLATFORM_ID Linux ) +set( CMAKE_C_SIZEOF_DATA_PTR 4 ) +set( CMAKE_C_HAS_ISYSROOT 1 ) +set( CMAKE_C_COMPILER_ABI ELF ) +CMAKE_FORCE_CXX_COMPILER( "${CMAKE_CXX_COMPILER}" GNU ) +if( ANDROID_COMPILER_IS_CLANG ) + set( CMAKE_CXX_COMPILER_ID Clang) +endif() +set( CMAKE_CXX_PLATFORM_ID Linux ) +set( CMAKE_CXX_SIZEOF_DATA_PTR 4 ) +set( CMAKE_CXX_HAS_ISYSROOT 1 ) +set( CMAKE_CXX_COMPILER_ABI ELF ) +set( CMAKE_CXX_SOURCE_FILE_EXTENSIONS cc cp cxx cpp CPP c++ C ) +# force ASM compiler (required for CMake < 2.8.5) +set( CMAKE_ASM_COMPILER_ID_RUN TRUE ) +set( CMAKE_ASM_COMPILER_ID GNU ) +set( CMAKE_ASM_COMPILER_WORKS TRUE ) +set( CMAKE_ASM_COMPILER_FORCED TRUE ) +set( CMAKE_COMPILER_IS_GNUASM 1) +set( CMAKE_ASM_SOURCE_FILE_EXTENSIONS s S asm ) + +# flags and definitions +remove_definitions( -DANDROID ) +add_definitions( -DANDROID ) + +if( ANDROID_SYSROOT MATCHES "[ ;\"]" ) + if( CMAKE_HOST_WIN32 ) + # try to convert path to 8.3 form + file( WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cvt83.cmd" "@echo %~s1" ) + execute_process( COMMAND "$ENV{ComSpec}" /c "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cvt83.cmd" "${ANDROID_SYSROOT}" + OUTPUT_VARIABLE __path OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE __result ERROR_QUIET ) + if( __result EQUAL 0 ) + file( TO_CMAKE_PATH "${__path}" ANDROID_SYSROOT ) + set( ANDROID_CXX_FLAGS "--sysroot=${ANDROID_SYSROOT}" ) + else() + set( ANDROID_CXX_FLAGS "--sysroot=\"${ANDROID_SYSROOT}\"" ) + endif() + else() + set( ANDROID_CXX_FLAGS "'--sysroot=${ANDROID_SYSROOT}'" ) + endif() + if( NOT _CMAKE_IN_TRY_COMPILE ) + # quotes can break try_compile and compiler identification + message(WARNING "Path to your Android NDK (or toolchain) has non-alphanumeric symbols.\nThe build might be broken.\n") + endif() +else() + set( ANDROID_CXX_FLAGS "--sysroot=${ANDROID_SYSROOT}" ) +endif() + +# NDK flags +if( ARMEABI OR ARMEABI_V7A ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fpic -funwind-tables" ) + if( NOT ANDROID_FORCE_ARM_BUILD AND NOT ARMEABI_V6 ) + set( ANDROID_CXX_FLAGS_RELEASE "-mthumb -fomit-frame-pointer -fno-strict-aliasing" ) + set( ANDROID_CXX_FLAGS_DEBUG "-marm -fno-omit-frame-pointer -fno-strict-aliasing" ) + if( NOT ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -finline-limit=64" ) + endif() + else() + # always compile ARMEABI_V6 in arm mode; otherwise there is no difference from ARMEABI + set( ANDROID_CXX_FLAGS_RELEASE "-marm -fomit-frame-pointer -fstrict-aliasing" ) + set( ANDROID_CXX_FLAGS_DEBUG "-marm -fno-omit-frame-pointer -fno-strict-aliasing" ) + if( NOT ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funswitch-loops -finline-limit=300" ) + endif() + endif() +elseif( X86 ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funwind-tables" ) + if( NOT ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -funswitch-loops -finline-limit=300" ) + else() + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fPIC" ) + endif() + set( ANDROID_CXX_FLAGS_RELEASE "-fomit-frame-pointer -fstrict-aliasing" ) + set( ANDROID_CXX_FLAGS_DEBUG "-fno-omit-frame-pointer -fno-strict-aliasing" ) +elseif( MIPS ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fpic -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0" ) + set( ANDROID_CXX_FLAGS_RELEASE "-fomit-frame-pointer" ) + set( ANDROID_CXX_FLAGS_DEBUG "-fno-omit-frame-pointer" ) + if( NOT ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" ) + set( ANDROID_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} -funswitch-loops -finline-limit=300" ) + endif() +elseif() + set( ANDROID_CXX_FLAGS_RELEASE "" ) + set( ANDROID_CXX_FLAGS_DEBUG "" ) +endif() + +set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" ) # good/necessary when porting desktop libraries + +if( NOT X86 AND NOT ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "-Wno-psabi ${ANDROID_CXX_FLAGS}" ) +endif() + +if( NOT ANDROID_COMPILER_VERSION VERSION_LESS "4.6" ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -no-canonical-prefixes" ) # see https://android-review.googlesource.com/#/c/47564/ +endif() + +# ABI-specific flags +if( ARMEABI_V7A ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv7-a -mfloat-abi=softfp" ) + if( NEON ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=neon" ) + elseif( VFPV3 ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=vfpv3" ) + else() + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -mfpu=vfpv3-d16" ) + endif() +elseif( ARMEABI_V6 ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv6 -mfloat-abi=softfp -mfpu=vfp" ) # vfp == vfpv2 +elseif( ARMEABI ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -march=armv5te -mtune=xscale -msoft-float" ) +endif() + +if( ANDROID_STL MATCHES "gnustl" AND (EXISTS "${__libstl}" OR EXISTS "${__libsupcxx}") ) + set( CMAKE_CXX_CREATE_SHARED_LIBRARY " -o " ) + set( CMAKE_CXX_CREATE_SHARED_MODULE " -o " ) + set( CMAKE_CXX_LINK_EXECUTABLE " -o " ) +else() + set( CMAKE_CXX_CREATE_SHARED_LIBRARY " -o " ) + set( CMAKE_CXX_CREATE_SHARED_MODULE " -o " ) + set( CMAKE_CXX_LINK_EXECUTABLE " -o " ) +endif() + +# STL +if( EXISTS "${__libstl}" OR EXISTS "${__libsupcxx}" ) + if( EXISTS "${__libstl}" ) + set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${__libstl}\"" ) + set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${__libstl}\"" ) + set( CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} \"${__libstl}\"" ) + endif() + if( EXISTS "${__libsupcxx}" ) + set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${__libsupcxx}\"" ) + set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${__libsupcxx}\"" ) + set( CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} \"${__libsupcxx}\"" ) + # C objects: + set( CMAKE_C_CREATE_SHARED_LIBRARY " -o " ) + set( CMAKE_C_CREATE_SHARED_MODULE " -o " ) + set( CMAKE_C_LINK_EXECUTABLE " -o " ) + set( CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY} \"${__libsupcxx}\"" ) + set( CMAKE_C_CREATE_SHARED_MODULE "${CMAKE_C_CREATE_SHARED_MODULE} \"${__libsupcxx}\"" ) + set( CMAKE_C_LINK_EXECUTABLE "${CMAKE_C_LINK_EXECUTABLE} \"${__libsupcxx}\"" ) + endif() + if( ANDROID_STL MATCHES "gnustl" ) + if( NOT EXISTS "${ANDROID_LIBM_PATH}" ) + set( ANDROID_LIBM_PATH -lm ) + endif() + set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} ${ANDROID_LIBM_PATH}" ) + set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} ${ANDROID_LIBM_PATH}" ) + set( CMAKE_CXX_LINK_EXECUTABLE "${CMAKE_CXX_LINK_EXECUTABLE} ${ANDROID_LIBM_PATH}" ) + endif() +endif() + +# variables controlling optional build flags +if (ANDROID_NDK_RELEASE STRLESS "r7") + # libGLESv2.so in NDK's prior to r7 refers to missing external symbols. + # So this flag option is required for all projects using OpenGL from native. + __INIT_VARIABLE( ANDROID_SO_UNDEFINED VALUES ON ) +else() + __INIT_VARIABLE( ANDROID_SO_UNDEFINED VALUES OFF ) +endif() +__INIT_VARIABLE( ANDROID_NO_UNDEFINED OBSOLETE_NO_UNDEFINED VALUES ON ) +__INIT_VARIABLE( ANDROID_FUNCTION_LEVEL_LINKING VALUES ON ) +__INIT_VARIABLE( ANDROID_GOLD_LINKER VALUES ON ) +__INIT_VARIABLE( ANDROID_NOEXECSTACK VALUES ON ) +__INIT_VARIABLE( ANDROID_RELRO VALUES ON ) + +set( ANDROID_NO_UNDEFINED ${ANDROID_NO_UNDEFINED} CACHE BOOL "Show all undefined symbols as linker errors" ) +set( ANDROID_SO_UNDEFINED ${ANDROID_SO_UNDEFINED} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" ) +set( ANDROID_FUNCTION_LEVEL_LINKING ${ANDROID_FUNCTION_LEVEL_LINKING} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" ) +set( ANDROID_GOLD_LINKER ${ANDROID_GOLD_LINKER} CACHE BOOL "Enables gold linker (only avaialble for NDK r8b for ARM and x86 architectures on linux-86 and darwin-x86 hosts)" ) +set( ANDROID_NOEXECSTACK ${ANDROID_NOEXECSTACK} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" ) +set( ANDROID_RELRO ${ANDROID_RELRO} CACHE BOOL "Enables RELRO - a memory corruption mitigation technique" ) +mark_as_advanced( ANDROID_NO_UNDEFINED ANDROID_SO_UNDEFINED ANDROID_FUNCTION_LEVEL_LINKING ANDROID_GOLD_LINKER ANDROID_NOEXECSTACK ANDROID_RELRO ) + +# linker flags +set( ANDROID_LINKER_FLAGS "" ) + +if( ARMEABI_V7A ) + # this is *required* to use the following linker flags that routes around + # a CPU bug in some Cortex-A8 implementations: + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--fix-cortex-a8" ) +endif() + +if( ANDROID_NO_UNDEFINED ) + if( MIPS ) + # there is some sysroot-related problem in mips linker... + if( NOT ANDROID_SYSROOT MATCHES "[ ;\"]" ) + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--no-undefined -Wl,-rpath-link,${ANDROID_SYSROOT}/usr/lib" ) + endif() + else() + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--no-undefined" ) + endif() +endif() + +if( ANDROID_SO_UNDEFINED ) + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-allow-shlib-undefined" ) +endif() + +if( ANDROID_FUNCTION_LEVEL_LINKING ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fdata-sections -ffunction-sections" ) + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,--gc-sections" ) +endif() + +if( ANDROID_COMPILER_VERSION VERSION_EQUAL "4.6" ) + if( ANDROID_GOLD_LINKER AND (CMAKE_HOST_UNIX OR ANDROID_NDK_RELEASE STRGREATER "r8b") AND (ARMEABI OR ARMEABI_V7A OR X86) ) + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=gold" ) + elseif( ANDROID_NDK_RELEASE STRGREATER "r8b") + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=bfd" ) + elseif( ANDROID_NDK_RELEASE STREQUAL "r8b" AND ARMEABI AND NOT _CMAKE_IN_TRY_COMPILE ) + message( WARNING "The default bfd linker from arm GCC 4.6 toolchain can fail with 'unresolvable R_ARM_THM_CALL relocation' error message. See https://code.google.com/p/android/issues/detail?id=35342 + On Linux and OS X host platform you can workaround this problem using gold linker (default). + Rerun cmake with -DANDROID_GOLD_LINKER=ON option in case of problems. +" ) + endif() +endif() # version 4.6 + +if( ANDROID_NOEXECSTACK ) + if( ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -Xclang -mnoexecstack" ) + else() + set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -Wa,--noexecstack" ) + endif() + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-z,noexecstack" ) +endif() + +if( ANDROID_RELRO ) + set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -Wl,-z,relro -Wl,-z,now" ) +endif() + +if( ANDROID_COMPILER_IS_CLANG ) + set( ANDROID_CXX_FLAGS "-Qunused-arguments ${ANDROID_CXX_FLAGS}" ) + if( ARMEABI_V7A AND NOT ANDROID_FORCE_ARM_BUILD ) + set( ANDROID_CXX_FLAGS_RELEASE "-target thumbv7-none-linux-androideabi ${ANDROID_CXX_FLAGS_RELEASE}" ) + set( ANDROID_CXX_FLAGS_DEBUG "-target ${ANDROID_LLVM_TRIPLE} ${ANDROID_CXX_FLAGS_DEBUG}" ) + else() + set( ANDROID_CXX_FLAGS "-target ${ANDROID_LLVM_TRIPLE} ${ANDROID_CXX_FLAGS}" ) + endif() + if( BUILD_WITH_ANDROID_NDK ) + set( ANDROID_CXX_FLAGS "-gcc-toolchain ${ANDROID_TOOLCHAIN_ROOT} ${ANDROID_CXX_FLAGS}" ) + endif() +endif() + +INCLUDE_DIRECTORIES( SYSTEM ${ANDROID_NDK}/sources/android/cpufeatures) +INCLUDE_DIRECTORIES( SYSTEM ${ANDROID_NDK}/sources/android/native_app_glue) +INCLUDE_DIRECTORIES( SYSTEM ${ANDROID_NDK}/sources/android/support/include) + +# cache flags +set( CMAKE_CXX_FLAGS "" CACHE STRING "c++ flags" ) +set( CMAKE_C_FLAGS "" CACHE STRING "c flags" ) +set( CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG" CACHE STRING "c++ Release flags" ) +set( CMAKE_C_FLAGS_RELEASE "-O3 -DNDEBUG" CACHE STRING "c Release flags" ) +set( CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DDEBUG -D_DEBUG" CACHE STRING "c++ Debug flags" ) +set( CMAKE_C_FLAGS_DEBUG "-O0 -g -DDEBUG -D_DEBUG" CACHE STRING "c Debug flags" ) +set( CMAKE_SHARED_LINKER_FLAGS "" CACHE STRING "shared linker flags" ) +set( CMAKE_MODULE_LINKER_FLAGS "" CACHE STRING "module linker flags" ) +set( CMAKE_EXE_LINKER_FLAGS "-Wl,-z,nocopyreloc" CACHE STRING "executable linker flags" ) + +# put flags to cache (for debug purpose only) +set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS}" CACHE INTERNAL "Android specific c/c++ flags" ) +set( ANDROID_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE}" CACHE INTERNAL "Android specific c/c++ Release flags" ) +set( ANDROID_CXX_FLAGS_DEBUG "${ANDROID_CXX_FLAGS_DEBUG}" CACHE INTERNAL "Android specific c/c++ Debug flags" ) +set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS}" CACHE INTERNAL "Android specific c/c++ linker flags" ) + +# finish flags +set( CMAKE_CXX_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" ) +set( CMAKE_C_FLAGS "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" ) +set( CMAKE_CXX_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}" ) +set( CMAKE_C_FLAGS_RELEASE "${ANDROID_CXX_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}" ) +set( CMAKE_CXX_FLAGS_DEBUG "${ANDROID_CXX_FLAGS_DEBUG} ${CMAKE_CXX_FLAGS_DEBUG}" ) +set( CMAKE_C_FLAGS_DEBUG "${ANDROID_CXX_FLAGS_DEBUG} ${CMAKE_C_FLAGS_DEBUG}" ) +set( CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" ) +set( CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" ) +set( CMAKE_EXE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" ) + +if( MIPS AND BUILD_WITH_ANDROID_NDK AND ANDROID_NDK_RELEASE STREQUAL "r8" ) + set( CMAKE_SHARED_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.xsc ${CMAKE_SHARED_LINKER_FLAGS}" ) + set( CMAKE_MODULE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.xsc ${CMAKE_MODULE_LINKER_FLAGS}" ) + set( CMAKE_EXE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK_TOOLCHAINS_PATH}/${ANDROID_GCC_TOOLCHAIN_NAME}/mipself.x ${CMAKE_EXE_LINKER_FLAGS}" ) +endif() + +# configure rtti +if( DEFINED ANDROID_RTTI AND ANDROID_STL_FORCE_FEATURES ) + if( ANDROID_RTTI ) + set( CMAKE_CXX_FLAGS "-frtti ${CMAKE_CXX_FLAGS}" ) + else() + set( CMAKE_CXX_FLAGS "-fno-rtti ${CMAKE_CXX_FLAGS}" ) + endif() +endif() + +# configure exceptios +if( DEFINED ANDROID_EXCEPTIONS AND ANDROID_STL_FORCE_FEATURES ) + if( ANDROID_EXCEPTIONS ) + set( CMAKE_CXX_FLAGS "-fexceptions ${CMAKE_CXX_FLAGS}" ) + set( CMAKE_C_FLAGS "-fexceptions ${CMAKE_C_FLAGS}" ) + else() + set( CMAKE_CXX_FLAGS "-fno-exceptions ${CMAKE_CXX_FLAGS}" ) + set( CMAKE_C_FLAGS "-fno-exceptions ${CMAKE_C_FLAGS}" ) + endif() +endif() + +# global includes and link directories +include_directories( SYSTEM "${ANDROID_SYSROOT}/usr/include" ${ANDROID_STL_INCLUDE_DIRS} ) +get_filename_component(__android_install_path "${CMAKE_INSTALL_PREFIX}/libs/${ANDROID_NDK_ABI_NAME}" ABSOLUTE) # avoid CMP0015 policy warning +link_directories( "${__android_install_path}" ) + +# detect if need link crtbegin_so.o explicitly +if( NOT DEFINED ANDROID_EXPLICIT_CRT_LINK ) + set( __cmd "${CMAKE_CXX_CREATE_SHARED_LIBRARY}" ) + string( REPLACE "" "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1}" __cmd "${__cmd}" ) + string( REPLACE "" "${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}" __cmd "${__cmd}" ) + string( REPLACE "" "${CMAKE_CXX_FLAGS}" __cmd "${__cmd}" ) + string( REPLACE "" "" __cmd "${__cmd}" ) + string( REPLACE "" "${CMAKE_SHARED_LINKER_FLAGS}" __cmd "${__cmd}" ) + string( REPLACE "" "-shared" __cmd "${__cmd}" ) + string( REPLACE "" "" __cmd "${__cmd}" ) + string( REPLACE "" "" __cmd "${__cmd}" ) + string( REPLACE "" "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/toolchain_crtlink_test.so" __cmd "${__cmd}" ) + string( REPLACE "" "\"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" __cmd "${__cmd}" ) + string( REPLACE "" "" __cmd "${__cmd}" ) + separate_arguments( __cmd ) + foreach( __var ANDROID_NDK ANDROID_NDK_TOOLCHAINS_PATH ANDROID_STANDALONE_TOOLCHAIN ) + if( ${__var} ) + set( __tmp "${${__var}}" ) + separate_arguments( __tmp ) + string( REPLACE "${__tmp}" "${${__var}}" __cmd "${__cmd}") + endif() + endforeach() + string( REPLACE "'" "" __cmd "${__cmd}" ) + string( REPLACE "\"" "" __cmd "${__cmd}" ) + execute_process( COMMAND ${__cmd} RESULT_VARIABLE __cmd_result OUTPUT_QUIET ERROR_QUIET ) + if( __cmd_result EQUAL 0 ) + set( ANDROID_EXPLICIT_CRT_LINK ON ) + else() + set( ANDROID_EXPLICIT_CRT_LINK OFF ) + endif() +endif() + +if( ANDROID_EXPLICIT_CRT_LINK ) + set( CMAKE_CXX_CREATE_SHARED_LIBRARY "${CMAKE_CXX_CREATE_SHARED_LIBRARY} \"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" ) + set( CMAKE_CXX_CREATE_SHARED_MODULE "${CMAKE_CXX_CREATE_SHARED_MODULE} \"${ANDROID_SYSROOT}/usr/lib/crtbegin_so.o\"" ) +endif() + +# setup output directories +set( LIBRARY_OUTPUT_PATH_ROOT ${CMAKE_SOURCE_DIR} CACHE PATH "root for library output, set this to change where android libs are installed to" ) +set( CMAKE_INSTALL_PREFIX "${ANDROID_TOOLCHAIN_ROOT}/user" CACHE STRING "path for installing" ) + +if(NOT _CMAKE_IN_TRY_COMPILE) + if( EXISTS "${CMAKE_SOURCE_DIR}/jni/CMakeLists.txt" ) + set( EXECUTABLE_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/bin/${ANDROID_NDK_ABI_NAME}" CACHE PATH "Output directory for applications" ) + else() + set( EXECUTABLE_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/bin" CACHE PATH "Output directory for applications" ) + endif() + set( LIBRARY_OUTPUT_PATH "${LIBRARY_OUTPUT_PATH_ROOT}/libs/${ANDROID_NDK_ABI_NAME}" CACHE PATH "path for android libs" ) +endif() + +# copy shaed stl library to build directory +if( NOT _CMAKE_IN_TRY_COMPILE AND __libstl MATCHES "[.]so$" ) + get_filename_component( __libstlname "${__libstl}" NAME ) + execute_process( COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${__libstl}" "${LIBRARY_OUTPUT_PATH}/${__libstlname}" RESULT_VARIABLE __fileCopyProcess ) + if( NOT __fileCopyProcess EQUAL 0 OR NOT EXISTS "${LIBRARY_OUTPUT_PATH}/${__libstlname}") + message( SEND_ERROR "Failed copying of ${__libstl} to the ${LIBRARY_OUTPUT_PATH}/${__libstlname}" ) + endif() + unset( __fileCopyProcess ) + unset( __libstlname ) +endif() + + +# set these global flags for cmake client scripts to change behavior +set( ANDROID True ) +set( BUILD_ANDROID True ) + +# where is the target environment +set( CMAKE_FIND_ROOT_PATH "${ANDROID_TOOLCHAIN_ROOT}/bin" "${ANDROID_TOOLCHAIN_ROOT}/${ANDROID_TOOLCHAIN_MACHINE_NAME}" "${ANDROID_SYSROOT}" "${CMAKE_INSTALL_PREFIX}" "${CMAKE_INSTALL_PREFIX}/share" ) + +# only search for libraries and includes in the ndk toolchain +set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY ) +set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY ) +set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY ) + + +# macro to find packages on the host OS +macro( find_host_package ) + set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER ) + set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER ) + set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER ) + if( CMAKE_HOST_WIN32 ) + SET( WIN32 1 ) + SET( UNIX ) + elseif( CMAKE_HOST_APPLE ) + SET( APPLE 1 ) + SET( UNIX ) + endif() + find_package( ${ARGN} ) + SET( WIN32 ) + SET( APPLE ) + SET( UNIX 1 ) + set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY ) + set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY ) + set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY ) +endmacro() + + +# macro to find programs on the host OS +macro( find_host_program ) + set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER ) + set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER ) + set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER ) + if( CMAKE_HOST_WIN32 ) + SET( WIN32 1 ) + SET( UNIX ) + elseif( CMAKE_HOST_APPLE ) + SET( APPLE 1 ) + SET( UNIX ) + endif() + find_program( ${ARGN} ) + SET( WIN32 ) + SET( APPLE ) + SET( UNIX 1 ) + set( CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY ) + set( CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY ) + set( CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY ) +endmacro() + + +macro( ANDROID_GET_ABI_RAWNAME TOOLCHAIN_FLAG VAR ) + if( "${TOOLCHAIN_FLAG}" STREQUAL "ARMEABI" ) + set( ${VAR} "armeabi" ) + elseif( "${TOOLCHAIN_FLAG}" STREQUAL "ARMEABI_V7A" ) + set( ${VAR} "armeabi-v7a" ) + elseif( "${TOOLCHAIN_FLAG}" STREQUAL "X86" ) + set( ${VAR} "x86" ) + elseif( "${TOOLCHAIN_FLAG}" STREQUAL "MIPS" ) + set( ${VAR} "mips" ) + else() + set( ${VAR} "unknown" ) + endif() +endmacro() + + +# export toolchain settings for the try_compile() command +if( NOT PROJECT_NAME STREQUAL "CMAKE_TRY_COMPILE" ) + set( __toolchain_config "") + foreach( __var NDK_CCACHE LIBRARY_OUTPUT_PATH_ROOT ANDROID_FORBID_SYGWIN ANDROID_SET_OBSOLETE_VARIABLES + ANDROID_NDK_HOST_X64 + ANDROID_NDK + ANDROID_NDK_LAYOUT + ANDROID_STANDALONE_TOOLCHAIN + ANDROID_TOOLCHAIN_NAME + ANDROID_ABI + ANDROID_NATIVE_API_LEVEL + ANDROID_STL + ANDROID_STL_FORCE_FEATURES + ANDROID_FORCE_ARM_BUILD + ANDROID_NO_UNDEFINED + ANDROID_SO_UNDEFINED + ANDROID_FUNCTION_LEVEL_LINKING + ANDROID_GOLD_LINKER + ANDROID_NOEXECSTACK + ANDROID_RELRO + ANDROID_LIBM_PATH + ANDROID_EXPLICIT_CRT_LINK + ) + if( DEFINED ${__var} ) + if( "${__var}" MATCHES " ") + set( __toolchain_config "${__toolchain_config}set( ${__var} \"${${__var}}\" CACHE INTERNAL \"\" )\n" ) + else() + set( __toolchain_config "${__toolchain_config}set( ${__var} ${${__var}} CACHE INTERNAL \"\" )\n" ) + endif() + endif() + endforeach() + file( WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/android.toolchain.config.cmake" "${__toolchain_config}" ) + unset( __toolchain_config ) +endif() + + +# force cmake to produce / instead of \ in build commands for Ninja generator +if( CMAKE_GENERATOR MATCHES "Ninja" AND CMAKE_HOST_WIN32 ) + # it is a bad hack after all + # CMake generates Ninja makefiles with UNIX paths only if it thinks that we are going to build with MinGW + set( CMAKE_COMPILER_IS_MINGW TRUE ) # tell CMake that we are MinGW + set( CMAKE_CROSSCOMPILING TRUE ) # stop recursion + enable_language( C ) + enable_language( CXX ) + # unset( CMAKE_COMPILER_IS_MINGW ) # can't unset because CMake does not convert back-slashes in response files without it + unset( MINGW ) +endif() + + +# set some obsolete variables for backward compatibility +set( ANDROID_SET_OBSOLETE_VARIABLES ON CACHE BOOL "Define obsolete Andrid-specific cmake variables" ) +mark_as_advanced( ANDROID_SET_OBSOLETE_VARIABLES ) +if( ANDROID_SET_OBSOLETE_VARIABLES ) + set( ANDROID_API_LEVEL ${ANDROID_NATIVE_API_LEVEL} ) + set( ARM_TARGET "${ANDROID_ABI}" ) + set( ARMEABI_NDK_NAME "${ANDROID_NDK_ABI_NAME}" ) +endif() + + +# Variables controlling behavior or set by cmake toolchain: +# ANDROID_ABI : "armeabi-v7a" (default), "armeabi", "armeabi-v7a with NEON", "armeabi-v7a with VFPV3", "armeabi-v6 with VFP", "x86", "mips" +# ANDROID_NATIVE_API_LEVEL : 3,4,5,8,9,14 (depends on NDK version) +# ANDROID_STL : gnustl_static/gnustl_shared/stlport_static/stlport_shared/gabi++_static/gabi++_shared/system_re/system/none +# ANDROID_FORBID_SYGWIN : ON/OFF +# ANDROID_NO_UNDEFINED : ON/OFF +# ANDROID_SO_UNDEFINED : OFF/ON (default depends on NDK version) +# ANDROID_FUNCTION_LEVEL_LINKING : ON/OFF +# ANDROID_GOLD_LINKER : ON/OFF +# ANDROID_NOEXECSTACK : ON/OFF +# ANDROID_RELRO : ON/OFF +# ANDROID_FORCE_ARM_BUILD : ON/OFF +# ANDROID_STL_FORCE_FEATURES : ON/OFF +# ANDROID_SET_OBSOLETE_VARIABLES : ON/OFF +# Can be set only at the first run: +# ANDROID_NDK +# ANDROID_STANDALONE_TOOLCHAIN +# ANDROID_TOOLCHAIN_NAME : the NDK name of compiler toolchain +# ANDROID_NDK_HOST_X64 : try to use x86_64 toolchain (default for x64 host systems) +# ANDROID_NDK_LAYOUT : the inner NDK structure (RELEASE, LINARO, ANDROID) +# LIBRARY_OUTPUT_PATH_ROOT : +# NDK_CCACHE : +# Obsolete: +# ANDROID_API_LEVEL : superseded by ANDROID_NATIVE_API_LEVEL +# ARM_TARGET : superseded by ANDROID_ABI +# ARM_TARGETS : superseded by ANDROID_ABI (can be set only) +# ANDROID_NDK_TOOLCHAIN_ROOT : superseded by ANDROID_STANDALONE_TOOLCHAIN (can be set only) +# ANDROID_USE_STLPORT : superseded by ANDROID_STL=stlport_static +# ANDROID_LEVEL : superseded by ANDROID_NATIVE_API_LEVEL (completely removed) +# +# Primary read-only variables: +# ANDROID : always TRUE +# ARMEABI : TRUE for arm v6 and older devices +# ARMEABI_V6 : TRUE for arm v6 +# ARMEABI_V7A : TRUE for arm v7a +# NEON : TRUE if NEON unit is enabled +# VFPV3 : TRUE if VFP version 3 is enabled +# X86 : TRUE if configured for x86 +# MIPS : TRUE if configured for mips +# BUILD_ANDROID : always TRUE +# BUILD_WITH_ANDROID_NDK : TRUE if NDK is used +# BUILD_WITH_STANDALONE_TOOLCHAIN : TRUE if standalone toolchain is used +# ANDROID_NDK_HOST_SYSTEM_NAME : "windows", "linux-x86" or "darwin-x86" depending on host platform +# ANDROID_NDK_ABI_NAME : "armeabi", "armeabi-v7a", "x86" or "mips" depending on ANDROID_ABI +# ANDROID_NDK_RELEASE : one of r5, r5b, r5c, r6, r6b, r7, r7b, r7c, r8, r8b, r8c, r8d, r8e, r9, r9b, r9c; set only for NDK +# ANDROID_ARCH_NAME : "arm" or "x86" or "mips" depending on ANDROID_ABI +# ANDROID_SYSROOT : path to the compiler sysroot +# TOOL_OS_SUFFIX : "" or ".exe" depending on host platform +# ANDROID_COMPILER_IS_CLANG : TRUE if clang compiler is used +# Obsolete: +# ARMEABI_NDK_NAME : superseded by ANDROID_NDK_ABI_NAME +# +# Secondary (less stable) read-only variables: +# ANDROID_COMPILER_VERSION : GCC version used +# ANDROID_CXX_FLAGS : C/C++ compiler flags required by Android platform +# ANDROID_SUPPORTED_ABIS : list of currently allowed values for ANDROID_ABI +# ANDROID_TOOLCHAIN_MACHINE_NAME : "arm-linux-androideabi", "arm-eabi" or "i686-android-linux" +# ANDROID_TOOLCHAIN_ROOT : path to the top level of toolchain (standalone or placed inside NDK) +# ANDROID_CLANG_TOOLCHAIN_ROOT : path to clang tools +# ANDROID_SUPPORTED_NATIVE_API_LEVELS : list of native API levels found inside NDK +# ANDROID_STL_INCLUDE_DIRS : stl include paths +# ANDROID_RTTI : if rtti is enabled by the runtime +# ANDROID_EXCEPTIONS : if exceptions are enabled by the runtime +# ANDROID_GCC_TOOLCHAIN_NAME : read-only, differs from ANDROID_TOOLCHAIN_NAME only if clang is used +# ANDROID_CLANG_VERSION : version of clang compiler if clang is used +# ANDROID_LIBM_PATH : path to libm.so (set to something like $(TOP)/out/target/product//obj/lib/libm.so) to workaround unresolved `sincos` +# +# Defaults: +# ANDROID_DEFAULT_NDK_API_LEVEL +# ANDROID_DEFAULT_NDK_API_LEVEL_${ARCH} +# ANDROID_NDK_SEARCH_PATHS +# ANDROID_STANDALONE_TOOLCHAIN_SEARCH_PATH +# ANDROID_SUPPORTED_ABIS_${ARCH} +# ANDROID_SUPPORTED_NDK_VERSIONS diff --git a/datafiles/animations/GameMenu.anims b/datafiles/animations/GameMenuSample.anims similarity index 100% rename from datafiles/animations/GameMenu.anims rename to datafiles/animations/GameMenuSample.anims diff --git a/datafiles/animations/example.anims b/datafiles/animations/example.anims index 2743004be..6fcf5f083 100644 --- a/datafiles/animations/example.anims +++ b/datafiles/animations/example.anims @@ -5,7 +5,7 @@
- + @@ -13,7 +13,7 @@
- + diff --git a/datafiles/imagesets/GameMenu.imageset b/datafiles/imagesets/GameMenuSample.imageset similarity index 95% rename from datafiles/imagesets/GameMenu.imageset rename to datafiles/imagesets/GameMenuSample.imageset index 81b436e30..0165534c3 100644 --- a/datafiles/imagesets/GameMenu.imageset +++ b/datafiles/imagesets/GameMenuSample.imageset @@ -1,4 +1,4 @@ - + diff --git a/datafiles/imagesets/GameMenu.png b/datafiles/imagesets/GameMenuSample.png similarity index 100% rename from datafiles/imagesets/GameMenu.png rename to datafiles/imagesets/GameMenuSample.png diff --git a/datafiles/imagesets/HUDDemo.imageset b/datafiles/imagesets/RestaurantGameSample.imageset similarity index 93% rename from datafiles/imagesets/HUDDemo.imageset rename to datafiles/imagesets/RestaurantGameSample.imageset index 7b58be700..bf69053b0 100644 --- a/datafiles/imagesets/HUDDemo.imageset +++ b/datafiles/imagesets/RestaurantGameSample.imageset @@ -1,4 +1,4 @@ - + diff --git a/datafiles/imagesets/HUDDemo.png b/datafiles/imagesets/RestaurantGameSample.png similarity index 100% rename from datafiles/imagesets/HUDDemo.png rename to datafiles/imagesets/RestaurantGameSample.png diff --git a/datafiles/imagesets/HUDDemoGameOver.png b/datafiles/imagesets/RestaurantGameSampleGameOver.png similarity index 100% rename from datafiles/imagesets/HUDDemoGameOver.png rename to datafiles/imagesets/RestaurantGameSampleGameOver.png diff --git a/datafiles/imagesets/SVGSampleImage.svg b/datafiles/imagesets/SVGSampleImage.svg new file mode 100644 index 000000000..6286b9cbd --- /dev/null +++ b/datafiles/imagesets/SVGSampleImage.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/imagesets/SVGSampleImageset.imageset b/datafiles/imagesets/SVGSampleImageset.imageset new file mode 100644 index 000000000..2f5471cd3 --- /dev/null +++ b/datafiles/imagesets/SVGSampleImageset.imageset @@ -0,0 +1,4 @@ + + + + diff --git a/datafiles/imagesets/TaharezLook.imageset b/datafiles/imagesets/TaharezLook.imageset index cff0b0677..a050c8df4 100644 --- a/datafiles/imagesets/TaharezLook.imageset +++ b/datafiles/imagesets/TaharezLook.imageset @@ -241,4 +241,8 @@ + + + + \ No newline at end of file diff --git a/datafiles/imagesets/TaharezLook.png b/datafiles/imagesets/TaharezLook.png index 546fbe14e..f6055d2dd 100644 Binary files a/datafiles/imagesets/TaharezLook.png and b/datafiles/imagesets/TaharezLook.png differ diff --git a/datafiles/imagesets/ic_launcher.png b/datafiles/imagesets/ic_launcher.png new file mode 100644 index 000000000..1f50365c3 Binary files /dev/null and b/datafiles/imagesets/ic_launcher.png differ diff --git a/datafiles/layouts/Console.wnd b/datafiles/layouts/Console.layout similarity index 100% rename from datafiles/layouts/Console.wnd rename to datafiles/layouts/Console.layout diff --git a/datafiles/layouts/DragDropDemo.layout b/datafiles/layouts/DragDropSample.layout similarity index 96% rename from datafiles/layouts/DragDropDemo.layout rename to datafiles/layouts/DragDropSample.layout index 6fecf4d6e..42a478c13 100644 --- a/datafiles/layouts/DragDropDemo.layout +++ b/datafiles/layouts/DragDropSample.layout @@ -18,7 +18,7 @@ - + @@ -55,7 +55,7 @@ - + diff --git a/datafiles/layouts/EffectsDemo.layout b/datafiles/layouts/EffectsSample.layout similarity index 95% rename from datafiles/layouts/EffectsDemo.layout rename to datafiles/layouts/EffectsSample.layout index 9af674f7b..a6b8c98f9 100644 --- a/datafiles/layouts/EffectsDemo.layout +++ b/datafiles/layouts/EffectsSample.layout @@ -1,6 +1,6 @@ - + diff --git a/datafiles/layouts/FontsDemo.layout b/datafiles/layouts/FontsSample.layout similarity index 98% rename from datafiles/layouts/FontsDemo.layout rename to datafiles/layouts/FontsSample.layout index a45c9bd70..e02f105e4 100644 --- a/datafiles/layouts/FontsDemo.layout +++ b/datafiles/layouts/FontsSample.layout @@ -14,13 +14,12 @@ - - + - + - + diff --git a/datafiles/layouts/GameMenu.layout b/datafiles/layouts/GameMenuSample.layout similarity index 80% rename from datafiles/layouts/GameMenu.layout rename to datafiles/layouts/GameMenuSample.layout index b9bb20d95..96bb7f1b3 100644 --- a/datafiles/layouts/GameMenu.layout +++ b/datafiles/layouts/GameMenuSample.layout @@ -1,18 +1,18 @@ - + - + - + - + - + @@ -23,12 +23,12 @@ - + - + @@ -42,15 +42,15 @@ - + - + - + @@ -66,18 +66,18 @@ - + - + - + @@ -85,53 +85,53 @@ - + - + - + - + - + - + - + - - + + - + - + - + @@ -151,7 +151,7 @@ - + @@ -161,17 +161,17 @@ - + - + - + @@ -180,7 +180,7 @@ - + @@ -189,7 +189,7 @@ - + @@ -198,7 +198,7 @@ - + @@ -207,7 +207,7 @@ - + @@ -226,14 +226,14 @@ - + - + @@ -246,14 +246,14 @@ - + - + @@ -311,13 +311,13 @@ - + - + @@ -357,13 +357,13 @@ - + - + @@ -394,7 +394,7 @@ - + @@ -403,393 +403,393 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -797,10 +797,10 @@ - + - + @@ -815,36 +815,36 @@ - + - + - + - + - + - + - + - + diff --git a/datafiles/layouts/MenuNavigationSample.layout b/datafiles/layouts/MenuNavigationSample.layout new file mode 100644 index 000000000..93d6f02c5 --- /dev/null +++ b/datafiles/layouts/MenuNavigationSample.layout @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/layouts/MenuNavigationSampleTabPage1.layout b/datafiles/layouts/MenuNavigationSampleTabPage1.layout new file mode 100644 index 000000000..90d794a7b --- /dev/null +++ b/datafiles/layouts/MenuNavigationSampleTabPage1.layout @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/layouts/MenuNavigationSampleTabPage2.layout b/datafiles/layouts/MenuNavigationSampleTabPage2.layout new file mode 100644 index 000000000..a5084a7f4 --- /dev/null +++ b/datafiles/layouts/MenuNavigationSampleTabPage2.layout @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/layouts/ModelViewSample.layout b/datafiles/layouts/ModelViewSample.layout new file mode 100644 index 000000000..427f4740b --- /dev/null +++ b/datafiles/layouts/ModelViewSample.layout @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/layouts/HUDDemoGameOver.layout b/datafiles/layouts/RestaurantGameSampleGameOver.layout similarity index 76% rename from datafiles/layouts/HUDDemoGameOver.layout rename to datafiles/layouts/RestaurantGameSampleGameOver.layout index 0ea79032a..d9ca090cc 100644 --- a/datafiles/layouts/HUDDemoGameOver.layout +++ b/datafiles/layouts/RestaurantGameSampleGameOver.layout @@ -3,7 +3,7 @@ - + @@ -16,10 +16,10 @@ - - - - + + + + @@ -28,7 +28,7 @@ - + diff --git a/datafiles/layouts/HUDDemoIngame.layout b/datafiles/layouts/RestaurantGameSampleIngame.layout similarity index 86% rename from datafiles/layouts/HUDDemoIngame.layout rename to datafiles/layouts/RestaurantGameSampleIngame.layout index ffa7c7b60..8f0001981 100644 --- a/datafiles/layouts/HUDDemoIngame.layout +++ b/datafiles/layouts/RestaurantGameSampleIngame.layout @@ -1,40 +1,40 @@ - + - + - + - + - + - + - + - + @@ -51,7 +51,7 @@ - + @@ -60,7 +60,7 @@ - + @@ -88,14 +88,14 @@ - + - + @@ -103,14 +103,14 @@ - + - + @@ -118,7 +118,7 @@ - + @@ -126,7 +126,7 @@ - + @@ -134,7 +134,7 @@ - + @@ -142,7 +142,7 @@ - + @@ -150,7 +150,7 @@ - + @@ -161,7 +161,7 @@ - + @@ -169,7 +169,7 @@ - + @@ -179,7 +179,7 @@ - + @@ -188,7 +188,7 @@ - + @@ -198,7 +198,7 @@ - + @@ -207,7 +207,7 @@ - + @@ -218,7 +218,7 @@ - + @@ -233,7 +233,7 @@ - + @@ -248,36 +248,36 @@ - + - + - + - + - + - + diff --git a/datafiles/layouts/SampleBrowser.layout b/datafiles/layouts/SampleBrowser.layout index 12688dea9..c3237f95b 100644 --- a/datafiles/layouts/SampleBrowser.layout +++ b/datafiles/layouts/SampleBrowser.layout @@ -40,7 +40,7 @@ - + @@ -82,13 +82,13 @@ - + - + @@ -108,56 +108,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -187,7 +137,7 @@ - + diff --git a/datafiles/layouts/SimpleGameMenuSample.layout b/datafiles/layouts/SimpleGameMenuSample.layout new file mode 100644 index 000000000..e73210267 --- /dev/null +++ b/datafiles/layouts/SimpleGameMenuSample.layout @@ -0,0 +1,149 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/layouts/TabControlDemo.layout b/datafiles/layouts/TabControlSample.layout similarity index 94% rename from datafiles/layouts/TabControlDemo.layout rename to datafiles/layouts/TabControlSample.layout index 917979c5c..0098e522d 100644 --- a/datafiles/layouts/TabControlDemo.layout +++ b/datafiles/layouts/TabControlSample.layout @@ -2,7 +2,7 @@ - + diff --git a/datafiles/layouts/TabPage1.layout b/datafiles/layouts/TabPage1.layout index 7df6d3eab..b31c7de25 100644 --- a/datafiles/layouts/TabPage1.layout +++ b/datafiles/layouts/TabPage1.layout @@ -21,7 +21,7 @@ - + diff --git a/datafiles/layouts/TextDemo.layout b/datafiles/layouts/TextSample.layout similarity index 99% rename from datafiles/layouts/TextDemo.layout rename to datafiles/layouts/TextSample.layout index 8d350ea89..432ed61c8 100644 --- a/datafiles/layouts/TextDemo.layout +++ b/datafiles/layouts/TextSample.layout @@ -5,7 +5,7 @@ - + diff --git a/datafiles/layouts/TreeDemoTaharez.layout b/datafiles/layouts/TreeSampleTaharez.layout similarity index 91% rename from datafiles/layouts/TreeDemoTaharez.layout rename to datafiles/layouts/TreeSampleTaharez.layout index 6b171e197..d6b4ed58d 100644 --- a/datafiles/layouts/TreeDemoTaharez.layout +++ b/datafiles/layouts/TreeSampleTaharez.layout @@ -5,17 +5,17 @@ - + - + - + diff --git a/datafiles/layouts/VanillaWindows.layout b/datafiles/layouts/VanillaWindows.layout index 4a5e94be8..a15559953 100644 --- a/datafiles/layouts/VanillaWindows.layout +++ b/datafiles/layouts/VanillaWindows.layout @@ -14,7 +14,7 @@ - + @@ -72,7 +72,7 @@ - + diff --git a/datafiles/looknfeel/AlfiskoSkin.looknfeel b/datafiles/looknfeel/AlfiskoSkin.looknfeel index 3a1ffc6ac..68d44d600 100644 --- a/datafiles/looknfeel/AlfiskoSkin.looknfeel +++ b/datafiles/looknfeel/AlfiskoSkin.looknfeel @@ -904,7 +904,7 @@ - + @@ -994,7 +994,7 @@ - + @@ -1440,7 +1440,7 @@ - + @@ -1890,7 +1890,7 @@ - + @@ -2124,7 +2124,7 @@ - + @@ -2171,8 +2171,7 @@ - - + @@ -2251,7 +2250,7 @@ - + @@ -2299,8 +2298,7 @@ - - + @@ -2379,7 +2377,6 @@ - diff --git a/datafiles/looknfeel/GameMenu.looknfeel b/datafiles/looknfeel/GameMenuSample.looknfeel similarity index 71% rename from datafiles/looknfeel/GameMenu.looknfeel rename to datafiles/looknfeel/GameMenuSample.looknfeel index a29263c64..a5cc17a8d 100644 --- a/datafiles/looknfeel/GameMenu.looknfeel +++ b/datafiles/looknfeel/GameMenuSample.looknfeel @@ -1,59 +1,59 @@ - + - + - + - + - + - + - - - - - - - - - + + + + + + + + + - + @@ -65,7 +65,7 @@ - + diff --git a/datafiles/looknfeel/OgreTray.looknfeel b/datafiles/looknfeel/OgreTray.looknfeel index 294e16d8a..8ffb39520 100644 --- a/datafiles/looknfeel/OgreTray.looknfeel +++ b/datafiles/looknfeel/OgreTray.looknfeel @@ -4,7 +4,7 @@ This looknfeel specifies a set of WidgetLook definitions that are intended to recreate the overall look of Ogre's new SDK tray system within CEGUI. - + This looknfeel has been made for use in some upcoming recreations of the Ogre samples, that use CEGUI instead of the new Ogre SDK tray system. This is being done mostly for fun, though also to demonstrate the use of CEGUI @@ -474,7 +474,6 @@ --> - @@ -583,7 +582,6 @@ --> - @@ -2067,10 +2065,11 @@ - + + @@ -2332,7 +2331,7 @@ - + @@ -2797,8 +2796,7 @@ --> - - + @@ -3185,200 +3183,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - - + @@ -4323,7 +4128,6 @@ - diff --git a/datafiles/looknfeel/HUDDemo.looknfeel b/datafiles/looknfeel/RestaurantGameSample.looknfeel similarity index 92% rename from datafiles/looknfeel/HUDDemo.looknfeel rename to datafiles/looknfeel/RestaurantGameSample.looknfeel index 2eb422151..6680e11eb 100644 --- a/datafiles/looknfeel/HUDDemo.looknfeel +++ b/datafiles/looknfeel/RestaurantGameSample.looknfeel @@ -3,19 +3,19 @@ - + - + @@ -66,7 +66,7 @@ - + @@ -100,7 +100,7 @@ - + @@ -121,7 +121,7 @@ - + diff --git a/datafiles/looknfeel/SampleBrowser.looknfeel b/datafiles/looknfeel/SampleBrowser.looknfeel index 8c987036a..06ce1982e 100644 --- a/datafiles/looknfeel/SampleBrowser.looknfeel +++ b/datafiles/looknfeel/SampleBrowser.looknfeel @@ -120,7 +120,6 @@ - @@ -336,8 +335,8 @@ - - + + @@ -345,8 +344,8 @@ - - + + @@ -894,7 +893,6 @@ --> - @@ -961,7 +959,6 @@ --> - diff --git a/datafiles/looknfeel/TaharezLook.looknfeel b/datafiles/looknfeel/TaharezLook.looknfeel index 60f53eeb1..66912b3f2 100644 --- a/datafiles/looknfeel/TaharezLook.looknfeel +++ b/datafiles/looknfeel/TaharezLook.looknfeel @@ -56,7 +56,7 @@ - + @@ -112,6 +112,18 @@ + + + + + + + + + + + +
@@ -154,6 +166,14 @@
+ + +
+
+ +
+ + - + @@ -1238,8 +1292,7 @@ --> - - + @@ -1263,6 +1316,11 @@
+ + +
+ +
@@ -1279,7 +1337,7 @@ --> - + @@ -1381,6 +1439,13 @@
+ + +
+ +
+
+
@@ -1397,7 +1462,7 @@ --> - + @@ -1500,126 +1565,13 @@
- +
- +
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
@@ -1636,6 +1588,7 @@ --> + @@ -1759,7 +1712,7 @@ - + @@ -2243,7 +2196,7 @@ - + @@ -2405,7 +2358,7 @@ --> - + @@ -2535,6 +2488,11 @@
+ + +
+ +
@@ -2554,7 +2512,7 @@ - + @@ -2671,11 +2629,21 @@
+ + +
+ +
+ + +
+ +
@@ -2759,16 +2727,16 @@
- + - + - + @@ -2778,7 +2746,7 @@ - + @@ -2951,6 +2919,22 @@
+ + +
+
+ +
+ + + + +
+
+ +
+ +
@@ -3270,7 +3254,6 @@ - @@ -3625,7 +3608,7 @@ --> - + @@ -3893,12 +3876,88 @@ - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+
+ + +
+ +
+
+
+ + +
+
+ +
+ + + + +
+
+ +
+ + + + + + + + + @@ -3916,7 +3975,7 @@ - + @@ -3927,16 +3986,22 @@ - + + + + - + - + + + + @@ -3946,15 +4011,21 @@ - + - + + + + - + + + + @@ -3964,15 +4035,13 @@ - - + - @@ -3992,140 +4061,123 @@
- +
+ + +
+ +
+
+
- - - - - - - - - - + + + + + - - + + + + + + + - - + + + + + - - - - - - - - - - - - - - - - - - - - - - -
- -
-
-
- - -
- -
-
-
- - -
-
- -
- - - - -
-
- -
- - - - - - - - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + - - - - + + - + - + + - + @@ -4147,8 +4199,6 @@ - - diff --git a/datafiles/looknfeel/Vanilla.looknfeel b/datafiles/looknfeel/Vanilla.looknfeel index a0872aa1f..9161b9c6d 100644 --- a/datafiles/looknfeel/Vanilla.looknfeel +++ b/datafiles/looknfeel/Vanilla.looknfeel @@ -192,7 +192,6 @@ - @@ -710,7 +709,7 @@ - + @@ -752,7 +751,7 @@ - + @@ -1364,80 +1363,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
-
-
- - -
- -
-
-
-
+ @@ -1682,8 +1608,9 @@ - + + @@ -2221,7 +2148,7 @@ - + @@ -2290,16 +2217,16 @@
- + - + - + @@ -2309,8 +2236,84 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+
+ + +
+ +
+
+
+
diff --git a/datafiles/looknfeel/VanillaCommonDialogs.looknfeel b/datafiles/looknfeel/VanillaCommonDialogs.looknfeel index 4f97e01cf..311704177 100644 --- a/datafiles/looknfeel/VanillaCommonDialogs.looknfeel +++ b/datafiles/looknfeel/VanillaCommonDialogs.looknfeel @@ -3,7 +3,7 @@ - + @@ -55,8 +55,7 @@ - - + @@ -224,7 +223,7 @@ - + @@ -276,8 +275,7 @@ - - + diff --git a/datafiles/looknfeel/WindowsLook.looknfeel b/datafiles/looknfeel/WindowsLook.looknfeel index 7b10ba8e5..30ece996f 100644 --- a/datafiles/looknfeel/WindowsLook.looknfeel +++ b/datafiles/looknfeel/WindowsLook.looknfeel @@ -468,7 +468,6 @@ - @@ -564,6 +563,7 @@ --> + @@ -790,7 +790,7 @@ - + @@ -1296,7 +1296,6 @@ - @@ -1346,317 +1345,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - - + - + @@ -2503,7 +2191,7 @@ - + @@ -3141,7 +2829,7 @@ - + @@ -3358,7 +3046,6 @@ --> - @@ -3489,7 +3176,7 @@ - + @@ -3706,7 +3393,6 @@ --> - @@ -3832,7 +3518,7 @@ --> - + @@ -3905,8 +3591,7 @@ --> - - + @@ -5239,4 +4924,162 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + diff --git a/datafiles/schemes/AlfiskoSkin.scheme b/datafiles/schemes/AlfiskoSkin.scheme index 15303bbfa..ef25132e4 100644 --- a/datafiles/schemes/AlfiskoSkin.scheme +++ b/datafiles/schemes/AlfiskoSkin.scheme @@ -34,13 +34,11 @@ - + - - @@ -53,7 +51,6 @@ - --> diff --git a/datafiles/schemes/GameMenu.scheme b/datafiles/schemes/GameMenuSample.scheme similarity index 51% rename from datafiles/schemes/GameMenu.scheme rename to datafiles/schemes/GameMenuSample.scheme index d849c2cf5..2fa963afb 100644 --- a/datafiles/schemes/GameMenu.scheme +++ b/datafiles/schemes/GameMenuSample.scheme @@ -1,13 +1,13 @@ - + - + - + diff --git a/datafiles/schemes/HUDDemo.scheme b/datafiles/schemes/HUDDemo.scheme deleted file mode 100644 index 529cb446a..000000000 --- a/datafiles/schemes/HUDDemo.scheme +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/datafiles/schemes/OgreTray.scheme b/datafiles/schemes/OgreTray.scheme index fe38d1a1d..d96ae6003 100644 --- a/datafiles/schemes/OgreTray.scheme +++ b/datafiles/schemes/OgreTray.scheme @@ -18,8 +18,7 @@ - - + @@ -29,10 +28,9 @@ - - - + + @@ -45,5 +43,9 @@ + + + + diff --git a/datafiles/schemes/RestaurantGameSample.scheme b/datafiles/schemes/RestaurantGameSample.scheme new file mode 100644 index 000000000..5f39616a2 --- /dev/null +++ b/datafiles/schemes/RestaurantGameSample.scheme @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/datafiles/schemes/SampleBrowser.scheme b/datafiles/schemes/SampleBrowser.scheme index 1261d68bf..78839a233 100644 --- a/datafiles/schemes/SampleBrowser.scheme +++ b/datafiles/schemes/SampleBrowser.scheme @@ -20,6 +20,4 @@ - - - + \ No newline at end of file diff --git a/datafiles/schemes/TaharezLook.scheme b/datafiles/schemes/TaharezLook.scheme index 5893bf081..c186e6780 100644 --- a/datafiles/schemes/TaharezLook.scheme +++ b/datafiles/schemes/TaharezLook.scheme @@ -30,10 +30,9 @@ - + - @@ -44,9 +43,13 @@ - - + + + + + + diff --git a/datafiles/schemes/VanillaSkin.scheme b/datafiles/schemes/VanillaSkin.scheme index cef092c56..84c52b760 100644 --- a/datafiles/schemes/VanillaSkin.scheme +++ b/datafiles/schemes/VanillaSkin.scheme @@ -15,13 +15,16 @@ - - + + + + + diff --git a/datafiles/schemes/WindowsLook.scheme b/datafiles/schemes/WindowsLook.scheme index c81eb7db5..e5445c9a6 100644 --- a/datafiles/schemes/WindowsLook.scheme +++ b/datafiles/schemes/WindowsLook.scheme @@ -26,9 +26,8 @@ - + - @@ -40,10 +39,13 @@ - + + + + diff --git a/datafiles/xml_schemas/CEGUIConfig.xsd b/datafiles/xml_schemas/CEGUIConfig.xsd index 4c4d3cc79..95aa3de15 100644 --- a/datafiles/xml_schemas/CEGUIConfig.xsd +++ b/datafiles/xml_schemas/CEGUIConfig.xsd @@ -13,7 +13,7 @@ - + @@ -74,7 +74,7 @@ - + diff --git a/datafiles/xml_schemas/Falagard.xsd b/datafiles/xml_schemas/Falagard.xsd index a456a366c..a67defac1 100644 --- a/datafiles/xml_schemas/Falagard.xsd +++ b/datafiles/xml_schemas/Falagard.xsd @@ -185,7 +185,6 @@ - @@ -409,12 +408,12 @@ - - + + - + diff --git a/datafiles/xml_schemas/Imageset.xsd b/datafiles/xml_schemas/Imageset.xsd index 944b2d3a2..1928ff9e5 100644 --- a/datafiles/xml_schemas/Imageset.xsd +++ b/datafiles/xml_schemas/Imageset.xsd @@ -1,39 +1,59 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/datafiles/xml_schemas/Samples.xsd b/datafiles/xml_schemas/Samples.xsd deleted file mode 100644 index 6a475b64c..000000000 --- a/datafiles/xml_schemas/Samples.xsd +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/doc/doxygen/authors.dox b/doc/doxygen/authors.dox index 3b1b67c5a..8389a1768 100644 --- a/doc/doxygen/authors.dox +++ b/doc/doxygen/authors.dox @@ -59,6 +59,10 @@ The following have made large, important, or on-going contributions to the syste - Tree Demo. - Andrew Zabolotny: - Font class rewrite. +- Henri Hyyryläinen: + - 3rd version of the Ogre3D renderer module. +- Luca Ebach: + - SamplesBrowser rework to merge the 'zillion' sample libraries into the executable
@section authors_sec_5 Other Contributors diff --git a/doc/doxygen/falagard/fal_baseclass_ref.dox b/doc/doxygen/falagard/fal_baseclass_ref.dox index f2b25b95a..78c508518 100644 --- a/doc/doxygen/falagard/fal_baseclass_ref.dox +++ b/doc/doxygen/falagard/fal_baseclass_ref.dox @@ -33,6 +33,7 @@ The following is a reference to the required elements in a WidgetLook as dictate @ref fal_baseclass_ref_sec_28
@ref fal_baseclass_ref_sec_29
@ref fal_baseclass_ref_sec_30
+@ref fal_baseclass_ref_sec_31
@section fal_baseclass_ref_sec_1 DefaultWindow @@ -58,9 +59,9 @@ Assigned WidgetLook should provide the following: @section fal_baseclass_ref_sec_3 CEGUI/ComboDropList -Base class providing logic for the combo box drop down list sub-widget. This is a specialisation of the "CEGUI/Listbox" class. +Base class providing logic for the combo box drop down list sub-widget. This is a specialisation of the "CEGUI/ListWidget" class. -You should use a "Core/Listbox" window renderer for this widget. +You should use a "Core/ListView" window renderer for this widget. Assigned WidgetLook should provide the following:
    @@ -125,7 +126,7 @@ Assigned WidgetLook should provide the following: @section fal_baseclass_ref_sec_8 CEGUI/ItemEntry -Base class providing logic for entries in supporting list widgets such as ItemListbox. +Base class providing logic for entries in supporting list widgets such as ItemListBase. You should use a "Core/ItemEntry" window renderer for this widget. @@ -134,26 +135,21 @@ Assigned WidgetLook should provide the following:
  • This class currently has no WidgetLook requirements.
+@section fal_baseclass_ref_sec_9 CEGUI/ListHeader +Base class providing logic for a multi columned header widget - intended for use on the multi column list. -@section fal_baseclass_ref_sec_9 CEGUI/ItemListbox -Base class providing logic for a listbox widget that is able to use ItemEntry based windows as items in the list. - -You should use a "Core/ItemListbox" window renderer for this widget. +You should use a "Core/ListHeader" window renderer for this widget. Assigned WidgetLook should provide the following:
    -
  • Child widget definitions:
  • -
      -
    • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
    • -
    • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
    • -
    +
  • This class currently has no WidgetLook requirements.
-@section fal_baseclass_ref_sec_10 CEGUI/ListHeader -Base class providing logic for a multi columned header widget - intended for use on the multi column list. +@section fal_baseclass_ref_sec_10 CEGUI/ListHeaderSegment +Base class providing logic for a widget representing single segment / column of the ListHeader widget. -You should use a "Core/ListHeader" window renderer for this widget. +You should use a "Core/ListHeaderSegment" window renderer for this widget. Assigned WidgetLook should provide the following:
    @@ -161,28 +157,32 @@ Assigned WidgetLook should provide the following:
-@section fal_baseclass_ref_sec_11 CEGUI/ListHeaderSegment -Base class providing logic for a widget representing single segment / column of the ListHeader widget. +@section fal_baseclass_ref_sec_11 CEGUI/ListView +Base class providing logic for a simple single column list view. -You should use a "Core/ListHeaderSegment" window renderer for this widget. +You should use a "Core/ListView" window renderer for this view. Assigned WidgetLook should provide the following:
    -
  • This class currently has no WidgetLook requirements.
  • +
  • Child widget definitions:
  • +
      +
    • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
    • +
    • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
    • +
-@section fal_baseclass_ref_sec_12 CEGUI/Listbox -Base class providing logic for a simple single column list widget. +@section fal_baseclass_ref_sec_12 CEGUI/ListWidget +Base class providing logic for a simple single column list widget. This is a ListView, with additional convenience methods, making it closer in functionality to the old ListBox widget. -You should use a "Core/Listbox" window renderer for this widget. +You should use a "Core/ListWidget" window renderer for this widget. Assigned WidgetLook should provide the following:
  • Child widget definitions:
    • -
    • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
    • -
    • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
    • +
    • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
    • +
    • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
@@ -408,23 +408,44 @@ Assigned WidgetLook should provide the following:
  • This class currently has no WidgetLook requirements.
  • -@section fal_baseclass_ref_sec_30 CEGUI/Tree -Base class providing logic for a basic Tree type widget. +@section fal_baseclass_ref_sec_30 CEGUI/TreeView +Base class providing logic for a basic Tree type view. + +You should use a "Core/TreeView" window renderer for this view. + +Assigned WidgetLook should provide the following: +
      +
    • Child view definitions:
    • +
        +
      • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
      • +
      • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
      • +
      + +
    • Imagery section definitions:
    • +
        +
      • ImagerySection named "SubtreeExpander". This imagery is diplayed for the root of a subtree that is closed / collapsed to indicate that the subtree may be opened / expanded.
      • +
      • ImagerySection named "SubtreeCollapser". This imagery is diplayed for the root of a subtree that is opened / expanded to indicate that the subtree may be closed / collapsed.
      • +
      +
    + -You should use a "Core/Tree" window renderer for this widget. +@section fal_baseclass_ref_sec_31 CEGUI/TreeWidget +Base class providing logic for a basic Tree type widget. This is a TreeView, with additional convenience methods, making it closer in functionality to the old Tree widget. + +You should use a "Core/TreeWidget" window renderer for this widget. Assigned WidgetLook should provide the following:
    • Child widget definitions:
      • -
      • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
      • -
      • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
      • +
      • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position.
      • +
      • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
      - +
    • Imagery section definitions:
      • -
      • ImagerySection named "OpenTreeButton". This imagery is diplayed for the root of a subtree that is closed / collapsed to indicate that the subtree may be opened / expanded.
      • -
      • ImagerySection named "CloseTreeButton". This imagery is diplayed for the root of a subtree that is opened / expanded to indicate that the subtree may be closed / collapsed.
      • +
      • ImagerySection named "SubtreeExpander". This imagery is diplayed for the root of a subtree that is closed / collapsed to indicate that the subtree may be opened / expanded.
      • +
      • ImagerySection named "SubtreeCollapser". This imagery is diplayed for the root of a subtree that is opened / expanded to indicate that the subtree may be closed / collapsed.
    diff --git a/doc/doxygen/falagard/fal_element_ref.dox b/doc/doxygen/falagard/fal_element_ref.dox index 5c4eb9d0a..26f7b60a2 100644 --- a/doc/doxygen/falagard/fal_element_ref.dox +++ b/doc/doxygen/falagard/fal_element_ref.dox @@ -376,7 +376,7 @@ The @c \ element is intended as a container element for a single dimension @subsection fal_elem_ref_sec_9_3 Usage:
    • The @c \ element may only appear within the @c \ element.
    • - +
    • The @c \ element may contain any of the following specialised dimension elements:
      • @c \
      • @@ -595,7 +595,7 @@ Note: the sub-elements should appear in the order that they are defined here.
      • @c \ defining the target area for this frame.
      • Up to nine @c \ or @c \ elements specifying the images to be drawn and in what positions. Note that it is acceptable to - freely mix @c \ and @c \ in a single + freely mix @c \ and @c \ in a single @c \ definition.
      • Optionally specifying the colours for the entire frame, one of the colour elements:
      • @@ -623,7 +623,7 @@ Note: the sub-elements should appear in the order that they are defined here. @subsection fal_elem_ref_sec_14_4 Examples: The following defines a full frame and background. It is taken from -the TaharezLook skin specification for the Listbox widget: +the TaharezLook skin specification for the ListView widget: @code @@ -772,7 +772,7 @@ Optional attribute, defaults to "Background". @subsection fal_elem_ref_sec_17_3 Usage:
        • The @c \ element may not contain sub-elements.
        • - +
        • The @c \ element may appear as a sub-element within any of the following elements:
          • @c \ to specify a horizontal formatting to be used the the image.
          • @@ -908,32 +908,32 @@ Note: the sub-elements should appear in the order that they are defined here.
            • @c \ defining the target area for this image.
            • - +
            • Either one of:
              • @c \ element specifying the image to be drawn.
              • @c \ element specifying a property defining the image to be drawn.
              - +
            • Optionally specifying the colours for this single image, one of the colour elements:
              • @c \
              • @c \
              • @c \
              - +
            • Optionally, to specify the vertical formatting to use, either of:
              • @c \
              • @c \
              - +
            • Optionally, to specify the horizontal formatting to use, either of:
              • @c \
              • @c \
              - +
            • The @c \ element may only appear as a sub-element of the element @c \.
            @@ -1002,7 +1002,7 @@ Note: the sub-elements should appear in the order that they are defined here.
          • @c \
          • @c \
          - +
        • Any number of @c \ elements may then follow.
        • Followed by any number of @c \ elements.
        • Finally, any number of @c \ elements may be given.
        • @@ -1118,7 +1118,7 @@ indicating the mathematical operation to be performed. Required attribute.
        • @c \
        • @c \
        - +
      • The @c \ element must contain any of two the following dimension elements:
        • @c \
        • @@ -1427,7 +1427,7 @@ behaviour). Optional attribute. @subsection fal_elem_ref_sec_29_3 Usage:
          • The @c \ element may only appear as a sub-element within the @c \ element.
          • - +
          • The @c \ element may specify colours to be modulated with any current colours used for each component within the named ImagerySection, by optionally specifying one of the colour elements as a sub-element:
            • @c \
            • diff --git a/doc/doxygen/falagard/fal_enum_ref.dox b/doc/doxygen/falagard/fal_enum_ref.dox index 731bb5dd3..6f8e2dd97 100644 --- a/doc/doxygen/falagard/fal_enum_ref.dox +++ b/doc/doxygen/falagard/fal_enum_ref.dox @@ -83,12 +83,12 @@ @arg @c "UDim" specifies a property that accesses a CEGUI::UDim value. @arg @c "UVector2" specifies a property that accesses a CEGUI::UVector2 value. @arg @c "Sizef" specifies a property that accesses a CEGUI::Sizef value. -@arg @c "Vector2f" specifies a property that accesses a CEGUI::Vector2f value. -@arg @c "Vector3f" specifies a property that accesses a CEGUI::Vector3f value. +@arg @c "vec2" specifies a property that accesses a glm::vec2 value. +@arg @c "vec3" specifies a property that accesses a glm::vec3 value. @arg @c "Rectf" specifies a property that accesses a CEGUI::Rectf value. @arg @c "Font" specifies a property that accesses a font via its name string. @arg @c "Image" specifies a property that accesses an image via its name string. -@arg @c "Quaternion" specifies a property that accesses a CEGUI::Quaternion value. +@arg @c "quat" specifies a property that accesses a glm::quat value. @arg @c "AspectMode" specifies a property that accesses a CEGUI::AspectMode value. @arg @c "HorizontalAlignment" specifies a property that accesses a CEGUI::HorizontalAlignment enumerated value. @arg @c "VerticalAlignment" specifies a property that accesses a CEGUI::VerticalAlignment enumerated value. diff --git a/doc/doxygen/falagard/fal_wr_ref.dox b/doc/doxygen/falagard/fal_wr_ref.dox index 7e1f3ea17..8e234d466 100644 --- a/doc/doxygen/falagard/fal_wr_ref.dox +++ b/doc/doxygen/falagard/fal_wr_ref.dox @@ -30,6 +30,7 @@ @ref fal_wr_ref_sec_26
              @ref fal_wr_ref_sec_27
              @ref fal_wr_ref_sec_28
              +@ref fal_wr_ref_sec_29
              @section fal_wr_ref_sec_1 Falagard/Button @@ -83,7 +84,7 @@ Assigned WidgetLook should provide the following:
            • PropertyDefinition specifications (optional, defaults will be black):
              • NormalTextColour - property that accesses a colour value to be used to render normal unselected text. -
              • SelectedTextColour - property that accesses a colour value to be used to render selected text. +
              • SelectedTextColour - property that accesses a colour value to be used to render selected text.
            • ImagerySection definitions: @@ -142,24 +143,25 @@ Assigned WidgetLook should provide the following:
            -@section fal_wr_ref_sec_6 Falagard/ItemListbox -Improved single column list widget that is able to make use of ItemEntry based windows for listbox items. +@section fal_wr_ref_sec_6 Falagard/ListView +General purpose single column list view. Assigned WidgetLook should provide the following:
            • StateImagery definitions:
                -
              • Enabled - General imagery for when the widget is enabled. -
              • Disabled - General imagery for when the widget is disabled. +
              • Enabled - General imagery for when the view is enabled. +
              • Disabled - General imagery for when the view is disabled. +
              • \a Optional EnabledFocused - General imagery for when the view is enabled *and* focused.
              - +
            • NamedArea definitions (you should choose one set, or the other):
              • ItemRenderArea - Target area where list items will appear when no scrollbars are visible (also acts as default area). Required.
              • ItemRenderAreaHScroll - Target area where list items will appear when the horizontal scrollbar is visible. Optional.
              • ItemRenderAreaVScroll - Target area where list items will appear when the vertical scrollbar is visible. Optional.
              • ItemRenderAreaHVScroll - Target area where list items will appear when both the horizontal and vertical scrollbars are visible. Optional. -
              +
          • OR:
            • ItemRenderingArea - Target area where list items will appear when no scrollbars are visible (also acts as default area). Required. @@ -170,7 +172,7 @@ Assigned WidgetLook should provide the following:
            -@section fal_wr_ref_sec_7 Falagard/Listbox +@section fal_wr_ref_sec_7 Falagard/ListWidget General purpose single column list widget. Assigned WidgetLook should provide the following: @@ -179,8 +181,9 @@ Assigned WidgetLook should provide the following:
            • Enabled - General imagery for when the widget is enabled.
            • Disabled - General imagery for when the widget is disabled. +
            • _Optional_ EnabledFocused - General imagery for when the widget is enabled *and* focused.
            - +
          • NamedArea definitions (you should choose one set, or the other):
            • ItemRenderingArea - Target area where list items will appear when no scrollbars are visible (also acts as default area). Required. @@ -194,7 +197,7 @@ Assigned WidgetLook should provide the following:
            • ItemRenderAreaHScroll - Target area where list items will appear when the horizontal scrollbar is visible. Optional.
            • ItemRenderAreaVScroll - Target area where list items will appear when the vertical scrollbar is visible. Optional.
            • ItemRenderAreaHVScroll - Target area where list items will appear when both the horizontal and vertical scrollbars are visible. Optional. -
            +
        @@ -208,7 +211,7 @@ Assigned WidgetLook should provide the following:
      • Enabled - General imagery for when the widget is enabled.
      • Disabled - General imagery for when the widget is disabled.
      - +
    • Property initialiser definitions:
      • SegmentWidgetType - specifies the name of a "ListHeaderSegment" based widget type; an instance of which will be created for each column within the header. (Required) @@ -232,7 +235,7 @@ Assigned WidgetLook should provide the following:
      • GhostAscendingSortIcon - Additional imagery used for the drag-moving 'ghost' when the segment has the ascending sort direction set.
      • GhostDescendingSortDown - Additional imagery used for the drag-moving 'ghost' when the segment has the descending sort direction set.
      - +
    • Property initialiser definitions:
      • MovingCursorImage - Property to define a mouse cursor image to use when drag-moving the widget. (Optional). @@ -250,7 +253,7 @@ Assigned WidgetLook should provide the following:
      • Enabled - General imagery for when the widget is enabled.
      • Disabled - General imagery for when the widget is disabled.
      - +
    • NamedArea definitions:
      • ItemRenderArea - Target area where menu items will appear. @@ -276,7 +279,7 @@ Assigned WidgetLook should provide the following:
      • PopupClosedIcon - Additional imagery used when the item is attached to a popup menu widget and has a a 'sub' popup menu attached to itself, and that popup is closed.
      • PopupOpenIcon - Additional imagery used when the item is attached to a popup menu widget and has a a 'sub' popup menu attached to itself, and that popup is open.
      - +
    • NamedArea definitions:
      • ContentSize - Area defining the size of this item's content. Required. @@ -295,7 +298,7 @@ Assigned WidgetLook should provide the following:
      • Enabled - General imagery for when the widget is enabled.
      • Disabled - General imagery for when the widget is disabled.
      - +
    • NamedArea definitions:
      • ItemRenderingArea - Target area where list items will appear when no scrollbars are visible (also acts as default area). Required. @@ -317,7 +320,7 @@ Assigned WidgetLook should provide the following:
      • Disabled - Imagery used when widget is disabled.
      • ReadOnly - Imagery used when widget is in 'Read Only' state.
      - +
    • NamedArea definitions:
      • TextArea - Target area where text lines will appear when no scrollbars are visible (also acts as default area). Required. @@ -325,12 +328,12 @@ Assigned WidgetLook should provide the following:
      • TextAreaVScroll - Target area where text lines will appear when the vertical scrollbar is visible. Optional.
      • TextAreaHVScroll - Target area where text lines will appear when both the horizontal and vertical scrollbars are visible. Optional.
      - +
    • ImagerySection definitions:
      • Carat - Additional imagery used to display the insertion position carat.
      - +
    • PropertyDefinition specifications (optional, defaults will be black):
      • NormalTextColour - property that accesses a colour value to be used to render normal unselected text. @@ -351,7 +354,7 @@ Assigned WidgetLook should provide the following:
      • Enabled - General imagery for when the widget is enabled.
      • Disabled - General imagery for when the widget is disabled.
      - +
    • NamedArea definitions:
      • ItemRenderArea - Target area where menu items will appear. @@ -371,12 +374,12 @@ Assigned WidgetLook should provide the following:
      • EnabledProgress - imagery for 100\ progress used when widget is enabled. The drawn imagery will appear in named area "ProgressArea" and will be clipped appropriately according to widget settings and the current progress value.
      • DisabledProgress - imagery for 100\ progress used when widget is disabled. The drawn imagery will appear in named area "ProgressArea" and will be clipped appropriately according to widget settings and the current progress value.
      - +
    • NamedArea definitions:
      • ProgressArea - Target area where progress imagery will appear.
      - +
    • Property initialiser definitions:
      • VerticalProgress - boolean property. Determines whether the progress widget is horizontal or vertical. Default is horizontal. Optional. @@ -416,7 +419,7 @@ Assigned WidgetLook should provide the following:
      • Enabled - General imagery for when the widget is enabled.
      • Disabled - General imagery for when the widget is disabled.
      - +
    • NamedArea definitions:
      • ViewableArea - Target area where visible content will appear when no scrollbars are visible (also acts as default area). Required. @@ -460,12 +463,12 @@ Assigned WidgetLook should provide the following:
      • Enabled - General imagery for when the widget is enabled.
      • Disabled - General imagery for when the widget is disabled.
      - +
    • NamedArea definitions:
      • ThumbTrackArea - Target area in which thumb may be moved.
      - +
    • Property initialiser definitions:
      • VerticalSlider - boolean property. Indicates whether this slider will operate in the vertical or horizontal direction. Default is for horizontal. Optional. @@ -528,7 +531,7 @@ Assigned WidgetLook should provide the following:
      • NoFrameEnabledBackground - Additional imagery used when the widget is enabled, the widget frame is disabled, and the widget background is enabled.
      • NoFrameDisabledBackground - Additional imagery used when the widgetis disabled, the widget frame is disabled, and the widget background is enabled.
      - +
    • NamedArea definitions (missing areas will default to WithFrameTextRenderArea):
      • WithFrameTextRenderArea - Target area where text will appear when the frame is enabled and no scrollbars are visible (also acts as default area). Required. @@ -540,11 +543,11 @@ Assigned WidgetLook should provide the following:
      • NoFrameTextRenderAreaVScroll - Target area where text will appear when the frame is disabled and the vertical scrollbar is visible. Optional.
      • NoFrameTextRenderAreaHVScroll - Target area where text will appear when the frame is disabled and both the horizontal and vertical scrollbars are visible. Optional.
      - +
    • Child widget definitions:
      • Scrollbar based widget with name suffix "__auto_vscrollbar__". This widget will be used to control vertical scroll position. -
      • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position. +
      • Scrollbar based widget with name suffix "__auto_hscrollbar__". This widget will be used to control horizontal scroll position.
    @@ -592,7 +595,7 @@ Assigned WidgetLook should provide the following:
  • Enabled - General imagery for when the widget is enabled.
  • Disabled - General imagery for when the widget is disabled. - +
  • Property initialiser definitions:
    • TabButtonType - specifies a TabButton based widget type to be created each time a new tab button is required. @@ -624,7 +627,7 @@ Assigned WidgetLook should provide the following:
    • Enabled - General imagery for when the widget is enabled.
    • Disabled - General imagery for when the widget is disabled.
    - +
  • NamedArea definitions:
    • TextArea - Typically this would be the same area as the TextComponent you define to receive the tool-tip text. This named area is used when deciding how to dynamically size the tool-tip so that text is not clipped. @@ -632,7 +635,28 @@ Assigned WidgetLook should provide the following:
    -@section fal_wr_ref_sec_28 Falagard/Tree +@section fal_wr_ref_sec_28 Falagard/TreeView +Basic Tree type view. + +Assigned WidgetLook should provide the following: +
      +
    • StateImagery definitions: +
        +
      • Enabled - General imagery for when the view is enabled. +
      • Disabled - General imagery for when the view is disabled. +
      + +
    • NamedArea definitions: +
        +
      • ItemRenderingArea - Target area where tree items will appear when no scrollbars are visible (also acts as default area). Required. +
      • ItemRenderingAreaHScroll - Target area where tree items will appear when the horizontal scrollbar is visible. Optional. +
      • ItemRenderingAreaVScroll - Target area where tree items will appear when the vertical scrollbar is visible. Optional. +
      • ItemRenderingAreaHVScroll - Target area where tree items will appear when both the horizontal and vertical scrollbars are visible. Optional. +
      +
    + + +@section fal_wr_ref_sec_29 Falagard/TreeWidget Basic Tree type widget. Assigned WidgetLook should provide the following: @@ -651,5 +675,4 @@ Assigned WidgetLook should provide the following:
  • ItemRenderingAreaHVScroll - Target area where tree items will appear when both the horizontal and vertical scrollbars are visible. Optional. - */ diff --git a/doc/doxygen/mainpage.dox b/doc/doxygen/mainpage.dox index 0b819cffa..bac66bd79 100644 --- a/doc/doxygen/mainpage.dox +++ b/doc/doxygen/mainpage.dox @@ -35,6 +35,7 @@ The documentation for CEGUI is split into the following sections: - @ref datafile_tutorial - @ref window_tutorial - @ref input_tutorial + - @ref gui_navigation_tutorial - Porting Guides - @ref porting6to7 diff --git a/doc/doxygen/tutorials/ce_guide_2.dox b/doc/doxygen/tutorials/ce_guide_2.dox index 505c67520..4525486f5 100644 --- a/doc/doxygen/tutorials/ce_guide_2.dox +++ b/doc/doxygen/tutorials/ce_guide_2.dox @@ -153,10 +153,26 @@ exposes the same property). For example: @code +<<<<<<< local +CEGUI::System::getSingleton().getDefaultGUIContext(). + getCursor().setDefaultImage( "TaharezLook/MouseArrow" ); +@endcode + +Finally, if you intend to use tool tips, you should specify the type of the +ToolTip based widget that you want used for that purpose. It is actually +possible to set this on a per-window basis, though this is not normally +required, and is beyond the scope of this introductory tutorial. The code to +set the default tool tip window type for the initial, default GUIContext looks +like this: +@code +CEGUI::System::getSingleton().getDefaultGUIContext(). + setDefaultTooltipType( "TaharezLook/Tooltip" ); +======= // setup default group for validation schemas CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser(); if (parser->isPropertyPresent("SchemaDefaultResourceGroup")) parser->setProperty("SchemaDefaultResourceGroup", "schemas"); +>>>>>>> other @endcode
    diff --git a/doc/doxygen/tutorials/ce_guide_5.dox b/doc/doxygen/tutorials/ce_guide_5.dox index 3598f56df..d97e34429 100644 --- a/doc/doxygen/tutorials/ce_guide_5.dox +++ b/doc/doxygen/tutorials/ce_guide_5.dox @@ -37,7 +37,6 @@ member function for each type of base input: - bool InjectedInputReceiver::injectKeyUp( Key::Scan scan_code ); - bool InjectedInputReceiver::injectChar( utf32 code_point ); - bool InjectedInputReceiver::injectMouseWheelChange( float delta ); -- bool InjectedInputReceiver::injectTimePulse( float timeElapsed ); And also some optional functions for click and multi-click events (which are normally automatically generated internally by the system): @@ -63,22 +62,55 @@ actually consumed the input. If this returns false, it means that CEGUI did nothing useful with the input, and that your application may like to perform some action based on it instead. Generally for this to work as described, you should have a fullscreen DefaultWindow as your layout root with the -MousePassThroughEnabled property set to true. +CursorPassThroughEnabled property set to true. -Finally, you must know that InjectedInputReceiver is implemented by GUIContext -and that input injection is per GUIContext, this is a very important -and a very powerful concept. In the generic case, though, it simply means that -when you come to inject inputs, you get access to the initial, default -GUIContext and inject your inputs there: -@code -CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext(); -@endcode +Finally, you must know that InjectedInputReceiver is implemented by InputAggregator. +In the next section you can read about the new input events system. + +
    +@section input_tutorial_inputevents Input Events System +Starting with version YYY of CEGUI, the input system has changed completely. +While previously it worked with raw injected inputs in the GUIContext, now it +uses the concept of input event. This is a generic term for +an event which represents the end result of a (sequence) of input(s). For example, +the mouse buttons pressed and released can represent an activation event, the +combination of keys CTRL and V represent a paste event; and so on. With this +new way of getting input we can easily implement support for new devices +without having to emulate a keyboard/mouse. We can also implement GUI +navigation - you can check the @ref gui_navigation_tutorial for details. + +The input events are a central part of the new input system. In the +default implementation the InputAggregator takes in raw input and +generates input events based on it. There are currently two +default input events: +- TextInputEvent - An event with a character payload. +- SemanticInputEvent - An event with a semantic value and a payload. This event +tries to cover some specific input events with a certain semantic. -@note There is currently an oddity in the system that requires time pulses to be -injected both into whatever GUIContext objects you need input for and -additionally for CEGUI::System via CEGUI::System::injectTimePulse - if you fail -to inject into System, you may find some things -- such as animations -- not -working quite as they should! +There are a bunch of values defined by default in the SemanticValue +enumeration. You can create your own semantic values, and in order to +prevent collisions with the default ones, there is a value called +SemanticValue::SV_UserDefinedSemanticValue, which signals the minimum +value of a user-defined semantic value. The payload of a semantic input event +is a union which covers most of the usage cases: either a single or a double +float, or in the case of a cursor (see below), the source of the cursor (left, +right, middle). There is also no more knowledge of a mouse. Instead the generic +term Cursor is used, because this can represent also a touch pointer. + +You can create a totally different InputAggregator or you can +inherit the default behaviour while adding new semantics. Such example +can be consulted in the Scrollable_Pane sample. One scenario where +you would create a new InputAggregator is when you want to support additional +semantics or add a new type of input device: touch, Kinect, gamepad, etc. +For example, in the case of Kinect you could generate a TextEvent with the +spoken words or create an on-screen keyboard (sample coming soon) which +will generate TextEvents based on activation events. + +You can manually inject input events into the GUIContext or you can use +the decorator-like pattern, by creating a new InputAggregator attached +to the GUIContext. Then, you can inject the raw input like you did before +in the InputAggregator, which in turn will generate and inject the input +events into the GUIContext.
    @section input_tutorial_detail A little more detail: What each injector is used for @@ -177,27 +209,13 @@ wheel (whatever you like to call it!). Use positive values for forward movement (rolling the wheel away from the user), and negative values for backwards movement (rolling the wheel towards the user). -@subsection input_tutorial_pulse bool InjectedInputReceiver::injectTimePulse( float timeElapsed ) -This function is used to keep CEGUI informed about time (CEGUI doesn't have a -wristwatch, you see!). The value @c timeElapsed is a floating point number that -indicates the number of seconds - or part seconds - that have passed since the -last time the injector was called (or since CEGUI was started). The use of this -function is becoming more and more important - it now controls things such as -fades and timing for tool-tip widgets, menus, and also auto-repeat for -mouse buttons. -@note As mentioned above, there is currently an oddity in the system that -requires time pulses to be injected both into whatever GUIContext objects you -need input for and additionally for CEGUI::System via -CEGUI::System::injectTimePulse - if you fail to inject into System, you may find -some things -- such as animations -- not working quite as they should! - @subsection input_tutorial_click bool InjectedInputReceiver::injectMouseButtonClick( MouseButton button ) This is an optional injection function that informs CEGUI that a mouse button click has occurred; normally that is a down -> up sequence. Calling this -function is only neccessary if the built-in automatic generation of click and +function is only necessary if the built-in automatic generation of click and multi-click events is unsuitable for your needs. If you decide you need to use this function you will normally disable the automatic event generation first by -way of the GUIContext::setMouseClickEventGenerationEnabled function. While it is +way of the InputAggregator::setMouseClickEventGenerationEnabled function. While it is possible to call this injection function \e without disabling the auto generated events, it will affect the behaviour as to the way events are marked as 'handled' and therefore the return code from this function. @@ -205,10 +223,10 @@ events, it will affect the behaviour as to the way events are marked as @subsection input_tutorial_doubleclick bool InjectedInputReceiver::injectMouseButtonDoubleClick( MouseButton button ) This is an optional injection function that informs CEGUI that a mouse button double-click has occurred; normally that is a down -> up -> down sequence. -Calling this function is only neccessary if the built-in automatic generation of +Calling this function is only necessary if the built-in automatic generation of click and multi-click events is unsuitable for your needs. If you decide you need to use this function you will normally disable the automatic event -generation first by way of the GUIContext::setMouseClickEventGenerationEnabled +generation first by way of the InputAggregator::setMouseClickEventGenerationEnabled function. While it is possible to call this injection function \e without disabling the auto generated events, it will affect the behaviour as to the way events are marked as 'handled' and therefore the return code from this function. @@ -216,15 +234,42 @@ events are marked as 'handled' and therefore the return code from this function. @subsection input_tutorial_tripleclick bool InjectedInputReceiver::injectMouseButtonTripleClick( MouseButton button ) This is an optional injection function that informs CEGUI that a mouse button triple-click has occurred; normally that is a down -> up -> down -> up -> down -sequence. Calling this function is only neccessary if the built-in automatic +sequence. Calling this function is only necessary if the built-in automatic generation of click and multi-click events is unsuitable for your needs. If you decide you need to use this function you will normally disable the automatic event generation first by way of the -GUIContext::setMouseClickEventGenerationEnabled function. While it is possible +InputAggregator::setMouseClickEventGenerationEnabled function. While it is possible to call this injection function \e without disabling the auto generated events, it will affect the behaviour as to the way events are marked as 'handled' and therefore the return code from this function. +
    +@section input_tutorial_migration Migrating from raw injected input to input events +The migration from the usage of GUIContext to inject input to the new input events +is an easy one, especially if you want to use the default previous behaviour. + +First thing to note is that the InjectedInputReceiver interface doesn't contain +the injectTimePulse method anymore. Time pulses are now injected directly in the +GUIContext. GUIContext doesn't implement InjectedInputReceiver anymore. Instead, +a new class called InputAggregator will do that job. Thus, all calls that previously +injected input in GUIContext will now inject in an InputAggregator instance. +For details on what the InputAggregator does please check above. To migrate +you need to perform the following steps - code examples are taken from the samples +(framework): + +- Create an InputAggregator instance, and pass a GUIContext to its constructor +@code +d_inputAggregator = new InputAggregator(&CEGUI::System::getSingletonPtr()->getDefaultGUIContext()); +@endcode +- Convert code like: +@code +CEGUI::System::getSingletonPtr()->injectMousePosition(x, y); +@endcode +to: +@code +d_inputAggregator->injectMousePosition(x, y); +@endcode +
    @section input_tutorial_conclusion Conclusion Here we have seen the general idiom that CEGUI uses for obtaining externally diff --git a/doc/doxygen/tutorials/ce_guide_5_gui_navigation.dox b/doc/doxygen/tutorials/ce_guide_5_gui_navigation.dox new file mode 100644 index 000000000..ab175e56c --- /dev/null +++ b/doc/doxygen/tutorials/ce_guide_5_gui_navigation.dox @@ -0,0 +1,83 @@ +namespace CEGUI { +/** +@page gui_navigation_tutorial The Beginners Guide to GUI navigation +@author Timotei Dolean +@tableofcontents + +@section gui_navigation_tutorial_intro Introduction +GUI navigation is a feature that allows the user of the application to be +able to navigate through the UI using a specific set of inputs. This can vary +based on the UI type: in a form you expect that a `tab` would go to the next +item to be completed or in a game, pressing up/down/enter would navigate the +menu. + +There are two important terms for GUI navigation: +- Window Navigator +- Navigation Strategy + +
    +@section gui_navigation_tutorial_navigation_strategy The Navigation Strategy +A navigation strategy provides a specific algorithm for navigating the UI. +This separation between the navigation strategy and the GUIContext or the +window navigator provides a powerful opportunity to implement custom logic +for navigation which takes into account any extra external data you want. + +The navigation strategy is represented by the NavigationStrategy interface, +which comprises a single method: +@code +Window* getWindow(Window* neighbour, const String& payload); +@endcode + +- The first parameter is (usually) the current focused (if any) window inside +the current GUIContext. +- The second parameter, the payload, is sent based on the way the developer +creates the window navigator (see below). + +Using just this two parameters one can compute the next logical window to be +focused. The way this strategy can access the current GUI tree is left to the +developer. For example, the samples define three different strategies: +LinearNavigationStrategy, MatrixNavigationStrategy and WindowChildrenNavigationStrategy. +Like their name suggest they either navigate the UI in a linear fashion (e.g.: +a form), in two dimensional way (e.g.: complex menu) or based on a specific +Window's children list. + +
    +@section gui_navigation_tutorial_window_navigator The Window Navigator +The WindowNavigator is the entity that manages the current focused (active) +window inside the GUIContext. It takes a series of mappings between +semantic values and a string payload. When a new semantic input event is injected +into the GUIContext it checks if the semantic value is present in the map. +If so, it will unfocus the current (if any) window, and focus the next window +(if any), which is retrieved based on the NavigationStrategy, by passing the +mapped payload. + +
    +@section gui_navigation_tutorial_adding_navigation How to add GUI navigation +To add GUI navigation you need to perform the following steps: +- Create a new navigation strategy which inherits from NavigationStrategy: +@code +class LinearNavigationStrategy : public CEGUI::NavigationStrategy { ... } +@endcode +- Create a method that creates the mappings between semantic values and +payloads: +@code +std::map createLinearNavigationMappings() +{ + std::map mappings; + + mappings[SV_NavigateToNext] = NAVIGATE_NEXT; + mappings[SV_NavigateToPrevious] = NAVIGATE_PREVIOUS; + + return mappings; +} +@endcode +- Create a navigation strategy and window navigator instance and attach them +to the GUIContext: +@code +LinearNavigationStrategy* d_linearNavigatorStrategy = new LinearNavigationStrategy(); +WindowNavigator* d_linearWindowNavigator = new WindowNavigator(createLinearNavigationMappings(), d_linearNavigatorStrategy); +getGUIContext()->setWindowNavigator(d_linearWindowNavigator); +@endcode + +*/ +} diff --git a/doc/doxygen/xml_confg.dox b/doc/doxygen/xml_confg.dox index ce8841809..5d95d8fc0 100644 --- a/doc/doxygen/xml_confg.dox +++ b/doc/doxygen/xml_confg.dox @@ -11,7 +11,7 @@ at system creation time. @ref xml_config_font
    @ref xml_config_guisheet
    @ref xml_config_imagecodec
    -@ref xml_config_mousecursor
    +@ref xml_config_cursor
    @ref xml_config_defaultresourcegroup
    @ref xml_config_xmlparser
    @ref xml_config_logging
    @@ -58,7 +58,7 @@ The reference for each element is arranged into sections, as described below: - \ elements. - \ elements. - \ elements. - - \ elements. + - \ elements. - \ elements. - \ elements. - No element may contain \ as a sub-element. @@ -240,22 +240,22 @@ The reference for each element is arranged into sections, as described below: - Examples:
    -@section xml_config_mousecursor \ +@section xml_config_cursor \ - Purpose: - - Sets the system default mouse cursor image. If this element appears + - Sets the system default cursor image. If this element appears multiple times, only the last occurence is used. - Attributes: - @c imageset: Specifies the name of the Imageset containing the image to - be used as the default mouse cursor. Required attribute. + be used as the default cursor. Required attribute. - @c image: Specifies the name of the image in the imagset specified in - the @c imageset attribute to be used as the default mouse cursor image. + the @c imageset attribute to be used as the default cursor image. Required attribute. - Usage: - - The \ element may only appear as a sub-element of + - The \ element may only appear as a sub-element of the \ element. - - The \ element may not contain any sub-elements. + - The \ element may not contain any sub-elements. - Examples: diff --git a/samples/CMakeLists.txt b/samples/CMakeLists.txt index 946f9bd74..aa6ffdafa 100644 --- a/samples/CMakeLists.txt +++ b/samples/CMakeLists.txt @@ -1,45 +1,58 @@ -# We clear the samples.xml file, which will be used by the samples browser, and -# add the samples header to it before starting to add the samples -file(WRITE ${CMAKE_BINARY_DIR}/datafiles/samples/samples.xml "") -file(READ ${CMAKE_CURRENT_SOURCE_DIR}/common/SamplesXmlHeader.xml DEMO_META_DATA) -file(APPEND ${CMAKE_BINARY_DIR}/datafiles/samples/samples.xml ${DEMO_META_DATA}) +# macro to list all subdirectories of a given directory +macro(subdirlist result curdir) + file(GLOB children RELATIVE ${curdir} ${curdir}/*) + set(dirlist "") + foreach(child ${children}) + if(IS_DIRECTORY ${curdir}/${child}) + list(APPEND dirlist ${child}) + endif() + endforeach() + set(${result} ${dirlist}) +endmacro() -add_subdirectory(HelloWorld) -add_subdirectory(Widgets) -add_subdirectory(RenderEffects) -add_subdirectory(Fonts) +# initialize variables +set(ADDITIONAL_LIBS "") +set(ADDITIONAL_INCLUDE_DIRS "") +set(SAMPLES_LIST "") +set(SAMPLES_SUBDIRS "") +set(SAMPLES_SOURCES_LIST "") +set(SAMPLES_HEADERS_LIST "") -add_subdirectory(Demo6) -add_subdirectory(DragDrop) -add_subdirectory(EditboxValidation) -add_subdirectory(GameMenu) -add_subdirectory(RestaurantGame) -add_subdirectory(Inventory) -add_subdirectory(Minesweeper) -add_subdirectory(ScrollablePane) -add_subdirectory(TabControl) -add_subdirectory(Text) -add_subdirectory(Tree) -add_subdirectory(CommonDialogs) +set(SAMPLE_LIST_HEADER ${CMAKE_CURRENT_BINARY_DIR}/common/include/samples.h) +set(SAMPLE_LIST_CODE ${CMAKE_CURRENT_BINARY_DIR}/common/include/samples.inc) -if (CEGUI_BUILD_LUA_MODULE) - # add_subdirectory(Demo8) -endif() +# gather sample dirs +subdirlist(SAMPLES_SUBDIRS ${CMAKE_CURRENT_SOURCE_DIR}) -# Simple test for GLES renderer. -# -# Commented since it's does not use the samples framework and is merely included -# such that recreation from scratch is not required in the future. Aka, it's -# one of CrazyEddie's hacks that he wants to keep around :-p -#if (CEGUI_BUILD_RENDERER_OPENGLES) -# add_subdirectory(GLESTest) -#endif() +# loop through samples and exclude those that should not be build +foreach(dir ${SAMPLES_SUBDIRS}) + if("${dir}" MATCHES "^GLESTest$") # exclude the GLES demo until CE gives his OK + elseif("${dir}" MATCHES "^common$") # exclude common folder; samples include files from there directly if necessary + elseif("${dir}" MATCHES "^samples$") # exclude this directory + elseif("${dir}" MATCHES "^Demo8$") # this demo doesn't work at the moment + elseif("${dir}" MATCHES "^browser$") # the directory has to be included at the end because it needs all samples' sources and headers + elseif("${dir}" MATCHES "^CommonDialogs$" AND ANDROID) # exclude this directory + elseif("${dir}" MATCHES "^CustomShapesDrawing$" AND ANDROID) # exclude this directory + elseif("${dir}" MATCHES "^RenderEffects$" AND ANDROID) # exclude this directory + elseif("${dir}" MATCHES "^SVG$" AND ANDROID) # exclude this directory + else() + add_subdirectory(${dir}) + endif() +endforeach() +# add all registered samples to samples.inc and samples.h file +file(WRITE ${SAMPLE_LIST_HEADER} "#ifndef _SamplesListHeader_h_\n#define _SamplesListHeader_h_\n\n#include \"Sample.h\"\n") +file(WRITE ${SAMPLE_LIST_CODE} "std::vector samples;") +foreach(sample ${SAMPLES_LIST}) + set(_PATH "${CMAKE_CURRENT_SOURCE_DIR}/${sample}/${sample}.h") + file(APPEND ${SAMPLE_LIST_HEADER} "\n#include \"${_PATH}\"") + file(APPEND ${SAMPLE_LIST_CODE} "\nsamples.push_back(new ${sample}Sample());") +endforeach() +file(APPEND ${SAMPLE_LIST_HEADER} "\n#endif") -# Finally we add the samples footer to the samples.xml -file(READ ${CMAKE_CURRENT_SOURCE_DIR}/common/SamplesXmlFooter.xml DEMO_META_DATA) -file(APPEND ${CMAKE_BINARY_DIR}/datafiles/samples/samples.xml ${DEMO_META_DATA}) +# additional include directories have to appear here +list(APPEND ADDITIONAL_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/common/include") +list(APPEND ADDITIONAL_INCLUDE_DIRS "${CMAKE_BINARY_DIR}/samples/common/include") -# And add it to the install -install(FILES ${CMAKE_BINARY_DIR}/datafiles/samples/samples.xml - DESTINATION ${CEGUI_DATA_INSTALL_DIR}/samples/) +# finally, include the samples browser directory +add_subdirectory(browser/) diff --git a/samples/CMakeLists.txt.template b/samples/CMakeLists.txt.template new file mode 100644 index 000000000..5940b01ee --- /dev/null +++ b/samples/CMakeLists.txt.template @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/CommonDialogs/CMakeLists.txt b/samples/CommonDialogs/CMakeLists.txt index f9307e361..0d87578fd 100644 --- a/samples/CommonDialogs/CMakeLists.txt +++ b/samples/CommonDialogs/CMakeLists.txt @@ -1,6 +1,16 @@ -option(CEGUI_SAMPLES_ENABLE_COMMON_DIALOGS "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_COMMON_DIALOGS) - cegui_add_sample(CEGUISample_CommonDialogs) -endif() +if(CEGUI_BUILD_COMMON_DIALOGS) + # Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample + get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) + set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") + set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_COMMON_DIALOGS_LIBNAME}) \ No newline at end of file + # Append the samples names to the list and make the list visible outside this scope + list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") + set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + + # Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope + file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) + file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) + set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) + set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) +endif() \ No newline at end of file diff --git a/samples/CommonDialogs/CommonDialogsDemo.cpp b/samples/CommonDialogs/CommonDialogs.cpp similarity index 83% rename from samples/CommonDialogs/CommonDialogsDemo.cpp rename to samples/CommonDialogs/CommonDialogs.cpp index 9d580dba8..188b44dff 100644 --- a/samples/CommonDialogs/CommonDialogsDemo.cpp +++ b/samples/CommonDialogs/CommonDialogs.cpp @@ -27,18 +27,22 @@ #include "SampleBase.h" #include "CEGUI/CEGUI.h" +#include "CommonDialogs.h" + #include "CEGUI/CommonDialogs/ColourPicker/ColourPicker.h" -//----------------------------------------------------------------------------// -class CommonDialogsDemo : public Sample +CommonDialogsSample::CommonDialogsSample() { -public: - virtual bool initialise(CEGUI::GUIContext* guiContext); - void deinitialise(void) {} -}; + Sample::d_name = "CommonDialogsSample"; + Sample::d_credits = "CrazyEddie, Lukas \"Ident\" Meindl"; + Sample::d_description = "The Sample uses the \"Vanilla/ColourPicker\" widget"; + Sample::d_summary = "Shows the functionalities of the Common Dialogues library." + " Currently this library consists only of the ColourPicker for CEGUI." + " It can be opened by clicking one of the coloured rectangle in the Sample."; +} //----------------------------------------------------------------------------// -bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext) +bool CommonDialogsSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -55,14 +59,14 @@ bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext) // load resources and set up system defaults SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme"); SchemeManager::getSingleton().createFromFile("VanillaCommonDialogs.scheme"); - guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow"); + guiContext->getCursor().setDefaultImage("Vanilla-Images/MouseArrow"); // set up the root window / gui sheet WindowManager& winMgr = WindowManager::getSingleton(); Window* root = winMgr.createWindow("DefaultWindow", "Root"); guiContext->setRootWindow(root); - // create container window for the demo + // create container window for the Sample FrameWindow* wnd = static_cast( winMgr.createWindow("Vanilla/FrameWindow")); root->addChild(wnd); @@ -71,7 +75,7 @@ bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext) wnd->setPosition(UVector2(cegui_reldim(0.05f), cegui_reldim( 0.25f))); wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f))); - wnd->setText("Common Dialogs Demo - Main Window"); + wnd->setText("Common Dialogs Sample - Main Window"); wnd->setCloseButtonEnabled(false); // Add a colour picker & label @@ -105,16 +109,4 @@ bool CommonDialogsDemo::initialise(CEGUI::GUIContext* guiContext) colourPicker->setColour(CEGUI::Colour(1.0f, 0.2f, 0.5f, 0.8f)); return true; -} - -//----------------------------------------------------------------------------// - - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static CommonDialogsDemo sample; - return sample; -} +} \ No newline at end of file diff --git a/samples/CommonDialogs/CommonDialogs.h b/samples/CommonDialogs/CommonDialogs.h new file mode 100644 index 000000000..d2a58946c --- /dev/null +++ b/samples/CommonDialogs/CommonDialogs.h @@ -0,0 +1,44 @@ +/*********************************************************************** +created: Aug 22 2014 +author: Luca Ebach + (based on original code by Paul D Turner ) +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CommonDialogsSample_h_ +#define _CommonDialogsSample_h_ + +#include "SampleBase.h" +#include "CEGUI/CEGUI.h" + +//----------------------------------------------------------------------------// +class CommonDialogsSample : public Sample +{ +public: + CommonDialogsSample(); + + virtual bool initialise(CEGUI::GUIContext* guiContext); + void deinitialise(void) {} +}; + +#endif // _CommonDialogs_h_ \ No newline at end of file diff --git a/samples/CommonDialogs/SampleMetaData.xml b/samples/CommonDialogs/SampleMetaData.xml deleted file mode 100644 index 169085df2..000000000 --- a/samples/CommonDialogs/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/CustomShapesDrawing/CMakeLists.txt b/samples/CustomShapesDrawing/CMakeLists.txt new file mode 100644 index 000000000..694aca6d7 --- /dev/null +++ b/samples/CustomShapesDrawing/CMakeLists.txt @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/CustomShapesDrawing/CustomShapesDrawing.cpp b/samples/CustomShapesDrawing/CustomShapesDrawing.cpp new file mode 100644 index 000000000..16f031dbf --- /dev/null +++ b/samples/CustomShapesDrawing/CustomShapesDrawing.cpp @@ -0,0 +1,778 @@ +/*********************************************************************** + created: 16/7/2013 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "CustomShapesDrawing.h" + +#include "CEGUI/SchemeManager.h" +#include "CEGUI/GUIContext.h" +#include "CEGUI/WindowManager.h" +#include "CEGUI/FontManager.h" +#include "CEGUI/Window.h" +#include "CEGUI/widgets/DefaultWindow.h" +#include "CEGUI/widgets/ToggleButton.h" +#include "CEGUI/GeometryBuffer.h" +#include "CEGUI/Vertex.h" +#include "CEGUI/ImageManager.h" +#include "CEGUI/svg/SVGDataManager.h" +#include "CEGUI/svg/SVGImage.h" +#include "CEGUI/svg/SVGData.h" +#include "CEGUI/svg/SVGBasicShape.h" + +#include "glm/glm.hpp" + +#include +#include +#include + +using namespace CEGUI; +using namespace glm; + +/************************************************************************* + Constructor. +*************************************************************************/ +CustomShapesDrawingSample::CustomShapesDrawingSample() : + d_FPSMaxGraphValue(1), + d_FPSGraphSamplesCount(30), + d_useRealFPS(false), + d_customSVGImageWidth(300.0f), + d_customSVGImageHeight(100.0f), + d_customGeometryGraphWidth(300.0f), + d_customGeometryGraphHeight(100.0f), + d_FPSElapsed(0.0f), + d_FPSFrames() +{ + Sample::d_name = "CustomShapesDrawingSample"; + Sample::d_credits = "Lukas \"Ident\" Meindl"; + Sample::d_description = + "In CEGUI the GeometryBuffer can be used to render vertices directly on the screen. However, this comes with limitations, " + "since CEGUI is not a Rendering Engine.For example only textured and coloured vertices are available out of the box.The vertices for all lines and " + "the quad of the background of the graph had to be calculated with extra code.The other possibility to render a graph, as display in this sample, " + "is by using an SVGImage.Each SVGImage points to a(possibly shared) SVGData object that contains its data.This data can be modified by adding shapes based " + "on the SVG BasicShapes.The vertices do not have to be calculated in this case and the rendering specifics like colours and line widths can be specified " + "more conveniently.Additionally, with SVGImages it is possible to switch on anti - aliasing, which is implemented by adding additional blending geometry to all shapes. " + "Also, it is easily possible to add the SVGImage to a window, by referring to it via a property, which is not possible with the GeometryBuffer method.This is " + "displayed in the sample with a WindowsLook / FrameWindow that contains an Generic / Image window.The FrameWindow is sizeable and will also scale its child window when " + "sized.The Generic / Image window has an 'Image' property that is pointing to our SVGImage.When the FrameWindow is sized it can thus be seen that the image is " + "being scaled too."; + Sample::d_summary = + "This sample displays rendering possibilities provided with CEGUI's GeometryBuffer and SVGImage/SVGData class. " + "The goal is to render an FPS graph that displays the last recorded FPS values.SVGImage provides optional anti - aliasing and the possibility to " + "use the Image as part of a window."; + + // Initialising the FPS values + for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i) + d_lastFPSValues.push_front(0); +} + +/************************************************************************* + Sample specific initialisation goes here. +*************************************************************************/ +bool CustomShapesDrawingSample::initialise(CEGUI::GUIContext* guiContext) +{ + d_usedFiles = CEGUI::String(__FILE__); + + // CEGUI setup + SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); + SchemeManager::getSingleton().createFromFile("Generic.scheme"); + guiContext->getCursor().setDefaultImage("WindowsLook/MouseArrow"); + WindowManager& winMgr = WindowManager::getSingleton(); + + // Create a Generic/image called 'Root' with a white image as Image property. + d_root = (DefaultWindow*)winMgr.createWindow("Generic/Image", "Root"); + d_root->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); + d_root->setProperty("Image", "WindowsLook/Background"); + + // load font and setup default if not loaded via scheme + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + FontManager::getSingleton().createFromFile("DejaVuSans-10.font"); + // Set default font for the gui context + guiContext->setDefaultFont(&defaultFont); + + // Set the root window as root of our GUI Context + guiContext->setRootWindow(d_root); + + // Initialise random-seed + srand(static_cast(time(0))); + + // We create a checkbox to switch between showing randomly generated FPS and real FPS + createCheckboxShowRealFPS(); + + // Create a label displaying the last FPS value + createLastFPSLabel(); + + // Create a label with description of the Sample + createDescriptionLabel(); + + /* We will render custom geometry in two different ways. The first uses an SVGImage with attached customly defined + SVGData. The SVGImage will be part of a window inside a Framewindow which can be moved around. The second directly + modifies a Geometrybuffer to render user-defined vertices directly on the screen. */ + + /* Our first method uses the SVGImage class of CEGUI. The SVGImage references an SVGData object that we will create. + This SVGData object commonly contains what is parsed from an SVG file. In our case we will manually create SVG BasicShape + objects, such as a polyline, which connects several points with lines, and add them to the SVGData. The SVGImage can be used + in the same way as a regular raster graphics Image (BitmapImage) in CEGUI and can therefore be set as a property of a window + that will then render the Image automatically, with appropriate scaling etc. + */ + setupCustomSVGImage(); + // We create a drag- and sizable FrameWindow and add a child-window to it that will render our SVGImage + createCustomSVGImageWindows(); + // We add labels to our graph using windows + createCustomSVGImageFPSLabels(); + + + /* Our second method directly modifies a GeometryBuffer of CEGUI. This has the disadvantage that we will have to calculate all + vertex positions of all triangles forming the geometry ourselves before filling them in. Compared to using SVGData and creating + and modifying SVG BasicShapes this can be inconvenient. Additionally, we cannot make our geometry be used in connection with a window, so that it could be moved around etc. wever this can be of great + use for overlays or backgrounds that use custom geometry that is calculated by the user. */ + setupCustomGeometryGraph(guiContext); + // We add labels to our graph using windows + createCustomGeometryFPSLabels(); + + + // Subscribe handler to reposition our labels when the window size is changed + CEGUI::System::getSingleton().subscribeEvent( + CEGUI::System::EventDisplaySizeChanged, + CEGUI::Event::Subscriber(&CustomShapesDrawingSample::handleDisplaySizeChange, + this)); + + // return true so that the samples framework knows that initialisation was a + // success, and that it should now run the sample. + return true; +} + +/************************************************************************* + Positions the GeometryBuffer based graph +*************************************************************************/ +void CustomShapesDrawingSample::positionCustomGeometryFPSGraph() +{ + CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer(); + const CEGUI::Rectf scrn(glm::vec2(0, 0), renderer->getDisplaySize()); + + d_FPSGraphGeometryBuffer->setClippingRegion(scrn); + d_FPSGraphGeometryBuffer->setTranslation(glm::vec3(250.0f, 250.0f, 0.0f)); +} + +/************************************************************************* + Triggers the drawing of our FPS graph after everything else was rendered +*************************************************************************/ +bool CustomShapesDrawingSample::drawFPSGraphOverlay(const CEGUI::EventArgs& args) +{ + if (static_cast(args).queueID != CEGUI::RQ_OVERLAY) + return false; + + // draw FPS value + d_FPSGraphGeometryBuffer->draw(); + + return true; +} + +/************************************************************************* + Update the FPS graph geometry when necessary +*************************************************************************/ +void CustomShapesDrawingSample::update(float timeSinceLastUpdate) +{ + updateFPS(timeSinceLastUpdate); + positionCustomGeometryFPSGraph(); +} + +/************************************************************************* + Update the FPS value +*************************************************************************/ +void CustomShapesDrawingSample::updateFPS(const float elapsed) +{ + // another frame + ++d_FPSFrames; + + // Add FPS count if a second has passed + if ((d_FPSElapsed += elapsed) >= 1.0f) + { + if(d_useRealFPS) + updateFPSData(d_FPSFrames); + else + { + int randomFPS = 50 + rand() % 60; + updateFPSData(randomFPS); + } + + // reset counter state + d_FPSFrames = 0; + float modValue = 1.0f; + d_FPSElapsed = std::modf(d_FPSElapsed, &modValue); + } +} + + +/************************************************************************* + Cleans up resources allocated in the initialiseSample call. +*************************************************************************/ +void CustomShapesDrawingSample::deinitialise() +{ + // Destroy the GeometryBuffer created for this sample + CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer(); + renderer->destroyGeometryBuffer(*d_FPSGraphGeometryBuffer); + // Destroy the SVGImage created for this sample + CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton(); + imageManager.destroy("FPSGraphSVG"); + // Destroy the created custom SVGData + CEGUI::SVGDataManager& svgDataManager = CEGUI::SVGDataManager::getSingleton(); + svgDataManager.destroy(*d_customSVGData); + + // This destroys the window and its child windows + WindowManager& winMgr = WindowManager::getSingleton(); + winMgr.destroyWindow(d_root); +} + +/************************************************************************* + Update the geometry used for the FPS graph +*************************************************************************/ +void CustomShapesDrawingSample::updateFPSGraphs() +{ + d_FPSGraphGeometryBuffer->reset(); + + std::vector linePositions; + + for(unsigned int i = 0; i < d_FPSGraphSamplesCount; ++i) + { + float currentOffset = i / static_cast(d_FPSGraphSamplesCount - 1); + + float relative_height = d_lastFPSValues.at(i) / static_cast(d_FPSMaxGraphValue); + + glm::vec2 currentPosition(currentOffset, relative_height); + linePositions.push_back(currentPosition); + } + + // We will update the SVG Polyline object by simply passing the linepoints to it and triggering + // a re-draw of the Image. + updateCustomSVGImagePolyline(linePositions); + + // Update the FPS labels for the SVGImage + updateCustomSVGImageFPSLabels(); + + // We will update the GeometryBuffer which contains our line vertices. We will need to calculate + // the vertices of a line with a width of 1.0 and which will be rendered in green colour. + updateCustomGeometryGraph(linePositions); + + // Update the FPS Labels for the GeometryBuffer + updateCustomGeometryFPSLabels(); + +} + +/************************************************************************* + Update the FPS graph geometry +*************************************************************************/ +void CustomShapesDrawingSample::updateCustomGeometryGraph(std::vector linePositions) +{ + // Reset all geometry data + d_FPSGraphGeometryBuffer->reset(); + + // Add the background vertices + d_FPSGraphGeometryBuffer->appendGeometry(d_customGeometryGraphBackgroundVertices); + + //Precalculate y and y coordinate of first point + linePositions.at(0).x = 0.0f; + linePositions.at(0).y = d_customGeometryGraphHeight - linePositions.at(0).y * d_customGeometryGraphHeight; + + //We will draw a simple quad for each line segment + size_t linePositionsCount = linePositions.size(); + for (size_t j = 1; j < linePositionsCount; ++j) + { + const glm::vec2& prevPos = linePositions.at(j - 1); + glm::vec2& currentPos = linePositions.at(j); + + currentPos.x = currentPos.x * d_customGeometryGraphWidth * 0.95f; + currentPos.y = d_customGeometryGraphHeight - currentPos.y * d_customGeometryGraphHeight; + + // Normalize and tilt the 2D direction vector by 90� to get the vector pointing in the offset direction + glm::vec2 offsetVector = currentPos - prevPos; + offsetVector = glm::normalize(offsetVector); + offsetVector = glm::vec2(offsetVector.y, -offsetVector.x) * 1.0f; + + CEGUI::ColouredVertex linePositionVertex; + static const CEGUI::Colour lineColour(0.0f, 1.0f, 0.0f, 1.0f); + + glm::vec2 vertexPosition; + linePositionVertex.setColour(lineColour); + + linePositionVertex.d_position = glm::vec3(prevPos - offsetVector, 0.0f); + d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(currentPos - offsetVector, 0.0f); + d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(currentPos + offsetVector, 0.0f); + d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(currentPos + offsetVector, 0.0f); + d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(prevPos - offsetVector, 0.0f); + d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(prevPos + offsetVector, 0.0f); + d_FPSGraphGeometryBuffer->appendVertex(linePositionVertex); + } +} + +/************************************************************************* + Update the FPS graph SVGImage's Polyline +*************************************************************************/ +void CustomShapesDrawingSample::updateCustomSVGImagePolyline(std::vector linePositions) +{ + //! We need to scale and offset our linepoints to match the chosen SVGImage size + size_t linePosCount = linePositions.size(); + for(size_t i = 0; i < linePosCount; ++i) + { + // Calculating the position with 95% horizontal scale + linePositions[i].x = linePositions[i].x * d_customSVGImageWidth * 0.95f; + // Calculating the position with 90% vertical scale and 5% vertical offset + linePositions[i].y = d_customSVGImageHeight * 0.975f - linePositions[i].y * d_customSVGImageHeight * 0.95f; + } + + d_customPolyline->d_points = linePositions; + + d_customSVGImageWindow->invalidate(); +} + +/************************************************************************* + Sets up everything we need to draw our graph into the GeometryBuffer +*************************************************************************/ +void CustomShapesDrawingSample::setupCustomGeometryGraph(CEGUI::GUIContext* guiContext) +{ + CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer(); + + // GeometryBuffer used for drawing in this Sample + d_FPSGraphGeometryBuffer = &renderer->createGeometryBufferColoured(renderer->createRenderMaterial(DS_SOLID)); + + // Calculate and save our custom graph background + setupCustomGeometryGraphBackground(); + + // Clearing this queue actually makes sure it's created(!) + guiContext->clearGeometry(CEGUI::RQ_OVERLAY); + + // Subscribe handler to render overlay items + guiContext->subscribeEvent(CEGUI::RenderingSurface::EventRenderQueueStarted, + CEGUI::Event::Subscriber(&CustomShapesDrawingSample::drawFPSGraphOverlay, + this)); +} + +/************************************************************************* + Sets up everything we need to draw our graph using an SVGImage object +*************************************************************************/ +void CustomShapesDrawingSample::setupCustomSVGImage() +{ + // Create an SVGImage using the ImageManager + CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton(); + d_customSVGImage = static_cast(&imageManager.create("SVGImage", "FPSGraphSVG")); + // Create an SVGData object + CEGUI::SVGDataManager& svgDataManager = CEGUI::SVGDataManager::getSingleton(); + d_customSVGData = &svgDataManager.create(CEGUI::String("FPSGraphCustomShape")); + + // Set the desired size of the SVGData + d_customSVGData->setWidth(d_customSVGImageWidth); + d_customSVGData->setHeight(d_customSVGImageHeight); + + // Set the pointer to the SVGData for the SVGImage + d_customSVGImage->setSVGData(d_customSVGData); + // We make our SVGImage the same size as the SVGData + const Rectf imageArea(glm::vec2(0, 0), CEGUI::Sizef(d_customSVGData->getWidth(), d_customSVGData->getHeight())); + d_customSVGImage->setImageArea(imageArea); + + // We create a graph background consisting of a grey background and some lines for better readability + setupCustomSVGImageGraphBackground(*d_customSVGData); + + // We create polyline object for the visualisation of the last FPS values. It contains no points yet. + std::vector pointsList; + d_customPolyline = new SVGPolyline(SVGPaintStyle(), glm::mat3x3(1.0f), pointsList); + d_customPolyline->d_paintStyle.d_stroke.d_colour = glm::vec3(0.0f, 1.0f, 0.0f); + d_customPolyline->d_paintStyle.d_strokeLinejoin = SVGPaintStyle::SLJ_ROUND; + d_customPolyline->d_paintStyle.d_strokeWidth = 2.0f; + //By default the SVG standard has the default fill set to black. We do not want any fill so we switch it to "none". + d_customPolyline->d_paintStyle.d_fill.d_none = true; + + //We add the created shape to the SVGData object + d_customSVGData->addShape(d_customPolyline); +} + +/************************************************************************* + Refreshes the maximum value that will be visualised in the graph +*************************************************************************/ +void CustomShapesDrawingSample::refreshFPSMaxGraphValue() +{ + d_FPSMaxGraphValue = 0; + + size_t lastFPSValuesCount = d_lastFPSValues.size(); + for(size_t i = 0; i < lastFPSValuesCount; ++i) + d_FPSMaxGraphValue = std::max(d_FPSMaxGraphValue, d_lastFPSValues[i]); +} + +/************************************************************************* + Creates a checkbox to let the user choose to display randomised or real FPS value +*************************************************************************/ +void CustomShapesDrawingSample::createCheckboxShowRealFPS() +{ + WindowManager& winMgr = WindowManager::getSingleton(); + + // We create a button and subscribe to its click events + ToggleButton* checkboxShowRealFPS = static_cast(winMgr.createWindow("WindowsLook/Checkbox")); + checkboxShowRealFPS->setSize(CEGUI::USize(cegui_reldim(0.25f), cegui_reldim(0.035f))); + checkboxShowRealFPS->setHorizontalAlignment(HA_CENTRE); + checkboxShowRealFPS->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.13f))); + checkboxShowRealFPS->setText("Show randomly generated FPS values"); + checkboxShowRealFPS->subscribeEvent(ToggleButton::EventSelectStateChanged, Event::Subscriber(&CustomShapesDrawingSample::handleToggleButtonShowRandomisedFpsSelectionChanged, this)); + checkboxShowRealFPS->setSelected(true); + d_root->addChild(checkboxShowRealFPS); +} + +/************************************************************************* + Creates a label that will display our last FPS value +*************************************************************************/ +void CustomShapesDrawingSample::createLastFPSLabel() +{ + WindowManager& winMgr = WindowManager::getSingleton(); + + // We create a button and subscribe to its click events + d_lastFPSLabel = winMgr.createWindow("Generic/Label"); + d_lastFPSLabel->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.035f))); + d_lastFPSLabel->setHorizontalAlignment(HA_CENTRE); + d_lastFPSLabel->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.18f))); + d_root->addChild(d_lastFPSLabel); +} + +/************************************************************************* + Creates a label that contains a description of what is seen in the sample +*************************************************************************/ +void CustomShapesDrawingSample::createDescriptionLabel() +{ + WindowManager& winMgr = WindowManager::getSingleton(); + + // We create a button and subscribe to its click events + CEGUI::Window* descriptionLabel = winMgr.createWindow("Generic/Label"); + descriptionLabel->setSize(CEGUI::USize(cegui_reldim(0.8f), cegui_reldim(0.25f))); + descriptionLabel->setHorizontalAlignment(HA_CENTRE); + descriptionLabel->setProperty("HorzFormatting", "WordWrapCentreAligned"); + descriptionLabel->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_absdim(400.0f))); + d_root->addChild(descriptionLabel); + descriptionLabel->setText("The left graph is rendered directly into a GeometryBuffer and rendered as overlay." + "The right graph is created using an SVGImage with modified SVGData and is then used in the same way as a regular CEGUI image" + " - it is set as a property for a window that renders the image. \n\n" + "The benefit of creating custom geometry by using an SVGImage and its SVGData is that it can be conveniently added to a CEGUI Window " + "and that defining primitive objects, such as lines, rectangles etc., is easier. Additionally, the internal CEGUI SVG classes which " + "create the geometry offer an anti-aliasing option that delivers anti-aliasing at almost no extra performance cost for the GPU."); +} + +/************************************************************************* + Event handler for the FPS value checkbox selection change +*************************************************************************/ +bool CustomShapesDrawingSample::handleToggleButtonShowRandomisedFpsSelectionChanged(const CEGUI::EventArgs& args) +{ + const CEGUI::WindowEventArgs& winArgs = static_cast(args); + CEGUI::ToggleButton* checkbox = static_cast(winArgs.window); + + d_useRealFPS = !checkbox->isSelected(); + + return true; +} + +/************************************************************************* + Updates everything needed for the graphs and then the graphs themselves +*************************************************************************/ +void CustomShapesDrawingSample::updateFPSData(int newFPSValue) +{ + //Update the window displaying the current FPS as text + std::stringstream sstream; + sstream << newFPSValue; + d_lastFPSLabel->setText(CEGUI::String("Currently recorded FPS: " + sstream.str())); + + d_lastFPSValues.pop_front(); + d_lastFPSValues.push_back(newFPSValue); + refreshFPSMaxGraphValue(); + + //Update the graphs + updateFPSGraphs(); +} + +/************************************************************************* + Sets up the background of the GeometryBuffer-based graph +*************************************************************************/ +void CustomShapesDrawingSample::setupCustomGeometryGraphBackground() +{ + // Add a grey background quad + static const glm::vec2 topLeft(0.0f, 0.0f); + static const glm::vec2 bottomLeft(0.0f, d_customGeometryGraphHeight); + static const glm::vec2 topRight(d_customGeometryGraphWidth * 0.9f + d_customGeometryGraphWidth * 0.05f, 0.0f); + static const glm::vec2 bottomRight(d_customGeometryGraphWidth * 0.9f + d_customGeometryGraphWidth * 0.05f, d_customGeometryGraphHeight); + + // Defining some colours we will use + static const CEGUI::Colour backgroundQuadColour(0.3f, 0.3f, 0.3f, 1.0f); + static const CEGUI::Colour lineColour(0.5f, 0.5f, 0.5f, 1.0f); + + CEGUI::ColouredVertex backgroundQuadVertex; + backgroundQuadVertex.setColour(backgroundQuadColour); + + backgroundQuadVertex.d_position = glm::vec3(topLeft, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex); + + backgroundQuadVertex.d_position = glm::vec3(bottomLeft, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex); + + backgroundQuadVertex.d_position = glm::vec3(topRight, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex); + + backgroundQuadVertex.d_position = glm::vec3(topRight, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex); + + backgroundQuadVertex.d_position = glm::vec3(bottomLeft, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex); + + backgroundQuadVertex.d_position = glm::vec3(bottomRight, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(backgroundQuadVertex); + + // We save some horizontical line vertices that we will use for our graph's background. + CEGUI::ColouredVertex linePositionVertex; + linePositionVertex.setColour(lineColour); + + size_t lineCount = 7; + for (size_t i = 0; i < lineCount; ++i) + { + const float currentHeight = d_customGeometryGraphHeight * i / (lineCount - 1); + const glm::vec2 linePointBegin(0.0f, currentHeight); + const glm::vec2 linePointEnd(d_customGeometryGraphWidth, currentHeight); + + glm::vec2 offsetVector(0.0f, 0.5f); + + linePositionVertex.d_position = glm::vec3(linePointBegin - offsetVector, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(linePointEnd - offsetVector, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(linePointEnd + offsetVector, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(linePointEnd + offsetVector, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(linePointBegin - offsetVector, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex); + + linePositionVertex.d_position = glm::vec3(linePointBegin + offsetVector, 0.0f); + d_customGeometryGraphBackgroundVertices.push_back(linePositionVertex); + } +} + +/************************************************************************* + Creates the labels that we will use to display the FPS values next to the GeometryBuffer-based graph +*************************************************************************/ +void CustomShapesDrawingSample::createCustomGeometryFPSLabels() +{ + WindowManager& winMgr = WindowManager::getSingleton(); + + // We create a button and subscribe to its click events + d_customGeometryFPSLabel1 = winMgr.createWindow("Generic/Label"); + d_customGeometryFPSLabel1->setSize(CEGUI::USize(cegui_absdim(100.0f), cegui_reldim(0.035f))); + d_customGeometryFPSLabel1->setProperty("HorzFormatting", "LeftAligned"); + d_root->addChild(d_customGeometryFPSLabel1); + d_customGeometryFPSLabel1->setFont("DejaVuSans-10"); + + // We create a button and subscribe to its click events + d_customGeometryFPSLabel2 = winMgr.createWindow("Generic/Label"); + d_customGeometryFPSLabel2->setSize(CEGUI::USize(cegui_absdim(100.0f), cegui_reldim(0.035f))); + d_customGeometryFPSLabel2->setProperty("HorzFormatting", "LeftAligned"); + d_root->addChild(d_customGeometryFPSLabel2); + d_customGeometryFPSLabel2->setFont("DejaVuSans-10"); + + // We create a button and subscribe to its click events + d_customGeometryFPSLabel3 = winMgr.createWindow("Generic/Label"); + d_customGeometryFPSLabel3->setSize(CEGUI::USize(cegui_absdim(100.0f), cegui_reldim(0.035f))); + d_customGeometryFPSLabel3->setProperty("HorzFormatting", "LeftAligned"); + d_root->addChild(d_customGeometryFPSLabel3); + d_customGeometryFPSLabel3->setFont("DejaVuSans-10"); +} + +/************************************************************************* + Updates the labels we will display next to the graph made with the GeometryBuffer +*************************************************************************/ +void CustomShapesDrawingSample::updateCustomGeometryFPSLabels() +{ + //Calculate our top position with the half of the window's height as offset for centering + float absoluteHeight = d_customGeometryFPSLabel1->getUnclippedOuterRect().get().getHeight(); + float centeredPositionTop = 250.0f - absoluteHeight * 0.5f; + std::stringstream sstream; + + d_customGeometryFPSLabel1->setPosition(CEGUI::UVector2(cegui_absdim(550.0f + 2.0f), cegui_absdim(centeredPositionTop + 100.0f))); + d_customGeometryFPSLabel1->setText(CEGUI::String("0")); + + d_customGeometryFPSLabel2->setPosition(CEGUI::UVector2(cegui_absdim(550.0f + 2.0f), cegui_absdim(centeredPositionTop + 100.f * 0.5f))); + unsigned int halfMaxValue = d_FPSMaxGraphValue / 2; + sstream << halfMaxValue; + d_customGeometryFPSLabel2->setText(sstream.str()); + sstream.str(""); + + d_customGeometryFPSLabel3->setPosition(CEGUI::UVector2(cegui_absdim(550.0f + 2.0f), cegui_absdim(centeredPositionTop))); + sstream << d_FPSMaxGraphValue; + d_customGeometryFPSLabel3->setText(sstream.str()); +} + +/************************************************************************* + Creates the labels we will display next to the graph using the SVGImage +*************************************************************************/ +void CustomShapesDrawingSample::createCustomSVGImageFPSLabels() +{ + WindowManager& winMgr = WindowManager::getSingleton(); + + // We create a button and subscribe to its click events + d_customSVGImageFPSLabel1 = winMgr.createWindow("Generic/Label"); + d_customSVGImageFPSLabel1->setSize(CEGUI::USize(cegui_reldim(0.3f), cegui_reldim(0.15f))); + d_customSVGImageFPSLabel1->setProperty("HorzFormatting", "LeftAligned"); + d_customSVGImageFrameWindow->addChild(d_customSVGImageFPSLabel1); + d_customSVGImageFPSLabel1->setFont("DejaVuSans-10"); + + // We create a button and subscribe to its click events + d_customSVGImageFPSLabel2 = winMgr.createWindow("Generic/Label"); + d_customSVGImageFPSLabel2->setSize(CEGUI::USize(cegui_reldim(0.3f), cegui_reldim(0.15f))); + d_customSVGImageFPSLabel2->setProperty("HorzFormatting", "LeftAligned"); + d_customSVGImageFrameWindow->addChild(d_customSVGImageFPSLabel2); + d_customSVGImageFPSLabel2->setFont("DejaVuSans-10"); + + // We create a button and subscribe to its click events + d_customSVGImageFPSLabel3 = winMgr.createWindow("Generic/Label"); + d_customSVGImageFPSLabel3->setSize(CEGUI::USize(cegui_reldim(0.3f), cegui_reldim(0.15f))); + d_customSVGImageFPSLabel3->setProperty("HorzFormatting", "LeftAligned"); + d_customSVGImageFrameWindow->addChild(d_customSVGImageFPSLabel3); + d_customSVGImageFPSLabel3->setFont("DejaVuSans-10"); +} + +/************************************************************************* + Updates the labels we will display next to the graph using the SVGImage +*************************************************************************/ +void CustomShapesDrawingSample::updateCustomSVGImageFPSLabels() +{ + //Calculate our top position with the half of the window's height as offset for centering + float absoluteHeight = d_customSVGImageFPSLabel1->getUnclippedOuterRect().get().getHeight(); + float centeredPositionOffset = -absoluteHeight * 0.5f; + std::stringstream sstream; + + //We horizontically position the windows after the graph SVGImage window + CEGUI::UDim labelPosX = CEGUI::UDim(0.75f, 2.0f); + + //The vertical position is calculated from the image and window heights and results in a fixed value for the relative dimension. + d_customSVGImageFPSLabel1->setPosition(CEGUI::UVector2(labelPosX, CEGUI::UDim(0.9275f, centeredPositionOffset))); + d_customSVGImageFPSLabel1->setText(CEGUI::String("0")); + + d_customSVGImageFPSLabel2->setPosition(CEGUI::UVector2(labelPosX, CEGUI::UDim(0.5f, centeredPositionOffset))); + unsigned int halfMaxValue = d_FPSMaxGraphValue / 2; + sstream << halfMaxValue; + d_customSVGImageFPSLabel2->setText(sstream.str()); + sstream.str(""); + + d_customSVGImageFPSLabel3->setPosition(CEGUI::UVector2(labelPosX, CEGUI::UDim(0.0725f, centeredPositionOffset))); + sstream << d_FPSMaxGraphValue; + d_customSVGImageFPSLabel3->setText(sstream.str()); +} + +/************************************************************************* + Sets up the background of the SVGImage-based graph +*************************************************************************/ +void CustomShapesDrawingSample::setupCustomSVGImageGraphBackground(CEGUI::SVGData &fpsSVGData) +{ + // We make a grey quad background for the graph. We offset its position by 2.5% of the height and + // make the total height of the rect 95% of the image height. We will later do the same with our lines + // so that their strokes won't be clipped by the image's area. + SVGRect* svg_rect = new SVGRect(SVGPaintStyle(), glm::mat3x3(1.0f), + 0.0f, d_customSVGImageHeight * 0.025f, + d_customSVGImageWidth * 0.95f, d_customSVGImageHeight * 0.95f); + svg_rect->d_paintStyle.d_fill.d_colour = glm::vec3(0.3f, 0.3f, 0.3f); + // We don't want a stroke to be rendered. SVG offers a black stroke with 1 width by default. + svg_rect->d_paintStyle.d_stroke.d_none = true; + fpsSVGData.addShape(svg_rect); + + //We create our background line's style + SVGPaintStyle graphBGLineStyle; + graphBGLineStyle.d_stroke.d_colour = glm::vec3(0.5f, 0.5f, 0.5f); + graphBGLineStyle.d_strokeWidth = 0.35f; + + // We don't fill the full height because the strokes need some extra space + float adjustedHeight = d_customSVGImageHeight * 0.95f; + + // We save some horizontical line vertices that we will use for our graph's background. + size_t lineCount = 7; + for (size_t i = 0; i < lineCount; ++i) + { + // We calculate the current height of the line vertex using an offset from the top and the modified height, so that the stroke won't get clipped by the image + const float currentHeight = d_customSVGImageHeight * 0.025f + adjustedHeight * i / static_cast(lineCount - 1); + const glm::vec2 linePointBegin(0.0f, currentHeight); + const glm::vec2 linePointEnd(d_customSVGImageWidth, currentHeight); + + SVGLine* currentLine = new SVGLine(graphBGLineStyle, glm::mat3x3(1.0f), linePointBegin, linePointEnd); + fpsSVGData.addShape(currentLine); + } +} + +/************************************************************************* + Creates the windows which will be used to display the SVGImage graph +*************************************************************************/ +void CustomShapesDrawingSample::createCustomSVGImageWindows() +{ + WindowManager& winMgr = WindowManager::getSingleton(); + + //We create a draggable and resizable frame window that will contain our Image window. + d_customSVGImageFrameWindow = winMgr.createWindow("WindowsLook/FrameWindow"); + d_customSVGImageFrameWindow->setSize(CEGUI::USize(cegui_absdim(490.0f), cegui_absdim(160.0f))); + d_customSVGImageFrameWindow->setPosition(CEGUI::UVector2(cegui_reldim(0.5f), cegui_reldim(0.29f))); + d_root->addChild(d_customSVGImageFrameWindow); + d_customSVGImageFrameWindow->subscribeEvent(CEGUI::Window::EventSized, + CEGUI::Event::Subscriber(&CustomShapesDrawingSample::handleSVGImageFrameWindowSizeChanged, + this)); + + //We create the image window through which our custom SVGImage will be rendered. + d_customSVGImageWindow = winMgr.createWindow("Generic/Image"); + d_customSVGImageWindow->setSize(CEGUI::USize(cegui_reldim(0.7f), cegui_reldim(0.9f))); + d_customSVGImageWindow->setPosition(CEGUI::UVector2(cegui_reldim(0.05f), cegui_reldim(0.05f))); + d_customSVGImageFrameWindow->addChild(d_customSVGImageWindow); + d_customSVGImageWindow->setProperty("Image", "FPSGraphSVG"); +} + +/************************************************************************* + Display size change handler +*************************************************************************/ +bool CustomShapesDrawingSample::handleDisplaySizeChange(const CEGUI::EventArgs& args) +{ + updateCustomGeometryFPSLabels(); + + updateCustomSVGImageFPSLabels(); + + return false; +} + +/************************************************************************* + Handler for size changes of the custom-SVGImage FrameWindow +*************************************************************************/ +bool CustomShapesDrawingSample::handleSVGImageFrameWindowSizeChanged(const CEGUI::EventArgs& args) +{ + updateCustomSVGImageFPSLabels(); + + return false; +} diff --git a/samples/CustomShapesDrawing/CustomShapesDrawing.h b/samples/CustomShapesDrawing/CustomShapesDrawing.h new file mode 100644 index 000000000..e9c69494e --- /dev/null +++ b/samples/CustomShapesDrawing/CustomShapesDrawing.h @@ -0,0 +1,195 @@ +/*********************************************************************** + created: 16/7/2013 + author: Lukas E Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SampleCustomShapesDrawingSample_h_ +#define _SampleCustomShapesDrawingSample_h_ + +#include "SampleBase.h" + +#include "CEGUI/ForwardRefs.h" +#include "glm/glm.hpp" + +#include +#include + +namespace CEGUI +{ + class Window; + class DefaultWindow; +} + +class CustomShapesDrawingSample : public Sample +{ +public: + CustomShapesDrawingSample(); + + //! Initialises our sample + virtual bool initialise(CEGUI::GUIContext* guiContext); + + virtual void deinitialise(); + +private: + //! The general update function of our sample + void update(float timeSinceLastUpdate); + + //! Updates the counted FPS and triggers the recreation of FPS Graph geometry if needed. + void updateFPS(float timeSinceLastUpdate); + + //! Updates everything needed for the graphs including the graphs themselves + void updateFPSData(int randomFPS); + + //! Refreshes the maximum value that will be visualised in the graph + void refreshFPSMaxGraphValue(); + + //! Update the geometry used for the FPS graph + void updateFPSGraphs(); + + //! Event handler that triggers the redrawing of our GeometryBuffer-based graph. + bool drawFPSGraphOverlay(const CEGUI::EventArgs& args); + + //! Sets up everything necessary to use and render our custom SVGImage. + void setupCustomSVGImage(); + + //! Sets up the background of the SVGImage-based graph + void setupCustomSVGImageGraphBackground(CEGUI::SVGData& fpsSVGData); + + //! Sets up everything necessary to use and render our custom GeometryBuffer. + void setupCustomGeometryGraph(CEGUI::GUIContext* guiContext); + + //! Positions the GeometryBuffer based graph + void positionCustomGeometryFPSGraph(); + + //! Sets up the background of the GeometryBuffer-based graph + void setupCustomGeometryGraphBackground(); + + //! Update the FPS graph geometry + void updateCustomGeometryGraph(std::vector linePositions); + + //! Update the FPS graph SVGImage's Polyline + void updateCustomSVGImagePolyline(std::vector linePositions); + + //! Creates the labels we will display next to the graph using the SVGImage + void createCustomSVGImageFPSLabels(); + + //! Updates the labels we will display next to the graph made with the GeometryBuffer + void updateCustomGeometryFPSLabels(); + + //! Creates the windows which will be used to display the SVGImage graph + void createCustomSVGImageWindows(); + + //! Creates the labels that we will use to display the FPS values next to the GeometryBuffer-based graph + void createCustomGeometryFPSLabels(); + + //! Updates the labels we will display next to the graph using the SVGImage + void updateCustomSVGImageFPSLabels(); + + //! Creator function for our Random-FPS checkbox + void createCheckboxShowRealFPS(); + + //! Creates a label that will display our last FPS value + void createLastFPSLabel(); + + //! Creates a label that contains a description of what is seen in the sample + void createDescriptionLabel(); + + //! The event handler for clicks on the Random-FPS checkbox. + bool handleToggleButtonShowRandomisedFpsSelectionChanged(const CEGUI::EventArgs& args); + + //! Display size change handler + bool handleDisplaySizeChange(const CEGUI::EventArgs& args); + + //! Handler for size changes of the custom-SVGImage FrameWindow + bool handleSVGImageFrameWindowSizeChanged(const CEGUI::EventArgs& args); + + + + //! Our sample's root window. + CEGUI::DefaultWindow* d_root; + + //! Our window that renders the custom SVGImage. + CEGUI::Window* d_customSVGImageWindow; + + //! A Framewindow to size and drag around. It contains our custom SVGImage window. + CEGUI::Window* d_customSVGImageFrameWindow; + + //! The Polyline used to define our FPS graph lines. It will be added in the custom SVGImage's SVGData in our sample. + CEGUI::SVGPolyline* d_customPolyline; + + //! The GeometryBuffer that will be used to draw the FPS graph. + CEGUI::GeometryBuffer* d_FPSGraphGeometryBuffer; + + //! The FPS values we want to display. + std::deque d_lastFPSValues; + + //! The number of samples we want to display in our FPS graph. + unsigned int d_FPSGraphSamplesCount; + + //! Number of frames drawn so far. + int d_FPSFrames; + + //! Fraction of second elapsed (used for counting frames per second). + float d_FPSElapsed; + + //! The maximum FPS value the graph will be normalised to. + unsigned int d_FPSMaxGraphValue; + + //! Defines if we should use actual FPS values or use random generated ones of a certain range for better display. + bool d_useRealFPS; + + //! Width of the sample SVGImage + float d_customSVGImageWidth; + + //! Height of the sample SVGImage + float d_customSVGImageHeight; + + //! The vertices we generated to draw the static background of our GeometryBuffer based graph + std::vector d_customGeometryGraphBackgroundVertices; + + //! The width of the graph made using a GeometryBuffer + float d_customGeometryGraphWidth; + //! The height of the graph made using a GeometryBuffer + float d_customGeometryGraphHeight; + + //! The window displaying the last FPS + CEGUI::Window* d_lastFPSLabel; + + //! Labels that we will use to display the FPS next to the GeometryBuffer-based graph + CEGUI::Window* d_customGeometryFPSLabel1; + CEGUI::Window* d_customGeometryFPSLabel2; + CEGUI::Window* d_customGeometryFPSLabel3; + + //! Labels that we will use to display the FPS next to the SVGImage-based graph + CEGUI::Window* d_customSVGImageFPSLabel1; + CEGUI::Window* d_customSVGImageFPSLabel2; + CEGUI::Window* d_customSVGImageFPSLabel3; + + //! The custom SVGImage we will create to render one of the graphs + CEGUI::SVGImage* d_customSVGImage; + //! The custom SVGData we will use for our custom SVGImage + CEGUI::SVGData* d_customSVGData; +}; + +#endif // end of guard _Sample_FirstWindow_h_ diff --git a/samples/Demo6/CMakeLists.txt b/samples/Demo6/CMakeLists.txt index e19dde5cc..694aca6d7 100644 --- a/samples/Demo6/CMakeLists.txt +++ b/samples/Demo6/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_DEMO6 "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_DEMO6) - cegui_add_sample(CEGUISample_Demo6) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Demo6/Sample_Demo6.cpp b/samples/Demo6/Demo6.cpp similarity index 82% rename from samples/Demo6/Sample_Demo6.cpp rename to samples/Demo6/Demo6.cpp index 2a41d9f0a..3f33b2589 100644 --- a/samples/Demo6/Sample_Demo6.cpp +++ b/samples/Demo6/Demo6.cpp @@ -24,7 +24,7 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "Sample_Demo6.h" +#include "Demo6.h" #include "CEGUI/CEGUI.h" #include @@ -33,6 +33,14 @@ using namespace CEGUI; +Demo6Sample::Demo6Sample() +{ + Sample::d_name = "Demo6Sample"; + Sample::d_credits = "The CEGUI team"; + Sample::d_summary = "Demo6Sample"; + Sample::d_description = "Demo6Sample"; +} + /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ @@ -45,7 +53,7 @@ bool Demo6Sample::initialise(CEGUI::GUIContext* guiContext) // load scheme and set up defaults SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); - guiContext->getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); + guiContext->getCursor().setDefaultImage("TaharezLook/MouseArrow"); // load font and setup default if not loaded via scheme @@ -54,13 +62,13 @@ bool Demo6Sample::initialise(CEGUI::GUIContext* guiContext) guiContext->setDefaultFont(&defaultFont); // load an image to use as a background - if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + if (!ImageManager::getSingleton().isDefined("SpaceBackgroundImage")) + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow("TaharezLook/StaticImage", "root_wnd"); // set position and size - background->setPosition(UVector2(cegui_reldim(0), cegui_reldim( 0))); + background->setPosition(UVector2(cegui_reldim(0), cegui_reldim(0))); background->setSize(USize(cegui_reldim(1), cegui_reldim(1))); // disable frame and standard background background->setProperty("FrameEnabled", "false"); @@ -92,76 +100,53 @@ void Demo6Sample::deinitialise() void Demo6Sample::createDemoWindows(CEGUI::Window* root) { using namespace CEGUI; - ListboxTextItem* itm; WindowManager& winMgr = WindowManager::getSingleton(); // create the main list. MultiColumnList* mcl = static_cast(winMgr.createWindow("TaharezLook/MultiColumnList", "MainList")); root->addChild(mcl); - mcl->setPosition(UVector2(cegui_reldim(0.01f), cegui_reldim( 0.1f))); - mcl->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.8f))); + mcl->setPosition(UVector2(cegui_reldim(0.01f), cegui_reldim(0.1f))); + mcl->setSize(USize(cegui_reldim(0.5f), cegui_reldim(0.8f))); // create frame window for control panel FrameWindow* fwnd = static_cast(winMgr.createWindow("TaharezLook/FrameWindow", "ControlPanel")); root->addChild(fwnd); - fwnd->setPosition(UVector2(cegui_reldim(0.53f), cegui_reldim( 0.03f))); - fwnd->setMaxSize(USize(cegui_reldim(1.0f), cegui_reldim( 1.0f))); - fwnd->setSize(USize(cegui_reldim(0.44f), cegui_reldim( 0.94f))); + fwnd->setPosition(UVector2(cegui_reldim(0.53f), cegui_reldim(0.03f))); + fwnd->setMaxSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); + fwnd->setSize(USize(cegui_reldim(0.44f), cegui_reldim(0.94f))); fwnd->setText("Demo 6 - Control Panel"); // create combo-box. Combobox* cbbo = static_cast(winMgr.createWindow("TaharezLook/Combobox", "SelModeBox")); fwnd->addChild(cbbo); - cbbo->setPosition(UVector2(cegui_reldim(0.04f), cegui_reldim( 0.06f))); - cbbo->setSize(USize(cegui_reldim(0.66f), cegui_reldim( 0.33f))); + cbbo->setPosition(UVector2(cegui_reldim(0.04f), cegui_reldim(0.06f))); + cbbo->setSize(USize(cegui_reldim(0.66f), cegui_reldim(0.33f))); //cbbo->setSortingEnabled(true); // populate combobox with possible selection modes - const CEGUI::Image* sel_img = &ImageManager::getSingleton().get("TaharezLook/MultiListSelectionBrush"); - itm = new ListboxTextItem("Full Row (Single)", 0); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Full Row (Multiple)", 1); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Full Column (Single)", 2); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Full Column (Multiple)", 3); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Single Cell (Single)", 4); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Single Cell (Multiple)", 5); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Nominated Column (Single)", 6); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Nominated Column (Multiple)", 7); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - ListboxTextItem* pStore = itm; - itm = new ListboxTextItem("Nominated Row (Single)", 8); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); - itm = new ListboxTextItem("Nominated Row (Multiple)", 9); - itm->setSelectionBrushImage(sel_img); - cbbo->addItem(itm); + cbbo->addItem(new StandardItem("Full Row (Single)", 0)); + cbbo->addItem(new StandardItem("Full Row (Multiple)", 1)); + cbbo->addItem(new StandardItem("Full Column (Single)", 2)); + cbbo->addItem(new StandardItem("Full Column (Multiple)", 3)); + cbbo->addItem(new StandardItem("Single Cell (Single)", 4)); + cbbo->addItem(new StandardItem("Single Cell (Multiple)", 5)); + cbbo->addItem(new StandardItem("Nominated Column (Single)", 6)); + StandardItem* pStore = new StandardItem("Nominated Column (Multiple)", 7); + cbbo->addItem(pStore); + cbbo->addItem(new StandardItem("Nominated Row (Single)", 8)); + cbbo->addItem(new StandardItem("Nominated Row (Multiple)", 9)); cbbo->setReadOnly(true); // Now change the text to test the sorting pStore->setText("Abracadabra"); - //cbbo->setSortingEnabled(false); cbbo->setSortingEnabled(true); - //cbbo->handleUpdatedListItemData(); + cbbo->handleUpdatedListItemData(); // column control section Window* st = winMgr.createWindow("TaharezLook/StaticText", "ColumnPanel"); fwnd->addChild(st); - st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.12f))); - st->setSize(USize(cegui_reldim(0.96f), cegui_reldim( 0.25f))); + st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.12f))); + st->setSize(USize(cegui_reldim(0.96f), cegui_reldim(0.25f))); st->setText("Column Control"); st->setProperty("VertFormatting", "TopAligned"); @@ -169,76 +154,76 @@ void Demo6Sample::createDemoWindows(CEGUI::Window* root) st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("ID Code:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label2"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Width:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label3"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Caption:"); PushButton* btn = static_cast(winMgr.createWindow("TaharezLook/Button", "AddColButton")); st->addChild(btn); - btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim( 0.32f))); - btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim( 0.2f))); + btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim(0.32f))); + btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim(0.2f))); btn->setText("Add"); Editbox* ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "NewColIDBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox->setText("Test -- "); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "NewColWidthBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "NewColTextBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.36f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.36f), cegui_reldim(0.2f))); ebox->setValidationString(".*"); label = winMgr.createWindow("TaharezLook/StaticText", "Label4"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.55f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.55f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("ID Code:"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "DelColIDBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.67f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.67f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); btn = static_cast(winMgr.createWindow("TaharezLook/Button", "DelColButton")); st->addChild(btn); - btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.67f))); - btn->setSize(USize(cegui_reldim(0.4f), cegui_reldim( 0.2f))); + btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim(0.67f))); + btn->setSize(USize(cegui_reldim(0.4f), cegui_reldim(0.2f))); btn->setText("Delete Column"); // Row control box st = winMgr.createWindow("TaharezLook/StaticText", "RowControl"); fwnd->addChild(st); - st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.38f))); - st->setSize(USize(cegui_reldim(0.96f), cegui_reldim( 0.25f))); + st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.38f))); + st->setSize(USize(cegui_reldim(0.96f), cegui_reldim(0.25f))); st->setText("Row Control"); st->setProperty("VertFormatting", "TopAligned"); @@ -246,61 +231,61 @@ void Demo6Sample::createDemoWindows(CEGUI::Window* root) st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Col ID:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label6"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.55f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.55f), cegui_reldim(0.12f))); label->setText("Item Text:"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "RowColIDBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "RowTextBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.55f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.55f), cegui_reldim(0.2f))); ebox->setValidationString(".*"); btn = static_cast(winMgr.createWindow("TaharezLook/Button", "AddRowButton")); st->addChild(btn); - btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim( 0.32f))); - btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim( 0.2f))); + btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim(0.32f))); + btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim(0.2f))); btn->setText("Add"); label = winMgr.createWindow("TaharezLook/StaticText", "Label7"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.55f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.55f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Row Idx:"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "DelRowIdxBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.67f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.67f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); btn = static_cast(winMgr.createWindow("TaharezLook/Button", "DelRowButton")); st->addChild(btn); - btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.67f))); - btn->setSize(USize(cegui_reldim(0.4f), cegui_reldim( 0.2f))); + btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim(0.67f))); + btn->setSize(USize(cegui_reldim(0.4f), cegui_reldim(0.2f))); btn->setText("Delete Row"); // set item box st = winMgr.createWindow("TaharezLook/StaticText", "SetItemPanel"); fwnd->addChild(st); - st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.65f))); - st->setSize(USize(cegui_reldim(0.96f), cegui_reldim( 0.25f))); + st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.65f))); + st->setSize(USize(cegui_reldim(0.96f), cegui_reldim(0.25f))); st->setText("Item Modification"); st->setProperty("VertFormatting", "TopAligned"); @@ -308,78 +293,78 @@ void Demo6Sample::createDemoWindows(CEGUI::Window* root) st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Row Idx:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label9"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Col ID:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label10"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim( 0.2f))); - label->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.2f))); + label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Item Text:"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "SetItemRowBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "SetItemIDBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast(winMgr.createWindow("TaharezLook/Editbox", "SetItemTextBox")); st->addChild(ebox); - ebox->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim( 0.32f))); - ebox->setSize(USize(cegui_reldim(0.36f), cegui_reldim( 0.2f))); + ebox->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.32f))); + ebox->setSize(USize(cegui_reldim(0.36f), cegui_reldim(0.2f))); ebox->setValidationString(".*"); btn = static_cast(winMgr.createWindow("TaharezLook/Button", "SetItemButton")); st->addChild(btn); - btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim( 0.32f))); - btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim( 0.2f))); + btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim(0.32f))); + btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim(0.2f))); btn->setText("Set"); label = winMgr.createWindow("TaharezLook/StaticText", "RowCount"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.55f))); - label->setSize(USize(cegui_reldim(1.0f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.55f))); + label->setSize(USize(cegui_reldim(1.0f), cegui_reldim(0.12f))); label->setText("Current Row Count:"); label = winMgr.createWindow("TaharezLook/StaticText", "ColCount"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.67f))); - label->setSize(USize(cegui_reldim(1.0f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.67f))); + label->setSize(USize(cegui_reldim(1.0f), cegui_reldim(0.12f))); label->setText("Current Column Count:"); label = winMgr.createWindow("TaharezLook/StaticText", "SelCount"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); - label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim( 0.79f))); - label->setSize(USize(cegui_reldim(1.0f), cegui_reldim( 0.12f))); + label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.79f))); + label->setSize(USize(cegui_reldim(1.0f), cegui_reldim(0.12f))); label->setText("Current Selected Count:"); btn = static_cast(winMgr.createWindow("TaharezLook/Button", "QuitButton")); fwnd->addChild(btn); - btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.93f))); - btn->setSize(USize(cegui_reldim(0.50f), cegui_reldim( 0.05f))); + btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim(0.93f))); + btn->setSize(USize(cegui_reldim(0.50f), cegui_reldim(0.05f))); btn->setText("Quit This Demo!"); } @@ -409,8 +394,8 @@ void Demo6Sample::initDemoEventWiring(CEGUI::Window* root) subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleSetItem, this)); // subscribe handler that quits the application - root->getChild("ControlPanel/QuitButton")-> - subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleQuit, this)); + root->getChild("ControlPanel/QuitButton")-> + subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleQuit, this)); // subscribe handler that processes a change in the 'selection mode' combobox root->getChild("ControlPanel/SelModeBox")-> @@ -628,12 +613,12 @@ bool Demo6Sample::handleSelectModeChanged(const CEGUI::EventArgs& args) Combobox* combo = static_cast(static_cast(args).window->getRootWindow()->getChild("ControlPanel/SelModeBox")); // find the selected item in the combobox - ListboxItem* item = combo->findItemWithText(combo->getText(), 0); + StandardItem* item = combo->findItemWithText(combo->getText(), 0); // set new selection mode according to ID of selected ListboxItem if (item) { - switch (item->getID()) + switch (item->getId()) { case 0: mcl->setSelectionMode(MultiColumnList::RowSingle); @@ -713,12 +698,3 @@ bool Demo6Sample::handleContentsChanged(const CEGUI::EventArgs& args) // event was handled. return true; } - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static Demo6Sample sample; - return sample; -} \ No newline at end of file diff --git a/samples/Demo6/Sample_Demo6.h b/samples/Demo6/Demo6.h similarity index 95% rename from samples/Demo6/Sample_Demo6.h rename to samples/Demo6/Demo6.h index d79a56c9e..bcf1911bb 100644 --- a/samples/Demo6/Sample_Demo6.h +++ b/samples/Demo6/Demo6.h @@ -24,8 +24,8 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_Demo6_h_ -#define _Sample_Demo6_h_ +#ifndef _Demo6Sample_h_ +#define _Demo6Sample_h_ #include "SampleBase.h" @@ -40,6 +40,8 @@ namespace CEGUI class Demo6Sample : public Sample { public: + Demo6Sample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); // method to perform any required cleanup operations. @@ -62,4 +64,4 @@ class Demo6Sample : public Sample bool handleContentsChanged(const CEGUI::EventArgs& e); }; -#endif // end of guard _Sample_Demo6_h_ +#endif // end of guard _Demo6Sample_h_ diff --git a/samples/Demo8/CMakeLists.txt b/samples/Demo8/CMakeLists.txt index fe47d42c1..694aca6d7 100644 --- a/samples/Demo8/CMakeLists.txt +++ b/samples/Demo8/CMakeLists.txt @@ -1,6 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_DEMO8 "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_DEMO8) - cegui_add_sample(CEGUISample_Demo8) -endif() +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_LUA_SCRIPTMODULE_LIBNAME}) \ No newline at end of file +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Demo8/Sample_Demo8.cpp b/samples/Demo8/Demo8.cpp similarity index 99% rename from samples/Demo8/Sample_Demo8.cpp rename to samples/Demo8/Demo8.cpp index c813898ee..42c46250b 100644 --- a/samples/Demo8/Sample_Demo8.cpp +++ b/samples/Demo8/Demo8.cpp @@ -24,7 +24,7 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "Sample_Demo8.h" +#include "Demo8.h" #include "CEGUI/CEGUI.h" #include "CEGUI/ScriptModules/Lua/ScriptModule.h" diff --git a/samples/Demo8/Sample_Demo8.h b/samples/Demo8/Demo8.h similarity index 93% rename from samples/Demo8/Sample_Demo8.h rename to samples/Demo8/Demo8.h index c3189c376..e615b7362 100644 --- a/samples/Demo8/Sample_Demo8.h +++ b/samples/Demo8/Demo8.h @@ -24,14 +24,14 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_Demo8_h_ -#define _Sample_Demo8_h_ +#ifndef _Demo8_h_ +#define _Demo8_h_ #include "CEGuiSample.h" #include "CEGUI/CEGUI.h" // Sample class -class Demo8Sample : public CEGuiSample +class Demo8 : public CEGuiSample { public: // method to initialse the samples windows and events. @@ -43,4 +43,4 @@ class Demo8Sample : public CEGuiSample protected: }; -#endif // end of guard _Sample_Demo7_h_ +#endif // end of guard _Demo8_h_ diff --git a/samples/DragDrop/CMakeLists.txt b/samples/DragDrop/CMakeLists.txt index c937c7089..694aca6d7 100644 --- a/samples/DragDrop/CMakeLists.txt +++ b/samples/DragDrop/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_DRAG_AND_DROP "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_DRAG_AND_DROP) - cegui_add_sample(CEGUISample_DragAndDrop) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/DragDrop/Sample_DragAndDrop.cpp b/samples/DragDrop/DragDrop.cpp similarity index 84% rename from samples/DragDrop/Sample_DragAndDrop.cpp rename to samples/DragDrop/DragDrop.cpp index bbfdbb29b..aae91e9d3 100644 --- a/samples/DragDrop/Sample_DragAndDrop.cpp +++ b/samples/DragDrop/DragDrop.cpp @@ -24,11 +24,21 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "Sample_DragAndDrop.h" +#include "DragDrop.h" #include "CEGUI/CEGUI.h" //----------------------------------------------------------------------------// -bool DragDropDemo::initialise(CEGUI::GUIContext* guiContext) +DragDropSample::DragDropSample() : + Sample(96) +{ + Sample::d_name = "DragDropSample"; + Sample::d_credits = "The CEGUI team"; + Sample::d_summary = "Drag and drop Sample"; + Sample::d_description = "Drag and drop Sample"; +} + +//----------------------------------------------------------------------------// +bool DragDropSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -44,14 +54,14 @@ bool DragDropDemo::initialise(CEGUI::GUIContext* guiContext) guiContext->setDefaultFont(&defaultFont); // set up defaults - guiContext->getMouseCursor().setDefaultImage("WindowsLook/MouseArrow"); + guiContext->getCursor().setDefaultImage("WindowsLook/MouseArrow"); // load the drive icons imageset ImageManager::getSingleton().loadImageset("DriveIcons.imageset"); // load the initial layout guiContext->setRootWindow( - WindowManager::getSingleton().loadLayoutFromFile("DragDropDemo.layout")); + WindowManager::getSingleton().loadLayoutFromFile("DragDropSample.layout")); // setup events subscribeEvents(); @@ -61,13 +71,13 @@ bool DragDropDemo::initialise(CEGUI::GUIContext* guiContext) } //----------------------------------------------------------------------------// -void DragDropDemo::deinitialise() +void DragDropSample::deinitialise() { // nothing doing in here! } //----------------------------------------------------------------------------// -void DragDropDemo::subscribeEvents() +void DragDropSample::subscribeEvents() { using namespace CEGUI; @@ -81,7 +91,7 @@ void DragDropDemo::subscribeEvents() Window* main_wnd = root->getChild("MainWindow"); main_wnd->subscribeEvent( FrameWindow::EventCloseClicked, - Event::Subscriber(&DragDropDemo::handle_CloseButton, this)); + Event::Subscriber(&DragDropSample::handle_CloseButton, this)); } // if something goes wrong, log the issue but do not bomb! CEGUI_CATCH(CEGUI::Exception&) @@ -103,7 +113,7 @@ void DragDropDemo::subscribeEvents() // subscribe the handler. wnd->subscribeEvent( Window::EventDragDropItemDropped, - Event::Subscriber(&DragDropDemo::handle_ItemDropped, this)); + Event::Subscriber(&DragDropSample::handle_ItemDropped, this)); } // if something goes wrong, log the issue but do not bomb! CEGUI_CATCH(CEGUI::Exception&) @@ -112,7 +122,7 @@ void DragDropDemo::subscribeEvents() } //----------------------------------------------------------------------------// -bool DragDropDemo::handle_ItemDropped(const CEGUI::EventArgs& args) +bool DragDropSample::handle_ItemDropped(const CEGUI::EventArgs& args) { using namespace CEGUI; @@ -134,19 +144,7 @@ bool DragDropDemo::handle_ItemDropped(const CEGUI::EventArgs& args) } //----------------------------------------------------------------------------// -bool DragDropDemo::handle_CloseButton(const CEGUI::EventArgs&) +bool DragDropSample::handle_CloseButton(const CEGUI::EventArgs&) { return true; -} - -//----------------------------------------------------------------------------// - - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static DragDropDemo sample; - return sample; } \ No newline at end of file diff --git a/samples/DragDrop/Sample_DragAndDrop.h b/samples/DragDrop/DragDrop.h similarity index 93% rename from samples/DragDrop/Sample_DragAndDrop.h rename to samples/DragDrop/DragDrop.h index a103bb38e..7f291cf5c 100644 --- a/samples/DragDrop/Sample_DragAndDrop.h +++ b/samples/DragDrop/DragDrop.h @@ -24,8 +24,8 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_DragDropDemo_h_ -#define _Sample_DragDropDemo_h_ +#ifndef _DragDropSample_h_ +#define _DragDropSample_h_ #include "SampleBase.h" @@ -36,9 +36,11 @@ namespace CEGUI } // Sample class -class DragDropDemo : public Sample +class DragDropSample : public Sample { public: + DragDropSample(); + // override member to initialse the sample. virtual bool initialise(CEGUI::GUIContext* guiContext); // override member to perform cleanup. @@ -55,5 +57,5 @@ class DragDropDemo : public Sample CEGUI::GUIContext* d_guiContext; }; -#endif // end of guard _Sample_DragDropDemo_h_ +#endif // end of guard _DragDropSample_h_ diff --git a/samples/DragDrop/SampleMetaData.xml b/samples/DragDrop/SampleMetaData.xml deleted file mode 100644 index af596976d..000000000 --- a/samples/DragDrop/SampleMetaData.xml +++ /dev/null @@ -1,6 +0,0 @@ - diff --git a/samples/EditboxValidation/CMakeLists.txt b/samples/EditboxValidation/CMakeLists.txt index 01789b743..694aca6d7 100644 --- a/samples/EditboxValidation/CMakeLists.txt +++ b/samples/EditboxValidation/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_EDITBOX_VALIDATION "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_EDITBOX_VALIDATION) - cegui_add_sample(CEGUISample_EditboxValidation) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/EditboxValidation/EditboxValidation.cpp b/samples/EditboxValidation/EditboxValidation.cpp index 8717f9c94..91907cde8 100644 --- a/samples/EditboxValidation/EditboxValidation.cpp +++ b/samples/EditboxValidation/EditboxValidation.cpp @@ -28,7 +28,21 @@ #include "CEGUI/CEGUI.h" //----------------------------------------------------------------------------// -bool EditboxValidation::initialise(CEGUI::GUIContext* guiContext) +EditboxValidationSample::EditboxValidationSample() +{ + Sample::d_name = "EditboxValidationSample"; + Sample::d_credits = "CrazyEddie"; + Sample::d_description = + "The \"RegexMatchStateEventArgs\" are used in the Sample to retrieve " + "the validation status of a text matched against a regular expression"; + Sample::d_summary = + "Displays how text can be validated. In the Sample an editbox is presented which " + "validates incoming text. Partially valid, valid and invalid entries in the " + "editbox are displayed using different text colours"; +} + +//----------------------------------------------------------------------------// +bool EditboxValidationSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -40,7 +54,7 @@ bool EditboxValidation::initialise(CEGUI::GUIContext* guiContext) guiContext->setDefaultFont(&defaultFont); SchemeManager::getSingleton().createFromFile("AlfiskoSkin.scheme"); - guiContext->getMouseCursor().setDefaultImage("AlfiskoSkin/MouseArrow"); + guiContext->getCursor().setDefaultImage("AlfiskoSkin/MouseArrow"); WindowManager& winMgr = WindowManager::getSingleton(); Window* root = winMgr.createWindow("DefaultWindow"); @@ -49,7 +63,7 @@ bool EditboxValidation::initialise(CEGUI::GUIContext* guiContext) Window* wnd = root->createChild("AlfiskoSkin/FrameWindow"); wnd->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.25f))); wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f))); - wnd->setText("Editbox Validation Demo"); + wnd->setText("Editbox Validation Sample"); Window* label = wnd->createChild("AlfiskoSkin/Label"); label->setProperty("HorzFormatting", "WordWrapCentreAligned"); @@ -64,7 +78,7 @@ bool EditboxValidation::initialise(CEGUI::GUIContext* guiContext) eb->setSize(USize(cegui_reldim(0.8f), cegui_reldim(0.15f))); eb->subscribeEvent( Editbox::EventTextValidityChanged, - Event::Subscriber(&EditboxValidation::validationChangeHandler, this)); + Event::Subscriber(&EditboxValidationSample::validationChangeHandler, this)); eb->setValidationString("[0-9]{4}"); eb->activate(); @@ -73,7 +87,7 @@ bool EditboxValidation::initialise(CEGUI::GUIContext* guiContext) } //----------------------------------------------------------------------------// -bool EditboxValidation::validationChangeHandler(const CEGUI::EventArgs& args) +bool EditboxValidationSample::validationChangeHandler(const CEGUI::EventArgs& args) { using namespace CEGUI; const RegexMatchStateEventArgs& ra( @@ -99,24 +113,13 @@ bool EditboxValidation::validationChangeHandler(const CEGUI::EventArgs& args) } //----------------------------------------------------------------------------// -bool EditboxValidation::quitButtonHandler(const CEGUI::EventArgs& args) +bool EditboxValidationSample::quitButtonHandler(const CEGUI::EventArgs& args) { return true; } //----------------------------------------------------------------------------// -void EditboxValidation::deinitialise() +void EditboxValidationSample::deinitialise() { // nothing to do here! } - -//----------------------------------------------------------------------------// - -/************************************************************************* -Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static EditboxValidation sample; - return sample; -} diff --git a/samples/EditboxValidation/EditboxValidation.h b/samples/EditboxValidation/EditboxValidation.h index 6aae92e72..f333393fc 100644 --- a/samples/EditboxValidation/EditboxValidation.h +++ b/samples/EditboxValidation/EditboxValidation.h @@ -24,15 +24,17 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _EditboxValidation_h_ -#define _EditboxValidation_h_ +#ifndef _EditboxValidationSample_h_ +#define _EditboxValidationSample_h_ #include "SampleBase.h" #include "CEGUI/EventArgs.h" -class EditboxValidation : public Sample +class EditboxValidationSample : public Sample { public: + EditboxValidationSample(); + bool initialise(CEGUI::GUIContext* guiContext); void deinitialise(); diff --git a/samples/EditboxValidation/SampleMetaData.xml b/samples/EditboxValidation/SampleMetaData.xml deleted file mode 100644 index c366a9340..000000000 --- a/samples/EditboxValidation/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/Fonts/CMakeLists.txt b/samples/Fonts/CMakeLists.txt index c22e96a39..694aca6d7 100644 --- a/samples/Fonts/CMakeLists.txt +++ b/samples/Fonts/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_FONTS "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_FONTS) - cegui_add_sample(CEGUISample_Fonts) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Fonts/Sample_FontsDemo.cpp b/samples/Fonts/Fonts.cpp similarity index 76% rename from samples/Fonts/Sample_FontsDemo.cpp rename to samples/Fonts/Fonts.cpp index fd53c5faf..1bf9641a6 100644 --- a/samples/Fonts/Sample_FontsDemo.cpp +++ b/samples/Fonts/Fonts.cpp @@ -29,7 +29,7 @@ author: Paul D Turner // sample texts might show up unreadable in this source file. The sample // should look okay though when running. -#include "Sample_FontsDemo.h" +#include "Fonts.h" #include "CEGUI/CEGUI.h" using namespace CEGUI; @@ -56,7 +56,7 @@ static struct (encoded_char*)"DejaVuSans-12", (encoded_char*)"Try out writing text in any language here. The used font can be changed on the right.\n" "You can create new fonts if needed. The new font will be set as font for the selected text/language...\n" - "You can also edit the fonts that are part of this demo or the ones you created here (however, this demo won't allow to change the fonts of the other demos)\n" + "You can also edit the fonts that are part of this demo or the ones you created here (however, this demo won't allow to change the fonts of the other Samples)\n" "Important: When you switch to a font the FIRST time, it takes some time to load it. Especially for fonts with asian characters this load time might be noticable.!" }, { @@ -91,8 +91,8 @@ static struct "æœè¾­ç™½å¸å½©é›²é–“,\n" "åƒé‡Œæ±Ÿé™µä¸€æ—¥é‚„。\n" "兩岸猿è²å•¼ä¸ä½ï¼Œ\n" - "輕舟己éŽè¬é‡å±±ã€‚\n\n\n\n\n" - + "輕舟己éŽè¬é‡å±±ã€‚\n\n\n\n\n" + //Korean "ì´ëª¸ì´/죽고죽어/ì¼ë°±ë²ˆ/ê³ ì³ì£½ì–´/\n" "백골ì´/진퇴ë˜ì–´/ë„‹ì´ë¼ë„/있고없고/\n" @@ -131,7 +131,7 @@ static struct (encoded_char*)"RichStyle Icons font", (encoded_char*)"RichStyle-22", (encoded_char*)"+ - ? B I W Y f n t ℹ ⇦ ⇧ ⇨ ⇩ ⌘ ☎ ☠☑ âš– âš™ âš  ⛠✎ ✑ ✓ ✔ ✕ ✖ â âž âž¡ ⬀ ⬠⬂ ⬃ ⬅ ⬆ ⬇ ⬈ ⬉ ⬊ ⬋  î€ î€‚        î€ î€‘           " - }, + }, { (encoded_char*)"Old Runic writing using Futhark Adapted font", (encoded_char*)"FutharkAdapted-18", @@ -155,20 +155,31 @@ static struct } }; -// Sample sub-class for ListboxTextItem that auto-sets the selection brush -// image. This saves doing it manually every time in the code. -class MyListItem : public ListboxTextItem +FontsSample::FontsSample() : + Sample(88) { -public: - MyListItem(const String& text, CEGUI::uint item_id = 0) : - ListboxTextItem(text, item_id) - { - setSelectionBrushImage("Vanilla-Images/GenericBrush"); - } -}; - + Sample::d_name = "FontsSample"; + Sample::d_credits = "Lukas \"Ident\" Meindl"; + Sample::d_description = + "Showcase of different fonts packaged with CEGUI. A selection of " + "fonts and predefined texts, with characters from a variety of languages, " + "is given. It is possible to edit the Samplenstration text and create or " + "edit fonts the font editor window."; + Sample::d_summary = + "The Sample displays the usage of CEGUI::Font's using the fonts " + "from the datafiles folder. For the special characters, UTF-8 " + "character encoding is supported by CEGUI and is used in the Sample. " + "All \".font\" files found in the datafiles' font folder are " + "loaded into the Sample. Additionally, some of the supported font " + "file endings (.ttf, .pcf, .otf) are added to the list in the " + "font editor window using the CEGUI ResourceProvider. CEGUI Fonts " + "have size and autoscale settings that can be adjusted in the Sample. " + "In CEGUI fonts can be loaded using the \".font\" files or " + "can be created in run-time using the CEGUI::FontManager. " + "They can be edited at any time."; +} -bool FontsDemo::initialise(CEGUI::GUIContext* guiContext) +bool FontsSample::initialise(CEGUI::GUIContext* guiContext) { d_usedFiles = CEGUI::String(__FILE__); @@ -179,7 +190,7 @@ bool FontsDemo::initialise(CEGUI::GUIContext* guiContext) // load scheme and set up defaults SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme"); - d_guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow"); + d_guiContext->getCursor().setDefaultImage("Vanilla-Images/MouseArrow"); // Create a custom font which we use to draw the list items. This custom // font won't get effected by the scaler and such. @@ -195,8 +206,8 @@ bool FontsDemo::initialise(CEGUI::GUIContext* guiContext) retrieveLoadedFontNames(false); // Now that we know about all existing fonts we will initialise - // the fonts we wanna use for this demo hardcoded - initialiseDemoFonts(); + // the fonts we wanna use for this sample hardcoded + initialiseSampleFonts(); // Fill list with all new and thus editable font names retrieveLoadedFontNames(true); @@ -208,23 +219,23 @@ bool FontsDemo::initialise(CEGUI::GUIContext* guiContext) d_guiContext->setDefaultTooltipType("Vanilla/Tooltip"); // Load the GUI layout and attach it to the context as root window - d_root = winMgr.loadLayoutFromFile("FontsDemo.layout"); + d_root = winMgr.loadLayoutFromFile("FontsSample.layout"); d_guiContext->setRootWindow(d_root); //Here we create a font and apply it to the renew font name button CEGUI::Font& buttonFont = fontManager.createFreeTypeFont("DejaVuSans-14", 14.f, true, "DejaVuSans.ttf", Font::getDefaultResourceGroup(), ASM_Vertical, CEGUI::Sizef(1280.0f, 720.0f)); - d_renewFontNameButton = static_cast(d_root->getChild("FontsSampleWindow/FontCreator/RenewNameButton")); + d_renewFontNameButton = static_cast(d_root->getChild("FontsSampleWindow/FontCreator/RenewNameButton")); d_renewFontNameButton->setFont(&buttonFont); d_root->getChild("FontsSampleWindow/FontCreator/FontSizeLabel"); //Subscribe click event for renewing font name based on font file name and size - d_renewFontNameButton->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&FontsDemo::handleRenewFontNameButtonClicked, this)); + d_renewFontNameButton->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&FontsSample::handleRenewFontNameButtonClicked, this)); // Get the editbox where we display the text d_textDisplayMultiLineEditbox = static_cast(d_root->getChild("FontsSampleWindow/MultiLineTextWindow")); - d_textDisplayMultiLineEditbox->subscribeEvent(CEGUI::MultiLineEditbox::EventTextChanged, Event::Subscriber(&FontsDemo::handleTextMultiLineEditboxTextChanged, this)); + d_textDisplayMultiLineEditbox->subscribeEvent(CEGUI::MultiLineEditbox::EventTextChanged, Event::Subscriber(&FontsSample::handleTextMultiLineEditboxTextChanged, this)); //Get the font editor info label and apply an animation to it for blending out initialiseFontEditorInfoLabel(); @@ -245,25 +256,25 @@ bool FontsDemo::initialise(CEGUI::GUIContext* guiContext) initialiseTextSelector(); //Subscribe font selection event - d_fontSelector->subscribeEvent(CEGUI::Listbox::EventSelectionChanged, Event::Subscriber(&FontsDemo::handleFontSelectionChanged, this)); + d_fontSelector->subscribeEvent(ListView::EventSelectionChanged, Event::Subscriber(&FontsSample::handleFontSelectionChanged, this)); - d_textSelector->setItemSelectState(size_t(0), true); + d_textSelector->setIndexSelectionState(static_cast(0), true); return true; } // method to perform any required cleanup operations. -void FontsDemo::deinitialise() +void FontsSample::deinitialise() { } -bool FontsDemo::handleFontCreationButtonClicked(const EventArgs& e) +bool FontsSample::handleFontCreationButtonClicked(const EventArgs& e) { FontManager& fontMgr(FontManager::getSingleton()); CEGUI::String fontName = d_fontNameEditbox->getText(); bool fontNameExists = fontMgr.isDefined(fontName); - if(fontNameExists ||fontName.size() == 0) + if (fontNameExists || fontName.size() == 0) { d_fontEditorInfoLabel->setText("Font name already in use."); return true; @@ -273,42 +284,40 @@ bool FontsDemo::handleFontCreationButtonClicked(const EventArgs& e) CEGUI::String fontSizeString = d_fontSizeEditbox->getText(); float fontSize = CEGUI::PropertyHelper::fromString(fontSizeString); - if(fontSize == 0.0f) + if (fontSize == 0.0f) return true; bool antiAlias = d_fontAntiAliasCheckbox->isSelected(); - + AutoScaledMode autoScaleMode = static_cast(getAutoScaleMode()); String::size_type pos = fontFileName.rfind(".imageset"); - if(pos != -1) + if (pos != -1) { CEGUI::Font& createdFont = fontMgr.createPixmapFont(fontName, fontFileName, Font::getDefaultResourceGroup(), autoScaleMode, CEGUI::Sizef(1280.0f, 720.0f), XREA_THROW); } else { - CEGUI::Font& createdFont = fontMgr.createFreeTypeFont(fontName, fontSize, antiAlias, fontFileName, Font::getDefaultResourceGroup(), autoScaleMode, + CEGUI::Font& createdFont = fontMgr.createFreeTypeFont(fontName, fontSize, antiAlias, fontFileName, Font::getDefaultResourceGroup(), autoScaleMode, CEGUI::Sizef(1280.0f, 720.0f), XREA_THROW); } - ListboxItem* item = new MyListItem(fontName, 0); - d_fontSelector->addItem(item); - d_fontSelector->setItemSelectState(item, true); + d_fontSelector->addItem(fontName); + d_fontSelector->setIndexSelectionState(d_fontSelector->getItemCount(), true); return true; } - -bool FontsDemo::handleFontEditButtonClicked(const EventArgs& e) +bool FontsSample::handleFontEditButtonClicked(const EventArgs& e) { FontManager& fontMgr(FontManager::getSingleton()); CEGUI::String fontName = d_fontNameEditbox->getText(); bool fontNameExists = fontMgr.isDefined(fontName); - if(!fontNameExists) + if (!fontNameExists) { d_fontEditorInfoLabel->setText("A font with this name does not exist."); return true; @@ -317,15 +326,15 @@ bool FontsDemo::handleFontEditButtonClicked(const EventArgs& e) CEGUI::Font& font(fontMgr.get(fontName)); - if(font.isPropertyPresent("PointSize")) + if (font.isPropertyPresent("PointSize")) { CEGUI::String fontSizeString = d_fontSizeEditbox->getText(); float fontSize = CEGUI::PropertyHelper::fromString(fontSizeString); - if(fontSize != 0.0f) + if (fontSize != 0.0f) font.setProperty("PointSize", fontSize); } - if(font.isPropertyPresent("Antialiased")) + if (font.isPropertyPresent("Antialiased")) { bool antiAlias = d_fontAntiAliasCheckbox->isSelected(); font.setProperty("Antialiased", PropertyHelper::toString(antiAlias)); @@ -338,22 +347,22 @@ bool FontsDemo::handleFontEditButtonClicked(const EventArgs& e) return true; } -bool FontsDemo::handleFontSelectionChanged(const EventArgs& e) +bool FontsSample::handleFontSelectionChanged(const EventArgs& e) { //Change font of the selected language/text sample - if(d_textSelector->getFirstSelectedItem() && d_fontSelector->getFirstSelectedItem()) + if (d_textSelector->getFirstSelectedItem() && d_fontSelector->getFirstSelectedItem()) { - unsigned int index = d_textSelector->getFirstSelectedItem()->getID(); - + unsigned int index = d_textSelector->getFirstSelectedItem()->getId(); + d_languageToFontMap[LangList[index].Language] = d_fontSelector->getFirstSelectedItem()->getText(); } //Change the font creatore fields according to the font - if(d_fontSelector->getFirstSelectedItem()) + if (d_fontSelector->getFirstSelectedItem()) { CEGUI::String fontName = d_fontSelector->getFirstSelectedItem()->getText(); - if(FontManager::getSingleton().isDefined(fontName)) + if (FontManager::getSingleton().isDefined(fontName)) { CEGUI::Font& font(FontManager::getSingleton().get(fontName)); @@ -366,7 +375,7 @@ bool FontsDemo::handleFontSelectionChanged(const EventArgs& e) d_fontAutoScaleCombobox->getEditbox()->setText(autoScaleString); d_fontAutoScaleCombobox->selectListItemWithEditboxText(); - if(font.isPropertyPresent("Antialiased")) + if (font.isPropertyPresent("Antialiased")) { bool fontAntiAlias = font.getProperty("Antialiased"); d_fontAntiAliasCheckbox->enable(); @@ -377,7 +386,7 @@ bool FontsDemo::handleFontSelectionChanged(const EventArgs& e) d_fontAntiAliasCheckbox->disable(); } - if(font.isPropertyPresent("PointSize")) + if (font.isPropertyPresent("PointSize")) { CEGUI::String fontPointSize = font.getProperty("PointSize"); d_fontSizeEditbox->enable(); @@ -394,7 +403,7 @@ bool FontsDemo::handleFontSelectionChanged(const EventArgs& e) //Change the font colour for pixmap fonts - if(font.getTypeName().compare(Font_xmlHandler::FontTypePixmap) == 0) + if (font.getTypeName().compare(Font_xmlHandler::FontTypePixmap) == 0) d_textDisplayMultiLineEditbox->setProperty("NormalTextColour", CEGUI::ColourRect(CEGUI::Colour(1.0f, 1.0f, 1.0f, 1.0f))); else d_textDisplayMultiLineEditbox->setProperty("NormalTextColour", CEGUI::ColourRect(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f))); @@ -405,11 +414,11 @@ bool FontsDemo::handleFontSelectionChanged(const EventArgs& e) return true; } -bool FontsDemo::handleTextSelectionChanged(const EventArgs& e) +bool FontsSample::handleTextSelectionChanged(const EventArgs& e) { - if(d_textSelector->getFirstSelectedItem()) + if (d_textSelector->getFirstSelectedItem()) { - unsigned int index = d_textSelector->getFirstSelectedItem()->getID(); + unsigned int index = d_textSelector->getFirstSelectedItem()->getId(); d_textDisplayMultiLineEditbox->setText(d_languageToTextMap[LangList[index].Language]); @@ -419,11 +428,11 @@ bool FontsDemo::handleTextSelectionChanged(const EventArgs& e) return true; } -bool FontsDemo::handleTextMultiLineEditboxTextChanged(const EventArgs& e) +bool FontsSample::handleTextMultiLineEditboxTextChanged(const EventArgs& e) { - if(d_textSelector->getFirstSelectedItem()) + if (d_textSelector->getFirstSelectedItem()) { - unsigned int index = d_textSelector->getFirstSelectedItem()->getID(); + unsigned int index = d_textSelector->getFirstSelectedItem()->getId(); d_languageToTextMap[LangList[index].Language] = d_textDisplayMultiLineEditbox->getText(); } @@ -431,21 +440,21 @@ bool FontsDemo::handleTextMultiLineEditboxTextChanged(const EventArgs& e) return true; } -bool FontsDemo::handleFontFileNameSelectionChanged(const EventArgs& e) +bool FontsSample::handleFontFileNameSelectionChanged(const EventArgs& e) { generateNewFontName(); return true; } -bool FontsDemo::handleRenewFontNameButtonClicked(const EventArgs& e) +bool FontsSample::handleRenewFontNameButtonClicked(const EventArgs& e) { generateNewFontName(); return true; } -void FontsDemo::initialiseAutoScaleOptionsArray() +void FontsSample::initialiseAutoScaleOptionsArray() { //AutoScale options in the enum order d_autoScaleOptionsArray.push_back("Disabled"); @@ -457,7 +466,7 @@ void FontsDemo::initialiseAutoScaleOptionsArray() } -void FontsDemo::retrieveLoadedFontNames(bool areEditable) +void FontsSample::retrieveLoadedFontNames(bool areEditable) { FontManager& fontManager(FontManager::getSingleton()); FontManager::FontIterator fi = fontManager.getIterator(); @@ -466,7 +475,7 @@ void FontsDemo::retrieveLoadedFontNames(bool areEditable) { CEGUI::Font& font(fontManager.get(fi.getCurrentKey())); - if(d_fontNameOptions.find(font.getName()) == d_fontNameOptions.end()) + if (d_fontNameOptions.find(font.getName()) == d_fontNameOptions.end()) { d_fontNameOptions[font.getName()] = areEditable; } @@ -475,32 +484,32 @@ void FontsDemo::retrieveLoadedFontNames(bool areEditable) } -void FontsDemo::retrieveFontFileNames() +void FontsSample::retrieveFontFileNames() { System::getSingleton().getResourceProvider()->getResourceGroupFileNames(d_fontFileNameOptions, "*.ttf", Font::getDefaultResourceGroup()); System::getSingleton().getResourceProvider()->getResourceGroupFileNames(d_fontFileNameOptions, "*.pcf", Font::getDefaultResourceGroup()); System::getSingleton().getResourceProvider()->getResourceGroupFileNames(d_fontFileNameOptions, "*.otf", Font::getDefaultResourceGroup()); } -void FontsDemo::initialiseFontFileNameCombobox() +void FontsSample::initialiseFontFileNameCombobox() { //Select a font file name if any are present - if(d_fontFileNameOptions.size() > 0) + if (d_fontFileNameOptions.size() > 0) { - // Add the font file names to the listbox - for(unsigned int i = 0; i < d_fontFileNameOptions.size(); i++) + // Add the font file names to the combo box + for (unsigned int i = 0; i < d_fontFileNameOptions.size(); i++) { const CEGUI::String& fileName(d_fontFileNameOptions[i]); - d_fontFileNameSelector->addItem(new MyListItem(fileName, i)); + d_fontFileNameSelector->addItem(new StandardItem(fileName, i)); } - d_fontFileNameSelector->getListboxItemFromIndex(0)->setSelected(true); - d_fontFileNameSelector->getEditbox()->setText(d_fontFileNameSelector->getListboxItemFromIndex(0)->getText()); + d_fontFileNameSelector->getDropList()->setIndexSelectionState(static_cast(0), true); + d_fontFileNameSelector->getEditbox()->setText(d_fontFileNameSelector->getItemFromIndex(0)->getText()); } } -void FontsDemo::initialiseFontCreator() +void FontsSample::initialiseFontCreator() { d_fontFileNameSelector = static_cast(d_root->getChild("FontsSampleWindow/FontCreator/FontFileCombobox")); d_fontNameEditbox = static_cast(d_root->getChild("FontsSampleWindow/FontCreator/FontNameEditbox")); @@ -510,79 +519,72 @@ void FontsDemo::initialiseFontCreator() d_fontCreationButton = static_cast(d_root->getChild("FontsSampleWindow/FontCreator/CreationButton")); d_fontEditButton = static_cast(d_root->getChild("FontsSampleWindow/FontCreator/EditButton")); - d_fontFileNameSelector->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, Event::Subscriber(&FontsDemo::handleFontFileNameSelectionChanged, this)); + d_fontFileNameSelector->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, Event::Subscriber(&FontsSample::handleFontFileNameSelectionChanged, this)); - d_fontCreationButton->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&FontsDemo::handleFontCreationButtonClicked, this)); - d_fontEditButton->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&FontsDemo::handleFontEditButtonClicked, this)); + d_fontCreationButton->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&FontsSample::handleFontCreationButtonClicked, this)); + d_fontEditButton->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&FontsSample::handleFontEditButtonClicked, this)); initialiseFontFileNameCombobox(); initialiseAutoScaleCombobox(); } -void FontsDemo::initialiseFontSelector() +void FontsSample::initialiseFontSelector() { - d_fontSelector = static_cast(d_root->getChild("FontsSampleWindow/FontSelector")); - - d_fontSelector->setSortingEnabled(true); + d_fontSelector = static_cast(d_root->getChild("FontsSampleWindow/FontSelector")); + d_fontSelector->setSortMode(VSM_Ascending); //Select a font file name if any are present - if(d_fontNameOptions.size() > 0) + if (d_fontNameOptions.size() > 0) { std::map::iterator iter = d_fontNameOptions.begin(); - for(; iter != d_fontNameOptions.end(); ++iter) + for (; iter != d_fontNameOptions.end(); ++iter) { - std::pair& currentPair = *iter; - d_fontSelector->addItem(new MyListItem(currentPair.first, 0)); + std::pair& currentPair = *iter; + d_fontSelector->addItem(currentPair.first); } } - - d_fontSelector->handleUpdatedItemData(); } -void FontsDemo::initialiseTextSelector() +void FontsSample::initialiseTextSelector() { - d_textSelector = static_cast(d_root->getChild("FontsSampleWindow/TextSelector")); - d_textSelector->subscribeEvent(CEGUI::Listbox::EventSelectionChanged, Event::Subscriber(&FontsDemo::handleTextSelectionChanged, this)); + d_textSelector = static_cast(d_root->getChild("FontsSampleWindow/TextSelector")); + d_textSelector->subscribeEvent(ListView::EventSelectionChanged, Event::Subscriber(&FontsSample::handleTextSelectionChanged, this)); - for(unsigned int i = 0; i < LangListSize; ++i) + for (unsigned int i = 0; i < LangListSize; ++i) { - d_textSelector->addItem(new MyListItem(LangList[i].Language, i)); - d_languageToFontMap[LangList[i].Language] = LangList[i].Font; + d_textSelector->addItem(new StandardItem(LangList[i].Language, i)); + d_languageToFontMap[LangList[i].Language] = LangList[i].Font; } } -void FontsDemo::changeFontSelectorFontSelection(const CEGUI::String& font) +void FontsSample::changeFontSelectorFontSelection(const CEGUI::String& font) { - while(d_fontSelector->getFirstSelectedItem()) - { - d_fontSelector->setItemSelectState(d_fontSelector->getFirstSelectedItem(), false); - } + d_fontSelector->clearSelections(); unsigned int itemCount = d_fontSelector->getItemCount(); - for(unsigned int i = 0; i < itemCount; ++i) + for (unsigned int i = 0; i < itemCount; ++i) { - CEGUI::ListboxItem* item = d_fontSelector->getListboxItemFromIndex(i); - - CEGUI::String itemFontName = item->getText(); + StandardItem* item = d_fontSelector->getItemAtIndex(i); + String itemFontName = item->getText(); - if(itemFontName.compare(font) == 0) + if (itemFontName.compare(font) == 0) { - d_fontSelector->setItemSelectState(item, true); + d_fontSelector->setIndexSelectionState(i, true); return; } } } -void FontsDemo::initialiseLangToTextMap() +void FontsSample::initialiseLangToTextMap() { - for(unsigned int i = 0; i < LangListSize; ++i) + for (unsigned int i = 0; i < LangListSize; ++i) { d_languageToTextMap[LangList[i].Language] = LangList[i].Text; } } -void FontsDemo::generateNewFontName() +void FontsSample::generateNewFontName() { CEGUI::String fileName = d_fontFileNameSelector->getText(); CEGUI::String pointSize = d_fontSizeEditbox->getText(); @@ -593,42 +595,42 @@ void FontsDemo::generateNewFontName() d_fontNameEditbox->setText(fontName); } -void FontsDemo::initialiseAutoScaleCombobox() +void FontsSample::initialiseAutoScaleCombobox() { - for(unsigned int i = 0; i < d_autoScaleOptionsArray.size(); ++i) + for (unsigned int i = 0; i < d_autoScaleOptionsArray.size(); ++i) { CEGUI::String itemText = d_autoScaleOptionsArray.at(i); - d_fontAutoScaleCombobox->addItem(new MyListItem(itemText, i)); + d_fontAutoScaleCombobox->addItem(new StandardItem(itemText, i)); } } -int FontsDemo::getAutoScaleMode() +int FontsSample::getAutoScaleMode() { CEGUI::String autoScaleString = d_fontAutoScaleCombobox->getSelectedItem()->getText(); - for(unsigned int i = 0; i < d_autoScaleOptionsArray.size(); ++i) + for (unsigned int i = 0; i < d_autoScaleOptionsArray.size(); ++i) { - if(autoScaleString.compare(d_autoScaleOptionsArray.at(i)) == 0) + if (autoScaleString.compare(d_autoScaleOptionsArray.at(i)) == 0) return i; } return 0; } -bool FontsDemo::findFontOption(CEGUI::String fontName) +bool FontsSample::findFontOption(CEGUI::String fontName) { std::map::iterator iter = d_fontNameOptions.begin(); - for(; iter != d_fontNameOptions.end(); ++iter) + for (; iter != d_fontNameOptions.end(); ++iter) { std::pair& currentPair = *iter; - if(currentPair.first.compare(fontName) == 0) - return currentPair.second; + if (currentPair.first.compare(fontName) == 0) + return currentPair.second; } return true; } -void FontsDemo::initialiseFontEditorInfoLabel() +void FontsSample::initialiseFontEditorInfoLabel() { d_fontEditorInfoLabel = d_root->getChild("FontsSampleWindow/FontCreator/InfoLabel"); @@ -655,15 +657,15 @@ void FontsDemo::initialiseFontEditorInfoLabel() instance->start(); } -void FontsDemo::checkIfEditButtonShouldBeDisabled(CEGUI::Font &font) +void FontsSample::checkIfEditButtonShouldBeDisabled(CEGUI::Font &font) { bool isEditable = findFontOption(font.getName()); - if(!isEditable) + if (!isEditable) { d_fontEditButton->disable(); - d_fontEditButton->setTooltipText("This demo won't allow editing of\n" - "fonts that were created outside the demo or\n" + d_fontEditButton->setTooltipText("This Sample won't allow editing of\n" + "fonts that were created outside the Sample or\n" "were loaded from .font files"); } else @@ -673,7 +675,7 @@ void FontsDemo::checkIfEditButtonShouldBeDisabled(CEGUI::Font &font) } } -void FontsDemo::initialiseDemoFonts() +void FontsSample::initialiseSampleFonts() { FontManager& fontManager(FontManager::getSingleton()); fontManager.createFreeTypeFont("Junicode-14", 14.f, true, "Junicode.ttf", @@ -703,12 +705,3 @@ void FontsDemo::initialiseDemoFonts() fontManager.createFreeTypeFont("mizufalp-12", 12.f, true, "mizufalp.ttf", Font::getDefaultResourceGroup(), ASM_Disabled, CEGUI::Sizef(1280.0f, 720.0f)); } - -/************************************************************************* -Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static FontsDemo sample; - return sample; -} diff --git a/samples/Fonts/Sample_FontsDemo.h b/samples/Fonts/Fonts.h similarity index 94% rename from samples/Fonts/Sample_FontsDemo.h rename to samples/Fonts/Fonts.h index c5c5f9e62..7280dc830 100644 --- a/samples/Fonts/Sample_FontsDemo.h +++ b/samples/Fonts/Fonts.h @@ -24,8 +24,8 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_FontsDemo_h_ -#define _Sample_FontsDemo_h_ +#ifndef _FontsSample_h_ +#define _FontsSample_h_ #include "SampleBase.h" @@ -37,13 +37,15 @@ author: Lukas E Meindl struct FontOption; // Sample class -class FontsDemo : public Sample +class FontsSample : public Sample { public: + FontsSample(); + // method to initialse the samples windows and events. bool initialise(CEGUI::GUIContext* guiContext); - void initialiseDemoFonts(); + void initialiseSampleFonts(); void initialiseFontEditorInfoLabel(); void deinitialise(); @@ -91,8 +93,8 @@ class FontsDemo : public Sample CEGUI::PushButton* d_renewFontNameButton; CEGUI::Window* d_fontEditorInfoLabel; - CEGUI::Listbox* d_fontSelector; - CEGUI::Listbox* d_textSelector; + CEGUI::ListWidget* d_fontSelector; + CEGUI::ListWidget* d_textSelector; CEGUI::MultiLineEditbox* d_textDisplayMultiLineEditbox; @@ -106,5 +108,4 @@ class FontsDemo : public Sample std::vector d_autoScaleOptionsArray; }; - -#endif \ No newline at end of file +#endif // _FontsSample_h_ \ No newline at end of file diff --git a/samples/Fonts/SampleMetaData.xml b/samples/Fonts/SampleMetaData.xml deleted file mode 100644 index 5bbbc49b6..000000000 --- a/samples/Fonts/SampleMetaData.xml +++ /dev/null @@ -1,9 +0,0 @@ - diff --git a/samples/FormNavigation/CMakeLists.txt b/samples/FormNavigation/CMakeLists.txt new file mode 100644 index 000000000..694aca6d7 --- /dev/null +++ b/samples/FormNavigation/CMakeLists.txt @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/FormNavigation/FormNavigation.cpp b/samples/FormNavigation/FormNavigation.cpp new file mode 100644 index 000000000..7c3b53062 --- /dev/null +++ b/samples/FormNavigation/FormNavigation.cpp @@ -0,0 +1,175 @@ +/*********************************************************************** + created: 30/5/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "FormNavigation.h" +#include "CEGUI/CEGUI.h" + +#include + +using namespace CEGUI; +using namespace NavigationStrategiesPayloads; + +/** This sample uses most of the code from the 'HelloWorld' sample. + Thus, most of the clarifying comments have been removed for brevity. **/ + +FormNavigationSample::FormNavigationSample() +{ + Sample::d_name = "FormNavigationSample"; + Sample::d_credits = "Timotei Dolean"; + Sample::d_description = + "A Sample that shows a form which can be navigated using the keyboard or other devices."; + Sample::d_summary = + "The Sample uses the WindowManager to create from code, " + "a window with a form that contains: labels, editboxes, " + "checkboxes, 'submit' and 'reset' buttons."; +} + +/************************************************************************* + Sample specific initialisation goes here. +*************************************************************************/ +bool FormNavigationSample::initialise(CEGUI::GUIContext* gui_context) +{ + d_usedFiles = CEGUI::String(__FILE__); + + SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); + gui_context->getCursor().setDefaultImage("TaharezLook/MouseArrow"); + + WindowManager& win_mgr = WindowManager::getSingleton(); + d_root = (DefaultWindow*)win_mgr.createWindow("DefaultWindow", "Root"); + + Font& default_font = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + gui_context->setDefaultFont(&default_font); + + gui_context->setRootWindow(d_root); + + d_navigationStrategy = new LinearNavigationStrategy; + d_windowNavigator = new WindowNavigator(getNavigationMappings(), d_navigationStrategy); + gui_context->setWindowNavigator(d_windowNavigator); + + FrameWindow* wnd = (FrameWindow*)win_mgr.createWindow("TaharezLook/FrameWindow", + "Sample Window"); + d_root->addChild(wnd); + + wnd->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim( 0.25f))); + wnd->setSize(USize(cegui_reldim(0.5f), cegui_reldim( 0.5f))); + wnd->setMaxSize(USize(cegui_reldim(1.0f), cegui_reldim( 1.0f))); + wnd->setMinSize(USize(cegui_reldim(0.1f), cegui_reldim( 0.1f))); + + wnd->setText("Phony form"); + + createForm(wnd); + + return true; +} + +/************************************************************************* + Cleans up resources allocated in the initialiseSample call. +*************************************************************************/ +void FormNavigationSample::deinitialise() +{ +} + +void FormNavigationSample::createForm(FrameWindow* wnd) +{ + wnd->addChild(createWidget("TaharezLook/Label", 0.0f, 0.0f, "Char name:")); + wnd->addChild(createWidget("TaharezLook/Label", 0.0f, 0.1f, "Guild name:")); + wnd->addChild(createWidget("TaharezLook/Label", 0.0f, 0.2f, "Initial gold:")); + + Window* editbox = createWidget("TaharezLook/Editbox", 0.2f, 0.0f); + wnd->addChild(editbox); + d_editboxes.push_back(editbox); + d_navigationStrategy->d_windows.push_back(editbox); + + editbox = createWidget("TaharezLook/Editbox", 0.2f, 0.1f); + wnd->addChild(editbox); + d_editboxes.push_back(editbox); + d_navigationStrategy->d_windows.push_back(editbox); + + editbox = createWidget("TaharezLook/Editbox", 0.2f, 0.2f); + wnd->addChild(editbox); + d_editboxes.push_back(editbox); + d_navigationStrategy->d_windows.push_back(editbox); + + d_isGameMasterCheckbox = static_cast( + createWidget("TaharezLook/Checkbox", 0.01f, 0.3f, "Is Game Master")); + d_isGameMasterCheckbox->setSize(USize(cegui_reldim(0.5f), cegui_reldim(0.1f))); + wnd->addChild(d_isGameMasterCheckbox); + d_navigationStrategy->d_windows.push_back(d_isGameMasterCheckbox); + + d_confirmButton = createWidget("TaharezLook/Button", 0.1f, 0.4f, "Confirm"); + d_confirmButton->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&FormNavigationSample::disableConfirmButton, this)); + wnd->addChild(d_confirmButton); + d_navigationStrategy->d_windows.push_back(d_confirmButton); + + Window* resetButton = createWidget("TaharezLook/Button", 0.3f, 0.4f, "Reset"); + resetButton->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&FormNavigationSample::resetForm, this)); + wnd->addChild(resetButton); + d_navigationStrategy->d_windows.push_back(resetButton); +} + +CEGUI::Window* FormNavigationSample::createWidget(const String& type, + float position_x, float position_y, const String& text) +{ + Window* widget = WindowManager::getSingleton().createWindow(type); + + widget->setText(text); + widget->setPosition(UVector2(cegui_reldim(position_x), cegui_reldim(position_y))); + + return widget; +} + +bool FormNavigationSample::resetForm(const CEGUI::EventArgs& e) +{ + for(std::vector::const_iterator itor = d_editboxes.begin(); + itor != d_editboxes.end(); ++itor) + { + (*itor)->setText(""); + } + + d_isGameMasterCheckbox->setSelected(false); + d_confirmButton->setEnabled(true); + + return true; +} + +bool FormNavigationSample::disableConfirmButton(const CEGUI::EventArgs& e) +{ + d_confirmButton->setEnabled(false); + + return true; +} + +std::map FormNavigationSample::getNavigationMappings() +{ + std::map mappings; + + mappings[SV_NavigateToNext] = NAVIGATE_NEXT; + mappings[SV_NavigateToPrevious] = NAVIGATE_PREVIOUS; + + return mappings; +} diff --git a/samples/FormNavigation/FormNavigation.h b/samples/FormNavigation/FormNavigation.h new file mode 100644 index 000000000..0f3c50175 --- /dev/null +++ b/samples/FormNavigation/FormNavigation.h @@ -0,0 +1,57 @@ +/*********************************************************************** + created: 30/5/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _Sample_Form_Navigation_h_ +#define _Sample_Form_Navigation_h_ + +#include "SampleBase.h" +#include "NavigationStrategies.h" + +class FormNavigationSample : public Sample +{ +public: + FormNavigationSample(); + + virtual bool initialise(CEGUI::GUIContext* gui_context); + virtual void deinitialise(); + +private: + void createForm(CEGUI::FrameWindow* wnd); + + CEGUI::Window* createWidget(const CEGUI::String& type, float position_x, float position_y, const CEGUI::String& text = ""); + bool resetForm(const CEGUI::EventArgs& e); + bool disableConfirmButton(const CEGUI::EventArgs& e); + std::map getNavigationMappings(); + + CEGUI::DefaultWindow* d_root; + CEGUI::ToggleButton* d_isGameMasterCheckbox; + CEGUI::Window* d_confirmButton; + std::vector d_editboxes; + LinearNavigationStrategy* d_navigationStrategy; + CEGUI::WindowNavigator* d_windowNavigator; +}; + +#endif // end of guard _Sample_Form_Navigation_h_ diff --git a/samples/GLESTest/CMakeLists.txt b/samples/GLESTest/CMakeLists.txt index 48c32a260..dd89dedec 100644 --- a/samples/GLESTest/CMakeLists.txt +++ b/samples/GLESTest/CMakeLists.txt @@ -1,4 +1,15 @@ -cegui_add_sample(CEGUISample_GLESTest) +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +#get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +#set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +#set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_OPENGLES_RENDERER_LIBNAME}) -cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGLES) +# Append the samples names to the list and make the list visible outside this scope +#list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +#set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +#file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +#file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +#set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +#set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) +message("You should not use GLESTest until CrazyEddie gives his OK. Skipping.") \ No newline at end of file diff --git a/samples/GLESTest/Sample_GLESTest.cpp b/samples/GLESTest/GLESTest.cpp similarity index 100% rename from samples/GLESTest/Sample_GLESTest.cpp rename to samples/GLESTest/GLESTest.cpp diff --git a/samples/GameMenu/CMakeLists.txt b/samples/GameMenu/CMakeLists.txt index 14d8dcdca..694aca6d7 100644 --- a/samples/GameMenu/CMakeLists.txt +++ b/samples/GameMenu/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_GAMEMENU "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_GAMEMENU) - cegui_add_sample(CEGUISample_GameMenuDemo) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/GameMenu/GameMenu.cpp b/samples/GameMenu/GameMenu.cpp index f78396794..d7587ec87 100644 --- a/samples/GameMenu/GameMenu.cpp +++ b/samples/GameMenu/GameMenu.cpp @@ -38,11 +38,27 @@ author: Lukas E Meindl using namespace CEGUI; -const float GameMenuDemo::s_firstStartDelay = 5.0f; -const float GameMenuDemo::s_secondStartDelay = 11.0f; -const float GameMenuDemo::s_loginDisplayStartDelay = 15.77f; +const float GameMenuSample::s_firstStartDelay = 5.0f; +const float GameMenuSample::s_secondStartDelay = 11.0f; +const float GameMenuSample::s_loginDisplayStartDelay = 15.77f; -bool GameMenuDemo::initialise(CEGUI::GUIContext* guiContext) +GameMenuSample::GameMenuSample() : + Sample(100) +{ + Sample::d_name = "GameMenuSample"; + Sample::d_credits = + "Lukas \"Ident\" Meindl, graphics: Charles \"Syg\" Mattei"; + Sample::d_description = + "Displays a science-fiction game menu using a lot of animations."; + Sample::d_summary = + "The Sample uses a custom skin (look n' feel) and a great variety " + "of animations defined. The animations are loaded from xml and " + "utilized via C++ code. For the animated windows, which do not " + "display text, the pixel alignment setting was switched off for " + "smoother transitions, and event handlers are used to control the animations."; +} + +bool GameMenuSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -50,9 +66,9 @@ bool GameMenuDemo::initialise(CEGUI::GUIContext* guiContext) d_guiContext = guiContext; // load scheme and set up defaults - SchemeManager::getSingleton().createFromFile("GameMenu.scheme"); + SchemeManager::getSingleton().createFromFile("GameMenuSample.scheme"); SchemeManager::getSingleton().createFromFile("Generic.scheme"); - d_guiContext->getMouseCursor().setDefaultImage("GameMenuImages/MouseCursor"); + d_guiContext->getCursor().setDefaultImage("GameMenuSampleImages/MouseCursor"); // load font and setup default if not loaded via scheme Font& defaultFont = FontManager::getSingleton().createFromFile("Jura-13.font"); @@ -63,7 +79,7 @@ bool GameMenuDemo::initialise(CEGUI::GUIContext* guiContext) CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton(); - d_root = winMgr.loadLayoutFromFile("GameMenu.layout"); + d_root = winMgr.loadLayoutFromFile("GameMenuSample.layout"); d_guiContext->setRootWindow(d_root); setupWindows(); @@ -74,7 +90,7 @@ bool GameMenuDemo::initialise(CEGUI::GUIContext* guiContext) d_interactivePlanetElementsAreEnabled = false; d_navigationIsEnabled = false; d_loginWasAccepted = false; - d_mouseIsHoveringNavi = false; + d_cursorIsHoveringNavi = false; d_currentWriteFocus = WF_BotBar; @@ -84,14 +100,14 @@ bool GameMenuDemo::initialise(CEGUI::GUIContext* guiContext) /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ -void GameMenuDemo::deinitialise() +void GameMenuSample::deinitialise() { } -void GameMenuDemo::setupAnimations() +void GameMenuSample::setupAnimations() { AnimationManager& animMgr = AnimationManager::getSingleton(); - animMgr.loadAnimationsFromXML("GameMenu.anims"); + animMgr.loadAnimationsFromXML("GameMenuSample.anims"); CEGUI::Animation* startButtAnim = animMgr.getAnimation("StartButtonPulsating"); CEGUI::AnimationInstance* startButtAnimInstance = animMgr.instantiateAnimation(startButtAnim); @@ -240,7 +256,7 @@ void GameMenuDemo::setupAnimations() setupSelectionIconAnimations(); } -void GameMenuDemo::onEnteringSample() +void GameMenuSample::onEnteringSample() { d_navigationTravelIcon->setEnabled(false); @@ -282,7 +298,7 @@ void GameMenuDemo::onEnteringSample() makeAllSelectionIconsInvisible(); } -void GameMenuDemo::update(float timeSinceLastUpdate) +void GameMenuSample::update(float timeSinceLastUpdate) { d_timeSinceStart += timeSinceLastUpdate; @@ -305,7 +321,7 @@ void GameMenuDemo::update(float timeSinceLastUpdate) } } -bool GameMenuDemo::handleLoginAcceptButtonClicked(const CEGUI::EventArgs& args) +bool GameMenuSample::handleLoginAcceptButtonClicked(const CEGUI::EventArgs& args) { d_startButtonClickArea->setAlpha(0.0f); d_startButtonBlendInAnimInst->start(); @@ -327,7 +343,7 @@ bool GameMenuDemo::handleLoginAcceptButtonClicked(const CEGUI::EventArgs& args) return false; } -bool GameMenuDemo::handleInnerPartStartClickAreaClick(const CEGUI::EventArgs& args) +bool GameMenuSample::handleInnerPartStartClickAreaClick(const CEGUI::EventArgs& args) { if(!d_interactivePlanetElementsAreEnabled) enableInteractivePlanetElements(); @@ -341,31 +357,31 @@ bool GameMenuDemo::handleInnerPartStartClickAreaClick(const CEGUI::EventArgs& ar } -bool GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange(const CEGUI::EventArgs& args) +bool GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange(const CEGUI::EventArgs& args) { if(!d_loginWasAccepted) return false; - bool mouseIsHovering = false; + bool curcursor_is_hovering = false; CEGUI::Window* window; window = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NavigationLabel"); - mouseIsHovering |= window->isMouseContainedInArea(); + curcursor_is_hovering |= window->isPointerContainedInArea(); window = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NavigationIcon"); - mouseIsHovering |= window->isMouseContainedInArea(); + curcursor_is_hovering |= window->isPointerContainedInArea(); window = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NaviBotSelectionIcon"); - mouseIsHovering |= window->isMouseContainedInArea(); - mouseIsHovering |= d_botNaviRightArrowArea->isMouseContainedInArea(); - mouseIsHovering |= d_botNaviLeftArrowArea->isMouseContainedInArea(); + curcursor_is_hovering |= window->isPointerContainedInArea(); + curcursor_is_hovering |= d_botNaviRightArrowArea->isPointerContainedInArea(); + curcursor_is_hovering |= d_botNaviLeftArrowArea->isPointerContainedInArea(); - //We fire an event to trigger the animation depending on if the mouse hovers a critical + //We fire an event to trigger the animation depending on if the cursor hovers a critical //window or not. Additionally we perform a check to not fire an event for an animation that is already running - if(d_mouseIsHoveringNavi != mouseIsHovering) + if(d_cursorIsHoveringNavi != curcursor_is_hovering) { - d_mouseIsHoveringNavi = mouseIsHovering; + d_cursorIsHoveringNavi = curcursor_is_hovering; CEGUI::EventArgs args; - if(mouseIsHovering) + if(curcursor_is_hovering) { d_navigationSelectionIcon->fireEvent("StartRotate", args); d_navigationTravelIcon->fireEvent("StartRotate", args); @@ -381,13 +397,13 @@ bool GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange(const CEGUI::EventA } -float getAngle(const CEGUI::Quaternion& quat) +float getAngle(const glm::quat& quat) { - return 2.0f * std::acos(quat.d_w); + return 2.0f * std::acos(quat.w); } -bool GameMenuDemo::handleNaviSelectionIconAnimStart(const CEGUI::EventArgs& args) +bool GameMenuSample::handleNaviSelectionIconAnimStart(const CEGUI::EventArgs& args) { const CEGUI::AnimationEventArgs& animArgs = static_cast(args); @@ -395,7 +411,7 @@ bool GameMenuDemo::handleNaviSelectionIconAnimStart(const CEGUI::EventArgs& args if(animInst->getDefinition() == CEGUI::AnimationManager::getSingleton().getAnimation("LoopRotateRight")) { - CEGUI::Quaternion curRotation = animInst->getTarget()->getProperty("Rotation"); + const glm::quat curRotation = animInst->getTarget()->getProperty("Rotation"); float curAngle = getAngle(curRotation); float progress = curAngle / (2.0f * static_cast(M_PI)); @@ -405,7 +421,7 @@ bool GameMenuDemo::handleNaviSelectionIconAnimStart(const CEGUI::EventArgs& args return false; } -bool GameMenuDemo::handleMouseEntersLeftArrowArea(const CEGUI::EventArgs& args) +bool GameMenuSample::handlePointerEntersLeftArrowArea(const CEGUI::EventArgs& args) { CEGUI::EventArgs fireArgs; if(d_loginWasAccepted) @@ -414,7 +430,7 @@ bool GameMenuDemo::handleMouseEntersLeftArrowArea(const CEGUI::EventArgs& args) return false; } -bool GameMenuDemo::handleMouseLeavesLeftArrowArea(const CEGUI::EventArgs& args) +bool GameMenuSample::handlePointerLeavesLeftArrowArea(const CEGUI::EventArgs& args) { CEGUI::EventArgs fireArgs; if(d_loginWasAccepted) @@ -423,7 +439,7 @@ bool GameMenuDemo::handleMouseLeavesLeftArrowArea(const CEGUI::EventArgs& args) return false; } -bool GameMenuDemo::handleMouseEntersRightArrowArea(const CEGUI::EventArgs& args) +bool GameMenuSample::handlePointerEntersRightArrowArea(const CEGUI::EventArgs& args) { CEGUI::EventArgs fireArgs; if(d_loginWasAccepted) @@ -432,7 +448,7 @@ bool GameMenuDemo::handleMouseEntersRightArrowArea(const CEGUI::EventArgs& args) return false; } -bool GameMenuDemo::handleMouseLeavesRightArrowArea(const CEGUI::EventArgs& args) +bool GameMenuSample::handlePointerLeavesRightArrowArea(const CEGUI::EventArgs& args) { CEGUI::EventArgs fireArgs; if(d_loginWasAccepted) @@ -442,7 +458,7 @@ bool GameMenuDemo::handleMouseLeavesRightArrowArea(const CEGUI::EventArgs& args) } -bool GameMenuDemo::handleStartPopupLinesSaveDisplay(const CEGUI::EventArgs& args) +bool GameMenuSample::handleStartPopupLinesSaveDisplay(const CEGUI::EventArgs& args) { if(!d_startButtonClicked) return false; @@ -457,7 +473,7 @@ bool GameMenuDemo::handleStartPopupLinesSaveDisplay(const CEGUI::EventArgs& args return false; } -bool GameMenuDemo::handleStartPopupLinesLoadDisplay(const CEGUI::EventArgs& args) +bool GameMenuSample::handleStartPopupLinesLoadDisplay(const CEGUI::EventArgs& args) { if(!d_startButtonClicked) return false; @@ -472,7 +488,7 @@ bool GameMenuDemo::handleStartPopupLinesLoadDisplay(const CEGUI::EventArgs& args return false; } -bool GameMenuDemo::handleStartPopupLinesCharactersDisplay(const CEGUI::EventArgs& args) +bool GameMenuSample::handleStartPopupLinesCharactersDisplay(const CEGUI::EventArgs& args) { if(!d_startButtonClicked) return false; @@ -491,7 +507,7 @@ bool GameMenuDemo::handleStartPopupLinesCharactersDisplay(const CEGUI::EventArgs } -bool GameMenuDemo::handleStartPopupLinesOptionsDisplay(const CEGUI::EventArgs& args) +bool GameMenuSample::handleStartPopupLinesOptionsDisplay(const CEGUI::EventArgs& args) { if(!d_startButtonClicked) return false; @@ -509,7 +525,7 @@ bool GameMenuDemo::handleStartPopupLinesOptionsDisplay(const CEGUI::EventArgs& a } -bool GameMenuDemo::handleStartPopupLinesQuitDisplay(const CEGUI::EventArgs& args) +bool GameMenuSample::handleStartPopupLinesQuitDisplay(const CEGUI::EventArgs& args) { if(!d_startButtonClicked) return false; @@ -526,11 +542,11 @@ bool GameMenuDemo::handleStartPopupLinesQuitDisplay(const CEGUI::EventArgs& args } -bool GameMenuDemo::handleInnerButtonsLabelEntered(const CEGUI::EventArgs& args) +bool GameMenuSample::handleInnerButtonsLabelEntered(const CEGUI::EventArgs& args) { - const CEGUI::MouseEventArgs& mouseArgs = static_cast(args); + const CEGUI::CursorInputEventArgs& cursor_args = static_cast(args); - CEGUI::Window* iconWindow = getIconWindowFromLabel(mouseArgs.window); + CEGUI::Window* iconWindow = getIconWindowFromLabel(cursor_args.window); CEGUI::EventArgs fireArgs; iconWindow->fireEvent("StartRotate", fireArgs); @@ -538,12 +554,12 @@ bool GameMenuDemo::handleInnerButtonsLabelEntered(const CEGUI::EventArgs& args) return false; } -bool GameMenuDemo::handleInnerButtonsLabelLeft(const CEGUI::EventArgs& args) +bool GameMenuSample::handleInnerButtonsLabelLeft(const CEGUI::EventArgs& args) { - const CEGUI::MouseEventArgs& mouseArgs = static_cast(args); + const CEGUI::CursorInputEventArgs& cursor_args = static_cast(args); + + CEGUI::Window* iconWindow = getIconWindowFromLabel(cursor_args.window); - CEGUI::Window* iconWindow = getIconWindowFromLabel(mouseArgs.window); - CEGUI::EventArgs fireArgs; iconWindow->fireEvent("StopRotate", fireArgs); @@ -551,7 +567,7 @@ bool GameMenuDemo::handleInnerButtonsLabelLeft(const CEGUI::EventArgs& args) } -void GameMenuDemo::makeAllSelectionIconsInvisible() +void GameMenuSample::makeAllSelectionIconsInvisible() { CEGUI::EventArgs fireArgs; @@ -568,7 +584,7 @@ void GameMenuDemo::makeAllSelectionIconsInvisible() d_root->getChild("InnerButtonsContainer/NewSelectionIcon")->setVisible(false); } -void GameMenuDemo::stopStartPopupLinesAnimations() +void GameMenuSample::stopStartPopupLinesAnimations() { d_popupLinesCharactersAnimInst->setPosition(d_popupLinesLoadAnimInst->getDefinition()->getDuration()); d_popupLinesCharactersAnimInst->apply(); @@ -595,7 +611,7 @@ void GameMenuDemo::stopStartPopupLinesAnimations() } -void GameMenuDemo::setupWindows() +void GameMenuSample::setupWindows() { d_botBarLabel = d_root->getChild("BotBar/BotBarLabel"); d_topBarLabel = d_root->getChild("TopBar/TopBarLabel"); @@ -610,15 +626,15 @@ void GameMenuDemo::setupWindows() d_botNaviCenter = d_root->getChild("BotNavigationContainer/NaviCenterContainer"); d_loginAcceptButton = d_loginContainer->getChild("AcceptButton"); - d_loginAcceptButton->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleLoginAcceptButtonClicked, this)); + d_loginAcceptButton->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleLoginAcceptButtonClicked, this)); - d_startButtonClickArea = d_root->getChild("InnerPartContainer/InsideStartClickArea"); - d_startButtonClickArea->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleInnerPartStartClickAreaClick, this)); + d_startButtonClickArea = d_root->getChild("InnerPartContainer/InsideStartClickArea"); + d_startButtonClickArea->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleInnerPartStartClickAreaClick, this)); d_navigationTravelIcon = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NavigationIcon"); d_navigationSelectionIcon = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NaviBotSelectionIcon"); - d_navigationSelectionIcon->subscribeEvent(CEGUI::AnimationInstance::EventAnimationStarted, Event::Subscriber(&GameMenuDemo::handleNaviSelectionIconAnimStart, this)); + d_navigationSelectionIcon->subscribeEvent(CEGUI::AnimationInstance::EventAnimationStarted, Event::Subscriber(&GameMenuSample::handleNaviSelectionIconAnimStart, this)); setupNaviIconAnimationEventHandlers(); @@ -626,7 +642,7 @@ void GameMenuDemo::setupWindows() } -void GameMenuDemo::disableInteractivePlanetElements() +void GameMenuSample::disableInteractivePlanetElements() { d_centerButtonsBlendInInst->pause(); d_centerButtonsPartialBlendOutInst->start(); @@ -635,7 +651,7 @@ void GameMenuDemo::disableInteractivePlanetElements() d_interactiveElementsWereInitiallyBlendedOut = true; } -void GameMenuDemo::enableInteractivePlanetElements() +void GameMenuSample::enableInteractivePlanetElements() { d_centerButtonsPartialBlendOutInst->pause(); d_centerButtonsBlendInInst->start(); @@ -643,7 +659,7 @@ void GameMenuDemo::enableInteractivePlanetElements() d_interactivePlanetElementsAreEnabled = true; } -void GameMenuDemo::disableNavigationBarElements() +void GameMenuSample::disableNavigationBarElements() { d_naviBlendInInst->pause(); d_naviPartialBlendOutInst->start(); @@ -654,7 +670,7 @@ void GameMenuDemo::disableNavigationBarElements() d_navigationIsEnabled = false; } -void GameMenuDemo::enableNavigationBarElements() +void GameMenuSample::enableNavigationBarElements() { d_naviPartialBlendOutInst->pause(); d_naviBlendInInst->start(); @@ -665,7 +681,7 @@ void GameMenuDemo::enableNavigationBarElements() d_navigationIsEnabled = true; } -void GameMenuDemo::updateIntroText() +void GameMenuSample::updateIntroText() { static const CEGUI::String firstPart = "Connection established..."; static const CEGUI::String secondPart = "Warning! User Authentication required!"; @@ -693,7 +709,7 @@ void GameMenuDemo::updateIntroText() d_botBarLabel->setText(finalText); } -void GameMenuDemo::updateLoginWelcomeText(float passedTime) +void GameMenuSample::updateLoginWelcomeText(float passedTime) { if(d_timeSinceLoginAccepted <= 0.0f) return; @@ -719,7 +735,7 @@ void GameMenuDemo::updateLoginWelcomeText(float passedTime) } -void GameMenuDemo::updateLoginStartButtonText(float passedTime) +void GameMenuSample::updateLoginStartButtonText(float passedTime) { if(d_timeSinceLoginAccepted <= 0.0f) return; @@ -749,25 +765,25 @@ void GameMenuDemo::updateLoginStartButtonText(float passedTime) d_botBarLabel->setText(finalText); } -void GameMenuDemo::setupNaviIconAnimationEventHandlers() +void GameMenuSample::setupNaviIconAnimationEventHandlers() { - d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); - d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); - d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); - d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); + d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); + d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); + d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); + d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); CEGUI::Window* window; window = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NavigationLabel"); - window->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); - window->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); + window->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); + window->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); window = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NavigationIcon"); - window->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); - window->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); + window->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); + window->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); window = d_root->getChild("BotNavigationContainer/NaviCenterContainer/NaviBotSelectionIcon"); - window->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); - window->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleCheckIfNaviIconAnimationNeedsChange, this)); + window->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); + window->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleCheckIfNaviIconAnimationNeedsChange, this)); } -void GameMenuDemo::startEntranceAnimations() +void GameMenuSample::startEntranceAnimations() { d_topBarAnimInst->start(); d_botBarAnimInst->start(); @@ -785,7 +801,7 @@ void GameMenuDemo::startEntranceAnimations() d_naviBotMoveInInst->start(); } -void GameMenuDemo::resetAnimations() +void GameMenuSample::resetAnimations() { //Set animations to end and apply their changes to the windows //For every animation instance that uses source properties @@ -810,69 +826,69 @@ void GameMenuDemo::resetAnimations() d_naviBotMoveInInst->apply(); } -void GameMenuDemo::setupButtonClickHandlers() +void GameMenuSample::setupButtonClickHandlers() { CEGUI::Window* buttonSave = d_root->getChild("InnerButtonsContainer/ButtonSave"); - buttonSave->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleStartPopupLinesSaveDisplay, this)); + buttonSave->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleStartPopupLinesSaveDisplay, this)); CEGUI::Window* buttonLoad = d_root->getChild("InnerButtonsContainer/ButtonLoad"); - buttonLoad->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleStartPopupLinesLoadDisplay, this)); + buttonLoad->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleStartPopupLinesLoadDisplay, this)); CEGUI::Window* buttonCharacters = d_root->getChild("InnerButtonsContainer/ButtonCharacters"); - buttonCharacters->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleStartPopupLinesCharactersDisplay, this)); + buttonCharacters->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleStartPopupLinesCharactersDisplay, this)); CEGUI::Window* buttonOptions = d_root->getChild("InnerButtonsContainer/ButtonOptions"); - buttonOptions->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleStartPopupLinesOptionsDisplay, this)); + buttonOptions->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleStartPopupLinesOptionsDisplay, this)); CEGUI::Window* buttonQuit = d_root->getChild("InnerButtonsContainer/ButtonQuit"); - buttonQuit->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&GameMenuDemo::handleStartPopupLinesQuitDisplay, this)); + buttonQuit->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&GameMenuSample::handleStartPopupLinesQuitDisplay, this)); } -void GameMenuDemo::setupNaviArrowWindows() +void GameMenuSample::setupNaviArrowWindows() { d_botNaviLeftArrowArea = d_root->getChild("BotNavigationContainer/LeftArrowArea"); d_botNaviRightArrowArea = d_root->getChild("BotNavigationContainer/RightArrowArea"); - d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleMouseEntersLeftArrowArea, this)); - d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleMouseLeavesLeftArrowArea, this)); - d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleMouseEntersRightArrowArea, this)); - d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleMouseLeavesRightArrowArea, this)); + d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handlePointerEntersLeftArrowArea, this)); + d_botNaviLeftArrowArea->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handlePointerLeavesLeftArrowArea, this)); + d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handlePointerEntersRightArrowArea, this)); + d_botNaviRightArrowArea->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handlePointerLeavesRightArrowArea, this)); } -void GameMenuDemo::setupInnerButtonsSubOptionsLabels() +void GameMenuSample::setupInnerButtonsSubOptionsLabels() { CEGUI::Window* label; label = d_root->getChild("InnerButtonsContainer/PopupLinesLoad/LabelLoad"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesSave/LabelSave"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesCharacters/LabelName2"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesCharacters/LabelNew"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesCharacters/LabelSelect"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesCharacters/LabelDelete"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesOptions/LabelVideo"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesOptions/LabelAudio"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesOptions/LabelControls"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesQuit/LabelYes"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); label = d_root->getChild("InnerButtonsContainer/PopupLinesQuit/LabelNo"); - label->subscribeEvent(CEGUI::Window::EventMouseEntersArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelEntered, this)); - label->subscribeEvent(CEGUI::Window::EventMouseLeavesArea, Event::Subscriber(&GameMenuDemo::handleInnerButtonsLabelLeft, this)); + label->subscribeEvent(CEGUI::Window::EventCursorEntersArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelEntered, this)); + label->subscribeEvent(CEGUI::Window::EventCursorLeavesArea, Event::Subscriber(&GameMenuSample::handleInnerButtonsLabelLeft, this)); } -CEGUI::Window* GameMenuDemo::getIconWindowFromLabel(CEGUI::Window* window) +CEGUI::Window* GameMenuSample::getIconWindowFromLabel(CEGUI::Window* window) { const CEGUI::String windowPrefix = "Label"; const CEGUI::String iconPostfix = "SelectionIcon"; @@ -883,7 +899,7 @@ CEGUI::Window* GameMenuDemo::getIconWindowFromLabel(CEGUI::Window* window) return window->getParent()->getParent()->getChild(windowName + iconPostfix); } -void GameMenuDemo::setupPopupLinesAnimations() +void GameMenuSample::setupPopupLinesAnimations() { CEGUI::Window* window; CEGUI::AnimationManager& animMgr = CEGUI::AnimationManager::getSingleton(); @@ -906,7 +922,7 @@ void GameMenuDemo::setupPopupLinesAnimations() d_popupLinesQuitAnimInst->setTarget(window); } -void GameMenuDemo::setupSelectionIconAnimations() +void GameMenuSample::setupSelectionIconAnimations() { CEGUI::Window* window; CEGUI::AnimationManager& animMgr = CEGUI::AnimationManager::getSingleton(); @@ -975,12 +991,4 @@ void GameMenuDemo::setupSelectionIconAnimations() iconAnimInst->setTargetWindow(window); iconAnimInst = animMgr.instantiateAnimation(iconAnimationStop); iconAnimInst->setTargetWindow(window); -} -/************************************************************************* -Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static GameMenuDemo sample; - return sample; } \ No newline at end of file diff --git a/samples/GameMenu/GameMenu.h b/samples/GameMenu/GameMenu.h index 198208436..03206e102 100644 --- a/samples/GameMenu/GameMenu.h +++ b/samples/GameMenu/GameMenu.h @@ -24,8 +24,8 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Game_Menu_Demo_ -#define _Game_Menu_Demo_ +#ifndef _Game_Menu_Sample_ +#define _Game_Menu_Sample_ #include "SampleBase.h" @@ -44,9 +44,11 @@ enum WriteFocus // Sample class -class GameMenuDemo : public Sample +class GameMenuSample : public Sample { public: + GameMenuSample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); @@ -57,7 +59,6 @@ class GameMenuDemo : public Sample virtual void update(float timeSinceLastUpdate); - protected: void setupWindows(); @@ -85,10 +86,10 @@ class GameMenuDemo : public Sample bool handleCheckIfNaviIconAnimationNeedsChange(const CEGUI::EventArgs& args); bool handleNaviSelectionIconAnimStart(const CEGUI::EventArgs& args); - bool handleMouseEntersLeftArrowArea(const CEGUI::EventArgs& args); - bool handleMouseLeavesLeftArrowArea(const CEGUI::EventArgs& args); - bool handleMouseEntersRightArrowArea(const CEGUI::EventArgs& args); - bool handleMouseLeavesRightArrowArea(const CEGUI::EventArgs& args); + bool handlePointerEntersLeftArrowArea(const CEGUI::EventArgs& args); + bool handlePointerLeavesLeftArrowArea(const CEGUI::EventArgs& args); + bool handlePointerEntersRightArrowArea(const CEGUI::EventArgs& args); + bool handlePointerLeavesRightArrowArea(const CEGUI::EventArgs& args); bool handleStartPopupLinesSaveDisplay(const CEGUI::EventArgs& args); bool handleStartPopupLinesLoadDisplay(const CEGUI::EventArgs& args); @@ -120,7 +121,7 @@ class GameMenuDemo : public Sample bool d_interactivePlanetElementsAreEnabled; bool d_navigationIsEnabled; bool d_loginWasAccepted; - bool d_mouseIsHoveringNavi; + bool d_cursorIsHoveringNavi; bool d_startButtonClicked; WriteFocus d_currentWriteFocus; diff --git a/samples/GameMenu/SampleMetaData.xml b/samples/GameMenu/SampleMetaData.xml deleted file mode 100644 index 97abfcdd0..000000000 --- a/samples/GameMenu/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/HelloWorld/CMakeLists.txt b/samples/HelloWorld/CMakeLists.txt index 8d8cd5b44..694aca6d7 100644 --- a/samples/HelloWorld/CMakeLists.txt +++ b/samples/HelloWorld/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_HELLO_WORLD "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_HELLO_WORLD) - cegui_add_sample(CEGUISample_HelloWorld) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/HelloWorld/HelloWorld.cpp b/samples/HelloWorld/HelloWorld.cpp index 265e42fa2..a745215e8 100644 --- a/samples/HelloWorld/HelloWorld.cpp +++ b/samples/HelloWorld/HelloWorld.cpp @@ -29,11 +29,23 @@ #include +HelloWorldSample::HelloWorldSample() : + Sample(90) +{ + Sample::d_name = "HelloWorldSample"; + Sample::d_credits = "CrazyEddie, Lukas \"Ident\" Meindl"; + Sample::d_description = + "A very simple \"Hello World\" sample. It contains a single " + "window which will write \"Hello-World\" to the console if clicked"; + Sample::d_summary = + "The Sample uses the WindowManager to create the window from code. " + "An event handler is used to handle the mouse clicks on the window."; +} /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ -bool HelloWorldDemo::initialise(CEGUI::GUIContext* guiContext) +bool HelloWorldSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -51,13 +63,13 @@ bool HelloWorldDemo::initialise(CEGUI::GUIContext* guiContext) // loads in a font that gets used as the system default. SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); - // The next thing we do is to set a default mouse cursor image. This is + // The next thing we do is to set a default cursor image. This is // not strictly essential, although it is nice to always have a visible - // cursor if a window or widget does not explicitly set one of its own. + // indicator if a window or widget does not explicitly set one of its own. // // The TaharezLook Imageset contains an Image named "MouseArrow" which is - // the ideal thing to have as a defult mouse cursor image. - guiContext->getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); + // the ideal thing to have as a defult cursor image. + guiContext->getCursor().setDefaultImage("TaharezLook/MouseArrow"); // Now the system is initialised, we can actually create some UI elements, for // this first example, a full-screen 'root' window is set as the active GUI @@ -87,8 +99,8 @@ bool HelloWorldDemo::initialise(CEGUI::GUIContext* guiContext) // A FrameWindow is a window with a frame and a titlebar which may be moved around // and resized. // - // Create a FrameWindow in the TaharezLook style, and name it 'Demo Window' - FrameWindow* wnd = (FrameWindow*)winMgr.createWindow("TaharezLook/FrameWindow", "Demo Window"); + // Create a FrameWindow in the TaharezLook style, and name it 'Sample Window' + FrameWindow* wnd = (FrameWindow*)winMgr.createWindow("TaharezLook/FrameWindow", "Sample Window"); // Here we attach the newly created FrameWindow to the previously created // DefaultWindow which we will be using as the root of the displayed gui. @@ -121,7 +133,7 @@ bool HelloWorldDemo::initialise(CEGUI::GUIContext* guiContext) // FrameWindow's titlebar. wnd->setText("Hello World!"); - wnd->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&HelloWorldDemo::handleHelloWorldClicked, this)); + wnd->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&HelloWorldSample::handleHelloWorldClicked, this)); // return true so that the samples framework knows that initialisation was a // success, and that it should now run the sample. @@ -132,22 +144,13 @@ bool HelloWorldDemo::initialise(CEGUI::GUIContext* guiContext) /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ -void HelloWorldDemo::deinitialise() +void HelloWorldSample::deinitialise() { } -bool HelloWorldDemo::handleHelloWorldClicked(const CEGUI::EventArgs& args) +bool HelloWorldSample::handleHelloWorldClicked(const CEGUI::EventArgs& args) { std::cout << "Hello World!" << std::endl; return false; -} - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static HelloWorldDemo sample; - return sample; } \ No newline at end of file diff --git a/samples/HelloWorld/HelloWorld.h b/samples/HelloWorld/HelloWorld.h index 8d30bc1a8..e2cda0609 100644 --- a/samples/HelloWorld/HelloWorld.h +++ b/samples/HelloWorld/HelloWorld.h @@ -35,9 +35,11 @@ namespace CEGUI class DefaultWindow; } -class HelloWorldDemo : public Sample +class HelloWorldSample : public Sample { public: + HelloWorldSample(); + virtual bool initialise(CEGUI::GUIContext* guiContext); virtual void deinitialise(); diff --git a/samples/HelloWorld/SampleMetaData.xml b/samples/HelloWorld/SampleMetaData.xml deleted file mode 100644 index da87c3b6f..000000000 --- a/samples/HelloWorld/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/Inventory/CMakeLists.txt b/samples/Inventory/CMakeLists.txt index 96e87e326..694aca6d7 100644 --- a/samples/Inventory/CMakeLists.txt +++ b/samples/Inventory/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_INVENTORY "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_INVENTORY) - cegui_add_sample(CEGUISample_Inventory) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Inventory/Sample_InventoryDemo.cpp b/samples/Inventory/Inventory.cpp similarity index 85% rename from samples/Inventory/Sample_InventoryDemo.cpp rename to samples/Inventory/Inventory.cpp index 840557a5e..7fcdfe1b8 100644 --- a/samples/Inventory/Sample_InventoryDemo.cpp +++ b/samples/Inventory/Inventory.cpp @@ -24,15 +24,34 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "Sample_InventoryDemo.h" +#include "Inventory.h" #include "InventoryItem.h" #include "InventoryItemRenderer.h" #include "InventoryReceiver.h" #include +InventorySample::InventorySample() : + Sample(97) +{ + Sample::d_name = "InventorySample"; + Sample::d_credits = "CrazyEddie"; + Sample::d_description = + "The sample contains an RPG style inventory that allows " + "dragging shaped items from one inventory window to another. " + "Red and green colours display if the item can be " + "dropped at the current position."; + Sample::d_summary = + "To achieve this the custom windows \"TaharezLook/InventoryReceiver\" " + "and \"TaharezLook/InventoryItem\" were added via the " + "\"InventoryComponents.looknfeel\" file. For handling the mechanics of " + "allowing or refusing items to be dropped at set position, the " + "InventoryReceiver class provides extra functionality in the C++ code. " + "Event handlers are used to react to drag n' drop events for this purpose."; +} + //----------------------------------------------------------------------------// -bool InventoryDemo::initialise(CEGUI::GUIContext* guiContext) +bool InventorySample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -46,7 +65,7 @@ bool InventoryDemo::initialise(CEGUI::GUIContext* guiContext) // basic system init using TaharezLook. WindowManager& winMgr = WindowManager::getSingleton(); SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); - guiContext->getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); + guiContext->getCursor().setDefaultImage("TaharezLook/MouseArrow"); Window* root = winMgr.createWindow("DefaultWindow", "root"); guiContext->setRootWindow(root); @@ -134,19 +153,9 @@ bool InventoryDemo::initialise(CEGUI::GUIContext* guiContext) } //----------------------------------------------------------------------------// -void InventoryDemo::deinitialise() +void InventorySample::deinitialise() { // nothing to do here! } -//----------------------------------------------------------------------------// - - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static InventoryDemo sample; - return sample; -} \ No newline at end of file +//----------------------------------------------------------------------------// \ No newline at end of file diff --git a/samples/Inventory/Sample_InventoryDemo.h b/samples/Inventory/Inventory.h similarity index 90% rename from samples/Inventory/Sample_InventoryDemo.h rename to samples/Inventory/Inventory.h index 2158d3c03..cf5beec2b 100644 --- a/samples/Inventory/Sample_InventoryDemo.h +++ b/samples/Inventory/Inventory.h @@ -24,15 +24,17 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_InventoryDemo_h_ -#define _Sample_InventoryDemo_h_ +#ifndef _Sample_InventorySample_h_ +#define _Sample_InventorySample_h_ #include "SampleBase.h" #include "CEGUI/CEGUI.h" -class InventoryDemo : public Sample +class InventorySample : public Sample { public: + InventorySample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); @@ -40,5 +42,5 @@ class InventoryDemo : public Sample virtual void deinitialise(); }; -#endif // end of guard _Sample_InventoryDemo_h_ +#endif // end of guard _Sample_InventorySample_h_ diff --git a/samples/Inventory/InventoryItem.cpp b/samples/Inventory/InventoryItem.cpp index 6420873f4..c82553f4e 100644 --- a/samples/Inventory/InventoryItem.cpp +++ b/samples/Inventory/InventoryItem.cpp @@ -87,13 +87,13 @@ void InventoryItem::setLocationOnReceiver(int x, int y) } //------------------------------------------------------------------------------// -bool InventoryItem::isHit(const Vector2f& position, const bool allow_disabled) const +bool InventoryItem::isHit(const glm::vec2& position, const bool allow_disabled) const { if (!DragContainer::isHit(position, allow_disabled)) return false; - int gx = gridXLocationFromPixelPosition(position.d_x); - int gy = gridYLocationFromPixelPosition(position.d_y); + int gx = gridXLocationFromPixelPosition(position.x); + int gy = gridYLocationFromPixelPosition(position.y); if (gx < 0 || gx >= d_content.width() || gy < 0 || gy >= d_content.height()) return false; @@ -130,10 +130,12 @@ void InventoryItem::populateGeometryBuffer() for (int x = 0; x < d_content.width(); ++x) { if (d_content.elementAtLocation(x, y)) - img->render(*d_geometry, - Vector2f(x * square_size.d_width + 1, y * square_size.d_height + 1), - Sizef(square_size.d_width - 2, square_size.d_height - 2), 0, + { + img->render(d_geometryBuffers, + glm::vec2(x * square_size.d_width + 1, y * square_size.d_height + 1), + Sizef(square_size.d_width - 2, square_size.d_height - 2), 0, false, ColourRect(colour)); + } } } } @@ -157,7 +159,7 @@ void InventoryItem::onMoved(ElementEventArgs& e) { const Sizef square_size(receiver->squarePixelSize()); Rectf area(getUnclippedOuterRect().get()); - area.offset(Vector2f(square_size.d_width / 2, square_size.d_height / 2)); + area.offset(0.5f * glm::vec2(square_size.d_width, square_size.d_height)); const int x = receiver->gridXLocationFromPixelPosition(area.left()); const int y = receiver->gridYLocationFromPixelPosition(area.top()); diff --git a/samples/Inventory/InventoryItem.h b/samples/Inventory/InventoryItem.h index 7961b0606..5f7cb5561 100644 --- a/samples/Inventory/InventoryItem.h +++ b/samples/Inventory/InventoryItem.h @@ -72,7 +72,7 @@ class InventoryItem : public DragContainer, public InventoryBase bool currentDropTargetIsValid() const; // base class overrides - bool isHit(const Vector2f& position, const bool allow_disabled = false) const; + bool isHit(const glm::vec2& position, const bool allow_disabled = false) const; void setContentSize(int width, int height); protected: diff --git a/samples/Inventory/InventoryReceiver.cpp b/samples/Inventory/InventoryReceiver.cpp index 1ad8fca1e..ca5f6af84 100644 --- a/samples/Inventory/InventoryReceiver.cpp +++ b/samples/Inventory/InventoryReceiver.cpp @@ -180,7 +180,7 @@ void InventoryReceiver::onDragDropItemDropped(DragDropEventArgs &e) const Sizef square_size(squarePixelSize()); Rectf item_area(item->getUnclippedOuterRect().get()); - item_area.offset(Vector2f(square_size.d_width / 2, square_size.d_height / 2)); + item_area.offset(0.5f * glm::vec2(square_size.d_width, square_size.d_height)); const int drop_x = gridXLocationFromPixelPosition(item_area.left()); const int drop_y = gridYLocationFromPixelPosition(item_area.top()); @@ -209,9 +209,9 @@ void InventoryReceiver::populateGeometryBuffer() if (d_content.elementAtLocation(x, y)) colour = 0xFF0000FF; - img->render(*d_geometry, - Vector2f(x * square_size.d_width + 1, y * square_size.d_height + 1), - Sizef(square_size.d_width - 2, square_size.d_height - 2), 0, + img->render(d_geometryBuffers, + glm::vec2(x * square_size.d_width + 1, y * square_size.d_height + 1), + Sizef(square_size.d_width - 2, square_size.d_height - 2), 0, false, ColourRect(colour)); } } diff --git a/samples/Inventory/SampleMetaData.xml b/samples/Inventory/SampleMetaData.xml deleted file mode 100644 index 14814b418..000000000 --- a/samples/Inventory/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/MenuNavigation/CMakeLists.txt b/samples/MenuNavigation/CMakeLists.txt new file mode 100644 index 000000000..694aca6d7 --- /dev/null +++ b/samples/MenuNavigation/CMakeLists.txt @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/MenuNavigation/MenuNavigation.cpp b/samples/MenuNavigation/MenuNavigation.cpp new file mode 100644 index 000000000..ddd634346 --- /dev/null +++ b/samples/MenuNavigation/MenuNavigation.cpp @@ -0,0 +1,203 @@ +/*********************************************************************** + created: 30/5/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "MenuNavigation.h" +#include "CEGUI/CEGUI.h" + +#include +#include + +using namespace CEGUI; +using namespace NavigationStrategiesPayloads; + +/** This sample uses most of the code from the 'HelloWorld' sample. + Thus, most of the clarifying comments have been removed for brevity. **/ + +MenuNavigationSample::MenuNavigationSample() +{ + Sample::d_name = "MenuNavigationSample"; + Sample::d_credits = "Timotei Dolean"; + Sample::d_description = + "A demo that shows a 2D menu which can be navigated using the keyboard or other devices."; + Sample::d_summary = + "The demo uses the WindowManager to create from code a window " + "with a menu that contains multiple buttons arranged in a 4x4 matrix."; +} +/*************************************************************************ech +Sample specific initialisation goes here. +*************************************************************************/ +bool MenuNavigationSample::initialise(CEGUI::GUIContext* gui_context) +{ + using namespace CEGUI; + + d_usedFiles = CEGUI::String(__FILE__); + + SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); + gui_context->getCursor().setDefaultImage("TaharezLook/MouseArrow"); + + WindowManager& win_mgr = WindowManager::getSingleton(); + d_root = win_mgr.loadLayoutFromFile("MenuNavigationSample.layout"); + + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + gui_context->setDefaultFont(&defaultFont); + + gui_context->setRootWindow(d_root); + + MatrixNavigationStrategy* d_matrixNavigationStrategy = new MatrixNavigationStrategy(); + d_matrixWindowNavigator = new WindowNavigator(createMatrixNavigationMappings(), + d_matrixNavigationStrategy); + gui_context->setWindowNavigator(d_matrixWindowNavigator); + + LinearNavigationStrategy* d_linearNavigatorStrategy = new LinearNavigationStrategy(); + d_linearWindowNavigator = new WindowNavigator(createLinearNavigationMappings(), + d_linearNavigatorStrategy); + + TabControl* tabControl = static_cast(d_root->getChild("FrameWindow/TabControl")); + tabControl->subscribeEvent(TabControl::EventSelectionChanged, + Event::Subscriber(&MenuNavigationSample::handleTabSelectionChanged, this)); + + Window* page1Window = win_mgr.loadLayoutFromFile("MenuNavigationSampleTabPage1.layout"); + d_logWidget1 = page1Window->getChild("StaticText"); + d_logWidget1->setText("OK"); + + // 4 rows + d_matrixNavigationStrategy->d_windows.resize(4); + for (int i = 1; i <= 16; ++i) + { + std::ostringstream os; + os << "Button" << i; + + PushButton* button = static_cast(page1Window->getChild(os.str())); + button->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&MenuNavigationSample::handleNumberButtonClicked, this)); + + d_matrixNavigationStrategy->d_windows.at((i - 1) % 4).push_back(button); + } + + tabControl->addTab(page1Window); + + Window* page2Window = win_mgr.loadLayoutFromFile("MenuNavigationSampleTabPage2.layout"); + d_logWidget2 = page2Window->getChild("StaticText"); + d_logWidget2->setText("OK"); + + Window* selectButton = page2Window->getChild("SelectButton"); + selectButton->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&MenuNavigationSample::handleSelectButtonClicked, this)); + + tabControl->addTab(page2Window); + + d_classesList = static_cast(page2Window->getChild("ClassesList")); + d_classesList->setMultiSelectEnabled(true); + initialiseClasses(d_classesList); + + d_linearNavigatorStrategy->d_windows.push_back(d_classesList); + d_linearNavigatorStrategy->d_windows.push_back(selectButton); + + return true; +} + +/************************************************************************* +Cleans up resources allocated in the initialiseSample call. +*************************************************************************/ +void MenuNavigationSample::deinitialise() +{ +} + +void MenuNavigationSample::initialiseClasses(ListWidget* classes_list_view) +{ + static const int classes_list_size = 5; + static const char* classes_list[] = + { + "Druid", + "Shaman", + "Warrior", + "Priest", + "Death Knight" + }; + + for (int i = 0; i < classes_list_size; ++i) + { + classes_list_view->addItem(new StandardItem(classes_list[i])); + } +} + +bool MenuNavigationSample::handleSelectButtonClicked(const CEGUI::EventArgs& e) +{ + using namespace CEGUI; + + StandardItem* item = d_classesList->getFirstSelectedItem(); + if (item != 0) + { + d_logWidget2->setText("Selected " + item->getText() + "\n"); + } + + return true; +} + +bool MenuNavigationSample::handleNumberButtonClicked(const CEGUI::EventArgs& e) +{ + d_logWidget1->setText("Button " + + static_cast(e).window->getText() + + " pressed\n"); + + return true; +} + +bool MenuNavigationSample::handleTabSelectionChanged(const CEGUI::EventArgs& e) +{ + TabControl* tabControl = static_cast(static_cast(e).window); + + // only the first tab has a window navigator + if (tabControl->getSelectedTabIndex() == 0) + d_root->getGUIContext().setWindowNavigator(d_matrixWindowNavigator); + else + d_root->getGUIContext().setWindowNavigator(d_linearWindowNavigator); + return true; +} + +std::map MenuNavigationSample::createMatrixNavigationMappings() +{ + std::map mappings; + + mappings[SV_NavigateToNext] = NAVIGATE_NEXT; + mappings[SV_NavigateToPrevious] = NAVIGATE_PREVIOUS; + mappings[SV_GoToPreviousCharacter] = NAVIGATE_LEFT; + mappings[SV_GoToNextCharacter] = NAVIGATE_RIGHT; + mappings[SV_GoDown] = NAVIGATE_DOWN; + mappings[SV_GoUp] = NAVIGATE_UP; + + return mappings; +} + +std::map MenuNavigationSample::createLinearNavigationMappings() +{ + std::map mappings; + + mappings[SV_NavigateToNext] = NAVIGATE_NEXT; + mappings[SV_NavigateToPrevious] = NAVIGATE_PREVIOUS; + + return mappings; +} diff --git a/samples/MenuNavigation/MenuNavigation.h b/samples/MenuNavigation/MenuNavigation.h new file mode 100644 index 000000000..0e7f0975d --- /dev/null +++ b/samples/MenuNavigation/MenuNavigation.h @@ -0,0 +1,59 @@ +/*********************************************************************** + created: 30/5/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _Sample_Menu_Navigation_h_ +#define _Sample_Menu_Navigation_h_ + +#include "SampleBase.h" +#include "NavigationStrategies.h" + +class MenuNavigationSample : public Sample +{ +public: + MenuNavigationSample(); + + virtual bool initialise(CEGUI::GUIContext* gui_context); + virtual void deinitialise(); + +private: + CEGUI::Window* d_root; + CEGUI::Window* d_logWidget1; + CEGUI::Window* d_logWidget2; + CEGUI::ListWidget* d_classesList;; + + CEGUI::WindowNavigator* d_matrixWindowNavigator; + CEGUI::WindowNavigator* d_linearWindowNavigator; + + void initialiseClasses(CEGUI::ListWidget* classes_listwidget); + bool handleSelectButtonClicked(const CEGUI::EventArgs& e); + bool handleNumberButtonClicked(const CEGUI::EventArgs& e); + bool handleTabSelectionChanged(const CEGUI::EventArgs& e); + + std::map createMatrixNavigationMappings(); + std::map createLinearNavigationMappings(); +}; + +#endif // end of guard _Sample_Menu_Navigation_h_ diff --git a/samples/Minesweeper/CMakeLists.txt b/samples/Minesweeper/CMakeLists.txt index ef0758da5..694aca6d7 100644 --- a/samples/Minesweeper/CMakeLists.txt +++ b/samples/Minesweeper/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_MINESWEEPER "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_MINESWEEPER) - cegui_add_sample(CEGUISample_Minesweeper) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Minesweeper/Sample_Minesweeper.cpp b/samples/Minesweeper/Minesweeper.cpp similarity index 84% rename from samples/Minesweeper/Sample_Minesweeper.cpp rename to samples/Minesweeper/Minesweeper.cpp index 056d3bb0a..2bbdfa5b5 100644 --- a/samples/Minesweeper/Sample_Minesweeper.cpp +++ b/samples/Minesweeper/Minesweeper.cpp @@ -26,69 +26,12 @@ author: Olivier Delannoy (Dalfy) ***************************************************************************/ #include "SampleBase.h" #include "CEGUI/CEGUI.h" + +#include "Minesweeper.h" #include "Minesweeper_Timer.h" -#include -#include -struct Location -{ - size_t d_row; - size_t d_col; -}; -const size_t MinesweeperSize = 10; -const size_t MineCount = 15; -class MinesweeperSample : public Sample -{ -public: - // method to initialse the samples windows and events. - virtual bool initialise(CEGUI::GUIContext* guiContext); - - // method to perform any required cleanup operations. - virtual void deinitialise(); - -protected: - // Handle new game - bool handleGameStartClicked(const CEGUI::EventArgs& event); - // Handle click on a button of the board - bool handleMineButtonClicked(const CEGUI::EventArgs& event); - // Handle mouse button down on a button of the board - bool handleMineButtonDown(const CEGUI::EventArgs& event); - // Update the timer if needed - bool handleUpdateTimer(const CEGUI::EventArgs& event); - // reset the board - void boardReset(); - // place mine and computes mine neighborhood - void boardPositionMines(); - // Test whether the player wins or not - bool isGameWin(); - // Call this function if the game is finished - void gameEnd(bool victory); - // When a button is clicked - bool boardDiscover(const Location& location); - // Store all buttons needed - CEGUI::PushButton* d_buttons[MinesweeperSize][MinesweeperSize]; - // Store button location - Location d_buttonsMapping[MinesweeperSize][MinesweeperSize]; - // Store the value of the board itself - size_t d_board[MinesweeperSize][MinesweeperSize]; - // Store the number of case the user discovered - size_t d_boardCellDiscovered; - // Store the number of mine to find - CEGUI::Editbox* d_counter; - // Store the number of second elapsed - CEGUI::Editbox* d_timer; - // Used to display the result text - CEGUI::Window* d_result; - - // True if the game is started false otherwise - bool d_gameStarted; - // time at the start of the game - clock_t d_timerStartTime; - // current value of the timer - clock_t d_timerValue; - // Custom window type to force refresh of the timer - Timer* d_alarm; -}; +#include +#include ////////////////////////////////////////////////////////////////////////// /************************************************************************* @@ -96,6 +39,17 @@ class MinesweeperSample : public Sample MinesweeperSample class *************************************************************************/ + +MinesweeperSample::MinesweeperSample() +{ + Sample::d_name = "MinesweeperSample"; + Sample::d_credits = "Olivier \"Dalfy\" Delannoy"; + Sample::d_description = + "The Minesweeper sample is a fully functional replication of the well known game using CEGUI"; + Sample::d_summary = + "The demo uses event handlers and the Vanilla and Taharez skins"; +} + ////////////////////////////////////////////////////////////////////////// /************************************************************************* Sample specific initialisation goes here. @@ -124,12 +78,12 @@ bool MinesweeperSample::initialise(CEGUI::GUIContext* guiContext) SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); guiContext->setDefaultTooltipType("TaharezLook/Tooltip"); - // set default mouse image - guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow"); + // set default cursor image + guiContext->getCursor().setDefaultImage("Vanilla-Images/MouseArrow"); // load an image to use as a background if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow("Vanilla/StaticImage"); @@ -155,8 +109,8 @@ bool MinesweeperSample::initialise(CEGUI::GUIContext* guiContext) d_alarm->addChild(frame); frame->setXPosition(UDim(0.3f, 0.0f)); frame->setYPosition(UDim(0.15f, 0.0f)); - frame->setWidth(UDim(0.4f, 0.0f)); - frame->setHeight(UDim(0.7f, 0.0f)); + frame->setWidth(UDim(0.4f, 0.0f)); + frame->setHeight(UDim(0.7f, 0.0f)); frame->setText("CEGUI Minesweeper"); // create the action panel @@ -204,7 +158,7 @@ bool MinesweeperSample::initialise(CEGUI::GUIContext* guiContext) grid->setYPosition(UDim(0.23f, 0.0f)); grid->setWidth( UDim(0.94f, 0.0f)); grid->setHeight( UDim(0.74f, 0.0f)); - const float d_inc = 1.0f / MinesweeperSize; + const float d_inc = 1.0f / MinesweeperSize; for(size_t i = 0 ; i < MinesweeperSize ; ++i) { // create a container for each row @@ -227,7 +181,7 @@ bool MinesweeperSample::initialise(CEGUI::GUIContext* guiContext) d_buttons[i][j]->setID(0); // Connect event handlers d_buttons[i][j]->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&MinesweeperSample::handleMineButtonClicked, this)); - d_buttons[i][j]->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&MinesweeperSample::handleMineButtonDown, this)); + d_buttons[i][j]->subscribeEvent(Window::EventCursorPressHold, Event::Subscriber(&MinesweeperSample::handleMinePointerPressHold, this)); } } d_result = winMgr.createWindow("Vanilla/StaticText"); @@ -326,12 +280,12 @@ bool MinesweeperSample::handleMineButtonClicked(const CEGUI::EventArgs& event) return true; } /************************************************************************ -Handle click on a mine button (any mouse button) +Handle click on a mine button (any cursor source) ************************************************************************/ -bool MinesweeperSample::handleMineButtonDown(const CEGUI::EventArgs& event) +bool MinesweeperSample::handleMinePointerPressHold(const CEGUI::EventArgs& event) { - const CEGUI::MouseEventArgs& me = static_cast(event); - if (me.button == CEGUI::RightButton) + const CEGUI::CursorInputEventArgs& me = static_cast(event); + if (me.source == CEGUI::CIS_Right) { CEGUI::Window* button = me.window; if (!button->isDisabled()) @@ -516,11 +470,4 @@ bool MinesweeperSample::boardDiscover(const Location& loc) } } return true; -} - - -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static MinesweeperSample sample; - return sample; } \ No newline at end of file diff --git a/samples/Minesweeper/Minesweeper.h b/samples/Minesweeper/Minesweeper.h new file mode 100644 index 000000000..6c58d1507 --- /dev/null +++ b/samples/Minesweeper/Minesweeper.h @@ -0,0 +1,99 @@ +/*********************************************************************** +created: 2014-08-23 +author: Luca Ebach +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _Minesweeper_h_ +#define _Minesweeper_h_ + +#include "Sample.h" +#include "CEGUI/ForwardRefs.h" +#include "Minesweeper_Timer.h" + +#include + +struct Location +{ + size_t d_row; + size_t d_col; +}; +const size_t MinesweeperSize = 10; +const size_t MineCount = 15; + +class MinesweeperSample : public Sample +{ +public: + MinesweeperSample(); + + // method to initialse the samples windows and events. + virtual bool initialise(CEGUI::GUIContext* guiContext); + + // method to perform any required cleanup operations. + virtual void deinitialise(); + +protected: + // Handle new game + bool handleGameStartClicked(const CEGUI::EventArgs& event); + // Handle click on a button of the board + bool handleMineButtonClicked(const CEGUI::EventArgs& event); + // Handle cursor press & hold on a button of the board + bool handleMinePointerPressHold(const CEGUI::EventArgs& event); + // Update the timer if needed + bool handleUpdateTimer(const CEGUI::EventArgs& event); + // reset the board + void boardReset(); + // place mine and computes mine neighborhood + void boardPositionMines(); + // Test whether the player wins or not + bool isGameWin(); + // Call this function if the game is finished + void gameEnd(bool victory); + // When a button is clicked + bool boardDiscover(const Location& location); + // Store all buttons needed + CEGUI::PushButton* d_buttons[MinesweeperSize][MinesweeperSize]; + // Store button location + Location d_buttonsMapping[MinesweeperSize][MinesweeperSize]; + // Store the value of the board itself + size_t d_board[MinesweeperSize][MinesweeperSize]; + // Store the number of case the user discovered + size_t d_boardCellDiscovered; + // Store the number of mine to find + CEGUI::Editbox* d_counter; + // Store the number of second elapsed + CEGUI::Editbox* d_timer; + // Used to display the result text + CEGUI::Window* d_result; + + // True if the game is started false otherwise + bool d_gameStarted; + // time at the start of the game + clock_t d_timerStartTime; + // current value of the timer + clock_t d_timerValue; + // Custom window type to force refresh of the timer + Timer* d_alarm; +}; + +#endif // _Minesweeper_h_ \ No newline at end of file diff --git a/samples/Minesweeper/Minesweeper_Timer.cpp b/samples/Minesweeper/Minesweeper_Timer.cpp index c173e73e2..a6889ea24 100644 --- a/samples/Minesweeper/Minesweeper_Timer.cpp +++ b/samples/Minesweeper/Minesweeper_Timer.cpp @@ -40,7 +40,7 @@ void Delay::set(CEGUI::PropertyReceiver* receiver, const CEGUI::String& value) } CEGUI::Property* Delay::clone() const { - return CEGUI_NEW_AO Delay(*this); + return new Delay(*this); } } diff --git a/samples/Minesweeper/SampleMetaData.xml b/samples/Minesweeper/SampleMetaData.xml deleted file mode 100644 index a3b6cab84..000000000 --- a/samples/Minesweeper/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/ModelView/CMakeLists.txt b/samples/ModelView/CMakeLists.txt new file mode 100644 index 000000000..694aca6d7 --- /dev/null +++ b/samples/ModelView/CMakeLists.txt @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/ModelView/InventoryModel.cpp b/samples/ModelView/InventoryModel.cpp new file mode 100644 index 000000000..b67ae97f0 --- /dev/null +++ b/samples/ModelView/InventoryModel.cpp @@ -0,0 +1,163 @@ +/*********************************************************************** + created: Tue May 27 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "InventoryModel.h" +#include "CEGUI/PropertyHelper.h" +#include +#include + +using namespace CEGUI; + +//----------------------------------------------------------------------------// +InventoryItem::InventoryItem(String name) : GenericItem(name) +{ +} + +//----------------------------------------------------------------------------// +InventoryItem* InventoryItem::make(const String& name, float weight, GenericItem* parent) +{ + InventoryItem* item = new InventoryItem(name); + + item->d_weight = weight; + item->d_parent = parent; + + return item; +} + +//----------------------------------------------------------------------------// +bool InventoryItem::operator==(const InventoryItem& other) +{ + if (!GenericItem::operator==(other)) + return false; + + return d_weight == other.d_weight; +} + +//----------------------------------------------------------------------------// +InventoryModel::InventoryModel() : +GenericItemModel(InventoryItem::make("Inventory", 0.0f)), +d_randomItemsCount(0) +{ +} + +//----------------------------------------------------------------------------// +void InventoryModel::load() +{ + InventoryItem* backpack = InventoryItem::make("Trip backpack", 2.0f, d_root); + InventoryItem* prev_matryoshka = 0; + + // matryoshka Z to A + for (char chr = 'Z'; chr >= 'A'; --chr) + { + InventoryItem* matryoshka = InventoryItem::make("Matryoshka " + String(1, chr), 1.0f, backpack); + + matryoshka->setIcon("DriveIcons/DriveStack"); + + if (prev_matryoshka != 0) + { + prev_matryoshka->setParent(matryoshka); + matryoshka->addItem(prev_matryoshka); + } + + prev_matryoshka = matryoshka; + } + + backpack->addItem(InventoryItem::make("Gepäckaufbewahrungsschein: Wiener Neustadt", 1.0f, backpack)); + backpack->addItem(InventoryItem::make("Gepäckaufbewahrungsschein: Frankfurt am Main", 1.0f, backpack)); + backpack->addItem(InventoryItem::make("Gepäckaufbewahrungsschein: Sankt Johann im Pongau", 1.0f, backpack)); + backpack->addItem(InventoryItem::make("Gepäckaufbewahrungsschein: Seekirchen am Wallersee", 1.0f, backpack)); + + InventoryItem* beans_can = InventoryItem::make("Beans can", 1.0f, backpack); + beans_can->setIcon("DriveIcons/GlobalDrive"); + InventoryItem* beans = InventoryItem::make("Beans!", 0.1f, beans_can); + beans_can->addItem(beans); + + backpack->addItem(prev_matryoshka); + backpack->addItem(beans_can); + + d_root->addItem(backpack); + + InventoryItem* bow = InventoryItem::make("Bow", 23.451f, d_root); + for (int i = 25; i >= 0; --i) + { + InventoryItem* arrow = InventoryItem::make( + "arrow " + PropertyHelper::toString(i), 0.2f, bow); + bow->addItem(arrow); + } + d_root->addItem(bow); + + // generate *many* items :D + for (int i = 2000; i >= 1960; i -= 2) + { + InventoryItem* almanach = InventoryItem::make( + "Almanach " + PropertyHelper::toString(i), 0.34f, d_root); + + if (i % 2 == 0) + almanach->setIcon("DriveIcons/Lime"); + + d_root->addItem(almanach); + } +} + +//----------------------------------------------------------------------------// +void InventoryModel::addRandomItemWithChildren(const ModelIndex& parent, size_t position, + size_t child_count) +{ + InventoryItem* new_item = InventoryItem::make( + "New random item #" + PropertyHelper::toString(d_randomItemsCount), + 0.3f, static_cast(parent.d_modelData)); + + for (size_t i = 0; i < child_count; ++i) + { + InventoryItem* new_subitem = InventoryItem::make( + "New sub item #" + PropertyHelper::toString(d_randomItemsCount), + 1.3f, new_item); + + new_item->addItem(new_subitem); + } + + addItemAtPosition(new_item, parent, position); + d_randomItemsCount++; +} + +//----------------------------------------------------------------------------// +void InventoryModel::updateItemName(const ModelIndex& index, const String& newName) +{ + ModelIndex parent_index = getParentIndex(index); + + notifyChildrenDataWillChange(parent_index, 0, 1); + + InventoryItem* item = static_cast(index.d_modelData); + item->setText(newName); + + notifyChildrenDataChanged(parent_index, 0, 1); +} + +//----------------------------------------------------------------------------// +std::ostream& operator<<(std::ostream& output, const InventoryItem& item) +{ + return output << item.getText() << " [" << item.d_weight << "]"; +} diff --git a/samples/ModelView/InventoryModel.h b/samples/ModelView/InventoryModel.h new file mode 100644 index 000000000..da6bb5ccf --- /dev/null +++ b/samples/ModelView/InventoryModel.h @@ -0,0 +1,80 @@ +/*********************************************************************** + created: Tue May 27 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _Sample_Model_View_Model_h_ +#define _Sample_Model_View_Model_h_ + +#include "CEGUI/views/GenericItemModel.h" +#include "CEGUI/String.h" +#include + +/* + This is a sample Model in order to show how different views render it. + So, we have multiple nested levels and columns (properties) for some of them, + in the following way. + + Inventory Item (backpack) weight + Inventory Item (can) ... + Inventory Item (beans) + Inventory Item (matryoshka doll) + Inventory Item (matryoshka doll) + Inventory Item (matryoshka doll) + Inventory Item (matryoshka doll) + ... + ... + ... +*/ + +class InventoryItem : public CEGUI::GenericItem +{ +public: + InventoryItem(CEGUI::String name); + float d_weight; + + bool operator==(const InventoryItem& other); + + static InventoryItem* make(const CEGUI::String& name, float weight, + GenericItem* parent = 0); + friend std::ostream& operator<< (std::ostream& output, const InventoryItem& item); +}; + +class InventoryModel : public CEGUI::GenericItemModel +{ +public: + InventoryModel(); + + // simulate loading the model + void load(); + + void addRandomItemWithChildren(const CEGUI::ModelIndex& parent, size_t position, + size_t child_count = 1); + void updateItemName(const CEGUI::ModelIndex& index, const CEGUI::String& newName); + +private: + int d_randomItemsCount; +}; + +#endif diff --git a/samples/ModelView/ModelView.cpp b/samples/ModelView/ModelView.cpp new file mode 100644 index 000000000..3887a96af --- /dev/null +++ b/samples/ModelView/ModelView.cpp @@ -0,0 +1,266 @@ +/*********************************************************************** + created: Sun May 25 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "ModelView.h" +#include "CEGUI/CEGUI.h" + +#include +#include + +using namespace CEGUI; + +ModelViewSample::ModelViewSample() +{ + d_name = "ModelViewSample"; + d_credits = "Timotei Dolean"; + d_summary = "A demo that shows the usage of the new Model-View widgets."; + d_description = "The demo uses the WindowManager to create from code a window with a listview, treeview and GridView."; +} + +/** This sample uses most of the code from the 'HelloWorld' sample. + Thus, most of the clarifying comments have been removed for brevity. **/ + +/************************************************************************* + Sample specific initialisation goes here. +*************************************************************************/ +bool ModelViewSample::initialise(GUIContext* gui_context) +{ + d_usedFiles = String(__FILE__); + + SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); + SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); + + gui_context->getCursor().setDefaultImage("TaharezLook/MouseArrow"); + + WindowManager& win_mgr = WindowManager::getSingleton(); + d_root = win_mgr.loadLayoutFromFile("ModelViewSample.layout"); + + ImageManager::getSingleton().loadImageset("DriveIcons.imageset"); + + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + gui_context->setDefaultFont(&defaultFont); + gui_context->setRootWindow(d_root); + gui_context->setDefaultTooltipType("TaharezLook/Tooltip"); + + d_inventoryModel.load(); + d_newItemsCount = 0; + + d_listView = static_cast(win_mgr.createWindow("TaharezLook/ListView", "listView")); + d_listView->setModel(&d_inventoryModel); + d_listView->setItemTooltipsEnabled(true); + d_listView->setSelectionColourRect(ColourRect(Colour(1.0f, 0, 0, 1))); + d_root->getChild("ListViewHolder")->addChild(d_listView); + + d_treeView = static_cast(win_mgr.createWindow("TaharezLook/TreeView", "treeView")); + d_treeView->setModel(&d_inventoryModel); + d_treeView->setItemTooltipsEnabled(true); + d_root->getChild("TreeViewHolder")->addChild(d_treeView); + + ListWidget* list_widget = static_cast(win_mgr.createWindow("TaharezLook/ListWidget", "listWidget")); + d_root->getChild("ListWidgetHolder")->addChild(list_widget); + initListWidgetItems(list_widget); + + d_root->getChild("btnAddRandomItem")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleAddRandomItem, this)); + + d_root->getChild("btnAddRandomItemInList")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleAddItemInList, this)); + + d_root->getChild("btnAddRandomItemInTree")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleAddItemInTree, this)); + + d_root->getChild("btnRemoveSelectedListItem")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleRemoveSelectedListItems, this)); + + d_root->getChild("btnRemoveSelectedTreeItem")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleRemoveSelectedTreeItems, this)); + + d_root->getChild("btnClearAllItems")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleClearItems, this)); + + d_root->getChild("btnUpdateListItemName")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleUpdateListItemName, this)); + + d_root->getChild("btnUpdateTreeItemName")->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::handleUpdateTreeItemName, this)); + + d_root->getChild("chkMultiSelectEnabled")->subscribeEvent( + ToggleButton::EventSelectStateChanged, + Event::Subscriber(&ModelViewSample::toggleMultiSelect, this)); + + d_root->getChild("btnSwitchSortingMode")->subscribeEvent( + PushButton::EventClicked, + Event::Subscriber(&ModelViewSample::toggleSorting, this)); + + d_txtNewItemName = d_root->getChild("txtNewItemName"); + + return true; + +} + +/************************************************************************* + Cleans up resources allocated in the initialiseSample call. +*************************************************************************/ +void ModelViewSample::deinitialise() +{ +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleClearItems(const EventArgs& e) +{ + d_inventoryModel.clear(); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleRemoveSelectedListItems(const EventArgs& e) +{ + removeSelectedItemsFromView(d_listView); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleRemoveSelectedTreeItems(const EventArgs& e) +{ + removeSelectedItemsFromView(d_treeView); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleAddRandomItem(const EventArgs& e) +{ + d_inventoryModel.addRandomItemWithChildren(d_inventoryModel.getRootIndex(), 0); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleAddItemInList(const EventArgs& e) +{ + const std::vector& selections = d_listView->getIndexSelectionStates(); + if (selections.empty()) + return false; + + const ModelIndexSelectionState& selection = (*selections.begin()); + + d_inventoryModel.addRandomItemWithChildren(selection.d_parentIndex, selection.d_childId + 1); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleAddItemInTree(const EventArgs& e) +{ + const std::vector& selections = d_treeView->getIndexSelectionStates(); + if (selections.empty()) + return false; + + const ModelIndexSelectionState& selection = (*selections.begin()); + + d_inventoryModel.addRandomItemWithChildren(selection.d_selectedIndex, 0); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleUpdateListItemName(const EventArgs& e) +{ + updateSelectedIndexText(d_listView, d_txtNewItemName->getText()); + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::handleUpdateTreeItemName(const EventArgs& e) +{ + updateSelectedIndexText(d_treeView, d_txtNewItemName->getText()); + return true; +} + +//----------------------------------------------------------------------------// +void ModelViewSample::removeSelectedItemsFromView(ItemView* view) +{ + while(!view->getIndexSelectionStates().empty()) + { + d_inventoryModel.removeItem(view->getIndexSelectionStates().back().d_selectedIndex); + } +} + +//----------------------------------------------------------------------------// +void ModelViewSample::updateSelectedIndexText(ItemView* view, const String& text) +{ + const std::vector& selections = view->getIndexSelectionStates(); + if (selections.empty()) + return; + + const ModelIndexSelectionState& selection = (*selections.begin()); + + d_inventoryModel.updateItemName(selection.d_selectedIndex, text); +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::toggleMultiSelect(const EventArgs& e) +{ + bool enabled = d_listView->isMultiSelectEnabled(); + + d_listView->setMultiSelectEnabled(!enabled); + d_treeView->setMultiSelectEnabled(!enabled); + + return true; +} + +//----------------------------------------------------------------------------// +bool ModelViewSample::toggleSorting(const EventArgs& e) +{ + Window* switch_button = d_root->getChild("btnSwitchSortingMode"); + ViewSortMode sort_mode = d_listView->getSortMode(); + + ViewSortMode next_sort_mode = static_cast((sort_mode + 1) % 3); + + d_listView->setSortMode(next_sort_mode); + d_treeView->setSortMode(next_sort_mode); + + switch_button->setText( + "Current sort mode: " + PropertyHelper::toString(next_sort_mode)); + + return true; +} + +//----------------------------------------------------------------------------// +void ModelViewSample::initListWidgetItems(ListWidget* list_widget) +{ + ImageManager::ImageIterator itor = ImageManager::getSingleton().getIterator(); + while (!itor.isAtEnd()) + { + list_widget->addItem(new StandardItem(itor.getCurrentKey(), itor.getCurrentKey())); + ++itor; + } +} + +/************************************************************************* + Define the module function that returns an instance of the sample +*************************************************************************/ +extern "C" SAMPLE_EXPORT Sample& getSampleInstance() +{ + static ModelViewSample sample; + return sample; +} diff --git a/samples/ModelView/ModelView.h b/samples/ModelView/ModelView.h new file mode 100644 index 000000000..203541826 --- /dev/null +++ b/samples/ModelView/ModelView.h @@ -0,0 +1,69 @@ +/*********************************************************************** + created: Sun May 25 2014 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _Sample_Model_View_h_ +#define _Sample_Model_View_h_ + +#include "SampleBase.h" +#include "InventoryModel.h" +#include "CEGUI/views/ListView.h" +#include "CEGUI/views/TreeView.h" +#include "CEGUI/widgets/ListWidget.h" + +class ModelViewSample : public Sample +{ +public: + ModelViewSample(); + + virtual bool initialise(CEGUI::GUIContext* gui_context); + virtual void deinitialise(); + +private: + + bool handleAddRandomItem(const CEGUI::EventArgs& e); + bool handleAddItemInList(const CEGUI::EventArgs& e); + bool handleAddItemInTree(const CEGUI::EventArgs& e); + bool handleRemoveSelectedListItems(const CEGUI::EventArgs& e); + bool handleRemoveSelectedTreeItems(const CEGUI::EventArgs& e); + bool handleClearItems(const CEGUI::EventArgs& e); + bool handleUpdateListItemName(const CEGUI::EventArgs& e); + bool handleUpdateTreeItemName(const CEGUI::EventArgs& e); + bool toggleMultiSelect(const CEGUI::EventArgs& e); + bool toggleSorting(const CEGUI::EventArgs& e); + + void updateSelectedIndexText(CEGUI::ItemView* view, const CEGUI::String& text); + void removeSelectedItemsFromView(CEGUI::ItemView* view); + void initListWidgetItems(CEGUI::ListWidget* list_widget); + CEGUI::Window* d_root; + InventoryModel d_inventoryModel; + + CEGUI::ListView* d_listView; + CEGUI::TreeView* d_treeView; + int d_newItemsCount; + CEGUI::Window* d_txtNewItemName; +}; + +#endif diff --git a/samples/README.md b/samples/README.md new file mode 100644 index 000000000..7936b5698 --- /dev/null +++ b/samples/README.md @@ -0,0 +1,28 @@ +This ReadMe gives a short introduction to the structure of the samples folder and explains how to create new samples. + +The structure of the samples folder is very simple: +- a "common" folder containing all files that are used by more than one sample +- a "browser" folder containing all files that are used by the SamplesBrowser. You should not use ANY of the sources as base code for creating own apps with CEGUI. Look into the "tests/app" folder instead. +- and a lot of other folders containing a sample corresponding to the name +- a CMakeLists.txt.template, a SampleTemplate.h, and a SampleTemplate.cpp - this files might be used as base files for your own sample + +If you want to create a new sample you simply have to add a new folder and rename it to what you want. +After that you have to create a source and a header file within that folder with exact the same name and you have to create a CMakeLists.txt file. +It is strongly recommended to use the prototype files that are in this folder! + +Due to the last major changes to the samples browser you have to follow some naming conventions: +- name your folder to what you want but choose a short, concise, and precise name regarding to what your sample wants to demonstrate. Every first letter of a word has to be capitalised! +- your core source and header files have to have the same name with the same capitalisation +- your sample's class name has to have the same name with the same capitalisation too +- append "Sample" to your class name + +If you followed these rules your folder structure should look like this (if you decided to name your sample "Widgets"): +``` +/Widgets + |- CMakeLists.txt + |- Widgets.cpp + |- Widgets.h +``` +And the name of your class would have to be "WidgetsSample". + +Right now you can start to implement your sample. Put all additional imagesets, layouts, etc. into the corresponding subfolder of the "datafiles" folder. \ No newline at end of file diff --git a/samples/ReadMe.txt b/samples/ReadMe.txt deleted file mode 100644 index df983a0ac..000000000 --- a/samples/ReadMe.txt +++ /dev/null @@ -1,6 +0,0 @@ -This ReadMe lists the items in the samples directory. - -common - directory containing interface files used by both the samples framework and the samples -GLESTest - A specific OpenGL ES sample by CrazyEddie that is currently not part of the samples framework - -The other folders are folders for each demo. For further information read the xml file contained in each demo's folder, or start the samples browser. diff --git a/samples/RenderEffects/CMakeLists.txt b/samples/RenderEffects/CMakeLists.txt index 8cf2e8a06..694aca6d7 100644 --- a/samples/RenderEffects/CMakeLists.txt +++ b/samples/RenderEffects/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_EFFECTS "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_EFFECTS) - cegui_add_sample(CEGUISample_Effects) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/RenderEffects/EffectsDemo.cpp b/samples/RenderEffects/RenderEffects.cpp similarity index 71% rename from samples/RenderEffects/EffectsDemo.cpp rename to samples/RenderEffects/RenderEffects.cpp index 294b824fd..ef57653cd 100644 --- a/samples/RenderEffects/EffectsDemo.cpp +++ b/samples/RenderEffects/RenderEffects.cpp @@ -24,12 +24,12 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "EffectsDemo.h" +#include "RenderEffects.h" #include "CEGUI/CEGUI.h" #include "CEGUI/RenderingWindow.h" -#include +#include //----------------------------------------------------------------------------// WobblyWindowEffect::WobblyWindowEffect(CEGUI::Window* window) : @@ -71,11 +71,11 @@ void WobblyWindowEffect::syncPivots(CEGUI::RenderingWindow& window) const float factorMinY = static_cast(ds_yPivotCount - y) / (ds_yPivotCount - 1); const float factorMaxY = static_cast(y) / (ds_yPivotCount - 1); - d_pivots[x][y] = CEGUI::Vector2f( + d_pivots[x][y] = glm::vec2( factorMinX * pixelRect.d_min.d_x + factorMaxX * pixelRect.d_max.d_x, factorMinY * pixelRect.d_min.d_y + factorMaxY * pixelRect.d_max.d_y); - d_pivotVelocities[x][y] = CEGUI::Vector2f( + d_pivotVelocities[x][y] = glm::vec2( 0.0f, 0.0f); } @@ -89,17 +89,17 @@ bool WobblyWindowEffect::realiseGeometry(CEGUI::RenderingWindow& window, using namespace CEGUI; Texture& tex = window.getTextureTarget().getTexture(); - static const CEGUI::Colour c(1, 1, 1, 1); + static const glm::vec4 colour(1.0f, 1.0f, 1.0f, 1.0f); // qw is the width of one subdivision "box", qh is the height of it const float qw = window.getSize().d_width / (ds_xPivotCount - 1); const float qh = window.getSize().d_height / (ds_yPivotCount - 1); - const float tcx = qw * tex.getTexelScaling().d_x; + const float tcx = qw * tex.getTexelScaling().x; const float tcy = (window.getTextureTarget().isRenderingInverted() ? -qh : qh) * - tex.getTexelScaling().d_y; + tex.getTexelScaling().y; - const Vector3f windowPosition = Vector3f(window.getPosition(), 0.0f); + const glm::vec3 windowPosition = glm::vec3(window.getPosition(), 0); for (size_t y = 0; y < ds_yPivotCount - 1; ++y) { @@ -112,40 +112,40 @@ bool WobblyWindowEffect::realiseGeometry(CEGUI::RenderingWindow& window, // first triangle // vertex 0 - top left - d_vertices[idx + 0].position = Vector3f(d_pivots[x][y], 0.0f) - windowPosition; - d_vertices[idx + 0].colour_val = c; - d_vertices[idx + 0].tex_coords = Vector2f(x * tcx, y * tcy); + d_vertices[idx + 0].d_position = glm::vec3(d_pivots[x][y], 0) - windowPosition; + d_vertices[idx + 0].d_colour = colour; + d_vertices[idx + 0].d_texCoords = glm::vec2(x * tcx, y * tcy); // vertex 1 - bottom left - d_vertices[idx + 1].position = Vector3f(d_pivots[x][y + 1], 0.0f) - windowPosition; - d_vertices[idx + 1].colour_val = c; - d_vertices[idx + 1].tex_coords = Vector2f(x * tcx, (y + 1) * tcy); + d_vertices[idx + 1].d_position = glm::vec3(d_pivots[x][y + 1], 0) - windowPosition; + d_vertices[idx + 1].d_colour = colour; + d_vertices[idx + 1].d_texCoords = glm::vec2(x * tcx, (y + 1) * tcy); // vertex 2 - bottom right - d_vertices[idx + 2].position = Vector3f(d_pivots[x + 1][y + 1], 0.0f) - windowPosition; - d_vertices[idx + 2].colour_val = c; - d_vertices[idx + 2].tex_coords = Vector2f((x + 1) * tcx, (y + 1) * tcy); + d_vertices[idx + 2].d_position = glm::vec3(d_pivots[x + 1][y + 1], 0) - windowPosition; + d_vertices[idx + 2].d_colour = colour; + d_vertices[idx + 2].d_texCoords = glm::vec2((x + 1) * tcx, (y + 1) * tcy); // second triangle // vertex 3 - bottom right - d_vertices[idx + 3].position = Vector3f(d_pivots[x + 1][y + 1], 0.0f) - windowPosition; - d_vertices[idx + 3].colour_val = c; - d_vertices[idx + 3].tex_coords = Vector2f((x + 1) * tcx, (y + 1) * tcy); + d_vertices[idx + 3].d_position = glm::vec3(d_pivots[x + 1][y + 1], 0) - windowPosition; + d_vertices[idx + 3].d_colour = colour; + d_vertices[idx + 3].d_texCoords = glm::vec2((x + 1) * tcx, (y + 1) * tcy); // vertex 4 - top right - d_vertices[idx + 4].position = Vector3f(d_pivots[x + 1][y], 0.0f) - windowPosition; - d_vertices[idx + 4].colour_val = c; - d_vertices[idx + 4].tex_coords = Vector2f((x + 1) * tcx, y * tcy); + d_vertices[idx + 4].d_position = glm::vec3(d_pivots[x + 1][y], 0) - windowPosition; + d_vertices[idx + 4].d_colour = colour; + d_vertices[idx + 4].d_texCoords = glm::vec2((x + 1) * tcx, y * tcy); // vertex 5 - top left - d_vertices[idx + 5].position = Vector3f(d_pivots[x][y], 0.0f) - windowPosition; - d_vertices[idx + 5].colour_val = c; - d_vertices[idx + 5].tex_coords = Vector2f(x * tcx, y * tcy); + d_vertices[idx + 5].d_position = glm::vec3(d_pivots[x][y], 0) - windowPosition; + d_vertices[idx + 5].d_colour = colour; + d_vertices[idx + 5].d_texCoords = glm::vec2(x * tcx, y * tcy); } } - geometry.setActiveTexture(&tex); + geometry.setTexture("texture0", &tex); geometry.appendGeometry(d_vertices, ds_vertexCount); // false, because we do not want the default geometry added! @@ -167,7 +167,7 @@ bool WobblyWindowEffect::update(const float elapsed, CEGUI::RenderingWindow& win const CEGUI::Rectf pixelRect = CEGUI::Rectf(window.getPosition(), window.getSize()); - const CEGUI::MouseCursor& cursor = d_window->getGUIContext().getMouseCursor(); + const CEGUI::Cursor& cursor = d_window->getGUIContext().getCursor(); bool changed = false; @@ -180,21 +180,21 @@ bool WobblyWindowEffect::update(const float elapsed, CEGUI::RenderingWindow& win const float factorMinY = static_cast(ds_yPivotCount - 1 - y) / (ds_yPivotCount - 1); const float factorMaxY = static_cast(y) / (ds_yPivotCount - 1); - const Vector2f desiredPos = Vector2f( + const glm::vec2 desiredPos = glm::vec2( factorMinX * pixelRect.d_min.d_x + factorMaxX * pixelRect.d_max.d_x, factorMinY * pixelRect.d_min.d_y + factorMaxY * pixelRect.d_max.d_y); - const Vector2f delta = desiredPos - d_pivots[x][y]; + const glm::vec2 delta = desiredPos - d_pivots[x][y]; float speed = 300.0f; - const Vector2f cursorDelta = d_window->getTitlebar()->isDragged() ? window.getPosition() + d_window->getTitlebar()->getDragPoint() - d_pivots[x][y] : Vector2f(0.0f, 0.0f); - const float cursorDeltaLength = sqrtf(cursorDelta.d_x * cursorDelta.d_x + cursorDelta.d_y * cursorDelta.d_y); + const glm::vec2 cursorDelta = d_window->getTitlebar()->isDragged() ? window.getPosition() + d_window->getTitlebar()->getDragPoint() - d_pivots[x][y] : glm::vec2(0.0f, 0.0f); + const float cursorDeltaLength = sqrtf(cursorDelta.x * cursorDelta.x + cursorDelta.y * cursorDelta.y); speed /= cursorDeltaLength > 64 ? sqrtf(cursorDeltaLength) * 0.125f : 1; d_pivotVelocities[x][y] *= pow(0.00001f, elapsed); d_pivotVelocities[x][y] += delta * (speed * elapsed); - const Vector2f old_pivot(d_pivots[x][y]); + const glm::vec2 old_pivot(d_pivots[x][y]); d_pivots[x][y] += d_pivotVelocities[x][y] * elapsed; changed |= (old_pivot != d_pivots[x][y]); } @@ -252,14 +252,14 @@ bool OldWobblyWindowEffect::realiseGeometry(CEGUI::RenderingWindow& window, using namespace CEGUI; Texture& tex = window.getTextureTarget().getTexture(); - static const CEGUI::Colour c(1, 1, 1, 1); + static const glm::vec4 colour(1.0f, 1.0f, 1.0f, 1.0f); const float qw = window.getSize().d_width / tess_x; const float qh = window.getSize().d_height / tess_y; - const float tcx = qw * tex.getTexelScaling().d_x; + const float tcx = qw * tex.getTexelScaling().x; const float tcy = (window.getTextureTarget().isRenderingInverted() ? -qh : qh) * - tex.getTexelScaling().d_y; + tex.getTexelScaling().y; for (int j = 0; j < tess_y; ++j) { @@ -278,38 +278,38 @@ bool OldWobblyWindowEffect::realiseGeometry(CEGUI::RenderingWindow& window, rig_adj = ((rig_adj*rig_adj) / 3) * (dragY < 0 ? -1 : 1); // vertex 0 - vb[idx + 0].position = Vector3f(i * qw - top_adj, j * qh - lef_adj, 0.0f); - vb[idx + 0].colour_val = c; - vb[idx + 0].tex_coords = Vector2f(i * tcx, j*tcy); + vb[idx + 0].d_position = glm::vec3(i * qw - top_adj, j * qh - lef_adj, 0.0f); + vb[idx + 0].d_colour = colour; + vb[idx + 0].d_texCoords = glm::vec2(i * tcx, j*tcy); // vertex 1 - vb[idx + 1].position = Vector3f(i * qw - bot_adj, j * qh + qh - lef_adj, 0.0f); - vb[idx + 1].colour_val = c; - vb[idx + 1].tex_coords = Vector2f(i*tcx, j*tcy+tcy); + vb[idx + 1].d_position = glm::vec3(i * qw - bot_adj, j * qh + qh - lef_adj, 0.0f); + vb[idx + 1].d_colour = colour; + vb[idx + 1].d_texCoords = glm::vec2(i*tcx, j*tcy+tcy); // vertex 2 - vb[idx + 2].position = Vector3f(i * qw + qw - bot_adj, j * qh + qh - rig_adj, 0.0f); - vb[idx + 2].colour_val = c; - vb[idx + 2].tex_coords = Vector2f(i*tcx+tcx, j*tcy+tcy); + vb[idx + 2].d_position = glm::vec3(i * qw + qw - bot_adj, j * qh + qh - rig_adj, 0.0f); + vb[idx + 2].d_colour = colour; + vb[idx + 2].d_texCoords = glm::vec2(i*tcx+tcx, j*tcy+tcy); // vertex 3 - vb[idx + 3].position = Vector3f(i * qw + qw - bot_adj, j * qh + qh - rig_adj, 0.0f); - vb[idx + 3].colour_val = c; - vb[idx + 3].tex_coords = Vector2f(i*tcx+tcx, j*tcy+tcy); + vb[idx + 3].d_position = glm::vec3(i * qw + qw - bot_adj, j * qh + qh - rig_adj, 0.0f); + vb[idx + 3].d_colour = colour; + vb[idx + 3].d_texCoords = glm::vec2(i*tcx+tcx, j*tcy+tcy); // vertex 4 - vb[idx + 4].position = Vector3f(i * qw + qw - top_adj, j * qh - rig_adj, 0.0f); - vb[idx + 4].colour_val = c; - vb[idx + 4].tex_coords = Vector2f(i*tcx+tcx, j*tcy); + vb[idx + 4].d_position = glm::vec3(i * qw + qw - top_adj, j * qh - rig_adj, 0.0f); + vb[idx + 4].d_colour = colour; + vb[idx + 4].d_texCoords = glm::vec2(i*tcx+tcx, j*tcy); // vertex 5 - vb[idx + 5].position = Vector3f(i * qw - top_adj, j * qh - lef_adj, 0.0f); - vb[idx + 5].colour_val = c; - vb[idx + 5].tex_coords = Vector2f(i * tcx, j*tcy); + vb[idx + 5].d_position = glm::vec3(i * qw - top_adj, j * qh - lef_adj, 0.0f); + vb[idx + 5].d_colour = colour; + vb[idx + 5].d_texCoords = glm::vec2(i * tcx, j*tcy); } } - geometry.setActiveTexture(&tex); + geometry.setTexture("texture0", &tex); geometry.appendGeometry(vb, buffsize); // false, because we do not want the default geometry added! @@ -320,26 +320,26 @@ bool OldWobblyWindowEffect::realiseGeometry(CEGUI::RenderingWindow& window, bool OldWobblyWindowEffect::update(const float elapsed, CEGUI::RenderingWindow& window) { using namespace CEGUI; - + // initialise ourself upon the first update call. if (!initialised) { initialised=true; - lastX = window.getPosition().d_x; - lastY = window.getPosition().d_y; + lastX = window.getPosition().x; + lastY = window.getPosition().y; return true; } - const Vector2f pos(window.getPosition()); + const glm::vec2 pos(window.getPosition()); // // Set up for X axis animation. // - if (pos.d_x != lastX) + if (pos.x != lastX) { - dragX += (pos.d_x - lastX) * 0.2f; + dragX += (pos.x - lastX) * 0.2f; elasX = 0.05f; - lastX = pos.d_x; + lastX = pos.x; if (dragX > 25) dragX = 25; @@ -350,11 +350,11 @@ bool OldWobblyWindowEffect::update(const float elapsed, CEGUI::RenderingWindow& // // Set up for y axis animation // - if (pos.d_y != lastY) + if (pos.y != lastY) { - dragY += (pos.d_y - lastY) * 0.2f; + dragY += (pos.y - lastY) * 0.2f; elasY = 0.05f; - lastY = pos.d_y; + lastY = pos.y; if (dragY > 25) dragY = 25; @@ -437,53 +437,53 @@ bool ElasticWindowEffect::realiseGeometry(CEGUI::RenderingWindow& window, using namespace CEGUI; Texture& tex = window.getTextureTarget().getTexture(); - static const CEGUI::Colour c(1, 1, 1, 1); + static const glm::vec4 colour(1.0f, 1.0f, 1.0f, 1.0f); float uvTop = window.getTextureTarget().isRenderingInverted() ? 1.0f : 0.0f; float uvBot = window.getTextureTarget().isRenderingInverted() ? 0.0f : 1.0f; - const Vector3f windowPosition = Vector3f(window.getPosition(), 0.0f); - const Vector2f& currentTopLeft = d_currentPosition ; - const Vector2f currentBottomRight = d_currentPosition + - Vector2f(window.getSize().d_width, window.getSize().d_height); + const glm::vec3 windowPosition = glm::vec3(window.getPosition(), 0); + const glm::vec2& currentTopLeft = d_currentPosition ; + const glm::vec2 currentBottomRight = d_currentPosition + + glm::vec2(window.getSize().d_width, window.getSize().d_height); { // first triangle // vertex 0 - top left - d_vertices[0].position = Vector3f(currentTopLeft, 0.0f) - windowPosition; - d_vertices[0].colour_val = c; - d_vertices[0].tex_coords = Vector2f(0.0f, uvTop); + d_vertices[0].d_position = glm::vec3(currentTopLeft, 0) - windowPosition; + d_vertices[0].d_colour = colour; + d_vertices[0].d_texCoords = glm::vec2(0.0f, uvTop); // vertex 1 - bottom left - d_vertices[1].position = Vector3f(currentTopLeft.d_x, currentBottomRight.d_y, 0.0f) - windowPosition; - d_vertices[1].colour_val = c; - d_vertices[1].tex_coords = Vector2f(0.0f, uvBot); + d_vertices[1].d_position = glm::vec3(currentTopLeft.x, currentBottomRight.y, 0) - windowPosition; + d_vertices[1].d_colour = colour; + d_vertices[1].d_texCoords = glm::vec2(0.0f, uvBot); // vertex 2 - bottom right - d_vertices[2].position = Vector3f(currentBottomRight, 0.0f) - windowPosition; - d_vertices[2].colour_val = c; - d_vertices[2].tex_coords = Vector2f(1.0f, uvBot); + d_vertices[2].d_position = glm::vec3(currentBottomRight, 0) - windowPosition; + d_vertices[2].d_colour = colour; + d_vertices[2].d_texCoords = glm::vec2(1.0f, uvBot); // second triangle // vertex 3 - bottom right - d_vertices[3].position = Vector3f(currentBottomRight, 0.0f) - windowPosition; - d_vertices[3].colour_val = c; - d_vertices[3].tex_coords = Vector2f(1.0f, uvBot); + d_vertices[3].d_position = glm::vec3(currentBottomRight, 0) - windowPosition; + d_vertices[3].d_colour = colour; + d_vertices[3].d_texCoords = glm::vec2(1.0f, uvBot); // vertex 4 - top right - d_vertices[4].position = Vector3f(currentBottomRight.d_x, currentTopLeft.d_y, 0.0f) - windowPosition; - d_vertices[4].colour_val = c; - d_vertices[4].tex_coords = Vector2f(1.0f, uvTop); + d_vertices[4].d_position = glm::vec3(currentBottomRight.x, currentTopLeft.y, 0) - windowPosition; + d_vertices[4].d_colour = colour; + d_vertices[4].d_texCoords = glm::vec2(1.0f, uvTop); // vertex 5 - top left - d_vertices[5].position = Vector3f(currentTopLeft, 0.0f) - windowPosition; - d_vertices[5].colour_val = c; - d_vertices[5].tex_coords = Vector2f(0.0f, uvTop); + d_vertices[5].d_position = glm::vec3(currentTopLeft, 0) - windowPosition; + d_vertices[5].d_colour = colour; + d_vertices[5].d_texCoords = glm::vec2(0.0f, uvTop); } - geometry.setActiveTexture(&tex); + geometry.setTexture("texture0", &tex); geometry.appendGeometry(d_vertices, ds_vertexCount); // false, because we do not want the default geometry added! @@ -499,19 +499,19 @@ bool ElasticWindowEffect::update(const float elapsed, CEGUI::RenderingWindow& wi if (!d_initialised) { d_currentPosition = window.getPosition(); - d_currentVelocity = Vector2f(0, 0); + d_currentVelocity = glm::vec2(0, 0); d_initialised = true; return true; } - const Vector2f delta = window.getPosition() - d_currentPosition; + const glm::vec2 delta = window.getPosition() - d_currentPosition; const float speed = 300.0f; d_currentVelocity *= pow(0.00001f, elapsed); d_currentVelocity += delta * (speed * elapsed); - const Vector2f old_position(d_currentPosition); + const glm::vec2 old_position(d_currentPosition); d_currentPosition += d_currentVelocity * elapsed; const bool changed = d_currentPosition != old_position; @@ -525,17 +525,31 @@ bool ElasticWindowEffect::update(const float elapsed, CEGUI::RenderingWindow& wi //----------------------------------------------------------------------------// -// The following are for the main EffectsDemo class. +// The following are for the main RenderEffectsSample class. //----------------------------------------------------------------------------// -const CEGUI::String EffectsDemo::s_effectNameElastic = "ElasticWindow"; -const CEGUI::String EffectsDemo::s_effectNameWobblyNew = "WobblyWindow"; -const CEGUI::String EffectsDemo::s_effectNameWobblyOld = "OldWobblyWindow"; +const CEGUI::String RenderEffectsSample::s_effectNameElastic = "ElasticWindow"; +const CEGUI::String RenderEffectsSample::s_effectNameWobblyNew = "WobblyWindow"; +const CEGUI::String RenderEffectsSample::s_effectNameWobblyOld = "OldWobblyWindow"; + +RenderEffectsSample::RenderEffectsSample() +{ + Sample::d_name = "RenderEffectsSample"; + Sample::d_credits = "Lukas \"Ident\" Meindl, Martin \"Kulik\" Preisler"; + Sample::d_description = + "Displays render effects that can be applied to CEGUI windows. " + "When moving the window the effect will render the windows " + "in a way specified by the effect."; + Sample::d_summary = + "Custom render effects (CEGUI::RenderEffect) can be created for the windows. " + "The demo's c++ files present 3 examples for such effects. The effects can be " + "mapped using schemes or can be directly applied using functions."; +} /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ -bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) +bool RenderEffectsSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -551,7 +565,7 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) // We create a type "Vanilla/WobblyFrameWindow". Note that it would be // more usual for this mapping to be specified in the scheme xml file, // though here we are doing in manually to save from needing either multiple - // versions of the schemes or from having demo specific definitions in + // versions of the schemes or from having Sample specific definitions in // the schemes. WindowFactoryManager::getSingleton().addFalagardWindowMapping( "Vanilla/WobblyFrameWindow", // type to create @@ -560,7 +574,7 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) "Core/FrameWindow", // WindowRenderer to use. s_effectNameWobblyNew); // effect to use. - // Since we want to be able to load the EffectsDemo.layout in the editor + // Since we want to be able to load the RenderEffectsSample.layout in the editor // tools (where the above mapping is not available), we now alias the // new window type onto the original TaharezLook/FrameWindow. This has // the effect that - after the alias is added - any time a window of @@ -577,7 +591,7 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) // load scheme and set up defaults SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme"); - guiContext->getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); + guiContext->getCursor().setDefaultImage("TaharezLook/MouseArrow"); // load font and setup default if not loaded via scheme Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); @@ -586,10 +600,10 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) // load an image to use as a background if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); if( !ImageManager::getSingleton().isDefined("AliasingTestImage") ) - ImageManager::getSingleton().addFromImageFile("AliasingTestImage", "Aliasing.jpg"); + ImageManager::getSingleton().addBitmapImageFromFile("AliasingTestImage", "Aliasing.jpg"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow("TaharezLook/StaticImage", "background_wnd"); @@ -604,9 +618,9 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) // set the background window as the root window for our GUIContext guiContext->setRootWindow(background); - // load the windows for the EffectsDemo from the layout file. - Window* sheet = winMgr.loadLayoutFromFile("EffectsDemo.layout"); - + // load the windows for the RenderEffectsSample from the layout file. + Window* sheet = winMgr.loadLayoutFromFile("EffectsSample.layout"); + // Get the combobox created from within the layout CEGUI::Combobox* effectsCombobox = static_cast(sheet->getChild("EffectsFrameWindow/EffectsCombobox")); @@ -617,7 +631,7 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) // Initialise the items and subscribe the event for the combobox initialiseEffectsCombobox(effectsCombobox); - + // We can switch the automatic effects mapping off now WindowFactoryManager::getSingleton().removeWindowTypeAlias( "Vanilla/FrameWindow", // alias name - can shadow existing types @@ -650,7 +664,7 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) aliasingFrameWnd->setSizingEnabled(true); aliasingFrameWnd->setCloseButtonEnabled(false); aliasingFrameWnd->setTitleBarEnabled(true); - aliasingFrameWnd->setText("Elastic Window - Aliasing Testimage"); + aliasingFrameWnd->setText("Elastic Window Effect"); // Image window setup aliasingWnd->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); @@ -665,7 +679,7 @@ bool EffectsDemo::initialise(CEGUI::GUIContext* guiContext) /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ -void EffectsDemo::deinitialise() +void RenderEffectsSample::deinitialise() { // nothing to do here! } @@ -673,13 +687,12 @@ void EffectsDemo::deinitialise() /************************************************************************* Initialises the effects ListItems for the Combobox. *************************************************************************/ -void EffectsDemo::initialiseEffectsCombobox(CEGUI::Combobox* effectsCombobox) +void RenderEffectsSample::initialiseEffectsCombobox(CEGUI::Combobox* effectsCombobox) { - d_listItemEffectWobblyNew = new MyListItem("Wobbly Window Effect"); - d_listItemEffectElastic = new MyListItem("Elastic Window Effect"); - d_listItemEffectWobblyOld = new MyListItem("Old Wobbly Window Effect"); - d_listItemEffectNone = new MyListItem("None"); - + d_listItemEffectWobblyNew = new CEGUI::StandardItem("Wobbly Window Effect"); + d_listItemEffectElastic = new CEGUI::StandardItem("Elastic Window Effect"); + d_listItemEffectWobblyOld = new CEGUI::StandardItem("Old Wobbly Window Effect"); + d_listItemEffectNone = new CEGUI::StandardItem("None"); effectsCombobox->addItem(d_listItemEffectWobblyNew); effectsCombobox->addItem(d_listItemEffectElastic); @@ -687,31 +700,31 @@ void EffectsDemo::initialiseEffectsCombobox(CEGUI::Combobox* effectsCombobox) effectsCombobox->addItem(d_listItemEffectNone); effectsCombobox->setItemSelectState(d_listItemEffectWobblyNew, true); - effectsCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&EffectsDemo::handleEffectsComboboxSelectionChanged, this)); + effectsCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, CEGUI::Event::Subscriber(&RenderEffectsSample::handleEffectsComboboxSelectionChanged, this)); } /************************************************************************* - Selection EventHandler for the effects Combobox. +Selection EventHandler for the effects Combobox. *************************************************************************/ -bool EffectsDemo::handleEffectsComboboxSelectionChanged(const CEGUI::EventArgs& args) +bool RenderEffectsSample::handleEffectsComboboxSelectionChanged(const CEGUI::EventArgs& args) { const CEGUI::WindowEventArgs& winArgs(static_cast(args)); CEGUI::Combobox* effectsCombobox = static_cast(winArgs.window); - CEGUI::ListboxItem* selectionItem = effectsCombobox->getSelectedItem(); + CEGUI::StandardItem* selectionItem = effectsCombobox->getSelectedItem(); CEGUI::FrameWindow* effectsWindow = static_cast(effectsCombobox->getParent()); CEGUI::RenderingWindow* effectsWindowRenderingWnd = static_cast(effectsWindow->getRenderingSurface()); - if(selectionItem == d_listItemEffectElastic) + if (selectionItem == d_listItemEffectElastic) { effectsWindowRenderingWnd->setRenderEffect(d_renderEffectElastic); } - else if(selectionItem == d_listItemEffectWobblyNew) + else if (selectionItem == d_listItemEffectWobblyNew) { effectsWindowRenderingWnd->setRenderEffect(d_renderEffectWobblyNew); } - else if(selectionItem == d_listItemEffectWobblyOld) + else if (selectionItem == d_listItemEffectWobblyOld) { effectsWindowRenderingWnd->setRenderEffect(d_renderEffectWobblyOld); } @@ -720,11 +733,10 @@ bool EffectsDemo::handleEffectsComboboxSelectionChanged(const CEGUI::EventArgs& effectsWindowRenderingWnd->setRenderEffect(0); } - return true; } -void EffectsDemo::initialiseEffects(CEGUI::Window* effectsWindow) +void RenderEffectsSample::initialiseEffects(CEGUI::Window* effectsWindow) { d_renderEffectElastic = &CEGUI::RenderEffectManager::getSingleton().create( s_effectNameElastic, @@ -738,12 +750,3 @@ void EffectsDemo::initialiseEffects(CEGUI::Window* effectsWindow) s_effectNameWobblyOld, effectsWindow); } - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static EffectsDemo sample; - return sample; -} diff --git a/samples/RenderEffects/EffectsDemo.h b/samples/RenderEffects/RenderEffects.h similarity index 87% rename from samples/RenderEffects/EffectsDemo.h rename to samples/RenderEffects/RenderEffects.h index 41ff5c6b2..35590ab1a 100644 --- a/samples/RenderEffects/EffectsDemo.h +++ b/samples/RenderEffects/RenderEffects.h @@ -24,8 +24,8 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Effects_Demo_ -#define _Effects_Demo_ +#ifndef _Effects_Sample_ +#define _Effects_Sample_ #include "SampleBase.h" #include "CEGUI/CEGUI.h" @@ -50,8 +50,8 @@ class WobblyWindowEffect : public CEGUI::RenderEffect // number of vertical subdivisions static const int ds_yPivotCount = 11; - CEGUI::Vector2f d_pivots[ds_xPivotCount][ds_yPivotCount]; - CEGUI::Vector2f d_pivotVelocities[ds_xPivotCount][ds_yPivotCount]; + glm::vec2 d_pivots[ds_xPivotCount][ds_yPivotCount]; + glm::vec2 d_pivotVelocities[ds_xPivotCount][ds_yPivotCount]; bool d_initialised; @@ -68,7 +68,7 @@ class WobblyWindowEffect : public CEGUI::RenderEffect // as we can see, we have 2x2 quads for 3x3 subdivision (because of reused // neighbouring vertices) static const unsigned int ds_vertexCount = (ds_xPivotCount - 1) * (ds_yPivotCount - 1) * 6; - CEGUI::Vertex d_vertices[ds_vertexCount]; + CEGUI::TexturedColouredVertex d_vertices[ds_vertexCount]; CEGUI::FrameWindow* d_window; }; @@ -99,7 +99,7 @@ class OldWobblyWindowEffect : public CEGUI::RenderEffect float dragX, dragY; float elasX, elasY; - CEGUI::Vertex vb[buffsize]; + CEGUI::TexturedColouredVertex vb[buffsize]; CEGUI::Window* d_window; }; @@ -117,21 +117,23 @@ class ElasticWindowEffect : public CEGUI::RenderEffect bool update(const float elapsed, CEGUI::RenderingWindow& window); protected: - CEGUI::Vector2f d_currentPosition; - CEGUI::Vector2f d_currentVelocity; + glm::vec2 d_currentPosition; + glm::vec2 d_currentVelocity; bool d_initialised; static const unsigned int ds_vertexCount = 6; - CEGUI::Vertex d_vertices[ds_vertexCount]; + CEGUI::TexturedColouredVertex d_vertices[ds_vertexCount]; CEGUI::Window* d_window; }; // Sample class -class EffectsDemo : public Sample +class RenderEffectsSample : public Sample { public: + RenderEffectsSample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); @@ -139,7 +141,7 @@ class EffectsDemo : public Sample virtual void deinitialise(); protected: - // Initialiser for the effects in the combobox + // Initialiser for the effects in the combobox void initialiseEffectsCombobox(CEGUI::Combobox* effectsCombobox); // Handler for the selection changes in the effects combobox @@ -157,11 +159,11 @@ class EffectsDemo : public Sample CEGUI::RenderEffect* d_renderEffectWobblyNew; CEGUI::RenderEffect* d_renderEffectWobblyOld; - // The listbox items of the effects combobox - CEGUI::ListboxItem* d_listItemEffectElastic; - CEGUI::ListboxItem* d_listItemEffectWobblyNew; - CEGUI::ListboxItem* d_listItemEffectWobblyOld; - CEGUI::ListboxItem* d_listItemEffectNone; + // The list items of the effects combobox + CEGUI::StandardItem* d_listItemEffectElastic; + CEGUI::StandardItem* d_listItemEffectWobblyNew; + CEGUI::StandardItem* d_listItemEffectWobblyOld; + CEGUI::StandardItem* d_listItemEffectNone; CEGUI::GUIContext* d_guiContext; }; diff --git a/samples/RenderEffects/SampleMetaData.xml b/samples/RenderEffects/SampleMetaData.xml deleted file mode 100644 index 7f897aa33..000000000 --- a/samples/RenderEffects/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/RestaurantGame/CMakeLists.txt b/samples/RestaurantGame/CMakeLists.txt index 9b9b67a23..694aca6d7 100644 --- a/samples/RestaurantGame/CMakeLists.txt +++ b/samples/RestaurantGame/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_RESTAURANT_GAME "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_RESTAURANT_GAME) - cegui_add_sample(CEGUISample_RestaurantGame) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/RestaurantGame/RestaurantGame.cpp b/samples/RestaurantGame/RestaurantGame.cpp index 656543086..7c9941fd1 100644 --- a/samples/RestaurantGame/RestaurantGame.cpp +++ b/samples/RestaurantGame/RestaurantGame.cpp @@ -3,7 +3,7 @@ created: 11/8/2012 author: Lukas E Meindl *************************************************************************/ /*************************************************************************** -* Copyright (C) 2004 - 2012 Paul D Turner & Thce CEGUI Development Team +* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -37,7 +37,7 @@ using namespace CEGUI; struct GamePlate { - GamePlate(HUDDemo* hudDemo); + GamePlate(RestaurantGameSample* RestaurantGameSample); ~GamePlate(); void update(float timeSinceLastUpdate); @@ -48,10 +48,10 @@ struct GamePlate bool d_isDestroyed; }; -GamePlate::GamePlate(HUDDemo* hudDemo) +GamePlate::GamePlate(RestaurantGameSample* RestaurantGameSample) : d_isDestroyed(false) { - d_window = hudDemo->spawnPlate(); + d_window = RestaurantGameSample->spawnPlate(); int randumNumber = rand() % 2; d_isComingFromRight = (randumNumber == 0 ? false : true); @@ -102,55 +102,77 @@ int GamePlate::getPoints() CEGUI::String objectImage = window->getProperty("Image"); - if(objectImage.compare(HUDDemo::s_imageNameBread) == 0) + if(objectImage.compare(RestaurantGameSample::s_imageNameBread) == 0) return 2; - else if(objectImage.compare(HUDDemo::s_imageNamePoo) == 0) + else if(objectImage.compare(RestaurantGameSample::s_imageNamePoo) == 0) return -6; - else if(objectImage.compare(HUDDemo::s_imageNameSteak) == 0) + else if(objectImage.compare(RestaurantGameSample::s_imageNameSteak) == 0) return -13; - else if(objectImage.compare(HUDDemo::s_imageNamePrizza) == 0) + else if(objectImage.compare(RestaurantGameSample::s_imageNamePrizza) == 0) return 3; - else if(objectImage.compare(HUDDemo::s_imageNameVegPeople) == 0) + else if(objectImage.compare(RestaurantGameSample::s_imageNameVegPeople) == 0) return 1; - else if(objectImage.compare(HUDDemo::s_imageNameVegFruits) == 0) + else if(objectImage.compare(RestaurantGameSample::s_imageNameVegFruits) == 0) return 88; return 0; } -const CEGUI::String HUDDemo::s_imageNamePlate = "HUDDemo/Plate"; -const CEGUI::String HUDDemo::s_imageNameBread = "HUDDemo/Bread"; -const CEGUI::String HUDDemo::s_imageNamePoo = "HUDDemo/Poo"; -const CEGUI::String HUDDemo::s_imageNamePrizza = "HUDDemo/Prizza"; -const CEGUI::String HUDDemo::s_imageNameSteak = "HUDDemo/Steak"; -const CEGUI::String HUDDemo::s_imageNameVegPeople = "HUDDemo/VegetablePeople"; -const CEGUI::String HUDDemo::s_imageNameVegFruits = "HUDDemo/VegetablesAndFruits"; +const CEGUI::String RestaurantGameSample::s_imageNamePlate = "RestaurantGameSample/Plate"; +const CEGUI::String RestaurantGameSample::s_imageNameBread = "RestaurantGameSample/Bread"; +const CEGUI::String RestaurantGameSample::s_imageNamePoo = "RestaurantGameSample/Poo"; +const CEGUI::String RestaurantGameSample::s_imageNamePrizza = "RestaurantGameSample/Prizza"; +const CEGUI::String RestaurantGameSample::s_imageNameSteak = "RestaurantGameSample/Steak"; +const CEGUI::String RestaurantGameSample::s_imageNameVegPeople = "RestaurantGameSample/VegetablePeople"; +const CEGUI::String RestaurantGameSample::s_imageNameVegFruits = "RestaurantGameSample/VegetablesAndFruits"; -bool HUDDemo::initialise(CEGUI::GUIContext* guiContext) +RestaurantGameSample::RestaurantGameSample() : + Sample(99) +{ + Sample::d_name = "RestaurantGameSample"; + Sample::d_credits = "Lukas \"Ident\" Meindl, graphics: Charles \"Syg\" Mattei"; + Sample::d_description = + "The RestaurantGame presents a game that uses a head-up display. This shows that CEGUI has " + "full capabilities for rendering HUD's for first person shooters or other any other types of games. " + "The interface consists of a health bar, lives, switchable weapons and power-ups. " + "The game itself consists of moving dishes that have to be clicked on to receive points. " + "When clicked, the points appear in red or green text as a pop-up text that moves " + "upwards and vanishes after some seconds."; + Sample::d_summary = + "The HUD consists of basic \"Generic/Label\" and \"Generic/Image\" windows to display its elements. " + "For some windows event handlers are registered to react to user interaction. " + "A CEGUI/Progressbar with custom skinning was made for this demo to display the life bar. " + "For the pop-up points a window with animations directly defined in the look n' feel file " + "was made. The animations are triggered by firing events and when the pop-up animation is " + "over the event handler will react to this and subsequently the window will be " + "deleted as defined in the C++ code."; +} + +bool RestaurantGameSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; d_usedFiles = CEGUI::String(__FILE__); d_guiContext = guiContext; - SchemeManager::getSingleton().createFromFile("HUDDemo.scheme"); + SchemeManager::getSingleton().createFromFile("RestaurantGameSample.scheme"); SchemeManager::getSingleton().createFromFile("Generic.scheme"); FontManager::getSingleton().createFromFile("DejaVuSans-14.font"); CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton(); - // Load the HUDDemo Layout - d_rootIngame = winMgr.loadLayoutFromFile("HUDDemoIngame.layout"); - d_rootGameOver = winMgr.loadLayoutFromFile("HUDDemoGameOver.layout"); - d_root = winMgr.createWindow("DefaultWindow", "HUDDemoRoot"); + // Load the RestaurantGameSample Layout + d_rootIngame = winMgr.loadLayoutFromFile("RestaurantGameSampleIngame.layout"); + d_rootGameOver = winMgr.loadLayoutFromFile("RestaurantGameSampleGameOver.layout"); + d_root = winMgr.createWindow("DefaultWindow", "RestaurantGameSampleRoot"); d_root->addChild(d_rootIngame); d_guiContext->setRootWindow(d_root); - if(!ImageManager::getSingleton().isDefined("HUDDemoGameOver")) - ImageManager::getSingleton().addFromImageFile("HUDDemoGameOver", "HUDDemoGameOver.png"); - d_rootGameOver->getChild("GameOverImage")->setProperty("Image", "HUDDemoGameOver"); + if(!ImageManager::getSingleton().isDefined("RestaurantGameSampleGameOver")) + ImageManager::getSingleton().addBitmapImageFromFile("RestaurantGameSampleGameOver", "RestaurantGameSampleGameOver.png"); + d_rootGameOver->getChild("GameOverImage")->setProperty("Image", "RestaurantGameSampleGameOver"); - setupMouseCursor(); + setupCursor(); srand(static_cast(time(0))); @@ -158,11 +180,11 @@ bool HUDDemo::initialise(CEGUI::GUIContext* guiContext) initGame(); - d_rootIngame->getChild("BotBar/WeaponBGImage/LeftArrowArea")->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&HUDDemo::handleWeaponLeftArrowClicked, this)); - d_rootIngame->getChild("BotBar/WeaponBGImage/RightArrowArea")->subscribeEvent(CEGUI::Window::EventMouseClick, Event::Subscriber(&HUDDemo::handleWeaponRightArrowClicked, this)); - - d_rootGameOver->getChild("ButtonRestart")->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&HUDDemo::handleRestartButtonClicked, this)); - + d_rootIngame->getChild("BotBar/WeaponBGImage/LeftArrowArea")->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&RestaurantGameSample::handleWeaponLeftArrowClicked, this)); + d_rootIngame->getChild("BotBar/WeaponBGImage/RightArrowArea")->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&RestaurantGameSample::handleWeaponRightArrowClicked, this)); + + d_rootGameOver->getChild("ButtonRestart")->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&RestaurantGameSample::handleRestartButtonClicked, this)); + return true; } @@ -170,7 +192,7 @@ bool HUDDemo::initialise(CEGUI::GUIContext* guiContext) /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ -void HUDDemo::deinitialise() +void RestaurantGameSample::deinitialise() { while(!d_gamePlates.empty()) { @@ -182,18 +204,18 @@ void HUDDemo::deinitialise() } -void HUDDemo::onEnteringSample() +void RestaurantGameSample::onEnteringSample() { initGame(); } -void HUDDemo::update(float timeSinceLastUpdate) +void RestaurantGameSample::update(float timeSinceLastUpdate) { static float timeSinceLastSpawn(0.0f); timeSinceLastSpawn += timeSinceLastUpdate; - updateMouseCursor(); + updateCursor(); if(timeSinceLastSpawn> 1.2f) @@ -209,37 +231,37 @@ void HUDDemo::update(float timeSinceLastUpdate) d_guiContext->markAsDirty(); } -void HUDDemo::setupMouseCursor() +void RestaurantGameSample::setupCursor() { CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton(); - d_mouseCursorWnd = winMgr.createWindow("Generic/Image"); - d_mouseCursorWnd->setProperty("Image", "HUDDemo/Spoon"); - d_mouseCursorWnd->setAspectMode(CEGUI::AM_EXPAND); - d_mouseCursorWnd->setAspectRatio(1.f); - d_mouseCursorWnd->setSize(CEGUI::USize(cegui_absdim(0.0f), cegui_reldim(0.1f))); - d_mouseCursorWnd->setAlwaysOnTop(true); - d_mouseCursorWnd->setMousePassThroughEnabled(true); - d_rootIngame->addChild(d_mouseCursorWnd); + d_cursorWnd = winMgr.createWindow("Generic/Image"); + d_cursorWnd->setProperty("Image", "RestaurantGameSample/Spoon"); + d_cursorWnd->setAspectMode(CEGUI::AM_EXPAND); + d_cursorWnd->setAspectRatio(1.0f); + d_cursorWnd->setSize(CEGUI::USize(cegui_absdim(0.0f), cegui_reldim(0.1f))); + d_cursorWnd->setAlwaysOnTop(true); + d_cursorWnd->setCursorPassThroughEnabled(true); + d_rootIngame->addChild(d_cursorWnd); } -void HUDDemo::updateMouseCursor() +void RestaurantGameSample::updateCursor() { - CEGUI::Vector2f position = d_guiContext->getMouseCursor().getPosition(); + glm::vec2 position = d_guiContext->getCursor().getPosition(); // We want to position the image-window right top of the actual // cursor point so we add its height - float absHeight = d_mouseCursorWnd->getPixelSize().d_height; - position.d_y -= absHeight; + float absHeight = d_cursorWnd->getPixelSize().d_height; + position.y -= absHeight; - d_mouseCursorWnd->setPosition( + d_cursorWnd->setPosition( CEGUI::UVector2( - cegui_absdim(position.d_x - 5.0f), cegui_absdim(position.d_y + 5.0f)) + cegui_absdim(position.x - 5.0f), cegui_absdim(position.y + 5.0f)) ); } -CEGUI::Window* HUDDemo::spawnPlate() +CEGUI::Window* RestaurantGameSample::spawnPlate() { CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton(); @@ -249,7 +271,7 @@ CEGUI::Window* HUDDemo::spawnPlate() plateRoot->setAspectRatio(1.0f); plateRoot->setRiseOnClickEnabled(false); plateRoot->setPixelAligned(false); - plateRoot->subscribeEvent(CEGUI::Window::EventMouseButtonDown, Event::Subscriber(&HUDDemo::handlePlateWindowClicked, this)); + plateRoot->subscribeEvent(CEGUI::Window::EventCursorActivate, Event::Subscriber(&RestaurantGameSample::handlePlateWindowActivated, this)); d_rootIngame->addChild(plateRoot); CEGUI::Window* plateImgWnd = winMgr.createWindow("Generic/Image", "ImageWindowPlate"); @@ -258,7 +280,7 @@ CEGUI::Window* HUDDemo::spawnPlate() plateImgWnd->setAspectRatio(3.308f); plateImgWnd->setAspectMode(CEGUI::AM_EXPAND); plateImgWnd->setVerticalAlignment(CEGUI::VA_BOTTOM); - plateImgWnd->setMousePassThroughEnabled(true); + plateImgWnd->setCursorPassThroughEnabled(true); plateImgWnd->setPixelAligned(false); plateRoot->addChild(plateImgWnd); @@ -270,7 +292,7 @@ CEGUI::Window* HUDDemo::spawnPlate() plateTopping->setAspectRatio(1.0f); plateTopping->setAspectMode(CEGUI::AM_EXPAND); plateTopping->setHorizontalAlignment(CEGUI::HA_CENTRE); - plateTopping->setMousePassThroughEnabled(true); + plateTopping->setCursorPassThroughEnabled(true); plateTopping->setPixelAligned(false); plateRoot->addChild(plateTopping); @@ -283,7 +305,7 @@ CEGUI::Window* HUDDemo::spawnPlate() return plateRoot; } -const CEGUI::String& HUDDemo::getRandomGameImage() +const CEGUI::String& RestaurantGameSample::getRandomGameImage() { int randumNumber = rand() % 100; @@ -304,7 +326,7 @@ const CEGUI::String& HUDDemo::getRandomGameImage() } -void HUDDemo::updatePlates(float timeSinceLastUpdate) +void RestaurantGameSample::updatePlates(float timeSinceLastUpdate) { unsigned int vectorSize = d_gamePlates.size(); @@ -325,22 +347,21 @@ void HUDDemo::updatePlates(float timeSinceLastUpdate) } } -void HUDDemo::updateScoreWindow() +void RestaurantGameSample::updateScoreWindow() { CEGUI::Window* scoreWnd = d_rootIngame->getChild("TopBar/ScoreBGImage/Score"); scoreWnd->setText(CEGUI::PropertyHelper::toString(d_score)); } -bool HUDDemo::handlePlateWindowClicked(const CEGUI::EventArgs& args) +bool RestaurantGameSample::handlePlateWindowActivated(const CEGUI::EventArgs& args) { - const CEGUI::MouseEventArgs& mouseArgs = static_cast(args); - + const CEGUI::CursorInputEventArgs& cursor_args = static_cast(args); for(unsigned int i = 0; i < d_gamePlates.size(); ++i) { GamePlate* gamePlate = d_gamePlates[i]; - if(gamePlate->d_window == mouseArgs.window) + if(gamePlate->d_window == cursor_args.window) { int points = gamePlate->getPoints(); d_score += points; @@ -362,23 +383,23 @@ bool HUDDemo::handlePlateWindowClicked(const CEGUI::EventArgs& args) } gamePlate->d_isDestroyed = true; - createScorePopup(mouseArgs.position, points); + createScorePopup(cursor_args.position, points); } } return false; } -void HUDDemo::createScorePopup(const CEGUI::Vector2& mousePos, int points) +void RestaurantGameSample::createScorePopup(const glm::vec2& cursor_pos, int points) { CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton(); - CEGUI::Window* popupWindow = winMgr.createWindow("HUDDemo/PopupLabel"); + CEGUI::Window* popupWindow = winMgr.createWindow("RestaurantGameSample/PopupLabel"); d_rootIngame->addChild(popupWindow); - popupWindow->setPosition(CEGUI::UVector2(cegui_absdim(mousePos.d_x), cegui_absdim(mousePos.d_y))); + popupWindow->setPosition(CEGUI::UVector2(cegui_absdim(cursor_pos.x), cegui_absdim(cursor_pos.y))); popupWindow->setText(CEGUI::PropertyHelper::toString(points)); popupWindow->setRiseOnClickEnabled(false); - popupWindow->subscribeEvent(AnimationInstance::EventAnimationEnded, Event::Subscriber(&HUDDemo::handleScorePopupAnimationEnded, this)); + popupWindow->subscribeEvent(AnimationInstance::EventAnimationEnded, Event::Subscriber(&RestaurantGameSample::handleScorePopupAnimationEnded, this)); popupWindow->setPixelAligned(false); popupWindow->setFont("DejaVuSans-14"); @@ -396,7 +417,7 @@ void HUDDemo::createScorePopup(const CEGUI::Vector2& mousePos, int points popupWindow->fireEvent("StartAnimation", args); } -bool HUDDemo::handleScorePopupAnimationEnded(const CEGUI::EventArgs& args) +bool RestaurantGameSample::handleScorePopupAnimationEnded(const CEGUI::EventArgs& args) { const CEGUI::AnimationEventArgs& animArgs = static_cast(args); @@ -406,7 +427,7 @@ bool HUDDemo::handleScorePopupAnimationEnded(const CEGUI::EventArgs& args) return false; } -void HUDDemo::delayDestroyWindows() +void RestaurantGameSample::delayDestroyWindows() { CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton(); @@ -420,13 +441,13 @@ void HUDDemo::delayDestroyWindows() } -void HUDDemo::handleLivesChanged() +void RestaurantGameSample::handleLivesChanged() { bool life1Visible = (d_lives >= 1); bool life2Visible = (d_lives >= 2); bool life3Visible = (d_lives >= 3); - + d_rootIngame->getChild("TopBar/Life1")->setAlpha( life1Visible ? 1.0f : 0.5f ); d_rootIngame->getChild("TopBar/Life2")->setAlpha( life2Visible ? 1.0f : 0.5f ); d_rootIngame->getChild("TopBar/Life3")->setAlpha( life3Visible ? 1.0f : 0.5f ); @@ -434,11 +455,11 @@ void HUDDemo::handleLivesChanged() if(d_lives <= 0) { d_root->addChild(d_rootGameOver); - d_rootGameOver->addChild(d_mouseCursorWnd); + d_rootGameOver->addChild(d_cursorWnd); } } -void HUDDemo::initGame() +void RestaurantGameSample::initGame() { d_lives = 3; handleLivesChanged(); @@ -451,7 +472,7 @@ void HUDDemo::initGame() d_lifeBar->setProgress(1.0f); } -void HUDDemo::selectedWeapon(SelectedWeapon weapon) +void RestaurantGameSample::selectedWeapon(SelectedWeapon weapon) { d_selectedWeapon = weapon; @@ -462,7 +483,7 @@ void HUDDemo::selectedWeapon(SelectedWeapon weapon) d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(0.5f); d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(0.5f); d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Spoon"); - + break; case SW_Fork: d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(0.5f); @@ -481,7 +502,7 @@ void HUDDemo::selectedWeapon(SelectedWeapon weapon) } } -bool HUDDemo::handleWeaponRightArrowClicked(const CEGUI::EventArgs& args) +bool RestaurantGameSample::handleWeaponRightArrowClicked(const CEGUI::EventArgs& args) { int weaponIndex = static_cast(d_selectedWeapon); weaponIndex = (weaponIndex - 1) % 3; @@ -492,29 +513,20 @@ bool HUDDemo::handleWeaponRightArrowClicked(const CEGUI::EventArgs& args) return false; } -bool HUDDemo::handleRestartButtonClicked(const CEGUI::EventArgs& args) +bool RestaurantGameSample::handleRestartButtonClicked(const CEGUI::EventArgs& args) { d_root->removeChild(d_rootGameOver); - d_rootIngame->addChild(d_mouseCursorWnd); + d_rootIngame->addChild(d_cursorWnd); initGame(); return false; } -bool HUDDemo::handleWeaponLeftArrowClicked(const CEGUI::EventArgs& args) +bool RestaurantGameSample::handleWeaponLeftArrowClicked(const CEGUI::EventArgs& args) { int weaponIndex = static_cast(d_selectedWeapon); selectedWeapon( static_cast(++weaponIndex % 3) ); return false; -} - -/************************************************************************* -Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static HUDDemo sample; - return sample; } \ No newline at end of file diff --git a/samples/RestaurantGame/RestaurantGame.h b/samples/RestaurantGame/RestaurantGame.h index a8bd01e6e..02ac67c43 100644 --- a/samples/RestaurantGame/RestaurantGame.h +++ b/samples/RestaurantGame/RestaurantGame.h @@ -24,11 +24,11 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _First_Person_HUD_ -#define _First_Person_HUD_ +#ifndef _Restaurant_Game_h +#define _Restaurant_Game_h #include "SampleBase.h" - +#include #include namespace CEGUI @@ -48,14 +48,16 @@ enum SelectedWeapon }; // Sample class -class HUDDemo : public Sample +class RestaurantGameSample : public Sample { public: + RestaurantGameSample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); void initGame(); - void setupMouseCursor(); + void setupCursor(); // method to perform any required cleanup operations. virtual void deinitialise(); @@ -77,17 +79,17 @@ class HUDDemo : public Sample protected: static const CEGUI::String& getRandomGameImage(); - void updateMouseCursor(); + void updateCursor(); void updatePlates(float timeSinceLastUpdate); - bool handlePlateWindowClicked(const CEGUI::EventArgs& args); + bool handlePlateWindowActivated(const CEGUI::EventArgs& args); bool handleScorePopupAnimationEnded(const CEGUI::EventArgs& args); bool handleWeaponLeftArrowClicked(const CEGUI::EventArgs& args); bool handleWeaponRightArrowClicked(const CEGUI::EventArgs& args); bool handleRestartButtonClicked(const CEGUI::EventArgs& args); void updateScoreWindow(); - void createScorePopup(const CEGUI::Vector2& mousePos, int points); + void createScorePopup(const glm::vec2& cursor_pos, int points); void handleLivesChanged(); @@ -99,7 +101,7 @@ class HUDDemo : public Sample CEGUI::Window* d_rootIngame; CEGUI::Window* d_rootGameOver; - CEGUI::Window* d_mouseCursorWnd; + CEGUI::Window* d_cursorWnd; int d_score; diff --git a/samples/RestaurantGame/SampleMetaData.xml b/samples/RestaurantGame/SampleMetaData.xml deleted file mode 100644 index 456d84c92..000000000 --- a/samples/RestaurantGame/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/SVG/CMakeLists.txt b/samples/SVG/CMakeLists.txt new file mode 100644 index 000000000..694aca6d7 --- /dev/null +++ b/samples/SVG/CMakeLists.txt @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/SVG/SVG.cpp b/samples/SVG/SVG.cpp new file mode 100644 index 000000000..5468e44e2 --- /dev/null +++ b/samples/SVG/SVG.cpp @@ -0,0 +1,129 @@ +/*********************************************************************** + created: 11th August 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "SVG.h" + +#include "CEGUI/SchemeManager.h" +#include "CEGUI/GUIContext.h" +#include "CEGUI/WindowManager.h" +#include "CEGUI/FontManager.h" +#include "CEGUI/Window.h" +#include "CEGUI/widgets/DefaultWindow.h" +#include "CEGUI/widgets/PushButton.h" +#include "CEGUI/ImageManager.h" +#include "CEGUI/svg/SVGImage.h" + +#include + +using namespace CEGUI; + +/************************************************************************* + Constructor. +*************************************************************************/ +SVGSample::SVGSample() : + Sample(-10) +{ + Sample::d_name = "SVGSample"; + Sample::d_credits = "Lukas \"Ident\" Meindl"; + Sample::d_description = ""; + Sample::d_summary = ""; +} + +/************************************************************************* + Sample specific initialisation goes here. +*************************************************************************/ +bool SVGSample::initialise(CEGUI::GUIContext* guiContext) +{ + d_usedFiles = CEGUI::String(__FILE__); + + //CEGUI setup + SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); + SchemeManager::getSingleton().createFromFile("Generic.scheme"); + guiContext->getCursor().setDefaultImage("WindowsLook/MouseArrow"); + WindowManager& winMgr = WindowManager::getSingleton(); + + // load font and setup default if not loaded via scheme + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + + // Create a DefaultWindow called 'Root'. + d_root = static_cast(winMgr.createWindow("DefaultWindow", "Root")); + + // Set default font for the gui context + guiContext->setDefaultFont(&defaultFont); + + // Set the root window as root of our GUI Context + guiContext->setRootWindow(d_root); + + // Load our SVG-based imageset via the ImageManager + CEGUI::ImageManager& imageManager = CEGUI::ImageManager::getSingleton(); + ImageManager::getSingleton().loadImageset("SVGSampleImageset.imageset"); + + // We get our loaded sample SVGImage and save it to a variable + d_svgSampleImage = static_cast( &ImageManager::getSingleton().get("SVGSampleImageset/SVGTestImage1") ); + + // We create a sizeable and movable FrameWindow that will contain our Image window + Window* svgSampleFrameWindow = winMgr.createWindow("WindowsLook/FrameWindow", "SvgSampleFrameWindow"); + svgSampleFrameWindow->setPosition(CEGUI::UVector2(cegui_absdim(50.0f), cegui_absdim(50.0f))); + svgSampleFrameWindow->setSize(CEGUI::USize(cegui_absdim(300.0f), cegui_absdim(300.0f))); + d_root->addChild(svgSampleFrameWindow); + + // We create a window that displays images and apply our SVGImage pointer to its "Image" property. Our sample SVGImage will be displayed by the window. + d_svgImageWindow = winMgr.createWindow("Generic/Image"); + d_svgImageWindow->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); + svgSampleFrameWindow->addChild(d_svgImageWindow); + d_svgImageWindow->setProperty("Image", d_svgSampleImage); + + // We create a button and subscribe to its click events + Window* svgAntialiasingButton = winMgr.createWindow("WindowsLook/Button"); + svgAntialiasingButton->setSize(CEGUI::USize(cegui_reldim(0.2f), cegui_reldim(0.035f))); + svgAntialiasingButton->setHorizontalAlignment(HA_CENTRE); + svgAntialiasingButton->setPosition(CEGUI::UVector2(cegui_absdim(0.0f), cegui_reldim(0.03f))); + svgAntialiasingButton->setText("Switch anti-aliasing mode"); + svgAntialiasingButton->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&SVGSample::handleAntialiasingButtonClicked, this)); + d_root->addChild(svgAntialiasingButton); + + // return true so that the samples framework knows that initialisation was a + // success, and that it should now run the sample. + return true; +} + + +bool SVGSample::handleAntialiasingButtonClicked(const CEGUI::EventArgs& args) +{ + d_svgSampleImage->setUseGeometryAntialiasing(!d_svgSampleImage->getUsesGeometryAntialiasing()); + d_svgImageWindow->invalidate(); + + return true; +} + + +void SVGSample::update(float timeSinceLastUpdate) +{ +} + +void SVGSample::deinitialise() +{ +} \ No newline at end of file diff --git a/samples/SVG/SVG.h b/samples/SVG/SVG.h new file mode 100644 index 000000000..1d694748a --- /dev/null +++ b/samples/SVG/SVG.h @@ -0,0 +1,63 @@ +/*********************************************************************** + created: 11th August 2013 + author: Lukas Meindl +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _SVG_Sample_h_ +#define _SVG_Sample_h_ + +#include "SampleBase.h" + +#include "CEGUI/ForwardRefs.h" + +namespace CEGUI +{ + class Window; + class DefaultWindow; +} + +class SVGSample : public Sample +{ +public: + SVGSample(); + + virtual bool initialise(CEGUI::GUIContext* guiContext); + virtual void deinitialise(); + + void update(float timeSinceLastUpdate); + +protected: + CEGUI::DefaultWindow* d_root; + +private: + //! An event handler that handles clicks on the anti-aliasing on/off button + bool handleAntialiasingButtonClicked(const CEGUI::EventArgs& args); + + //! A pointer to the window that will display the sample SVGImage + CEGUI::Window* d_svgImageWindow; + //! A pointer to our sample SVGImage object + CEGUI::SVGImage* d_svgSampleImage; +}; + +#endif diff --git a/samples/SampleTemplate.cpp b/samples/SampleTemplate.cpp new file mode 100644 index 000000000..a6256d52f --- /dev/null +++ b/samples/SampleTemplate.cpp @@ -0,0 +1,68 @@ +/*********************************************************************** + created: 20/5/2008 + author: name +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "SampleTemplate.h" +#include "CEGUI/CEGUI.h" + +//----------------------------------------------------------------------------// +WellNamedSample::WellNamedSample() +{ + // add your info here + // if you don't know what to write have a look + // into the other samples + + // the name of your sample + Sample::d_name = ""; + // your name goes here + Sample::d_credits = ""; + // summarise what your sample wants to demonstrate + Sample::d_summary = ""; + // explain how you achieve this + Sample::d_description = ""; +} + +//----------------------------------------------------------------------------// +bool WellNamedSample::initialise(CEGUI::GUIContext* guiContext) +{ + using namespace CEGUI; + + d_guiContext = guiContext; + + // add additional files, if you have some + d_usedFiles = CEGUI::String(__FILE__); + + // add your initialisation code below here + // e.g. loading layouts, etc. + + // success! + return true; +} + +//----------------------------------------------------------------------------// +void WellNamedSample::deinitialise() +{ + // add your deinitialisation code below (if there's a need for it) +} \ No newline at end of file diff --git a/samples/SampleTemplate.h b/samples/SampleTemplate.h new file mode 100644 index 000000000..03d0e0fe0 --- /dev/null +++ b/samples/SampleTemplate.h @@ -0,0 +1,54 @@ +/*********************************************************************** + created: dd-mm-yyyy + author: name +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - YYYY Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _WellNamedSample_h_ // change to your belongings (it is always a good idea to use +#define _WellNamedSample_h_ // the sample name because the name of your sample has to be unique) + +#include "SampleBase.h" + +namespace CEGUI +{ + // forward declarations (if necessary) +} + +// the sample class. needs to inherit from "Sample" class +class WellNamedSample : public Sample +{ +public: + // ctor + WellNamedSample(); + + // override member to initialise the sample. + virtual bool initialise(CEGUI::GUIContext* guiContext); + // override member to perform cleanup. + virtual void deinitialise(); + +private: + CEGUI::GUIContext* d_guiContext; +}; + +#endif // end of guard _Prototype_h_ + diff --git a/samples/ScrollablePane/CMakeLists.txt b/samples/ScrollablePane/CMakeLists.txt index 625f5689f..694aca6d7 100644 --- a/samples/ScrollablePane/CMakeLists.txt +++ b/samples/ScrollablePane/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_SCROLLABLEPANE "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_SCROLLABLEPANE) - cegui_add_sample(CEGUISample_ScrollablePane) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/ScrollablePane/SampleMetaData.xml b/samples/ScrollablePane/SampleMetaData.xml deleted file mode 100644 index a17d8d3ac..000000000 --- a/samples/ScrollablePane/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/ScrollablePane/Sample_ScrollablePane.cpp b/samples/ScrollablePane/ScrollablePane.cpp similarity index 63% rename from samples/ScrollablePane/Sample_ScrollablePane.cpp rename to samples/ScrollablePane/ScrollablePane.cpp index 4cefbdfb5..afad02dbb 100644 --- a/samples/ScrollablePane/Sample_ScrollablePane.cpp +++ b/samples/ScrollablePane/ScrollablePane.cpp @@ -1,9 +1,10 @@ /*********************************************************************** - created: Wed Aug 2 2006 - author: Tomas Lindquist Olsen + created: Aug 22 2014 + author: Luca Ebach + (based on original code by Tomas Lindquist Olsen) *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -24,11 +25,15 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ +#include "ScrollablePane.h" + #include "CEGUI/System.h" #include "CEGUI/SchemeManager.h" #include "CEGUI/WindowManager.h" #include "CEGUI/FontManager.h" #include "CEGUI/ImageManager.h" +#include "CEGUI/InputAggregator.h" +#include "CEGUI/InputEventReceiver.h" #include "CEGUI/Font.h" #include "CEGUI/Window.h" #include "CEGUI/CoordConverter.h" @@ -39,50 +44,20 @@ #include "SampleBase.h" -/* -This is a demonstration of the ScrollablePane widget -*/ - -// ScrollablePane demo sample class -class ScrollablePaneSample : public Sample +ScrollablePaneSample::ScrollablePaneSample() { -public: - // method to initialse the samples windows and events. - virtual bool initialise(CEGUI::GUIContext* guiContext); - // method to perform any required cleanup operations. - virtual void deinitialise(); - -private: - // creates the menubar with content - void createMenu(CEGUI::Window* bar); - - // quit menu item handler - bool fileQuit(const CEGUI::EventArgs&) - { - //d_sampleApp->setQuitting(true); - return true; - } - - // new dialog menu item handler - bool demoNewDialog(const CEGUI::EventArgs& e); - - // handler for all the global hotkeys - bool hotkeysHandler(const CEGUI::EventArgs& e); - - // member data - CEGUI::WindowManager* d_wm; // we will use the window manager alot - CEGUI::System* d_system; // the gui system - CEGUI::Window* d_root; // the gui sheet - CEGUI::Font* d_font; // the font we use - CEGUI::ScrollablePane* d_pane; // the scrollable pane. center piece of the demo - - CEGUI::GUIContext* d_guiContext; -}; - + Sample::d_name = "ScrollablePaneDemo"; + Sample::d_credits = "Tomas Lindquist Olsen"; + Sample::d_description = + "The ScrollbarPane sample uses the WindowsLook, which gives it a look similar " + "to old Windows applications. The background consists of a ScrollablePane to " + "which windows can be added, using the menu bar. The items on the pane can be " + "moved freely and the pane can be scrolled with the scrollbars."; + Sample::d_summary = + "The background window is of target type \"CEGUI/ScrollablePane\". " + "The WindowsLook skin is used for all the windows."; +} -/************************************************************************* -Sample specific initialisation goes here. -*************************************************************************/ bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -90,6 +65,8 @@ bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext) d_guiContext = guiContext; d_usedFiles = CEGUI::String(__FILE__); + d_inputAggregator = new SampleInputAggregator(d_guiContext); + // this sample will use WindowsLook SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); @@ -97,9 +74,9 @@ bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext) d_font = &FontManager::getSingleton().createFromFile("DejaVuSans-12-NoScale.font"); d_guiContext->setDefaultFont(d_font); - // set the mouse cursor + // set the cursor d_system = System::getSingletonPtr(); - d_guiContext->getMouseCursor().setDefaultImage("WindowsLook/MouseArrow"); + d_guiContext->getCursor().setDefaultImage("WindowsLook/MouseArrow"); // set the default tooltip type d_guiContext->setDefaultTooltipType("WindowsLook/Tooltip"); @@ -113,13 +90,13 @@ bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext) d_root->setProperty("FrameEnabled", "false"); d_root->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); d_root->setProperty("BackgroundColours", "tl:FFBFBFBF tr:FFBFBFBF bl:FFBFBFBF br:FFBFBFBF"); + d_root->subscribeEvent(Window::EventSemanticEvent, + Event::Subscriber(&ScrollablePaneSample::semanticEventHandler, this)); - // root window will take care of hotkeys - d_root->subscribeEvent(Window::EventKeyDown, Event::Subscriber(&ScrollablePaneSample::hotkeysHandler, this)); d_guiContext->setRootWindow(d_root); // create a menubar. - // this will fit in the top of the screen and have options for the demo + // this will fit in the top of the screen and have options for the Sample UDim bar_bottom(0,d_font->getLineSpacing(1.5f)); Window* bar = d_wm->createWindow("WindowsLook/Menubar"); @@ -129,7 +106,7 @@ bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext) // fill out the menubar createMenu(bar); - // create a scrollable pane for our demo content + // create a scrollable pane for our Sample content d_pane = static_cast(d_wm->createWindow("WindowsLook/ScrollablePane")); d_pane->setArea(URect(UDim(0,0),bar_bottom,UDim(1,0),UDim(1,0))); // this scrollable pane will be a kind of virtual desktop in the sense that it's bigger than @@ -148,109 +125,83 @@ bool ScrollablePaneSample::initialise(CEGUI::GUIContext* guiContext) return true; } -/************************************************************************* - Creates the menu bar and fills it up :) -*************************************************************************/ +/*************************************************************************/ void ScrollablePaneSample::createMenu(CEGUI::Window* bar) { using namespace CEGUI; - + // file menu item Window* file = d_wm->createWindow("WindowsLook/MenuItem"); file->setText("File"); bar->addChild(file); - + // file popup Window* popup = d_wm->createWindow("WindowsLook/PopupMenu"); file->addChild(popup); - + // quit item in file menu Window* item = d_wm->createWindow("WindowsLook/MenuItem"); item->setText("Quit"); item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::fileQuit, this)); popup->addChild(item); - // demo menu item - Window* demo = d_wm->createWindow("WindowsLook/MenuItem"); - demo->setText("Demo"); - bar->addChild(demo); + // Sample menu item + Window* Sample = d_wm->createWindow("WindowsLook/MenuItem"); + Sample->setText("Sample"); + bar->addChild(Sample); - // demo popup + // Sample popup popup = d_wm->createWindow("WindowsLook/PopupMenu"); - demo->addChild(popup); + Sample->addChild(popup); - // demo -> new window + // Sample -> new window item = d_wm->createWindow("WindowsLook/MenuItem"); item->setText("New dialog"); item->setTooltipText("Hotkey: Space"); - item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::demoNewDialog, this)); + item->subscribeEvent("Clicked", Event::Subscriber(&ScrollablePaneSample::SampleNewDialog, this)); popup->addChild(item); } -/************************************************************************* - Cleans up resources allocated in the initialiseSample call. -*************************************************************************/ +/************************************************************************/ void ScrollablePaneSample::deinitialise() { // everything we did is cleaned up by CEGUI + delete d_inputAggregator; } -/************************************************************************* - Handler for the 'Demo -> New dialog' menu item -*************************************************************************/ -bool ScrollablePaneSample::demoNewDialog(const CEGUI::EventArgs&) +/************************************************************************/ +bool ScrollablePaneSample::SampleNewDialog(const CEGUI::EventArgs&) { using namespace CEGUI; - + // add a dialog to this pane so we have some more stuff to drag around :) Window* dlg = d_wm->createWindow("WindowsLook/FrameWindow"); dlg->setMinSize(USize(UDim(0,200),UDim(0,100))); dlg->setSize(USize(UDim(0,200),UDim(0,100))); dlg->setText("Drag me around too!"); - + // we put this in the center of the viewport into the scrollable pane UVector2 uni_center(UDim(0.5f,0), UDim(0.5f,0)); // URGENT FIXME! //Vector2f center = CoordConverter::windowToScreen(*d_root, uni_center); //Vector2f target = CoordConverter::screenToWindow(*d_pane->getContentPane(), center); //dlg->setPosition(UVector2(UDim(0,target.d_x-100), UDim(0,target.d_y-50))); - + d_pane->addChild(dlg); - + return true; } -/************************************************************************* - Handler for global hotkeys -*************************************************************************/ -bool ScrollablePaneSample::hotkeysHandler(const CEGUI::EventArgs& e) +bool ScrollablePaneSample::semanticEventHandler(const CEGUI::EventArgs& e) { - using namespace CEGUI; - const KeyEventArgs& k = static_cast(e); - - switch (k.scancode) + const CEGUI::SemanticEventArgs& args = static_cast(e); + if (args.d_semanticValue == SpawnNewDialog) { - // space is a hotkey for demo -> new dialog - case Key::Space: // this handler does not use the event args at all so this is fine :) - // though maybe a bit hackish... - demoNewDialog(e); - break; - - // no hotkey found? event not used... - default: - return false; + // though maybe a bit hack-ish... + SampleNewDialog(e); + return true; } - return true; + return false; } - - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static ScrollablePaneSample sample; - return sample; -} \ No newline at end of file diff --git a/samples/ScrollablePane/ScrollablePane.h b/samples/ScrollablePane/ScrollablePane.h new file mode 100644 index 000000000..2d2746e3f --- /dev/null +++ b/samples/ScrollablePane/ScrollablePane.h @@ -0,0 +1,104 @@ +/*********************************************************************** +created: Aug 22 2014 +author: Luca Ebach + (based on origingal code by Tomas Lindquist Olsen) +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _ScrollablePaneSample_h_ +#define _ScrollablePaneSample_h_ + +#include "CEGUI/System.h" +#include "CEGUI/SchemeManager.h" +#include "CEGUI/WindowManager.h" +#include "CEGUI/FontManager.h" +#include "CEGUI/ImageManager.h" +#include "CEGUI/InputAggregator.h" +#include "CEGUI/InputEventReceiver.h" +#include "CEGUI/Font.h" +#include "CEGUI/Window.h" +#include "CEGUI/CoordConverter.h" +#include "CEGUI/GUIContext.h" + +#include "CEGUI/widgets/ScrollablePane.h" +#include "CEGUI/widgets/ScrolledContainer.h" + +#include "SampleBase.h" + + +/************************************************************************* +Custom implementation of InputAggregator +*************************************************************************/ +enum SampleSemanticValue +{ + // we start from the user-defined value + SpawnNewDialog = CEGUI::SV_UserDefinedSemanticValue +}; + +class SampleInputAggregator : public CEGUI::InputAggregator +{ +public: + SampleInputAggregator(CEGUI::InputEventReceiver* input_receiver) : + CEGUI::InputAggregator(input_receiver) + { + } + + void initialise() + { + d_keyValuesMappings[CEGUI::Key::Space] = SpawnNewDialog; + } +}; + +// ScrollablePane Sample sample class +class ScrollablePaneSample : public Sample +{ +public: + ScrollablePaneSample(); + + // method to initialse the samples windows and events. + virtual bool initialise(CEGUI::GUIContext* guiContext); + // method to perform any required cleanup operations. + virtual void deinitialise(); + +private: + // creates the menubar with content + void createMenu(CEGUI::Window* bar); + + // quit menu item handler + bool fileQuit(const CEGUI::EventArgs&) { return true; } + + // new dialog menu item handler + bool SampleNewDialog(const CEGUI::EventArgs& e); + bool semanticEventHandler(const CEGUI::EventArgs& e); + + // member data + CEGUI::WindowManager* d_wm; // we will use the window manager alot + CEGUI::System* d_system; // the gui system + CEGUI::Window* d_root; // the gui sheet + CEGUI::Font* d_font; // the font we use + CEGUI::ScrollablePane* d_pane; // the scrollable pane. center piece of the Sample + + CEGUI::GUIContext* d_guiContext; +}; + +#endif // _ScrollablePaneSample \ No newline at end of file diff --git a/samples/SimpleGameMenu/CMakeLists.txt b/samples/SimpleGameMenu/CMakeLists.txt new file mode 100644 index 000000000..694aca6d7 --- /dev/null +++ b/samples/SimpleGameMenu/CMakeLists.txt @@ -0,0 +1,14 @@ +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/SimpleGameMenu/SimpleGameMenu.cpp b/samples/SimpleGameMenu/SimpleGameMenu.cpp new file mode 100644 index 000000000..f1278b298 --- /dev/null +++ b/samples/SimpleGameMenu/SimpleGameMenu.cpp @@ -0,0 +1,210 @@ +/*********************************************************************** + created: 05/9/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "SimpleGameMenu.h" +#include "CEGUI/CEGUI.h" + +#include +#include + +static CEGUI::String MainMenu = "MainContainer"; +static CEGUI::String OptionsMenu = "OptionsContainer"; +static CEGUI::String DifficultyMenu = "DifficultyContainer"; +static CEGUI::String GeneralOptionsMenu = "GeneralOptionsContainer"; +static CEGUI::String VideoOptionsMenu = "VideoOptionsContainer"; +static CEGUI::String SoundOptionsMenu = "SoundOptionsContainer"; + +/** This sample uses most of the code from the 'HelloWorld' sample. + Thus, most of the clarifying comments have been removed for brevity. **/ + +SimpleGameMenuSample::SimpleGameMenuSample() : + Sample(98), + d_currentMenu(0), + d_layout(0), + d_root(0), + d_windowNavigator(0) +{ + Sample::d_name = "SimpleGameMenuSample"; + Sample::d_credits = "Timotei Dolean"; + Sample::d_description = "A demo that shows a simple game menu with navigation."; + Sample::d_summary = ""; +} + +/************************************************************************* + Sample specific initialisation goes here. +*************************************************************************/ +bool SimpleGameMenuSample::initialise(CEGUI::GUIContext* gui_context) +{ + using namespace CEGUI; + + d_usedFiles = CEGUI::String(__FILE__); + + SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); + gui_context->getCursor().setDefaultImage("TaharezLook/MouseArrow"); + + WindowManager& win_mgr = WindowManager::getSingleton(); + + if(!ImageManager::getSingleton().isDefined("SpaceBackgroundImage")) + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + + // here we will use a StaticImage as the root, then we can use it to place a background image + d_root = win_mgr.createWindow("TaharezLook/StaticImage", "root_wnd"); + // set position and size + d_root->setPosition(UVector2(cegui_reldim(0), cegui_reldim(0))); + d_root->setSize(USize(cegui_reldim(1), cegui_reldim(1))); + // disable frame and standard background + d_root->setProperty("BackgroundEnabled", "false"); + // set the background image + d_root->setProperty("Image", "SpaceBackgroundImage"); + // install this as the root GUI sheet + gui_context->setRootWindow(d_root); + + d_navigationStrategy = new WindowChildrenNavigationStrategy(0); + + d_windowNavigator = new WindowNavigator(createNavigationMappings(), + d_navigationStrategy); + gui_context->setWindowNavigator(d_windowNavigator); + + // load font and setup default if not loaded via scheme + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + gui_context->setDefaultFont(&defaultFont); + + d_layout = win_mgr.loadLayoutFromFile("SimpleGameMenuSample.layout"); + d_root->addChild(d_layout); + showMenu(MainMenu); + + createEventHandlers(); + + return true; +} + +/************************************************************************* + Cleans up resources allocated in the initialiseSample call. +*************************************************************************/ +void SimpleGameMenuSample::deinitialise() +{ + delete d_windowNavigator; +} + +std::map SimpleGameMenuSample::createNavigationMappings() +{ + using namespace CEGUI; + + std::map mappings; + + mappings[SV_GoDown] = NavigationStrategiesPayloads::NAVIGATE_NEXT; + mappings[SV_GoUp] = NavigationStrategiesPayloads::NAVIGATE_PREVIOUS; + + return mappings; +} + +void SimpleGameMenuSample::createEventHandlers() +{ + using namespace CEGUI; + + d_layout->getChild(MainMenu)->getChild("NewGameButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleNewGameButtonClick, this)); + d_layout->getChild(MainMenu)->getChild("ContinueGameButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleContinueGameButtonClick, this)); + d_layout->getChild(MainMenu)->getChild("OptionsButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleOptionsButtonClick, this)); + + d_layout->getChild(OptionsMenu)->getChild("GeneralOptionsButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleGeneralOptionsButtonClick, this)); + d_layout->getChild(OptionsMenu)->getChild("VideoOptionsButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleVideoOptionsButtonClick, this)); + d_layout->getChild(OptionsMenu)->getChild("SoundOptionsButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleSoundOptionsButtonClick, this)); + + d_layout->getChild(OptionsMenu)->getChild("OptionsBackButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleGoToMainMenu, this)); + d_layout->getChild(DifficultyMenu)->getChild("DifficultyBackButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleGoToMainMenu, this)); + + d_layout->getChild(VideoOptionsMenu)->getChild("VideoOptionsBackButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleGoToOptionsMenu, this)); + d_layout->getChild(SoundOptionsMenu)->getChild("SoundOptionsBackButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleGoToOptionsMenu, this)); + d_layout->getChild(GeneralOptionsMenu)->getChild("GeneralOptionsBackButton")->subscribeEvent( + PushButton::EventClicked, Event::Subscriber(&SimpleGameMenuSample::handleGoToOptionsMenu, this)); +} + +void SimpleGameMenuSample::showMenu(CEGUI::String menu_name) +{ + if (d_currentMenu != 0) + d_currentMenu->setVisible(false); + + d_currentMenu = d_layout->getChild(menu_name); + d_currentMenu->setVisible(true); + d_navigationStrategy->d_targetWindow = d_currentMenu; +} + +bool SimpleGameMenuSample::handleNewGameButtonClick(const CEGUI::EventArgs& e) +{ + showMenu(DifficultyMenu); + return true; +} + +bool SimpleGameMenuSample::handleContinueGameButtonClick(const CEGUI::EventArgs& e) +{ + return true; +} + +bool SimpleGameMenuSample::handleOptionsButtonClick(const CEGUI::EventArgs& e) +{ + showMenu(OptionsMenu); + return true; +} + +bool SimpleGameMenuSample::handleGoToOptionsMenu(const CEGUI::EventArgs& e) +{ + showMenu(OptionsMenu); + return true; +} + +bool SimpleGameMenuSample::handleSoundOptionsButtonClick(const CEGUI::EventArgs& e) +{ + showMenu(SoundOptionsMenu); + return true; +} + +bool SimpleGameMenuSample::handleVideoOptionsButtonClick(const CEGUI::EventArgs& e) +{ + showMenu(VideoOptionsMenu); + return true; +} + +bool SimpleGameMenuSample::handleGoToMainMenu(const CEGUI::EventArgs& e) +{ + showMenu(MainMenu); + return true; +} + +bool SimpleGameMenuSample::handleGeneralOptionsButtonClick(const CEGUI::EventArgs& e) +{ + showMenu(GeneralOptionsMenu); + return true; +} \ No newline at end of file diff --git a/samples/SimpleGameMenu/SimpleGameMenu.h b/samples/SimpleGameMenu/SimpleGameMenu.h new file mode 100644 index 000000000..463f63991 --- /dev/null +++ b/samples/SimpleGameMenu/SimpleGameMenu.h @@ -0,0 +1,64 @@ +/*********************************************************************** + created: 05/9/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _Sample_SimpleGameMenu_h_ +#define _Sample_SimpleGameMenu_h_ + +#include "SampleBase.h" +#include "NavigationStrategies.h" +#include + +class SimpleGameMenuSample : public Sample +{ +public: + SimpleGameMenuSample(); + virtual bool initialise(CEGUI::GUIContext* gui_context); + virtual void deinitialise(); + +private: + CEGUI::Window* d_layout; + CEGUI::Window* d_root; + CEGUI::Window* d_currentMenu; + + WindowChildrenNavigationStrategy* d_navigationStrategy; + CEGUI::WindowNavigator* d_windowNavigator; + + bool handleContinueGameButtonClick(const CEGUI::EventArgs& e); + bool handleNewGameButtonClick(const CEGUI::EventArgs& e); + bool handleOptionsButtonClick(const CEGUI::EventArgs& e); + bool handleVideoOptionsButtonClick(const CEGUI::EventArgs& e); + bool handleGeneralOptionsButtonClick(const CEGUI::EventArgs& e); + bool handleSoundOptionsButtonClick(const CEGUI::EventArgs& e); + + bool handleGoToOptionsMenu(const CEGUI::EventArgs& e); + bool handleGoToMainMenu(const CEGUI::EventArgs& e); + + void showMenu(CEGUI::String MainMenu); + void createEventHandlers(); + std::map createNavigationMappings(); +}; + +#endif // end of guard _Sample_SimpleGameMenuSample_h_ diff --git a/samples/TabControl/CMakeLists.txt b/samples/TabControl/CMakeLists.txt index 460caf38e..694aca6d7 100644 --- a/samples/TabControl/CMakeLists.txt +++ b/samples/TabControl/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_TABCONTROL "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_TABCONTROL) - cegui_add_sample(CEGUISample_TabControl) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/TabControl/SampleMetaData.xml b/samples/TabControl/SampleMetaData.xml deleted file mode 100644 index a509bf860..000000000 --- a/samples/TabControl/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/TabControl/Sample_TabControl.cpp b/samples/TabControl/Sample_TabControl.cpp deleted file mode 100644 index 14dc5cc42..000000000 --- a/samples/TabControl/Sample_TabControl.cpp +++ /dev/null @@ -1,442 +0,0 @@ -/*********************************************************************** - created: 27/6/2006 - author: Andrew Zabolotny -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "SampleBase.h" -#include "CEGUI/CEGUI.h" - -using namespace CEGUI; - -#define SKIN "TaharezLook" -// for this to work you'll have to change the .layout files -//#define SKIN "WindowsLook" - -static const char* PageText [] = -{ - "This is page three", - "And this is page four, it's not too different from page three, isn't it?", - "Yep, you guessed, this is page five", - "And this is page six", - "Seven", - "Eight", - "Nine. Quite boring, isn't it?", - "Ten", - "Eleven", - "Twelve", - "Thirteen", - "Fourteen", - "Fifteen", - "And, finally, sixteen. Congrats, you found the last page!", -}; - -// Sample sub-class for ListboxTextItem that auto-sets the selection brush -// image. This saves doing it manually every time in the code. -class MyListItem : public ListboxTextItem -{ -public: - MyListItem(const String& text) : ListboxTextItem(text) - { - setSelectionBrushImage(SKIN "/MultiListSelectionBrush"); - } -}; - -// Sample class -class TabControlDemo : public Sample -{ -public: - // method to initialse the samples windows and events. - bool initialise(CEGUI::GUIContext* guiContext) - { - d_guiContext = guiContext; - d_usedFiles = CEGUI::String(__FILE__); - - // load font and setup default if not loaded via scheme - Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); - // Set default font for the gui context - guiContext->setDefaultFont(&defaultFont); - - // we will use of the WindowManager. - WindowManager& winMgr = WindowManager::getSingleton(); - - // load scheme and set up defaults - SchemeManager::getSingleton().createFromFile(SKIN ".scheme"); - d_guiContext->getMouseCursor().setDefaultImage(SKIN "/MouseArrow"); - - // load an image to use as a background - if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); - - // here we will use a StaticImage as the root, then we can use it to place a background image - Window* background = winMgr.createWindow(SKIN "/StaticImage"); - // set area rectangle - background->setArea(URect(cegui_reldim(0), cegui_reldim(0), - cegui_reldim(1), cegui_reldim(1))); - // disable frame and standard background - background->setProperty("FrameEnabled", "false"); - background->setProperty("BackgroundEnabled", "false"); - // set the background image - background->setProperty("Image", "SpaceBackgroundImage"); - // install this as the root GUI sheet - d_guiContext->setRootWindow(background); - - // set tooltip styles (by default there is none) - d_guiContext->setDefaultTooltipType(SKIN "/Tooltip"); - - // load some demo windows and attach to the background 'root' - background->addChild(winMgr.loadLayoutFromFile("TabControlDemo.layout")); - - TabControl* tc = static_cast(background->getChild("Frame/TabControl")); - - // Add some pages to tab control - tc->addTab(winMgr.loadLayoutFromFile("TabPage1.layout")); - tc->addTab(winMgr.loadLayoutFromFile("TabPage2.layout")); - - WindowManager::getSingleton().DEBUG_dumpWindowNames("asd"); - - static_cast( - background->getChild("Frame/TabControl/Page1/AddTab"))->subscribeEvent( - PushButton::EventClicked, - Event::Subscriber(&TabControlDemo::handleAddTab, this)); - - // Click to visit this tab - static_cast( - background->getChild("Frame/TabControl/Page1/Go"))->subscribeEvent( - PushButton::EventClicked, - Event::Subscriber(&TabControlDemo::handleGoto, this)); - - // Click to make this tab button visible (when scrolling is required) - static_cast( - background->getChild("Frame/TabControl/Page1/Show"))->subscribeEvent( - PushButton::EventClicked, - Event::Subscriber(&TabControlDemo::handleShow, this)); - - static_cast( - background->getChild("Frame/TabControl/Page1/Del"))->subscribeEvent( - PushButton::EventClicked, - Event::Subscriber(&TabControlDemo::handleDel, this)); - - RadioButton* rb = static_cast( - background->getChild("Frame/TabControl/Page1/TabPaneTop")); - rb->setSelected(tc->getTabPanePosition() == TabControl::Top); - rb->subscribeEvent( - RadioButton::EventSelectStateChanged, - Event::Subscriber(&TabControlDemo::handleTabPanePos, this)); - - rb = static_cast( - background->getChild("Frame/TabControl/Page1/TabPaneBottom")); - rb->setSelected(tc->getTabPanePosition() == TabControl::Bottom); - rb->subscribeEvent( - RadioButton::EventSelectStateChanged, - Event::Subscriber(&TabControlDemo::handleTabPanePos, this)); - - Scrollbar* sb = static_cast( - background->getChild("Frame/TabControl/Page1/TabHeight")); - sb->setScrollPosition(tc->getTabHeight().d_offset); - sb->subscribeEvent( - Scrollbar::EventScrollPositionChanged, - Event::Subscriber(&TabControlDemo::handleTabHeight, this)); - - sb = static_cast( - background->getChild("Frame/TabControl/Page1/TabPadding")); - sb->setScrollPosition(tc->getTabTextPadding().d_offset); - sb->subscribeEvent( - Scrollbar::EventScrollPositionChanged, - Event::Subscriber(&TabControlDemo::handleTabPadding, this)); - - refreshPageList(); - - // From now on, we don't rely on the exceptions anymore, but perform nice (and recommended) checks - // ourselves. - - return true; - } - - // method to perform any required cleanup operations. - void deinitialise() - { - } - - void refreshPageList() - { - Window* root = d_guiContext->getRootWindow(); - // Check if the windows exists - Listbox* lbox = 0; - TabControl* tc = 0; - - if (root->isChild("Frame/TabControl/Page1/PageList")) - { - lbox = static_cast(root->getChild( - "Frame/TabControl/Page1/PageList")); - } - - if (root->isChild("Frame/TabControl")) - { - tc = static_cast(root->getChild( - "Frame/TabControl")); - } - - if (lbox && tc) - { - lbox->resetList(); - - for (size_t i = 0; i < tc->getTabCount(); i++) - { - lbox->addItem(new MyListItem( - tc->getTabContentsAtIndex(i)->getName())); - } - } - } - - bool handleTabPanePos(const EventArgs& e) - { - TabControl::TabPanePosition tpp; - - switch (static_cast(e).window->getID()) - { - case 0: - tpp = TabControl::Top; - break; - case 1: - tpp = TabControl::Bottom; - break; - default: - return false; - } - - // Check if the window exists - Window* root = d_guiContext->getRootWindow(); - - if (root->isChild("Frame/TabControl")) - { - static_cast(root->getChild( - "Frame/TabControl"))->setTabPanePosition(tpp); - } - - return true; - } - - bool handleTabHeight(const EventArgs& e) - { - Scrollbar* sb = static_cast( - static_cast(e).window); - - // Check if the window exists - Window* root = d_guiContext->getRootWindow(); - - if (root->isChild("Frame/TabControl")) - { - static_cast(root->getChild( - "Frame/TabControl"))->setTabHeight( - UDim(0, sb->getScrollPosition())); - } - - // The return value mainly sais that we handled it, not if something failed. - return true; - } - - bool handleTabPadding(const EventArgs& e) - { - Scrollbar* sb = static_cast( - static_cast(e).window); - - // Check if the window exists - Window* root = d_guiContext->getRootWindow(); - - if (root->isChild("Frame/TabControl")) - { - static_cast(root->getChild( - "Frame/TabControl"))->setTabTextPadding( - UDim(0, sb->getScrollPosition())); - } - - return true; - } - - bool handleAddTab(const EventArgs&) - { - Window* root = d_guiContext->getRootWindow(); - - // Check if the window exists - if (root->isChild("Frame/TabControl")) - { - TabControl* tc = static_cast(root->getChild( - "Frame/TabControl")); - - // Add some tab buttons once - for (int num = 3; num <= 16; num++) - { - std::stringstream pgname; - pgname << "Page" << num; - - if (root->isChild(String("Frame/TabControl/") + pgname.str().c_str())) - // Next - continue; - - Window* pg = 0; - - pg = WindowManager::getSingleton().loadLayoutFromFile("TabPage.layout"); - CEGUI_TRY - { - pg = WindowManager::getSingleton().loadLayoutFromFile("TabPage.layout"); - pg->setName(String(pgname.str().c_str())); - } - CEGUI_CATCH(CEGUI::Exception&) - { - Logger::getSingleton().logEvent("Some error occured while adding a tabpage. Please see the logfile."); - break; - } - - // This window has just been created while loading the layout - if (pg->isChild("Text")) - { - Window* txt = pg->getChild("Text"); - txt->setText(PageText [num - 3]); - - pg->setText(pgname.str().c_str()); - tc->addTab(pg); - - refreshPageList(); - break; - } - } - } - - return true; - } - - bool handleGoto(const EventArgs&) - { - Window* root = d_guiContext->getRootWindow(); - // Check if the windows exists - Listbox* lbox = 0; - TabControl* tc = 0; - - if (root->isChild("Frame/TabControl/Page1/PageList")) - { - lbox = static_cast(root->getChild( - "Frame/TabControl/Page1/PageList")); - } - - if (root->isChild("Frame/TabControl")) - { - tc = static_cast(root->getChild( - "Frame/TabControl")); - } - - if (lbox && tc) - { - ListboxItem* lbi = lbox->getFirstSelectedItem(); - - if (lbi) - { - tc->setSelectedTab(lbi->getText()); - } - } - - return true; - } - - bool handleShow(const EventArgs&) - { - Window* root = d_guiContext->getRootWindow(); - // Check if the windows exists - Listbox* lbox = 0; - TabControl* tc = 0; - - if (root->isChild("Frame/TabControl/Page1/PageList")) - { - lbox = static_cast(root->getChild( - "Frame/TabControl/Page1/PageList")); - } - - if (root->isChild("Frame/TabControl")) - { - tc = static_cast(root->getChild( - "Frame/TabControl")); - } - - if (lbox && tc) - { - ListboxItem* lbi = lbox->getFirstSelectedItem(); - - if (lbi) - { - tc->makeTabVisible(lbi->getText()); - } - } - - return true; - } - - bool handleDel(const EventArgs&) - { - Window* root = d_guiContext->getRootWindow(); - // Check if the windows exists - Listbox* lbox = 0; - TabControl* tc = 0; - - if (root->isChild("Frame/TabControl/Page1/PageList")) - { - lbox = static_cast(root->getChild( - "Frame/TabControl/Page1/PageList")); - } - - if (root->isChild("Frame/TabControl")) - { - tc = static_cast(root->getChild( - "Frame/TabControl")); - } - - if (lbox && tc) - { - ListboxItem* lbi = lbox->getFirstSelectedItem(); - - if (lbi) - { - Window* content = tc->getTabContents(lbi->getText()); - tc->removeTab(lbi->getText()); - // Remove the actual window from Cegui - WindowManager::getSingleton().destroyWindow(content); - - refreshPageList(); - } - } - - return true; - } - - - protected: - CEGUI::GUIContext* d_guiContext; -}; - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static TabControlDemo sample; - return sample; -} diff --git a/samples/TabControl/TabControl.cpp b/samples/TabControl/TabControl.cpp new file mode 100644 index 000000000..bd6dabde8 --- /dev/null +++ b/samples/TabControl/TabControl.cpp @@ -0,0 +1,376 @@ +/*********************************************************************** + created: 27/6/2006 + author: Andrew Zabolotny +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "SampleBase.h" +#include "CEGUI/CEGUI.h" + +#include "TabControl.h" + +using namespace CEGUI; + +TabControlSample::TabControlSample() +{ + Sample::d_name = "TabControlSample"; + Sample::d_credits = "Andrew Zabolotny"; + Sample::d_description = + "The TabControl sample contains a window that has multiple pages, " + "which can be switching by clicking the tabs. Tabs can be adjusted " + "and created with the widgets on the 1st page."; + Sample::d_summary = + "The tab window is of type \"TaharezLook/TabControl\". " + "For the seperate pages CEGUI layouts are loaded and attached."; +} + +bool TabControlSample::initialise(CEGUI::GUIContext* guiContext) +{ + d_guiContext = guiContext; + d_usedFiles = CEGUI::String(__FILE__); + + // load font and setup default if not loaded via scheme + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + // Set default font for the gui context + guiContext->setDefaultFont(&defaultFont); + + // we will use of the WindowManager. + WindowManager& winMgr = WindowManager::getSingleton(); + + // load scheme and set up defaults + SchemeManager::getSingleton().createFromFile(SKIN ".scheme"); + d_guiContext->getCursor().setDefaultImage(SKIN "/MouseArrow"); + + // load an image to use as a background + if (!ImageManager::getSingleton().isDefined("SpaceBackgroundImage")) + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + + // here we will use a StaticImage as the root, then we can use it to place a background image + Window* background = winMgr.createWindow(SKIN "/StaticImage"); + // set area rectangle + background->setArea(URect(cegui_reldim(0), cegui_reldim(0), + cegui_reldim(1), cegui_reldim(1))); + // disable frame and standard background + background->setProperty("FrameEnabled", "false"); + background->setProperty("BackgroundEnabled", "false"); + // set the background image + background->setProperty("Image", "SpaceBackgroundImage"); + // install this as the root GUI sheet + d_guiContext->setRootWindow(background); + + // set tooltip styles (by default there is none) + d_guiContext->setDefaultTooltipType(SKIN "/Tooltip"); + + // load some demo windows and attach to the background 'root' + background->addChild(winMgr.loadLayoutFromFile("TabControlSample.layout")); + + TabControl* tc = static_cast(background->getChild("Frame/TabControl")); + + // Add some pages to tab control + tc->addTab(winMgr.loadLayoutFromFile("TabPage1.layout")); + tc->addTab(winMgr.loadLayoutFromFile("TabPage2.layout")); + + WindowManager::getSingleton().DEBUG_dumpWindowNames("asd"); + + static_cast( + background->getChild("Frame/TabControl/Page1/AddTab"))->subscribeEvent( + PushButton::EventClicked, + Event::Subscriber(&TabControlSample::handleAddTab, this)); + + // Click to visit this tab + static_cast( + background->getChild("Frame/TabControl/Page1/Go"))->subscribeEvent( + PushButton::EventClicked, + Event::Subscriber(&TabControlSample::handleGoto, this)); + + // Click to make this tab button visible (when scrolling is required) + static_cast( + background->getChild("Frame/TabControl/Page1/Show"))->subscribeEvent( + PushButton::EventClicked, + Event::Subscriber(&TabControlSample::handleShow, this)); + + static_cast( + background->getChild("Frame/TabControl/Page1/Del"))->subscribeEvent( + PushButton::EventClicked, + Event::Subscriber(&TabControlSample::handleDel, this)); + + RadioButton* rb = static_cast( + background->getChild("Frame/TabControl/Page1/TabPaneTop")); + rb->setSelected(tc->getTabPanePosition() == TabControl::Top); + rb->subscribeEvent( + RadioButton::EventSelectStateChanged, + Event::Subscriber(&TabControlSample::handleTabPanePos, this)); + + rb = static_cast( + background->getChild("Frame/TabControl/Page1/TabPaneBottom")); + rb->setSelected(tc->getTabPanePosition() == TabControl::Bottom); + rb->subscribeEvent( + RadioButton::EventSelectStateChanged, + Event::Subscriber(&TabControlSample::handleTabPanePos, this)); + + Scrollbar* sb = static_cast( + background->getChild("Frame/TabControl/Page1/TabHeight")); + sb->setScrollPosition(tc->getTabHeight().d_offset); + sb->subscribeEvent( + Scrollbar::EventScrollPositionChanged, + Event::Subscriber(&TabControlSample::handleTabHeight, this)); + + sb = static_cast( + background->getChild("Frame/TabControl/Page1/TabPadding")); + sb->setScrollPosition(tc->getTabTextPadding().d_offset); + sb->subscribeEvent( + Scrollbar::EventScrollPositionChanged, + Event::Subscriber(&TabControlSample::handleTabPadding, this)); + + refreshPageList(); + + // From now on, we don't rely on the exceptions anymore, but perform nice (and recommended) checks + // ourselves. + + return true; +} + +void TabControlSample::deinitialise() +{ +} + +void TabControlSample::refreshPageList() +{ + Window* root = d_guiContext->getRootWindow(); + // Check if the windows exists + ListWidget* list_widget = getPageListWidget(root); + TabControl* tc = getTabControl(root); + + if (list_widget && tc) + { + list_widget->clearList(); + + for (size_t i = 0; i < tc->getTabCount(); i++) + { + list_widget->addItem(new StandardItem( + tc->getTabContentsAtIndex(i)->getName())); + } + } +} + +bool TabControlSample::handleTabPanePos(const EventArgs& e) +{ + TabControl::TabPanePosition tpp; + + switch (static_cast(e).window->getID()) + { + case 0: + tpp = TabControl::Top; + break; + case 1: + tpp = TabControl::Bottom; + break; + default: + return false; + } + + // Check if the window exists + Window* root = d_guiContext->getRootWindow(); + + if (root->isChild("Frame/TabControl")) + { + static_cast(root->getChild( + "Frame/TabControl"))->setTabPanePosition(tpp); + } + + return true; +} + +bool TabControlSample::handleTabHeight(const EventArgs& e) +{ + Scrollbar* sb = static_cast( + static_cast(e).window); + + // Check if the window exists + Window* root = d_guiContext->getRootWindow(); + + if (root->isChild("Frame/TabControl")) + { + static_cast(root->getChild( + "Frame/TabControl"))->setTabHeight( + UDim(0, sb->getScrollPosition())); + } + + // The return value mainly says that we handled it, not if something failed. + return true; +} + +bool TabControlSample::handleTabPadding(const EventArgs& e) +{ + Scrollbar* sb = static_cast( + static_cast(e).window); + + // Check if the window exists + Window* root = d_guiContext->getRootWindow(); + + if (root->isChild("Frame/TabControl")) + { + static_cast(root->getChild( + "Frame/TabControl"))->setTabTextPadding( + UDim(0, sb->getScrollPosition())); + } + + return true; +} + +bool TabControlSample::handleAddTab(const EventArgs&) +{ + Window* root = d_guiContext->getRootWindow(); + + // Check if the window exists + if (root->isChild("Frame/TabControl")) + { + TabControl* tc = static_cast(root->getChild( + "Frame/TabControl")); + + // Add some tab buttons once + for (int num = 3; num <= 16; num++) + { + std::stringstream pgname; + pgname << "Page" << num; + + if (root->isChild(String("Frame/TabControl/") + pgname.str().c_str())) + // Next + continue; + + Window* pg = 0; + + pg = WindowManager::getSingleton().loadLayoutFromFile("TabPage.layout"); + CEGUI_TRY + { + pg = WindowManager::getSingleton().loadLayoutFromFile("TabPage.layout"); + pg->setName(String(pgname.str().c_str())); + } + CEGUI_CATCH(CEGUI::Exception&) + { + Logger::getSingleton().logEvent("Some error occured while adding a tabpage. Please see the logfile."); + break; + } + + // This window has just been created while loading the layout + if (pg->isChild("Text")) + { + Window* txt = pg->getChild("Text"); + txt->setText(PageText[num - 3]); + + pg->setText(pgname.str().c_str()); + tc->addTab(pg); + + refreshPageList(); + break; + } + } + } + + return true; +} + +bool TabControlSample::handleGoto(const EventArgs&) +{ + Window* root = d_guiContext->getRootWindow(); + // Check if the windows exist + ListWidget* list_widget = getPageListWidget(root); + TabControl* tc = getTabControl(root); + + if (list_widget && tc) + { + StandardItem* item = list_widget->getFirstSelectedItem(); + + if (item) + { + tc->setSelectedTab(item->getText()); + } + } + + return true; +} + +bool TabControlSample::handleShow(const EventArgs&) +{ + Window* root = d_guiContext->getRootWindow(); + // Check if the windows exist + ListWidget* list_widget = getPageListWidget(root); + TabControl* tc = getTabControl(root); + + if (list_widget && tc) + { + StandardItem* item = list_widget->getFirstSelectedItem(); + + if (item) + { + tc->makeTabVisible(item->getText()); + } + } + + return true; +} + +bool TabControlSample::handleDel(const EventArgs&) +{ + Window* root = d_guiContext->getRootWindow(); + // Check if the windows exist + ListWidget* list_widget = getPageListWidget(root); + TabControl* tc = getTabControl(root); + + if (list_widget && tc) + { + StandardItem* item = list_widget->getFirstSelectedItem(); + + if (item) + { + Window* content = tc->getTabContents(item->getText()); + tc->removeTab(item->getText()); + // Remove the actual window from CEGUI + WindowManager::getSingleton().destroyWindow(content); + + refreshPageList(); + } + } + + return true; +} + +TabControl* TabControlSample::getTabControl(Window* root) +{ + String control_id("Frame/TabControl"); + if (root->isChild(control_id)) + { + return static_cast(root->getChild(control_id)); + } + return 0; +} + +ListWidget* TabControlSample::getPageListWidget(Window* root) +{ + String page_list_id("Frame/TabControl/Page1/PageList"); + if (root->isChild(page_list_id)) + { + return static_cast(root->getChild(page_list_id)); + } + return 0; +} \ No newline at end of file diff --git a/samples/TabControl/TabControl.h b/samples/TabControl/TabControl.h new file mode 100644 index 000000000..a19fdea34 --- /dev/null +++ b/samples/TabControl/TabControl.h @@ -0,0 +1,96 @@ +/*********************************************************************** +created: 2014-08-22 +author: Luca Ebach +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _TabControlSample_h_ +#define _TabControlSample_h_ + +#include "SampleBase.h" +#include "CEGUI/ForwardRefs.h" + +using namespace CEGUI; + +#define SKIN "TaharezLook" +// for this to work you'll have to change the .layout files +//#define SKIN "WindowsLook" + +static const char* PageText[] = +{ + "This is page three", + "And this is page four, it's not too different from page three, isn't it?", + "Yep, you guessed, this is page five", + "And this is page six", + "Seven", + "Eight", + "Nine. Quite boring, isn't it?", + "Ten", + "Eleven", + "Twelve", + "Thirteen", + "Fourteen", + "Fifteen", + "And, finally, sixteen. Congrats, you found the last page!", +}; + +// Sample sub-class for ListboxTextItem that auto-sets the selection brush +// image. This saves doing it manually every time in the code. +class TabControlListItem : public ListboxTextItem +{ +public: + TabControlListItem(const String& text) : ListboxTextItem(text) + { + setSelectionBrushImage(SKIN "/MultiListSelectionBrush"); + } +}; + +// Sample class +class TabControlSample : public Sample +{ +public: + TabControlSample(); + + // method to initialse the samples windows and events. + bool initialise(CEGUI::GUIContext* guiContext); + + // method to perform any required cleanup operations. + void deinitialise(); + + void refreshPageList(); + bool handleTabPanePos(const EventArgs& e); + bool handleTabHeight(const EventArgs& e); + bool handleTabPadding(const EventArgs& e); + bool handleAddTab(const EventArgs&); + bool handleGoto(const EventArgs&); + bool handleShow(const EventArgs&); + bool handleDel(const EventArgs&); + +protected: + TabControl* getTabControl(Window* root); + ListWidget* getPageListWidget(Window* root); + + CEGUI::GUIContext* d_guiContext; +}; + +#endif // _TabControlSample_h_ \ No newline at end of file diff --git a/samples/Text/CMakeLists.txt b/samples/Text/CMakeLists.txt index 82531eb32..694aca6d7 100644 --- a/samples/Text/CMakeLists.txt +++ b/samples/Text/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_TEXT "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_TEXT) - cegui_add_sample(CEGUISample_Text) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Text/SampleMetaData.xml b/samples/Text/SampleMetaData.xml deleted file mode 100644 index c561a8fb5..000000000 --- a/samples/Text/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/Text/Sample_Text.cpp b/samples/Text/Text.cpp similarity index 59% rename from samples/Text/Sample_Text.cpp rename to samples/Text/Text.cpp index 57d768547..05f3fb89a 100644 --- a/samples/Text/Sample_Text.cpp +++ b/samples/Text/Text.cpp @@ -24,16 +24,27 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "Sample_Text.h" +#include "Text.h" #include "CEGUI/CEGUI.h" -#include +#include using namespace CEGUI; +TextSample::TextSample() +{ + Sample::d_name = "TextSample"; + Sample::d_credits = "CEGUI team"; + Sample::d_description = + "The text sample contains text editing widgets and offers possibilities to " + "change the text formatting or enter text to play around with the options"; + Sample::d_summary = "The text formatting and scrollbar visibility " + "are adjusted using the properties of the windows"; +} + /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ -bool TextDemo::initialise(CEGUI::GUIContext* guiContext) +bool TextSample::initialise(CEGUI::GUIContext* guiContext) { d_guiContext = guiContext; d_usedFiles = CEGUI::String(__FILE__); @@ -48,11 +59,11 @@ bool TextDemo::initialise(CEGUI::GUIContext* guiContext) // load scheme and set up defaults SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); - guiContext->getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); + guiContext->getCursor().setDefaultImage("TaharezLook/MouseArrow"); // load an image to use as a background if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow("TaharezLook/StaticImage", "background_wnd"); @@ -68,7 +79,7 @@ bool TextDemo::initialise(CEGUI::GUIContext* guiContext) d_guiContext->setRootWindow(background); // Load our layout as a basic - background->addChild(winMgr.loadLayoutFromFile("TextDemo.layout")); + background->addChild(winMgr.loadLayoutFromFile("TextSample.layout")); // Init the seperate blocks which make up this sample initStaticText(); @@ -76,60 +87,60 @@ bool TextDemo::initialise(CEGUI::GUIContext* guiContext) initMultiLineEdit(); // Quit button - subscribeEvent("Root/TextDemo/Quit", PushButton::EventClicked, Event::Subscriber(&TextDemo::quit, this)); + subscribeEvent("Root/TextSample/Quit", PushButton::EventClicked, Event::Subscriber(&TextSample::quit, this)); // Success (so far) return true; } -void TextDemo::initStaticText() +void TextSample::initStaticText() { // Name, Group, Selected - initRadio("Root/TextDemo/StaticGroup/HorzLeft", 0, true); - initRadio("Root/TextDemo/StaticGroup/HorzRight", 0, false); - initRadio("Root/TextDemo/StaticGroup/HorzCentered", 0, false); + initRadio("Root/TextSample/StaticGroup/HorzLeft", 0, true); + initRadio("Root/TextSample/StaticGroup/HorzRight", 0, false); + initRadio("Root/TextSample/StaticGroup/HorzCentered", 0, false); // New group! - initRadio("Root/TextDemo/StaticGroup/VertTop", 1, true); - initRadio("Root/TextDemo/StaticGroup/VertBottom", 1, false); - initRadio("Root/TextDemo/StaticGroup/VertCentered", 1, false); + initRadio("Root/TextSample/StaticGroup/VertTop", 1, true); + initRadio("Root/TextSample/StaticGroup/VertBottom", 1, false); + initRadio("Root/TextSample/StaticGroup/VertCentered", 1, false); // // Events // // Word-wrap checkbox (we can't re-use a handler struct for the last argument!!) - subscribeEvent("Root/TextDemo/StaticGroup/Wrap", ToggleButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); - subscribeEvent("Root/TextDemo/StaticGroup/HorzLeft", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); - subscribeEvent("Root/TextDemo/StaticGroup/HorzRight", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); - subscribeEvent("Root/TextDemo/StaticGroup/HorzCentered", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); - subscribeEvent("Root/TextDemo/StaticGroup/VertTop", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); - subscribeEvent("Root/TextDemo/StaticGroup/VertBottom", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); - subscribeEvent("Root/TextDemo/StaticGroup/VertCentered", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/Wrap", ToggleButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/HorzLeft", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/HorzRight", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/HorzCentered", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/VertTop", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/VertBottom", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); + subscribeEvent("Root/TextSample/StaticGroup/VertCentered", RadioButton::EventSelectStateChanged, Event::Subscriber(&TextSample::formatChangedHandler, this)); } -void TextDemo::initSingleLineEdit() +void TextSample::initSingleLineEdit() { Window* root = d_guiContext->getRootWindow(); // Only accepts digits for the age field - if (root->isChild("Root/TextDemo/SingleLineGroup/editAge")) + if (root->isChild("Root/TextSample/SingleLineGroup/editAge")) { - static_cast(root->getChild("Root/TextDemo/SingleLineGroup/editAge"))->setValidationString("[0-9]*"); + static_cast(root->getChild("Root/TextSample/SingleLineGroup/editAge"))->setValidationString("[0-9]*"); } // Set password restrictions - if (root->isChild("Root/TextDemo/SingleLineGroup/editPasswd")) + if (root->isChild("Root/TextSample/SingleLineGroup/editPasswd")) { - Editbox* passwd = static_cast(root->getChild("Root/TextDemo/SingleLineGroup/editPasswd")); + Editbox* passwd = static_cast(root->getChild("Root/TextSample/SingleLineGroup/editPasswd")); passwd->setValidationString("[A-Za-z0-9]*"); // Render masked passwd->setTextMasked(true); } } -void TextDemo::initMultiLineEdit() +void TextSample::initMultiLineEdit() { // Scrollbar checkbox - subscribeEvent("Root/TextDemo/MultiLineGroup/forceScroll", ToggleButton::EventSelectStateChanged, Event::Subscriber(&TextDemo::vertScrollChangedHandler, this)); + subscribeEvent("Root/TextSample/MultiLineGroup/forceScroll", ToggleButton::EventSelectStateChanged, Event::Subscriber(&TextSample::vertScrollChangedHandler, this)); } -void TextDemo::initRadio(const CEGUI::String& radio, int group, bool selected) +void TextSample::initRadio(const CEGUI::String& radio, int group, bool selected) { Window* root = d_guiContext->getRootWindow(); if (root->isChild(radio)) @@ -140,7 +151,7 @@ void TextDemo::initRadio(const CEGUI::String& radio, int group, bool selected) } } -void TextDemo::subscribeEvent(const String& widget, const String& event, const Event::Subscriber& method) +void TextSample::subscribeEvent(const String& widget, const String& event, const Event::Subscriber& method) { Window* root = d_guiContext->getRootWindow(); if (root->isChild(widget)) @@ -150,7 +161,7 @@ void TextDemo::subscribeEvent(const String& widget, const String& event, const E } } -bool TextDemo::isRadioSelected(const CEGUI::String& radio) +bool TextSample::isRadioSelected(const CEGUI::String& radio) { Window* root = d_guiContext->getRootWindow(); // Check @@ -162,7 +173,7 @@ bool TextDemo::isRadioSelected(const CEGUI::String& radio) return false; } -bool TextDemo::isCheckboxSelected(const CEGUI::String& checkbox) +bool TextSample::isCheckboxSelected(const CEGUI::String& checkbox) { Window* root = d_guiContext->getRootWindow(); // Check @@ -174,31 +185,31 @@ bool TextDemo::isCheckboxSelected(const CEGUI::String& checkbox) return false; } -bool TextDemo::formatChangedHandler(const CEGUI::EventArgs&) +bool TextSample::formatChangedHandler(const CEGUI::EventArgs&) { Window* root = d_guiContext->getRootWindow(); - if (root->isChild("Root/TextDemo/StaticGroup/StaticText")) + if (root->isChild("Root/TextSample/StaticGroup/StaticText")) { // and also the static text for which we will set the formatting options - Window* st = root->getChild("Root/TextDemo/StaticGroup/StaticText"); + Window* st = root->getChild("Root/TextSample/StaticGroup/StaticText"); // handle vertical formatting settings - if (isRadioSelected("Root/TextDemo/StaticGroup/VertTop")) + if (isRadioSelected("Root/TextSample/StaticGroup/VertTop")) st->setProperty("VertFormatting", "TopAligned"); - else if (isRadioSelected("Root/TextDemo/StaticGroup/VertBottom")) + else if (isRadioSelected("Root/TextSample/StaticGroup/VertBottom")) st->setProperty("VertFormatting", "BottomAligned"); - else if (isRadioSelected("Root/TextDemo/StaticGroup/VertCentered")) + else if (isRadioSelected("Root/TextSample/StaticGroup/VertCentered")) st->setProperty("VertFormatting", "CentreAligned"); // handle horizontal formatting settings - bool wrap = isCheckboxSelected("Root/TextDemo/StaticGroup/Wrap"); + bool wrap = isCheckboxSelected("Root/TextSample/StaticGroup/Wrap"); - if (isRadioSelected("Root/TextDemo/StaticGroup/HorzLeft")) + if (isRadioSelected("Root/TextSample/StaticGroup/HorzLeft")) st->setProperty("HorzFormatting", wrap ? "WordWrapLeftAligned" : "LeftAligned"); - else if (isRadioSelected("Root/TextDemo/StaticGroup/HorzRight")) + else if (isRadioSelected("Root/TextSample/StaticGroup/HorzRight")) st->setProperty("HorzFormatting", wrap ? "WordWrapRightAligned" : "RightAligned"); - else if (isRadioSelected("Root/TextDemo/StaticGroup/HorzCentered")) + else if (isRadioSelected("Root/TextSample/StaticGroup/HorzCentered")) st->setProperty("HorzFormatting", wrap ? "WordWrapCentreAligned" : "CentreAligned"); } @@ -206,22 +217,22 @@ bool TextDemo::formatChangedHandler(const CEGUI::EventArgs&) return true; } -bool TextDemo::vertScrollChangedHandler(const CEGUI::EventArgs&) +bool TextSample::vertScrollChangedHandler(const CEGUI::EventArgs&) { Window* root = d_guiContext->getRootWindow(); - if (root->isChild("Root/TextDemo/MultiLineGroup/editMulti")) + if (root->isChild("Root/TextSample/MultiLineGroup/editMulti")) { - MultiLineEditbox* multiEdit = static_cast(root->getChild("Root/TextDemo/MultiLineGroup/editMulti")); + MultiLineEditbox* multiEdit = static_cast(root->getChild("Root/TextSample/MultiLineGroup/editMulti")); // Use setter for a change - multiEdit->setShowVertScrollbar(isCheckboxSelected("Root/TextDemo/MultiLineGroup/forceScroll")); + multiEdit->setShowVertScrollbar(isCheckboxSelected("Root/TextSample/MultiLineGroup/forceScroll")); } // event was handled return true; } -bool TextDemo::quit(const CEGUI::EventArgs&) +bool TextSample::quit(const CEGUI::EventArgs&) { // event was handled @@ -231,17 +242,7 @@ bool TextDemo::quit(const CEGUI::EventArgs&) /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ -void TextDemo::deinitialise() +void TextSample::deinitialise() { // nothing to do here! -} - - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static TextDemo sample; - return sample; } \ No newline at end of file diff --git a/samples/Text/Sample_Text.h b/samples/Text/Text.h similarity index 97% rename from samples/Text/Sample_Text.h rename to samples/Text/Text.h index 7e7f6b359..4ccdd2607 100644 --- a/samples/Text/Sample_Text.h +++ b/samples/Text/Text.h @@ -35,9 +35,11 @@ namespace CEGUI } // Sample class -class TextDemo : public Sample +class TextSample : public Sample { public: + TextSample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); @@ -48,6 +50,7 @@ class TextDemo : public Sample member functions used as event handlers *************************************************************************/ bool handleQuit(const CEGUI::EventArgs& e); + private: /** Sub routines for each edit panel.*/ void initStaticText(); @@ -71,4 +74,4 @@ class TextDemo : public Sample CEGUI::GUIContext* d_guiContext; }; -#endif // end of guard _Sample_Demo4_h_ +#endif // end of guard _Sample_Sample4_h_ diff --git a/samples/Tree/CMakeLists.txt b/samples/Tree/CMakeLists.txt index f15233a02..694aca6d7 100644 --- a/samples/Tree/CMakeLists.txt +++ b/samples/Tree/CMakeLists.txt @@ -1,4 +1,14 @@ -option(CEGUI_SAMPLES_ENABLE_TREE "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_TREE) - cegui_add_sample(CEGUISample_Tree) -endif() \ No newline at end of file +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) + +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Tree/SampleMetaData.xml b/samples/Tree/SampleMetaData.xml deleted file mode 100644 index dbe64a64a..000000000 --- a/samples/Tree/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/Tree/Sample_TreeDemo.cpp b/samples/Tree/Sample_TreeDemo.cpp deleted file mode 100644 index ba1e3cb24..000000000 --- a/samples/Tree/Sample_TreeDemo.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/************************************************************************ - created: 10/17/2004 - author: David Durant (based on code by Paul D Turner) -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "Sample_TreeDemo.h" -#include "CEGUI/CEGUI.h" - -#if defined( __WIN32__ ) || defined( _WIN32 ) -#define WIN32_LEAN_AND_MEAN -#include "windows.h" -#include -#endif - -#include -#include - - -const unsigned int TreeDemoSample::TreeID = 1; -const unsigned int TreeDemoSample::EditBoxID = 2; - -#define USE_VANILLA 0 - - -#if USE_VANILLA -#define SCHEME_FILE_NAME "VanillaSkin.scheme" -#define IMAGES_FILE_NAME "Vanilla-Images" -#define STATICIMAGE_NAME "Vanilla/StaticImage" -#define TOOLTIP_NAME "Vanilla/Tooltip" -#define LAYOUT_FILE_NAME "TreeDemo.layout" -#define BRUSH_NAME "GenericBrush" -#else -#define SCHEME_FILE_NAME "TaharezLook.scheme" -#define IMAGES_FILE_NAME "TaharezLook" -#define STATICIMAGE_NAME "TaharezLook/StaticImage" -#define TOOLTIP_NAME "TaharezLook/Tooltip" -#define LAYOUT_FILE_NAME "TreeDemoTaharez.layout" -#define BRUSH_NAME "/TextSelectionBrush" -#endif - - -int randInt(int low, int high) - { - int num; - CEGUI::uint32 range; - - range = high - low + 1; - if (range > RAND_MAX) - num = (int)(((CEGUI::uint32)rand() * (CEGUI::uint32)rand()) % range); - else - num = (rand()) % range; - - return(num + low); - } - - -////////////////////////////////////////////////////////////////////////// -/************************************************************************* - - TreeDemoSample class - -*************************************************************************/ -////////////////////////////////////////////////////////////////////////// - - -/************************************************************************* -Sample specific initialisation goes here. -*************************************************************************/ -bool TreeDemoSample::initialise(CEGUI::GUIContext* guiContext) -{ - using namespace CEGUI; - - d_usedFiles = CEGUI::String(__FILE__); - - Tree * theTree; - TreeItem * newTreeCtrlEntryLvl1; // Level 1 TreeCtrlEntry (branch) - TreeItem * newTreeCtrlEntryLvl2; // Level 2 TreeCtrlEntry (branch) - TreeItem * newTreeCtrlEntryLvl3; // Level 3 TreeCtrlEntry (branch) - TreeItem * newTreeCtrlEntryParent; - Image * iconArray[9]; - -#if defined( __WIN32__ ) || defined( _WIN32 ) - // Windows specific code. - srand(static_cast(time(NULL))); -#endif - - // Get window manager which we will use for a few jobs here. - WindowManager& winMgr = WindowManager::getSingleton(); - - // load font and setup default if not loaded via scheme - Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); - // Set default font for the gui context - guiContext->setDefaultFont(&defaultFont); - - // Load the scheme to initialise the skin which we use in this sample - SchemeManager::getSingleton().createFromFile(SCHEME_FILE_NAME); - - // set default mouse image - guiContext->getMouseCursor().setDefaultImage(IMAGES_FILE_NAME "/MouseArrow"); - - // load an image to use as a background - if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); - - // Load some icon images for our test tree - ImageManager::getSingleton().loadImageset("DriveIcons.imageset"); - - // here we will use a StaticImage as the root, then we can use it to place a background image - Window* background = winMgr.createWindow(STATICIMAGE_NAME); - - // set area rectangle - background->setArea(URect(cegui_reldim(0), cegui_reldim(0), cegui_reldim(1), cegui_reldim(1))); - // disable frame and standard background - background->setProperty("FrameEnabled", "false"); - background->setProperty("BackgroundEnabled", "false"); - // set the background image - background->setProperty("Image", "SpaceBackgroundImage"); - // install this as the root GUI sheet - guiContext->setRootWindow(background); - - FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); - - TreeDemoWindow = winMgr.loadLayoutFromFile(LAYOUT_FILE_NAME); - - background->addChild(TreeDemoWindow); - - // listen for key presses on the root window. - background->subscribeEvent(Window::EventKeyDown, Event::Subscriber(&TreeDemoSample::handleRootKeyDown, this)); - - theTree = (Tree *)TreeDemoWindow->getChild(TreeID); - theTree->initialise(); - theTree->subscribeEvent(Tree::EventSelectionChanged, Event::Subscriber(&TreeDemoSample::handleEventSelectionChanged, this)); - theTree->subscribeEvent(Tree::EventBranchOpened, Event::Subscriber(&TreeDemoSample::handleEventBranchOpened, this)); - theTree->subscribeEvent(Tree::EventBranchClosed, Event::Subscriber(&TreeDemoSample::handleEventBranchClosed, this)); - - // activate the background window - background->activate(); - - iconArray[0] = &ImageManager::getSingleton().get("DriveIcons/Artic"); - iconArray[1] = &ImageManager::getSingleton().get("DriveIcons/Black"); - iconArray[2] = &ImageManager::getSingleton().get("DriveIcons/Sunset"); - iconArray[3] = &ImageManager::getSingleton().get("DriveIcons/DriveStack"); - iconArray[4] = &ImageManager::getSingleton().get("DriveIcons/GlobalDrive"); - iconArray[5] = &ImageManager::getSingleton().get("DriveIcons/Blue"); - iconArray[6] = &ImageManager::getSingleton().get("DriveIcons/Lime"); - iconArray[7] = &ImageManager::getSingleton().get("DriveIcons/Silver"); - iconArray[8] = &ImageManager::getSingleton().get("DriveIcons/GreenCandy"); - - // Create a top-most TreeCtrlEntry - newTreeCtrlEntryLvl1 = new TreeItem("Tree Item Level 1a"); - newTreeCtrlEntryLvl1->setIcon(ImageManager::getSingleton().get("DriveIcons/Black")); - newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); -// newTreeCtrlEntryLvl1->setUserData((void *)someData); - theTree->addItem(newTreeCtrlEntryLvl1); - // Create a second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry - newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2a (1a)"); - newTreeCtrlEntryLvl2->setIcon(ImageManager::getSingleton().get("DriveIcons/Artic")); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); - // Create a third-level TreeCtrlEntry and attach it to the above TreeCtrlEntry - newTreeCtrlEntryLvl3 = new TreeItem("Tree Item Level 3a (2a)"); - newTreeCtrlEntryLvl3->setIcon(ImageManager::getSingleton().get("DriveIcons/Blue")); - newTreeCtrlEntryLvl3->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl2->addItem(newTreeCtrlEntryLvl3); - // Create another third-level TreeCtrlEntry and attach it to the above TreeCtrlEntry - newTreeCtrlEntryLvl3 = new TreeItem("Tree Item Level 3b (2a)"); - newTreeCtrlEntryLvl3->setIcon(ImageManager::getSingleton().get("DriveIcons/Lime")); - newTreeCtrlEntryLvl3->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl2->addItem(newTreeCtrlEntryLvl3); - // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry - newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2b (1a)"); - newTreeCtrlEntryLvl2->setIcon(ImageManager::getSingleton().get("DriveIcons/Sunset")); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); - // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry - newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2c (1a)"); - newTreeCtrlEntryLvl2->setIcon(ImageManager::getSingleton().get("DriveIcons/Silver")); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); - - // Create another top-most TreeCtrlEntry - newTreeCtrlEntryLvl1 = new TreeItem("Tree Item Level 1b"); - newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl1->setIcon(ImageManager::getSingleton().get("DriveIcons/DriveStack")); - newTreeCtrlEntryLvl1->setDisabled(true); // Let's disable this one just to be sure it works - theTree->addItem(newTreeCtrlEntryLvl1); - // Create a second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry - newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2a (1b)"); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); - // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry - newTreeCtrlEntryLvl2 = new TreeItem("Tree Item Level 2b (1b)"); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); - - newTreeCtrlEntryLvl1 = new TreeItem("Tree Item Level 1c"); - newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - theTree->addItem(newTreeCtrlEntryLvl1); - - // Now let's create a whole bunch of items automatically - int levelIndex = 3; - int idepthIndex; - int childIndex; - int childCount; - unsigned int iconIndex; - String itemText; - while (levelIndex < 10) - { - idepthIndex = 0; - itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex); - newTreeCtrlEntryLvl1 = new TreeItem(itemText); - // Set a random icon for the item. Sometimes blank (on purpose). - iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0])) + 2); - if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) - newTreeCtrlEntryLvl1->setIcon(*iconArray[iconIndex]); - newTreeCtrlEntryLvl1->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - theTree->addItem(newTreeCtrlEntryLvl1); - newTreeCtrlEntryParent = newTreeCtrlEntryLvl1; - -#if 1 - childIndex = 0; - childCount = randInt(0, 3); - while (childIndex < childCount) - { - itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex + 1) + " Child " + PropertyHelper::toString(childIndex + 1); - newTreeCtrlEntryLvl2 = new TreeItem(itemText); - // Set a random icon for the item. Sometimes blank (on purpose). - iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2)); - if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) - newTreeCtrlEntryLvl2->setIcon(*iconArray[iconIndex]); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2); - ++childIndex; - } -#endif - - while (idepthIndex < 15) - { - itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex + 1); - newTreeCtrlEntryLvl2 = new TreeItem(itemText); - // Set a random icon for the item. Sometimes blank (on purpose). - iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2)); - if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) - newTreeCtrlEntryLvl2->setIcon(*iconArray[iconIndex]); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2); - newTreeCtrlEntryParent = newTreeCtrlEntryLvl2; - -#if 1 - childIndex = 0; - childCount = randInt(0, 3); - while (childIndex < childCount) - { - itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex + 1) + " Child " + PropertyHelper::toString(childIndex + 1); - newTreeCtrlEntryLvl2 = new TreeItem(itemText); - // Set a random icon for the item. Sometimes blank (on purpose). - iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2)); - if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) - newTreeCtrlEntryLvl2->setIcon(*iconArray[iconIndex]); - newTreeCtrlEntryLvl2->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); - newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2); - ++childIndex; - } -#endif - ++idepthIndex; - } - ++levelIndex; - } - - return true; - } - - -/************************************************************************* - Cleans up resources allocated in the initialiseSample call. -*************************************************************************/ -void TreeDemoSample::deinitialise() - { - } - - -bool TreeDemoSample::handleEventSelectionChanged(const CEGUI::EventArgs& args) - { - using namespace CEGUI; - - const TreeEventArgs& treeArgs = static_cast(args); - Editbox *editBox = (Editbox *)TreeDemoWindow->getChild(EditBoxID); - - // Three different ways to get the item selected. -// TreeCtrlEntry *selectedItem = theTree->getFirstSelectedItem(); // the first selection in the list (may be more) -// TreeCtrlEntry *selectedItem = theTree->getLastSelectedItem(); // the last (time-wise) selected by the user - TreeItem *selectedItem = treeArgs.treeItem; // the actual item that caused this event - - if (selectedItem) - { -#if 0 - // A convoluted way to get the item text. - // Just here to test findFirstItemWithText. - selectedItem = theTree->findFirstItemWithText(selectedItem->getText()); - if (selectedItem) - editBox->setText("Selected: " + selectedItem->getText()); - else - editBox->setText("findItemWithText failed!"); -#else - // The simple way to do it. - editBox->setText("Selected: " + selectedItem->getText()); -#endif - } - else - editBox->setText("None Selected"); - - return true; - } - - - -bool TreeDemoSample::handleRootKeyDown(const CEGUI::EventArgs& args) - { - using namespace CEGUI; - - const KeyEventArgs& keyArgs = static_cast(args); - - switch (keyArgs.scancode) - { - case Key::F12: - break; - - default: - return false; - } - - return true; - } - - -bool TreeDemoSample::handleEventBranchOpened(const CEGUI::EventArgs& args) - { - using namespace CEGUI; - - const TreeEventArgs& treeArgs = static_cast(args); - Editbox *editBox = (Editbox *)TreeDemoWindow->getChild(EditBoxID); - editBox->setText("Opened: " + treeArgs.treeItem->getText()); - return true; - } - - -bool TreeDemoSample::handleEventBranchClosed(const CEGUI::EventArgs& args) - { - using namespace CEGUI; - - const TreeEventArgs& treeArgs = static_cast(args); - Editbox *editBox = (Editbox *)TreeDemoWindow->getChild(EditBoxID); - editBox->setText("Closed: " + treeArgs.treeItem->getText()); - return true; - } - - -/************************************************************************* - Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() -{ - static TreeDemoSample sample; - return sample; -} \ No newline at end of file diff --git a/samples/Tree/Tree.cpp b/samples/Tree/Tree.cpp new file mode 100644 index 000000000..2318ef666 --- /dev/null +++ b/samples/Tree/Tree.cpp @@ -0,0 +1,341 @@ +/************************************************************************ + created: 10/17/2004 + author: David Durant (based on code by Paul D Turner) +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "Tree.h" +#include "CEGUI/CEGUI.h" + +#if defined( __WIN32__ ) || defined( _WIN32 ) +#define WIN32_LEAN_AND_MEAN +#include "windows.h" +#include +#endif + +#include +#include + + +const unsigned int TreeSample::TreeID = 1; +const unsigned int TreeSample::EditBoxID = 2; + +#define USE_VANILLA 0 + + +#if USE_VANILLA +#define SCHEME_FILE_NAME "VanillaSkin.scheme" +#define IMAGES_FILE_NAME "Vanilla-Images" +#define STATICIMAGE_NAME "Vanilla/StaticImage" +#define TOOLTIP_NAME "Vanilla/Tooltip" +#define LAYOUT_FILE_NAME "TreeSample.layout" +#define BRUSH_NAME "GenericBrush" +#else +#define SCHEME_FILE_NAME "TaharezLook.scheme" +#define IMAGES_FILE_NAME "TaharezLook" +#define STATICIMAGE_NAME "TaharezLook/StaticImage" +#define TOOLTIP_NAME "TaharezLook/Tooltip" +#define LAYOUT_FILE_NAME "TreeSampleTaharez.layout" +#define BRUSH_NAME "/TextSelectionBrush" +#endif + + +int randInt(int low, int high) + { + int num; + CEGUI::uint32 range; + + range = high - low + 1; + if (range > RAND_MAX) + num = (int)(((CEGUI::uint32)rand() * (CEGUI::uint32)rand()) % range); + else + num = (rand()) % range; + + return(num + low); + } + + +////////////////////////////////////////////////////////////////////////// +/************************************************************************* + + TreeSample class + +*************************************************************************/ +////////////////////////////////////////////////////////////////////////// + +TreeSample::TreeSample() +{ + Sample::d_name = "TreeSample"; + Sample::d_credits = "David Durant"; + Sample::d_description = + "The Tree sample contains a tree of items that can be expanded and collapsed."; + Sample::d_summary = + "The sample showcases the \"CEGUI/Tree\" functionality. " + "The \"TaharezLook/Tree\" widget is used for this purpose."; +} + +/************************************************************************* +Sample specific initialisation goes here. +*************************************************************************/ +bool TreeSample::initialise(CEGUI::GUIContext* guiContext) +{ + using namespace CEGUI; + + d_usedFiles = String(__FILE__); + + TreeWidget* theTree; + StandardItem* newTreeCtrlEntryLvl1; // Level 1 TreeCtrlEntry (branch) + StandardItem* newTreeCtrlEntryLvl2; // Level 2 TreeCtrlEntry (branch) + StandardItem* newTreeCtrlEntryLvl3; // Level 3 TreeCtrlEntry (branch) + StandardItem* newTreeCtrlEntryParent; + Image * iconArray[9]; + +#if defined( __WIN32__ ) || defined( _WIN32 ) + // Windows specific code. + srand(static_cast(time(NULL))); +#endif + + // Get window manager which we will use for a few jobs here. + WindowManager& winMgr = WindowManager::getSingleton(); + + // load font and setup default if not loaded via scheme + Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + // Set default font for the gui context + guiContext->setDefaultFont(&defaultFont); + + // Load the scheme to initialise the skin which we use in this sample + SchemeManager::getSingleton().createFromFile(SCHEME_FILE_NAME); + + // set default cursor image + guiContext->getCursor().setDefaultImage(IMAGES_FILE_NAME "/MouseArrow"); + + // load an image to use as a background + if (!ImageManager::getSingleton().isDefined("SpaceBackgroundImage")) + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + + // Load some icon images for our test tree + ImageManager::getSingleton().loadImageset("DriveIcons.imageset"); + + // here we will use a StaticImage as the root, then we can use it to place a background image + Window* background = winMgr.createWindow(STATICIMAGE_NAME); + + // set area rectangle + background->setArea(URect(cegui_reldim(0), cegui_reldim(0), cegui_reldim(1), cegui_reldim(1))); + // disable frame and standard background + background->setProperty("FrameEnabled", "false"); + background->setProperty("BackgroundEnabled", "false"); + // set the background image + background->setProperty("Image", "SpaceBackgroundImage"); + // install this as the root GUI sheet + guiContext->setRootWindow(background); + + FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); + + d_rootWindow = winMgr.loadLayoutFromFile(LAYOUT_FILE_NAME); + + background->addChild(d_rootWindow); + + theTree = static_cast(d_rootWindow->getChild(TreeID)); + theTree->setSelectionBrushImage(IMAGES_FILE_NAME BRUSH_NAME); + theTree->subscribeEvent(TreeWidget::EventSelectionChanged, Event::Subscriber(&TreeSample::handleEventSelectionChanged, this)); + theTree->subscribeEvent(TreeWidget::EventSubtreeExpanded, Event::Subscriber(&TreeSample::handleEventSubtreeExpanded, this)); + theTree->subscribeEvent(TreeWidget::EventSubtreeCollapsed, Event::Subscriber(&TreeSample::handleEventSubtreeCollapsed, this)); + + // activate the background window + background->activate(); + + iconArray[0] = &ImageManager::getSingleton().get("DriveIcons/Artic"); + iconArray[1] = &ImageManager::getSingleton().get("DriveIcons/Black"); + iconArray[2] = &ImageManager::getSingleton().get("DriveIcons/Sunset"); + iconArray[3] = &ImageManager::getSingleton().get("DriveIcons/DriveStack"); + iconArray[4] = &ImageManager::getSingleton().get("DriveIcons/GlobalDrive"); + iconArray[5] = &ImageManager::getSingleton().get("DriveIcons/Blue"); + iconArray[6] = &ImageManager::getSingleton().get("DriveIcons/Lime"); + iconArray[7] = &ImageManager::getSingleton().get("DriveIcons/Silver"); + iconArray[8] = &ImageManager::getSingleton().get("DriveIcons/GreenCandy"); + + // Create a top-most TreeCtrlEntry + newTreeCtrlEntryLvl1 = new StandardItem("Tree Item Level 1a", "DriveIcons/Black"); + theTree->addItem(newTreeCtrlEntryLvl1); + + // Create a second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry + newTreeCtrlEntryLvl2 = new StandardItem("Tree Item Level 2a (1a)"); + newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); + // Create a third-level TreeCtrlEntry and attach it to the above TreeCtrlEntry + newTreeCtrlEntryLvl3 = new StandardItem("Tree Item Level 3a (2a)", "DriveIcons/Blue"); + newTreeCtrlEntryLvl2->addItem(newTreeCtrlEntryLvl3); + // Create another third-level TreeCtrlEntry and attach it to the above TreeCtrlEntry + newTreeCtrlEntryLvl3 = new StandardItem("Tree Item Level 3b (2a)", "DriveIcons/Lime"); + newTreeCtrlEntryLvl2->addItem(newTreeCtrlEntryLvl3); + // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry + newTreeCtrlEntryLvl2 = new StandardItem("Tree Item Level 2b (1a)", "DriveIcons/Sunset"); + newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); + // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry + newTreeCtrlEntryLvl2 = new StandardItem("Tree Item Level 2c (1a)", "DriveIcons/Silver"); + newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); + + // Create another top-most TreeCtrlEntry + newTreeCtrlEntryLvl1 = new StandardItem("Tree Item Level 1b", "DriveIcons/DriveStack"); + theTree->addItem(newTreeCtrlEntryLvl1); + // Create a second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry + newTreeCtrlEntryLvl2 = new StandardItem("Tree Item Level 2a (1b)"); + newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); + // Create another second-level TreeCtrlEntry and attach it to the top-most TreeCtrlEntry + newTreeCtrlEntryLvl2 = new StandardItem("Tree Item Level 2b (1b)"); + newTreeCtrlEntryLvl1->addItem(newTreeCtrlEntryLvl2); + + newTreeCtrlEntryLvl1 = new StandardItem("Tree Item Level 1c"); + theTree->addItem(newTreeCtrlEntryLvl1); + + // Now let's create a whole bunch of items automatically + int levelIndex = 3; + int idepthIndex; + int childIndex; + int childCount; + unsigned int iconIndex; + String itemText; + while (levelIndex < 10) + { + idepthIndex = 0; + itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex); + newTreeCtrlEntryLvl1 = new StandardItem(itemText); + // Set a random icon for the item. Sometimes blank (on purpose). + iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0])) + 2); + if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) + newTreeCtrlEntryLvl1->setIcon((*iconArray[iconIndex]).getName()); + theTree->addItem(newTreeCtrlEntryLvl1); + newTreeCtrlEntryParent = newTreeCtrlEntryLvl1; + + childIndex = 0; + childCount = randInt(0, 3); + while (childIndex < childCount) + { + itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex + 1) + " Child " + PropertyHelper::toString(childIndex + 1); + newTreeCtrlEntryLvl2 = new StandardItem(itemText); + // Set a random icon for the item. Sometimes blank (on purpose). + iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2)); + if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) + newTreeCtrlEntryLvl2->setIcon((*iconArray[iconIndex]).getName()); + newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2); + ++childIndex; + } + + while (idepthIndex < 15) + { + itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex + 1); + newTreeCtrlEntryLvl2 = new StandardItem(itemText); + // Set a random icon for the item. Sometimes blank (on purpose). + iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2)); + if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) + newTreeCtrlEntryLvl2->setIcon((*iconArray[iconIndex]).getName()); + newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2); + newTreeCtrlEntryParent = newTreeCtrlEntryLvl2; + + childIndex = 0; + childCount = randInt(0, 3); + while (childIndex < childCount) + { + itemText = "Tree Item Level " + PropertyHelper::toString(levelIndex) + " Depth " + PropertyHelper::toString(idepthIndex + 1) + " Child " + PropertyHelper::toString(childIndex + 1); + newTreeCtrlEntryLvl2 = new StandardItem(itemText); + // Set a random icon for the item. Sometimes blank (on purpose). + iconIndex = randInt(0, (sizeof(iconArray) / sizeof(iconArray[0]) + 2)); + if (iconIndex < sizeof(iconArray) / sizeof(iconArray[0])) + newTreeCtrlEntryLvl2->setIcon((*iconArray[iconIndex]).getName()); + newTreeCtrlEntryParent->addItem(newTreeCtrlEntryLvl2); + ++childIndex; + } + ++idepthIndex; + } + ++levelIndex; + } + + return true; +} + + +/************************************************************************* +Cleans up resources allocated in the initialiseSample call. +*************************************************************************/ +void TreeSample::deinitialise() +{ +} + + +bool TreeSample::handleEventSelectionChanged(const CEGUI::EventArgs& args) +{ + using namespace CEGUI; + + const ItemViewEventArgs& treeArgs = static_cast(args); + Editbox *editBox = (Editbox *)d_rootWindow->getChild(EditBoxID); + + TreeWidget* tree = static_cast(treeArgs.window); + // Three different ways to get the item selected. + // TreeCtrlEntry *selectedItem = theTree->getFirstSelectedItem(); // the first selection in the list (may be more) + // TreeCtrlEntry *selectedItem = theTree->getLastSelectedItem(); // the last (time-wise) selected by the user + StandardItem* selectedItem = tree->getModel()->getItemForIndex(treeArgs.d_index); // the actual item that caused this event + + if (selectedItem) + { +#if 0 + // A convoluted way to get the item text. + // Just here to test findFirstItemWithText. + selectedItem = theTree->findFirstItemWithText(selectedItem->getText()); + if (selectedItem) + editBox->setText("Selected: " + selectedItem->getText()); + else + editBox->setText("findItemWithText failed!"); +#else + // The simple way to do it. + editBox->setText("Selected: " + selectedItem->getText()); +#endif + } + else + editBox->setText("None Selected"); + + return true; +} + +bool TreeSample::handleEventSubtreeExpanded(const CEGUI::EventArgs& args) +{ + using namespace CEGUI; + + const ItemViewEventArgs& treeArgs = static_cast(args); + Editbox *editBox = (Editbox *)d_rootWindow->getChild(EditBoxID); + TreeWidget* tree = static_cast(treeArgs.window); + StandardItem* expanded_item = tree->getModel()->getItemForIndex(treeArgs.d_index); + editBox->setText("Opened: " + expanded_item->getText()); + return true; +} + + +bool TreeSample::handleEventSubtreeCollapsed(const CEGUI::EventArgs& args) +{ + using namespace CEGUI; + + const ItemViewEventArgs& treeArgs = static_cast(args); + Editbox *editBox = (Editbox *)d_rootWindow->getChild(EditBoxID); + TreeWidget* tree = static_cast(treeArgs.window); + StandardItem* collapsed_item = tree->getModel()->getItemForIndex(treeArgs.d_index); + editBox->setText("Closed: " + collapsed_item->getText()); + return true; +} diff --git a/samples/Tree/Sample_TreeDemo.h b/samples/Tree/Tree.h similarity index 81% rename from samples/Tree/Sample_TreeDemo.h rename to samples/Tree/Tree.h index eec0af2d8..82e54a06f 100644 --- a/samples/Tree/Sample_TreeDemo.h +++ b/samples/Tree/Tree.h @@ -24,32 +24,33 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_TreeDemo_h_ -#define _Sample_TreeDemo_h_ +#ifndef _Sample_TreeSample_h_ +#define _Sample_TreeSample_h_ #include "SampleBase.h" #include "CEGUI/CEGUI.h" -class TreeDemoSample : public Sample - { +class TreeSample : public Sample +{ public: - // method to initialse the samples windows and events. + TreeSample(); + + // method to initialise the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); // method to perform any required cleanup operations. virtual void deinitialise(); protected: - CEGUI::Window* TreeDemoWindow; + CEGUI::Window* d_rootWindow; static const unsigned int TreeID; static const unsigned int EditBoxID; - bool handleRootKeyDown(const CEGUI::EventArgs& args); bool handleEventSelectionChanged(const CEGUI::EventArgs& args); - bool handleEventBranchOpened(const CEGUI::EventArgs& args); - bool handleEventBranchClosed(const CEGUI::EventArgs& args); - }; + bool handleEventSubtreeExpanded(const CEGUI::EventArgs& args); + bool handleEventSubtreeCollapsed(const CEGUI::EventArgs& args); +}; -#endif // end of guard _Sample_TreeDemo_h_ +#endif // end of guard _Sample_TreeSample_h_ diff --git a/samples/Widgets/CMakeLists.txt b/samples/Widgets/CMakeLists.txt index 6c41f2153..1250b12fd 100644 --- a/samples/Widgets/CMakeLists.txt +++ b/samples/Widgets/CMakeLists.txt @@ -1,25 +1,32 @@ -option(CEGUI_SAMPLES_ENABLE_WIDGETS "Specifies whether this sample should be built or not" TRUE) -if(CEGUI_SAMPLES_ENABLE_WIDGETS) - file(GLOB WIDGET_HEADERS "${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/widgets/*.h") - list(APPEND WIDGET_HEADERS "${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/Window.h") - - set(ALL_EVENTS_CODE "std::set allEvents;") - - foreach (WIDGET_HEADER ${WIDGET_HEADERS}) - file(READ "${WIDGET_HEADER}" HEADER_SOURCE) - string(REGEX MATCHALL "static const String Event[^;]+" MATCHED_LINES "${HEADER_SOURCE}") - foreach (MATCHED_LINE ${MATCHED_LINES}) - string(REGEX REPLACE "static const String Event([^;]+)" "\\1" CAPTURE_GROUP "${MATCHED_LINE}") - if (NOT CAPTURE_GROUP STREQUAL "Namespace") - set(ALL_EVENTS_CODE "${ALL_EVENTS_CODE}\nallEvents.insert(\"${CAPTURE_GROUP}\");") - endif() - endforeach() +file(GLOB WIDGET_HEADERS "${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/widgets/*.h") +list(APPEND WIDGET_HEADERS "${CMAKE_SOURCE_DIR}/cegui/include/CEGUI/Window.h") + +set(ALL_EVENTS_CODE "std::set allEvents;") + +foreach(WIDGET_HEADER ${WIDGET_HEADERS}) + file(READ "${WIDGET_HEADER}" HEADER_SOURCE) + string(REGEX MATCHALL "static const String Event[^;]+" MATCHED_LINES "${HEADER_SOURCE}") + foreach(MATCHED_LINE ${MATCHED_LINES}) + string(REGEX REPLACE "static const String Event([^;]+)" "\\1" CAPTURE_GROUP "${MATCHED_LINE}") + if(NOT CAPTURE_GROUP STREQUAL "Namespace") + set(ALL_EVENTS_CODE "${ALL_EVENTS_CODE}\nallEvents.insert(\"${CAPTURE_GROUP}\");") + endif() endforeach() - - file(WRITE ${CMAKE_BINARY_DIR}/samples/common/include/AllEvents.inc "${ALL_EVENTS_CODE}") +endforeach() + +file(WRITE ${CMAKE_BINARY_DIR}/samples/common/include/AllEvents.inc "${ALL_EVENTS_CODE}") + +# Retrieve the current folder's name and generate the names that we will use for the variables containing the headers and source of this Sample +get_filename_component(SAMPLE_PARENT_DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME) +set(SAMPLE_HEADER_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_HEADERS") +set(SAMPLE_SOURCE_LIST_NAME "${SAMPLE_PARENT_DIR_NAME}_SAMPLE_SOURCES") + +# Append the samples names to the list and make the list visible outside this scope +list(APPEND SAMPLES_LIST "${SAMPLE_PARENT_DIR_NAME}") +set(SAMPLES_LIST "${SAMPLES_LIST}" PARENT_SCOPE) - include_directories(${CMAKE_BINARY_DIR}/samples/common/include) - - - cegui_add_sample(CEGUISample_Widgets) -endif() \ No newline at end of file +# Retrieve all headers and source files in this sample's folder and make the variables visible outside this scope +file(GLOB ${SAMPLE_HEADER_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.h) +file(GLOB ${SAMPLE_SOURCE_LIST_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) +set(${SAMPLE_HEADER_LIST_NAME} "${${SAMPLE_HEADER_LIST_NAME}}" PARENT_SCOPE) +set(${SAMPLE_SOURCE_LIST_NAME} "${${SAMPLE_SOURCE_LIST_NAME}}" PARENT_SCOPE) \ No newline at end of file diff --git a/samples/Widgets/SampleMetaData.xml b/samples/Widgets/SampleMetaData.xml deleted file mode 100644 index 61e10372e..000000000 --- a/samples/Widgets/SampleMetaData.xml +++ /dev/null @@ -1,7 +0,0 @@ - diff --git a/samples/Widgets/WidgetsDemo.cpp b/samples/Widgets/Widgets.cpp similarity index 71% rename from samples/Widgets/WidgetsDemo.cpp rename to samples/Widgets/Widgets.cpp index 952a4b1d8..b683cdaf4 100644 --- a/samples/Widgets/WidgetsDemo.cpp +++ b/samples/Widgets/Widgets.cpp @@ -24,7 +24,7 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "WidgetsDemo.h" +#include "Widgets.h" #include "CEGUI/CEGUI.h" @@ -55,7 +55,7 @@ struct WidgetPropertiesObject { std::vector d_propertyList; const CEGUI::Window* d_widget; -}; +}; //----------------------------------------------------------------------------// // Helper class to deal with the different event names, used to output the name @@ -63,15 +63,15 @@ struct WidgetPropertiesObject //----------------------------------------------------------------------------// class EventHandlerObject { -public: - EventHandlerObject(CEGUI::String eventName, WidgetDemo* owner); +public: + EventHandlerObject(CEGUI::String eventName, WidgetsSample* owner); bool handleEvent(const CEGUI::EventArgs& args); private: CEGUI::String d_eventName; - WidgetDemo* d_owner; + WidgetsSample* d_owner; }; -EventHandlerObject::EventHandlerObject(CEGUI::String eventName, WidgetDemo* owner) +EventHandlerObject::EventHandlerObject(CEGUI::String eventName, WidgetsSample* owner) : d_eventName(eventName), d_owner(owner) { @@ -82,17 +82,17 @@ bool EventHandlerObject::handleEvent(const CEGUI::EventArgs& args) CEGUI::String logMessage = "[colour='FFFFBBBB']" + d_eventName + "[colour='FFFFFFFF']"; logMessage += CEGUI::String(" ("); - if(dynamic_cast(&args)) + if(dynamic_cast(&args)) { - logMessage += "MouseEvent"; + logMessage += "CursorInputEvent"; } - else if(dynamic_cast(&args)) + else if(dynamic_cast(&args)) { - logMessage += "MouseCursorEvent"; + logMessage += "CursorEvent"; } - else if(const CEGUI::KeyEventArgs* keyArgs = dynamic_cast(&args)) + else if(const CEGUI::TextEventArgs* textArgs = dynamic_cast(&args)) { - logMessage += "KeyEvent: '" + CEGUI::String(1, keyArgs->codepoint) + "'"; + logMessage += "TextEvent: '" + CEGUI::String(1, textArgs->character) + "'"; } else if(dynamic_cast(&args)) { @@ -107,7 +107,6 @@ bool EventHandlerObject::handleEvent(const CEGUI::EventArgs& args) logMessage += "DragDropEvent"; } - logMessage += CEGUI::String(")"); logMessage += "\n"; @@ -118,15 +117,40 @@ bool EventHandlerObject::handleEvent(const CEGUI::EventArgs& args) //----------------------------------------------------------------------------// -// The following are for the main WidgetDemo class. +// The following are for the main WidgetSample class. //----------------------------------------------------------------------------// /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ -const CEGUI::String WidgetDemo::s_widgetDemoWindowPrefix = "WidgetDemoWindow_"; +const CEGUI::String WidgetsSample::s_widgetSampleWindowPrefix = "WidgetSampleWindow_"; -bool WidgetDemo::initialise(CEGUI::GUIContext* guiContext) +WidgetsSample::WidgetsSample() : + Sample(89) +{ + Sample::d_name = "WidgetsSample"; + Sample::d_credits = "Lukas \"Ident\" Meindl"; + Sample::d_description = + "The widgets sample allows to choose any of widgets from the stock " + "CEGUI skins. The widget will then be displayed and is ready for " + "interaction. All occuring events will be logged in the event " + "logger below the widget display. By accessing the \"Properties\" " + "tab, the user can see all properties the widget has and " + "their respective current values."; + Sample::d_summary = + "The Sample's code is quite specific and probably not of use for most " + "projects using CEGUI. The main purpose of this sample is demonstration " + "of the widgets and their triggered effects. It makes use of the list " + "of mapped widgets and subscribes to all throwable events of it. The " + "properties are retrieved from the widget using the PropertyIterator. " + "The greatest use of this Sample for users is to see the available properties " + "of specific widgets and to interactively inspect how events are thrown and " + "how widgets look. Additionally the special setup of certain widgets, for " + "example in initItemListbox(), initListbox(), initMenubar() and " + "initMultiColumnList(), can be useful interesting to look at in the code"; +} + +bool WidgetsSample::initialise(CEGUI::GUIContext* guiContext) { using namespace CEGUI; @@ -139,7 +163,7 @@ bool WidgetDemo::initialise(CEGUI::GUIContext* guiContext) SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); SchemeManager::getSingleton().createFromFile("VanillaSkin.scheme"); SchemeManager::getSingleton().createFromFile("OgreTray.scheme"); - d_guiContext->getMouseCursor().setDefaultImage("Vanilla-Images/MouseArrow"); + d_guiContext->getCursor().setDefaultImage("Vanilla-Images/MouseArrow"); // load font and setup default if not loaded via scheme Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); @@ -148,30 +172,35 @@ bool WidgetDemo::initialise(CEGUI::GUIContext* guiContext) guiContext->setDefaultFont(&defaultFont); // load an image to use as a background - if( !ImageManager::getSingleton().isDefined("SpaceBackgroundImage") ) - ImageManager::getSingleton().addFromImageFile("SpaceBackgroundImage", "SpaceBackground.jpg"); + if (!ImageManager::getSingleton().isDefined("SpaceBackgroundImage")) + ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); // Retrieve the available widget types and save them inside a map initialiseAvailableWidgetsMap(); initialiseEventHandlerObjects(); d_currentlyDisplayedWidgetRoot = 0; - //Create windows and initialise them + //Create windows and initialise them createLayout(); - d_guiContext->subscribeEvent(CEGUI::GUIContext::EventRenderQueueEnded, Event::Subscriber(&WidgetDemo::handleRenderingEnded, this)); - d_guiContext->getRootWindow()->subscribeEvent(CEGUI::Window::EventUpdated, Event::Subscriber(&WidgetDemo::handleRootWindowUpdate, this)); + d_guiContext->subscribeEvent(CEGUI::GUIContext::EventRenderQueueEnded, Event::Subscriber(&WidgetsSample::handleRenderingEnded, this)); + d_guiContext->getRootWindow()->subscribeEvent(CEGUI::Window::EventUpdated, Event::Subscriber(&WidgetsSample::handleRootWindowUpdate, this)); - if(CEGUI::ListboxItem* skinItem = d_skinSelectionCombobox->getListboxItemFromIndex(0)) + if (CEGUI::StandardItem* skinItem = d_skinSelectionCombobox->getItemFromIndex(0)) { d_skinSelectionCombobox->setItemSelectState(skinItem, true); handleSkinSelectionAccepted(CEGUI::WindowEventArgs(d_skinSelectionCombobox)); } - if(CEGUI::ListboxItem* widgetItem = d_widgetSelectorListbox->getListboxItemFromIndex(0)) + if (d_widgetSelectorListWidget->getItemCount() > 0) { - d_widgetSelectorListbox->setItemSelectState(widgetItem, true); + d_widgetSelectorListWidget->setIndexSelectionState(static_cast(0), true); } + d_listItemModel.addItem("item 1"); + d_listItemModel.addItem("item 2"); + d_listItemModel.addItem("item 3"); + d_listItemModel.addItem("item 4"); + // success! return true; } @@ -179,9 +208,9 @@ bool WidgetDemo::initialise(CEGUI::GUIContext* guiContext) /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ -void WidgetDemo::deinitialise() +void WidgetsSample::deinitialise() { - if(d_currentlyDisplayedWidgetRoot != 0) + if (d_currentlyDisplayedWidgetRoot != 0) d_widgetDisplayWindowInnerWindow->removeChild(d_currentlyDisplayedWidgetRoot); destroyWidgetWindows(); @@ -189,7 +218,7 @@ void WidgetDemo::deinitialise() deinitWidgetListItems(); } -bool WidgetDemo::handleSkinSelectionAccepted(const CEGUI::EventArgs& args) +bool WidgetsSample::handleSkinSelectionAccepted(const CEGUI::EventArgs& args) { const WindowEventArgs& winArgs = static_cast(args); @@ -198,46 +227,47 @@ bool WidgetDemo::handleSkinSelectionAccepted(const CEGUI::EventArgs& args) WidgetListType& widgetsList = d_skinListItemsMap[schemeName]; - d_widgetSelectorListbox->resetList(); + d_widgetSelectorListWidget->clearList(); - for(unsigned int i = 0; i < widgetsList.size(); ++i) + for (unsigned int i = 0; i < widgetsList.size(); ++i) { MyListItem* item = widgetsList[i]; - d_widgetSelectorListbox->addItem(item); + d_widgetSelectorListWidget->addItem( + new StandardItem(item->getText(), item->getID())); } // event was handled return true; } -bool WidgetDemo::handleRenderingEnded(const CEGUI::EventArgs& args) +bool WidgetsSample::handleRenderingEnded(const CEGUI::EventArgs& args) { - d_windowLightMouseMoveEvent->disable(); + d_windowLightCursorMoveEvent->disable(); d_windowLightUpdatedEvent->disable(); return true; } -bool WidgetDemo::handleRootWindowUpdate(const CEGUI::EventArgs& args) +bool WidgetsSample::handleRootWindowUpdate(const CEGUI::EventArgs& args) { const CEGUI::UpdateEventArgs& updateArgs = static_cast(args); float passedTime = updateArgs.d_timeSinceLastFrame; - if(d_currentlyDisplayedWidgetRoot == 0) + if (d_currentlyDisplayedWidgetRoot == 0) return true; CEGUI::ProgressBar* progressBar = dynamic_cast(d_currentlyDisplayedWidgetRoot); - if(progressBar != 0) + if (progressBar != 0) { float newProgress = progressBar->getProgress() + passedTime * 0.2f; - if(newProgress < 1.0f) + if (newProgress < 1.0f) progressBar->setProgress(newProgress); } return true; } -bool WidgetDemo::handleWidgetSelectionChanged(const CEGUI::EventArgs& args) +bool WidgetsSample::handleWidgetSelectionChanged(const CEGUI::EventArgs& args) { const WindowEventArgs& winArgs = static_cast(args); @@ -246,14 +276,14 @@ bool WidgetDemo::handleWidgetSelectionChanged(const CEGUI::EventArgs& args) CEGUI::String widgetTypeString; bool typesFound = getWidgetType(widgetName, widgetTypeString); - if(!typesFound) + if (!typesFound) return true; //Clear events log d_widgetsEventsLog->setText(""); //Remove previous children window from the widget-display window - if(d_currentlyDisplayedWidgetRoot) + if (d_currentlyDisplayedWidgetRoot) d_widgetDisplayWindowInnerWindow->removeChild(d_currentlyDisplayedWidgetRoot); //Get the widget root window @@ -275,13 +305,13 @@ bool WidgetDemo::handleWidgetSelectionChanged(const CEGUI::EventArgs& args) } -void WidgetDemo::initialiseAvailableWidgetsMap() +void WidgetsSample::initialiseAvailableWidgetsMap() { //Retrieve the widget look types and add a Listboxitem for each widget, to the right scheme in the map CEGUI::WindowFactoryManager& windowFactorymanager = CEGUI::WindowFactoryManager::getSingleton(); CEGUI::WindowFactoryManager::FalagardMappingIterator falMappingIter = windowFactorymanager.getFalagardMappingIterator(); - while(!falMappingIter.isAtEnd()) + while (!falMappingIter.isAtEnd()) { CEGUI::String falagardBaseType = falMappingIter.getCurrentValue().d_windowType; @@ -289,11 +319,11 @@ void WidgetDemo::initialiseAvailableWidgetsMap() CEGUI::String group = falagardBaseType.substr(0, slashPos); CEGUI::String name = falagardBaseType.substr(slashPos + 1, falagardBaseType.size() - 1); - if(group.compare("SampleBrowserSkin") != 0) + if (group.compare("SampleBrowserSkin") != 0) { std::map::iterator iter = d_skinListItemsMap.find(group); - if(iter == d_skinListItemsMap.end()) + if (iter == d_skinListItemsMap.end()) { //Create new list d_skinListItemsMap[group]; @@ -318,7 +348,7 @@ void WidgetDemo::initialiseAvailableWidgetsMap() } -void WidgetDemo::createLayout() +void WidgetsSample::createLayout() { // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = WindowManager::getSingleton().createWindow("TaharezLook/StaticImage", "BackgroundWindow"); @@ -331,7 +361,7 @@ void WidgetDemo::createLayout() initialiseWidgetInspector(background); } -void WidgetDemo::initialiseSkinCombobox(CEGUI::Window* container) +void WidgetsSample::initialiseSkinCombobox(CEGUI::Window* container) { WindowManager& winMgr = WindowManager::getSingleton(); @@ -346,12 +376,12 @@ void WidgetDemo::initialiseSkinCombobox(CEGUI::Window* container) d_skinSelectionCombobox->setReadOnly(true); d_skinSelectionCombobox->setSortingEnabled(false); - d_skinSelectionCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, Event::Subscriber(&WidgetDemo::handleSkinSelectionAccepted, this)); + d_skinSelectionCombobox->subscribeEvent(CEGUI::Combobox::EventListSelectionAccepted, Event::Subscriber(&WidgetsSample::handleSkinSelectionAccepted, this)); std::map::iterator iter = d_skinListItemsMap.begin(); - while(iter != d_skinListItemsMap.end()) + while (iter != d_skinListItemsMap.end()) { - d_skinSelectionCombobox->addItem(new MyListItem(iter->first)); + d_skinSelectionCombobox->addItem(new StandardItem(iter->first)); ++iter; } @@ -360,29 +390,30 @@ void WidgetDemo::initialiseSkinCombobox(CEGUI::Window* container) container->addChild(skinSelectionComboboxLabel); } -void WidgetDemo::initialiseBackgroundWindow(CEGUI::Window* background) +void WidgetsSample::initialiseBackgroundWindow(CEGUI::Window* background) { - background->setPosition(UVector2(cegui_reldim(0), cegui_reldim( 0))); - background->setSize(USize(cegui_reldim(1), cegui_reldim( 1))); + background->setPosition(UVector2(cegui_reldim(0), cegui_reldim(0))); + background->setSize(USize(cegui_reldim(1), cegui_reldim(1))); background->setProperty("FrameEnabled", "false"); background->setProperty("BackgroundEnabled", "false"); background->setProperty("Image", "SpaceBackgroundImage"); } -void WidgetDemo::initialiseWidgetSelectorListbox() +void WidgetsSample::initialiseWidgetSelectorListWidget() { WindowManager& winMgr = WindowManager::getSingleton(); - d_widgetSelectorListbox = static_cast(winMgr.createWindow("Vanilla/Listbox", "WidgetSelectorListbox")); - d_widgetSelectorListbox->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.075f))); - d_widgetSelectorListbox->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.925f))); - d_widgetSelectorListbox->setShowVertScrollbar(false); - d_widgetSelectorListbox->setSortingEnabled(true); + d_widgetSelectorListWidget = static_cast(winMgr.createWindow("Vanilla/ListWidget", "WidgetSelectorListWidget")); + d_widgetSelectorListWidget->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.075f))); + d_widgetSelectorListWidget->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.925f))); + d_widgetSelectorListWidget->setVertScrollbarDisplayMode(SDM_WhenNeeded); + d_widgetSelectorListWidget->setSortMode(VSM_Ascending); - d_widgetSelectorListbox->subscribeEvent(CEGUI::Listbox::EventSelectionChanged, Event::Subscriber(&WidgetDemo::handleWidgetSelectionChanged, this)); + d_widgetSelectorListWidget->subscribeEvent(ListWidget::EventSelectionChanged, + Event::Subscriber(&WidgetsSample::handleWidgetSelectionChanged, this)); } -void WidgetDemo::initialiseWidgetSelectorContainer(CEGUI::Window* widgetSelectorContainer) +void WidgetsSample::initialiseWidgetSelectorContainer(CEGUI::Window* widgetSelectorContainer) { widgetSelectorContainer->setPosition(CEGUI::UVector2(cegui_reldim(0.6f), cegui_reldim(0.25f))); widgetSelectorContainer->setSize(CEGUI::USize(cegui_reldim(0.325f), cegui_reldim(0.56f))); @@ -391,7 +422,7 @@ void WidgetDemo::initialiseWidgetSelectorContainer(CEGUI::Window* widgetSelector widgetSelectorContainer->setProperty("HorzFormatting", "CentreAligned"); } -void WidgetDemo::initialiseWidgetsEventsLog() +void WidgetsSample::initialiseWidgetsEventsLog() { WindowManager& winMgr = WindowManager::getSingleton(); @@ -400,7 +431,7 @@ void WidgetDemo::initialiseWidgetsEventsLog() d_widgetsEventsLog->setSize(CEGUI::USize(cegui_reldim(0.9f), cegui_reldim(0.25f))); d_widgetsEventsLog->setFont("DejaVuSans-12"); - d_widgetsEventsLog->setProperty("VertScrollbar", "true"); + d_widgetsEventsLog->setProperty("VertScrollbar", "true"); d_widgetsEventsLog->setProperty("HorzFormatting", "WordWrapLeftAligned"); @@ -410,19 +441,19 @@ void WidgetDemo::initialiseWidgetsEventsLog() /************************************************************************* Helper function to add MyListItem's to the widget list *************************************************************************/ -void WidgetDemo::addItemToWidgetList(const CEGUI::String& widgetName, WidgetListType &widgetList) +void WidgetsSample::addItemToWidgetList(const CEGUI::String& widgetName, WidgetListType &widgetList) { MyListItem* widgetListItem = new MyListItem(widgetName); widgetListItem->setAutoDeleted(false); widgetList.push_back(widgetListItem); } -void WidgetDemo::initialiseEventHandlerObjects() +void WidgetsSample::initialiseEventHandlerObjects() { #include "AllEvents.inc" std::set::iterator iter = allEvents.begin(); - while(iter != allEvents.end()) + while (iter != allEvents.end()) { addEventHandlerObjectToMap(*iter); @@ -430,18 +461,18 @@ void WidgetDemo::initialiseEventHandlerObjects() } } -CEGUI::Window* WidgetDemo::createWidget(const CEGUI::String &widgetMapping, const CEGUI::String &widgetType) +CEGUI::Window* WidgetsSample::createWidget(const CEGUI::String &widgetMapping, const CEGUI::String &widgetType) { //Create default widget of the selected type CEGUI::WindowManager& windowManager = CEGUI::WindowManager::getSingleton(); - CEGUI::Window* widgetWindow = windowManager.createWindow(widgetMapping, s_widgetDemoWindowPrefix + widgetMapping); + CEGUI::Window* widgetWindow = windowManager.createWindow(widgetMapping, s_widgetSampleWindowPrefix + widgetMapping); //Subscribe to all possible events the window could fire, the handler will output them to the log subscribeToAllEvents(widgetWindow); //Set a default text - for Spinners we set no text so it won't cause an exception - CEGUI::Spinner* spinner = dynamic_cast(widgetWindow); - if(!spinner) + CEGUI::Spinner* spinner = dynamic_cast(widgetWindow); + if (!spinner) widgetWindow->setText(widgetType); //Create extra widgets and special setups for certain widget types for better demonstration @@ -454,13 +485,13 @@ CEGUI::Window* WidgetDemo::createWidget(const CEGUI::String &widgetMapping, cons } -void WidgetDemo::handleWidgetEventFired(const CEGUI::String& eventName, CEGUI::String logMessage) +void WidgetsSample::handleWidgetEventFired(const CEGUI::String& eventName, CEGUI::String logMessage) { - if(eventName == CEGUI::Window::EventMouseMove) + if (eventName == CEGUI::Window::EventCursorMove) { - d_windowLightMouseMoveEvent->enable(); + d_windowLightCursorMoveEvent->enable(); } - else if(eventName == CEGUI::Window::EventUpdated) + else if (eventName == CEGUI::Window::EventUpdated) { d_windowLightUpdatedEvent->enable(); } @@ -470,36 +501,36 @@ void WidgetDemo::handleWidgetEventFired(const CEGUI::String& eventName, CEGUI::S } } -void WidgetDemo::addEventHandlerObjectToMap(CEGUI::String eventName) +void WidgetsSample::addEventHandlerObjectToMap(CEGUI::String eventName) { d_eventHandlerObjectsMap[eventName] = new EventHandlerObject(eventName, this); } -void WidgetDemo::deinitWidgetListItems() +void WidgetsSample::deinitWidgetListItems() { std::map::iterator iter = d_skinListItemsMap.begin(); - while(iter != d_skinListItemsMap.end()) + while (iter != d_skinListItemsMap.end()) { WidgetListType& widgetsList = iter->second; - while(widgetsList.size() > 0) + while (widgetsList.size() > 0) { MyListItem* item = widgetsList.back(); - d_widgetSelectorListbox->removeItem(item); delete item; widgetsList.pop_back(); } ++iter; } + d_widgetSelectorListWidget->clearList(); } -void WidgetDemo::destroyWidgetWindows() +void WidgetsSample::destroyWidgetWindows() { CEGUI::WindowManager& winMan = CEGUI::WindowManager::getSingleton(); std::map::iterator iter = d_widgetsMap.begin(); - while(iter != d_widgetsMap.end()) + while (iter != d_widgetsMap.end()) { winMan.destroyWindow(iter->second); @@ -507,7 +538,7 @@ void WidgetDemo::destroyWidgetWindows() } } -void WidgetDemo::initialiseEventLights(CEGUI::Window* container) +void WidgetsSample::initialiseEventLights(CEGUI::Window* container) { CEGUI::WindowManager &winMgr = CEGUI::WindowManager::getSingleton(); @@ -529,24 +560,24 @@ void WidgetDemo::initialiseEventLights(CEGUI::Window* container) updateEventLabel->setFont("DejaVuSans-12-NoScale"); updateEventLabel->setProperty("HorzFormatting", "LeftAligned"); - d_windowLightMouseMoveEvent = winMgr.createWindow("SampleBrowserSkin/Light"); - horizontalLayout->addChild(d_windowLightMouseMoveEvent); - d_windowLightMouseMoveEvent->setSize(CEGUI::USize(cegui_reldim(0.0f), cegui_reldim(0.04f))); - d_windowLightMouseMoveEvent->setAspectMode(CEGUI::AM_EXPAND); - d_windowLightMouseMoveEvent->setProperty("LightColour", "FF77BBFF"); - - CEGUI::Window* mouseMoveEventLabel = winMgr.createWindow("Vanilla/Label"); - horizontalLayout->addChild(mouseMoveEventLabel); - mouseMoveEventLabel->setSize(CEGUI::USize(cegui_reldim(0.25f), cegui_reldim(0.04f))); - mouseMoveEventLabel->setText("EventMouseMove"); - mouseMoveEventLabel->setFont("DejaVuSans-12-NoScale"); - mouseMoveEventLabel->setProperty("HorzFormatting", "LeftAligned"); + d_windowLightCursorMoveEvent = winMgr.createWindow("SampleBrowserSkin/Light"); + horizontalLayout->addChild(d_windowLightCursorMoveEvent); + d_windowLightCursorMoveEvent->setSize(CEGUI::USize(cegui_reldim(0.0f), cegui_reldim(0.04f))); + d_windowLightCursorMoveEvent->setAspectMode(CEGUI::AM_EXPAND); + d_windowLightCursorMoveEvent->setProperty("LightColour", "FF77BBFF"); + + CEGUI::Window* cursor_move_event_label = winMgr.createWindow("Vanilla/Label"); + horizontalLayout->addChild(cursor_move_event_label); + cursor_move_event_label->setSize(CEGUI::USize(cegui_reldim(0.25f), cegui_reldim(0.04f))); + cursor_move_event_label->setText("EventCursorMove"); + cursor_move_event_label->setFont("DejaVuSans-12-NoScale"); + cursor_move_event_label->setProperty("HorzFormatting", "LeftAligned"); } -void WidgetDemo::logFiredEvent(const CEGUI::String& logMessage) +void WidgetsSample::logFiredEvent(const CEGUI::String& logMessage) { - ListboxItem* item = d_widgetSelectorListbox->getFirstSelectedItem(); - if(!item) + StandardItem* item = d_widgetSelectorListWidget->getFirstSelectedItem(); + if (!item) return; CEGUI::String eventsLog = d_widgetsEventsLog->getText(); @@ -556,10 +587,10 @@ void WidgetDemo::logFiredEvent(const CEGUI::String& logMessage) int pos = std::max(static_cast(eventsLog.length() - 2056), 0); int len = std::min(static_cast(eventsLog.length()), 2056); eventsLog = eventsLog.substr(pos, len); - if(len == 2056) + if (len == 2056) { int newlinePos = eventsLog.find_first_of("\n"); - if(newlinePos != std::string::npos) + if (newlinePos != std::string::npos) eventsLog = eventsLog.substr(newlinePos, std::string::npos); } d_widgetsEventsLog->setText(eventsLog); @@ -569,11 +600,11 @@ void WidgetDemo::logFiredEvent(const CEGUI::String& logMessage) scrollbar->setScrollPosition(scrollbar->getDocumentSize() - scrollbar->getPageSize()); } -void WidgetDemo::subscribeToAllEvents(CEGUI::Window* widgetWindow) +void WidgetsSample::subscribeToAllEvents(CEGUI::Window* widgetWindow) { //Register all events for the widget window std::map::iterator iter = d_eventHandlerObjectsMap.begin(); - while(iter != d_eventHandlerObjectsMap.end()) + while (iter != d_eventHandlerObjectsMap.end()) { widgetWindow->subscribeEvent(iter->first, Event::Subscriber(&EventHandlerObject::handleEvent, iter->second)); @@ -581,16 +612,16 @@ void WidgetDemo::subscribeToAllEvents(CEGUI::Window* widgetWindow) } } -CEGUI::Window* WidgetDemo::initialiseSpecialWidgets(CEGUI::Window* widgetWindow, const CEGUI::String &widgetType) +CEGUI::Window* WidgetsSample::initialiseSpecialWidgets(CEGUI::Window* widgetWindow, const CEGUI::String &widgetType) { CEGUI::RadioButton* radioButton = dynamic_cast(widgetWindow); - if(radioButton) + if (radioButton) { initRadioButtons(radioButton, widgetWindow); } CEGUI::MultiLineEditbox* multilineEditbox = dynamic_cast(widgetWindow); - if(multilineEditbox || widgetType.compare("StaticText") == 0) + if (multilineEditbox || widgetType.compare("StaticText") == 0) { widgetWindow->setText("Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt" "ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco" @@ -598,58 +629,52 @@ CEGUI::Window* WidgetDemo::initialiseSpecialWidgets(CEGUI::Window* widgetWindow, "Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."); } - if(widgetType.compare("CaptionedStaticText") == 0) + if (widgetType.compare("CaptionedStaticText") == 0) { widgetWindow->setProperty("Text", "Caption"); } - if(widgetType.compare("StaticText") == 0) + if (widgetType.compare("StaticText") == 0) { - if(widgetWindow->isPropertyPresent("VertScrollbar")) - widgetWindow->setProperty("VertScrollbar", "true"); + if (widgetWindow->isPropertyPresent("VertScrollbar")) + widgetWindow->setProperty("VertScrollbar", "true"); - if(widgetWindow->isPropertyPresent("HorzFormatting")) + if (widgetWindow->isPropertyPresent("HorzFormatting")) widgetWindow->setProperty("HorzFormatting", "WordWrapLeftAligned"); } - if(widgetType.compare("StaticImage") == 0) + if (widgetType.compare("StaticImage") == 0) { widgetWindow->setProperty("Image", "SpaceBackgroundImage"); } - CEGUI::Listbox* listbox = dynamic_cast(widgetWindow); - if(listbox) + ListView* list_view = dynamic_cast(widgetWindow); + if (list_view) { - initListbox(listbox); + initListView(list_view); } CEGUI::ComboDropList* combodroplist = dynamic_cast(widgetWindow); - if(combodroplist) - { - initListbox(combodroplist); - } - - CEGUI::ItemListbox* itemListbox = dynamic_cast(widgetWindow); - if(itemListbox) + if (combodroplist) { - initItemListbox(itemListbox); + initListWidget(combodroplist); } CEGUI::Combobox* combobox = dynamic_cast(widgetWindow); - if(combobox) + if (combobox) { initCombobox(combobox); } CEGUI::MultiColumnList* multilineColumnList = dynamic_cast(widgetWindow); - if(multilineColumnList) + if (multilineColumnList) { initMultiColumnList(multilineColumnList); } CEGUI::Menubar* menuBar = dynamic_cast(widgetWindow); - if(menuBar) - { + if (menuBar) + { initMenubar(menuBar); } @@ -657,7 +682,7 @@ CEGUI::Window* WidgetDemo::initialiseSpecialWidgets(CEGUI::Window* widgetWindow, return widgetWindow; } -void WidgetDemo::initMultiColumnList(CEGUI::MultiColumnList* multilineColumnList) +void WidgetsSample::initMultiColumnList(CEGUI::MultiColumnList* multilineColumnList) { multilineColumnList->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(0.4f))); @@ -698,39 +723,31 @@ void WidgetDemo::initMultiColumnList(CEGUI::MultiColumnList* multilineColumnList multilineColumnList->setItem(new MyListItem("[colour='FFFF6600']284ms"), 2, 4); } -void WidgetDemo::initCombobox(CEGUI::Combobox* combobox) +void WidgetsSample::initCombobox(Combobox* combobox) { - MyListItem* item1 = new MyListItem("Combobox Item 1"); - combobox->addItem(item1); - MyListItem* item2 = new MyListItem("Combobox Item 2"); - combobox->addItem(item2); + combobox->getDropList()->setSelectionColourRect(Colour(0.3f, 0.7f, 1.0f, 1.0f)); - MyListItem* item3 = new MyListItem("Combobox Item 3"); - item3->setSelectionColours(CEGUI::Colour(0.3f, 0.7f, 1.0f, 1.0f)); - combobox->addItem(item3); + //TODO: implement per-item selection color in ItemModel? + combobox->addItem(new StandardItem("Combobox Item 1")); + combobox->addItem(new StandardItem("Combobox Item 2")); - MyListItem* item4 = new MyListItem("Combobox Item 4"); - item4->setSelectionColours(CEGUI::Colour(0.3f, 1.0f, 0.7f, 1.0f)); - combobox->addItem(item4); + combobox->addItem(new StandardItem("Combobox Item 3")); + combobox->addItem(new StandardItem("Combobox Item 4")); - if(combobox->getType().compare("WindowsLook/Combobox") == 0) + if (combobox->getType().compare("WindowsLook/Combobox") == 0) { - item1->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); - item2->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); - item3->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); - item4->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); + combobox->getDropList()->setTextColour(Colour(0.0f, 0.0f, 0.0f, 1.0f)); } } - -void WidgetDemo::saveWidgetPropertiesToMap(const CEGUI::Window* widgetRoot, const CEGUI::Window* widgetWindow) +void WidgetsSample::saveWidgetPropertiesToMap(const CEGUI::Window* widgetRoot, const CEGUI::Window* widgetWindow) { CEGUI::PropertySet::PropertyIterator propertyIter = widgetWindow->getPropertyIterator(); std::vector& propertyList = d_widgetPropertiesMap[widgetRoot].d_propertyList; d_widgetPropertiesMap[widgetRoot].d_widget = widgetWindow; - while(!propertyIter.isAtEnd()) + while (!propertyIter.isAtEnd()) { propertyList.push_back(*propertyIter); @@ -738,73 +755,40 @@ void WidgetDemo::saveWidgetPropertiesToMap(const CEGUI::Window* widgetRoot, cons } } -void WidgetDemo::initListbox(CEGUI::Listbox* listbox) +//----------------------------------------------------------------------------// +void WidgetsSample::initListWidget(ListWidget* list_widget) { - MyListItem* item1 = new MyListItem("Listbox Item 1"); - listbox->addItem(item1); - MyListItem* item2 = new MyListItem("Listbox Item 2"); - listbox->addItem(item2); - - MyListItem* item3 = new MyListItem("Listbox Item 3"); - item3->setSelectionColours(CEGUI::Colour(0.3f, 0.7f, 1.0f, 1.0f)); - listbox->addItem(item3); + list_widget->addItem("ListWidget Item 1"); + list_widget->addItem("ListWidget Item 2"); + list_widget->addItem("ListWidget Item 3"); + list_widget->addItem("ListWidget Item 4"); - MyListItem* item4 = new MyListItem("Listbox Item 4"); - item4->setSelectionColours(CEGUI::Colour(0.3f, 1.0f, 0.7f, 1.0f)); - listbox->addItem(item4); - - if(listbox->getType().compare("WindowsLook/Listbox") == 0) + if (list_widget->getType().compare("WindowsLook/ListWidget") == 0) { - item1->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); - item2->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); - item3->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); - item4->setTextColours(CEGUI::Colour(0.0f, 0.0f, 0.0f, 1.0f)); + list_widget->setTextColour(Colour(0.0f, 0.0f, 0.0f, 1.0f)); } } -void WidgetDemo::initItemListbox(CEGUI::ItemListbox* itemListbox) -{ - CEGUI::WindowManager& windowManager = CEGUI::WindowManager::getSingleton(); - - CEGUI::ItemEntry* itemListboxItem; - - itemListboxItem = static_cast(windowManager.createWindow("TaharezLook/ListboxItem", "ItemListboxTestItem1")); - itemListbox->addItem(itemListboxItem); - itemListbox->setText("Item 1"); - - itemListboxItem = static_cast(windowManager.createWindow("TaharezLook/ListboxItem", "ItemListboxTestItem2")); - itemListbox->addItem(itemListboxItem); - itemListbox->setText("Item 2"); - - itemListboxItem = static_cast(windowManager.createWindow("TaharezLook/ListboxItem", "ItemListboxTestItem3")); - itemListbox->addItem(itemListboxItem); - itemListbox->setText("Item 3"); - - itemListboxItem = static_cast(windowManager.createWindow("TaharezLook/ListboxItem", "ItemListboxTestItem4")); - itemListbox->addItem(itemListboxItem); - itemListbox->setText("Item 4"); -} - -void WidgetDemo::initRadioButtons(CEGUI::RadioButton* radioButton, CEGUI::Window*& widgetWindow) +void WidgetsSample::initRadioButtons(CEGUI::RadioButton* radioButton, CEGUI::Window*& widgetWindow) { CEGUI::WindowManager& windowManager = CEGUI::WindowManager::getSingleton(); CEGUI::RadioButton* radioButton1 = radioButton; - widgetWindow = windowManager.createWindow("DefaultWindow", "RadioButtonWidgetDemoRoot"); + widgetWindow = windowManager.createWindow("DefaultWindow", "RadioButtonWidgetsSampleRoot"); widgetWindow->addChild(radioButton1); - CEGUI::Window* radioButton2 = windowManager.createWindow(radioButton1->getType(), "WidgetDemoRadiobutton1"); + CEGUI::Window* radioButton2 = windowManager.createWindow(radioButton1->getType(), "WidgetsSampleRadiobutton1"); widgetWindow->addChild(radioButton2); radioButton2->setText("Additional Radiobutton1"); radioButton2->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.17f))); - CEGUI::Window* radioButton3 = windowManager.createWindow(radioButton1->getType(), "WidgetDemoRadiobutton2"); + CEGUI::Window* radioButton3 = windowManager.createWindow(radioButton1->getType(), "WidgetsSampleRadiobutton2"); widgetWindow->addChild(radioButton3); radioButton3->setText("Additional Radiobutton2"); radioButton3->setPosition(CEGUI::UVector2(cegui_reldim(0.0f), cegui_reldim(0.27f))); } -void WidgetDemo::initialiseWidgetDisplayWindow() +void WidgetsSample::initialiseWidgetDisplayWindow() { WindowManager& winMgr = WindowManager::getSingleton(); @@ -813,12 +797,12 @@ void WidgetDemo::initialiseWidgetDisplayWindow() d_widgetDisplayWindow->setSize(CEGUI::USize(cegui_reldim(0.9f), cegui_reldim(0.6f))); d_widgetDisplayWindow->setText("Widget Demo"); - d_widgetDisplayWindowInnerWindow = winMgr.createWindow("DefaultWindow", "WidgetDisplayWindowInnerContainer"); + d_widgetDisplayWindowInnerWindow = winMgr.createWindow("DefaultWindow", "WidgetDisplayWindowInnerContainer"); d_widgetDisplayWindowInnerWindow->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); d_widgetDisplayWindow->addChild(d_widgetDisplayWindowInnerWindow); } -void WidgetDemo::initialiseWidgetSelector(CEGUI::Window* container) +void WidgetsSample::initialiseWidgetSelector(CEGUI::Window* container) { WindowManager& winMgr = WindowManager::getSingleton(); @@ -828,16 +812,16 @@ void WidgetDemo::initialiseWidgetSelector(CEGUI::Window* container) initialiseWidgetSelectorContainer(widgetSelectorContainer); container->addChild(widgetSelectorContainer); - initialiseWidgetSelectorListbox(); - widgetSelectorContainer->addChild(d_widgetSelectorListbox); + initialiseWidgetSelectorListWidget(); + widgetSelectorContainer->addChild(d_widgetSelectorListWidget); } -void WidgetDemo::initialiseWidgetInspector(CEGUI::Window* container) +void WidgetsSample::initialiseWidgetInspector(CEGUI::Window* container) { WindowManager& winMgr = WindowManager::getSingleton(); //Add a tabcontrol serving as WidgetInspector, allowing to switch between events+widgets and the properties display - TabControl* tabControl = static_cast(winMgr.createWindow("TaharezLook/TabControl", "WidgetDemoWidgetInspector")); + TabControl* tabControl = static_cast(winMgr.createWindow("TaharezLook/TabControl", "WidgetsSampleWidgetInspector")); container->addChild(tabControl); tabControl->setSize(CEGUI::USize(cegui_reldim(0.55f), cegui_reldim(0.96f))); tabControl->setPosition(CEGUI::UVector2(cegui_reldim(0.02f), cegui_reldim(0.02f))); @@ -866,31 +850,31 @@ void WidgetDemo::initialiseWidgetInspector(CEGUI::Window* container) initialiseEventLights(widgetMainInspectionContainer); } -bool WidgetDemo::getWidgetType(CEGUI::String &widgetName, CEGUI::String &widgetTypeString) +bool WidgetsSample::getWidgetType(CEGUI::String &widgetName, CEGUI::String &widgetTypeString) { //Retrieving the Strings for the selections - CEGUI::ListboxItem* widgetListboxItem = d_widgetSelectorListbox->getFirstSelectedItem(); - CEGUI::ListboxItem* skinListboxItem = d_skinSelectionCombobox->getSelectedItem(); + StandardItem* widget_item = d_widgetSelectorListWidget->getFirstSelectedItem(); + StandardItem* skin_item = d_skinSelectionCombobox->getSelectedItem(); - if(!skinListboxItem || !widgetListboxItem) + if (!skin_item || !widget_item) return false; //Recreate the widget's type as String - widgetName = widgetListboxItem->getText(); + widgetName = widget_item->getText(); - if(skinListboxItem->getText().compare("No Skin") != 0) - widgetTypeString= skinListboxItem->getText() + "/"; + if (skin_item->getText().compare("No Skin") != 0) + widgetTypeString = skin_item->getText() + "/"; widgetTypeString += widgetName; return true; } -CEGUI::Window* WidgetDemo::retrieveOrCreateWidgetWindow(const CEGUI::String& widgetTypeString, const CEGUI::String& widgetName) +CEGUI::Window* WidgetsSample::retrieveOrCreateWidgetWindow(const CEGUI::String& widgetTypeString, const CEGUI::String& widgetName) { //Choose the existing widget if available, otherwise create it and save it to the list std::map::iterator iter = d_widgetsMap.find(widgetTypeString); - if(iter != d_widgetsMap.end()) + if (iter != d_widgetsMap.end()) { return iter->second; } @@ -901,16 +885,16 @@ CEGUI::Window* WidgetDemo::retrieveOrCreateWidgetWindow(const CEGUI::String& wid } } -void WidgetDemo::handleSpecialWindowCases(CEGUI::Window* widgetWindowRoot, CEGUI::String widgetTypeString) +void WidgetsSample::handleSpecialWindowCases(CEGUI::Window* widgetWindowRoot, CEGUI::String widgetTypeString) { //Reset to 0 progress in case of a progressbar CEGUI::ProgressBar* progressBar = dynamic_cast(d_currentlyDisplayedWidgetRoot); - if(progressBar != 0) + if (progressBar != 0) progressBar->setProgress(0.0f); //Apply the tooltip to the widget display window in case of a tooltip CEGUI::Tooltip* tooltip = dynamic_cast(d_currentlyDisplayedWidgetRoot); - if(tooltip) + if (tooltip) { d_widgetDisplayWindowInnerWindow->setTooltip(tooltip); d_widgetDisplayWindowInnerWindow->removeChild(widgetWindowRoot); @@ -921,7 +905,7 @@ void WidgetDemo::handleSpecialWindowCases(CEGUI::Window* widgetWindowRoot, CEGUI d_widgetDisplayWindowInnerWindow->setTooltip(0); } -void WidgetDemo::fillWidgetPropertiesDisplayWindow(CEGUI::Window* widgetWindowRoot) +void WidgetsSample::fillWidgetPropertiesDisplayWindow(CEGUI::Window* widgetWindowRoot) { d_widgetPropertiesDisplayWindow->resetList(); @@ -930,17 +914,17 @@ void WidgetDemo::fillWidgetPropertiesDisplayWindow(CEGUI::Window* widgetWindowRo std::vector::iterator iter = propertyList.begin(); unsigned int i = 0; - while(iter != propertyList.end()) + while (iter != propertyList.end()) { const CEGUI::Property* curProperty = *iter; - + // We have to call this function to update the MCL because the items have changed their properties meanwhile and thus are eventually not sorted anymore // When the order in the vector is not correct anymore this will result in an assert when adding a row. The following call will sort the list again and thus // it will be ensured everything will be sorted before adding a new row. d_widgetPropertiesDisplayWindow->handleUpdatedItemData(); // Add an empty row to the MultiColumnList - if(i >= d_widgetPropertiesDisplayWindow->getRowCount()) + if (i >= d_widgetPropertiesDisplayWindow->getRowCount()) d_widgetPropertiesDisplayWindow->addRow(); unsigned int rowID = d_widgetPropertiesDisplayWindow->getRowID(i); @@ -954,10 +938,10 @@ void WidgetDemo::fillWidgetPropertiesDisplayWindow(CEGUI::Window* widgetWindowRo try { // Set the second row item (value) for the property if it is gettable - if(widget->isPropertyPresent(curProperty->getName())) + if (widget->isPropertyPresent(curProperty->getName())) d_widgetPropertiesDisplayWindow->setItem(new MyListItem(widget->getProperty(curProperty->getName())), 2, rowID); } - catch(CEGUI::InvalidRequestException exception) + catch (CEGUI::InvalidRequestException exception) { } @@ -968,14 +952,14 @@ void WidgetDemo::fillWidgetPropertiesDisplayWindow(CEGUI::Window* widgetWindowRo d_widgetPropertiesDisplayWindow->handleUpdatedItemData(); } -void WidgetDemo::initialiseWidgetPropertiesDisplayWindow(CEGUI::Window* widgetPropertiesInspectionContainer) +void WidgetsSample::initialiseWidgetPropertiesDisplayWindow(CEGUI::Window* widgetPropertiesInspectionContainer) { WindowManager& winMgr = WindowManager::getSingleton(); d_widgetPropertiesDisplayWindow = static_cast( winMgr.createWindow("TaharezLook/MultiColumnList", "WidgetPropertiesDisplay") ); - //Create the properties display window + //Create the properties display window d_widgetPropertiesDisplayWindow->setSize(CEGUI::USize(cegui_reldim(0.9f), cegui_reldim(0.9f))); d_widgetPropertiesDisplayWindow->setPosition(CEGUI::UVector2(cegui_reldim(0.05f), cegui_reldim(0.05f))); @@ -984,7 +968,7 @@ void WidgetDemo::initialiseWidgetPropertiesDisplayWindow(CEGUI::Window* widgetPr d_widgetPropertiesDisplayWindow->addColumn("Name", 0, cegui_reldim(0.45f)); d_widgetPropertiesDisplayWindow->addColumn("Type ", 1, cegui_reldim(0.25f)); d_widgetPropertiesDisplayWindow->addColumn("Value", 2, cegui_reldim(0.8f)); - + d_widgetPropertiesDisplayWindow->setShowHorzScrollbar(false); d_widgetPropertiesDisplayWindow->setUserColumnDraggingEnabled(false); d_widgetPropertiesDisplayWindow->setUserColumnSizingEnabled(true); @@ -993,18 +977,18 @@ void WidgetDemo::initialiseWidgetPropertiesDisplayWindow(CEGUI::Window* widgetPr d_widgetPropertiesDisplayWindow->setSortDirection(CEGUI::ListHeaderSegment::Ascending); } -void WidgetDemo::initMenubar(CEGUI::Menubar* menuBar) +void WidgetsSample::initMenubar(CEGUI::Menubar* menuBar) { CEGUI::String skin = menuBar->getType(); skin = skin.substr(0, skin.find_first_of('/')); CEGUI::String menuItemMapping = skin + "/MenuItem"; CEGUI::String popupMenuMapping = skin + "/PopupMenu"; - CEGUI::WindowManager& windowManager = CEGUI::WindowManager::getSingleton(); + CEGUI::WindowManager& windowManager = CEGUI::WindowManager::getSingleton(); CEGUI::MenuItem* fileMenuItem = static_cast(windowManager.createWindow(menuItemMapping, "FileMenuItem")); fileMenuItem->setText("File"); menuBar->addChild(fileMenuItem); - + CEGUI::PopupMenu* filePopupMenu = static_cast(windowManager.createWindow(popupMenuMapping, "FilePopupMenu")); fileMenuItem->addChild(filePopupMenu); @@ -1033,11 +1017,14 @@ void WidgetDemo::initMenubar(CEGUI::Menubar* menuBar) menuItem->setText("Midgets"); viewPopupMenu->addItem(menuItem); } -/************************************************************************* -Define the module function that returns an instance of the sample -*************************************************************************/ -extern "C" SAMPLE_EXPORT Sample& getSampleInstance() + +//----------------------------------------------------------------------------// +void WidgetsSample::initListView(ListView* list_view) { - static WidgetDemo sample; - return sample; -} \ No newline at end of file + list_view->setModel(&d_listItemModel); + + if (list_view->getType().find("WindowsLook/List") == 0) + { + list_view->setTextColour(Colour(0.0f, 0.0f, 0.0f, 1.0f)); + } +} diff --git a/samples/Widgets/WidgetsDemo.h b/samples/Widgets/Widgets.h similarity index 87% rename from samples/Widgets/WidgetsDemo.h rename to samples/Widgets/Widgets.h index 5041b14a7..448606e48 100644 --- a/samples/Widgets/WidgetsDemo.h +++ b/samples/Widgets/Widgets.h @@ -24,8 +24,8 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Widget_Demo_ -#define _Widget_Demo_ +#ifndef _Widget_Sample_ +#define _Widget_Sample_ #include "SampleBase.h" @@ -34,6 +34,7 @@ author: Lukas E Meindl #include "CEGUI/ForwardRefs.h" +#include "CEGUI/views/StandardItemModel.h" class EventHandlerObject; class MyListItem; @@ -42,9 +43,11 @@ struct WidgetPropertiesObject; typedef std::vector WidgetListType; // Sample class -class WidgetDemo : public Sample +class WidgetsSample : public Sample { public: + WidgetsSample(); + // method to initialse the samples windows and events. virtual bool initialise(CEGUI::GUIContext* guiContext); @@ -52,6 +55,7 @@ class WidgetDemo : public Sample // method to perform any required cleanup operations. virtual void deinitialise(); + protected: // initialisation helpers void initialiseAvailableWidgetsMap(); @@ -66,7 +70,7 @@ class WidgetDemo : public Sample void initialiseWidgetDisplayWindow(); void initialiseEventLights(CEGUI::Window* container); void initialiseWidgetSelectorContainer(CEGUI::Window* widgetSelectorContainer); - void initialiseWidgetSelectorListbox(); + void initialiseWidgetSelectorListWidget(); void initialiseBackgroundWindow(CEGUI::Window* background); void initialiseSkinCombobox(CEGUI::Window* container); void initialiseWidgetsEventsLog(); @@ -78,8 +82,8 @@ class WidgetDemo : public Sample bool handleSkinSelectionAccepted(const CEGUI::EventArgs& args); bool handleWidgetSelectionChanged(const CEGUI::EventArgs& args); - void fillWidgetPropertiesDisplayWindow( CEGUI::Window* widgetWindowRoot ); - void handleSpecialWindowCases( CEGUI::Window* widgetWindowRoot, CEGUI::String widgetTypeString ); + void fillWidgetPropertiesDisplayWindow(CEGUI::Window* widgetWindowRoot); + void handleSpecialWindowCases(CEGUI::Window* widgetWindowRoot, CEGUI::String widgetTypeString); CEGUI::Window* retrieveOrCreateWidgetWindow(const CEGUI::String& widgetTypeString, const CEGUI::String& widgetName); bool getWidgetType(CEGUI::String &widgetName, CEGUI::String &widgetTypeString); CEGUI::Window* createWidget(const CEGUI::String &widgetMapping, const CEGUI::String &widgetType); @@ -88,14 +92,13 @@ class WidgetDemo : public Sample void initMenubar(CEGUI::Menubar* menuBar); void initRadioButtons(CEGUI::RadioButton* radioButton, CEGUI::Window*& widgetWindow); - void initListbox(CEGUI::Listbox* listbox); - void initItemListbox(CEGUI::ItemListbox* itemListbox); + void initListWidget(CEGUI::ListWidget* list_widget); + void initListView(CEGUI::ListView* item_view); void initCombobox(CEGUI::Combobox* combobox); void initMultiColumnList(CEGUI::MultiColumnList* multilineColumnList); void subscribeToAllEvents(CEGUI::Window* widgetWindow); void addEventHandlerObjectToMap(CEGUI::String eventName); - void logFiredEvent(const CEGUI::String& logMessage); void destroyWidgetWindows(); @@ -105,12 +108,11 @@ class WidgetDemo : public Sample bool handleRootWindowUpdate(const CEGUI::EventArgs& args); void saveWidgetPropertiesToMap(const CEGUI::Window* widgetRoot, const CEGUI::Window* widgetWindow); - - static const CEGUI::String s_widgetDemoWindowPrefix; + static const CEGUI::String s_widgetSampleWindowPrefix; CEGUI::GUIContext* d_guiContext; - CEGUI::Listbox* d_widgetSelectorListbox; + CEGUI::ListWidget* d_widgetSelectorListWidget; CEGUI::Combobox* d_skinSelectionCombobox; CEGUI::Window* d_widgetDisplayWindow; CEGUI::Window* d_widgetDisplayWindowInnerWindow; @@ -118,7 +120,7 @@ class WidgetDemo : public Sample CEGUI::Window* d_currentlyDisplayedWidgetRoot; - CEGUI::Window* d_windowLightMouseMoveEvent; + CEGUI::Window* d_windowLightCursorMoveEvent; CEGUI::Window* d_windowLightUpdatedEvent; CEGUI::MultiColumnList* d_widgetPropertiesDisplayWindow; @@ -127,6 +129,8 @@ class WidgetDemo : public Sample std::map d_widgetsMap; std::map d_eventHandlerObjectsMap; std::map d_widgetPropertiesMap; + + CEGUI::StandardItemModel d_listItemModel; }; #endif diff --git a/samples/browser/CMakeLists.txt b/samples/browser/CMakeLists.txt new file mode 100644 index 000000000..9d9f9e54b --- /dev/null +++ b/samples/browser/CMakeLists.txt @@ -0,0 +1,395 @@ +set(CEGUI_TARGET_NAME ${CEGUI_SAMPLEFRAMEWORK_EXENAME}) + +set(CORE_SOURCE_FILES + ./src/SampleBrowserBase.cpp + ./src/SampleBrowser.cpp + ./src/CEGuiBaseApplication.cpp + ./src/CEGuiRendererSelector.cpp + ./src/SampleHandler.cpp + ./src/MetaDataWindowManager.cpp + ./src/SampleBrowserManager.cpp +) + +set(CORE_HEADER_FILES + ./include/SampleBrowserBase.h + ./include/SampleBrowser.h + ./include/CEGuiBaseApplication.h + ./include/CEGuiRendererSelector.h + ./include/SampleHandler.h + ./include/MetaDataWindowManager.h + ./include/SampleBrowserManager.h +) + + +# Getting all header and source files from the common files folder +file(GLOB COMMON_HEADER_FILES "${CMAKE_SOURCE_DIR}/samples/common/*.h") +file(GLOB COMMON_SOURCE_FILES "${CMAKE_SOURCE_DIR}/samples/common/*.cpp") + + +include_directories(${CMAKE_SOURCE_DIR}/samples/browser/include + ${CMAKE_BINARY_DIR}/samples/common/include + ${CMAKE_SOURCE_DIR}/samples/common/include + ${CMAKE_SOURCE_DIR}/cegui/include) + +if(WIN32) + list(APPEND CORE_SOURCE_FILES + ./src/Win32AppHelper.cpp + ./src/Win32CEGuiRendererSelector.cpp + ) +elseif(APPLE) + list(APPEND CORE_SOURCE_FILES + ./src/MacCEGuiRendererSelector.mm + ) +elseif(CEGUI_SAMPLES_USE_GTK2) + list(APPEND CORE_SOURCE_FILES + ./src/GTK2CEGuiRendererSelector.cpp + ) +else() + list(APPEND CORE_SOURCE_FILES + ./src/CLICEGuiRendererSelector.cpp + ) +endif() + + +if(CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE) + # Append OpenGL and OpenGL3 files + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiGLFWSharedBase.cpp + ) + + if(CEGUI_BUILD_RENDERER_OPENGL) + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiOpenGLBaseApplication.cpp + ) + endif() + + if(CEGUI_BUILD_RENDERER_OPENGL3) + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiOpenGL3BaseApplication.cpp + ) + endif() + +endif() + +if(CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE) + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiEGLBaseApplication.cpp + ) + if (ANDROID) + list(APPEND CORE_SOURCE_FILES + ./src/AndroidAppHelper.cpp + ) + endif() +endif() + +if(CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) + # this prevents the boost auto-link dis-feature + add_definitions(-DBOOST_ALL_NO_LIB) + + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiOgreBaseApplication.cpp + ) + if (ANDROID) + list(APPEND CORE_SOURCE_FILES + ./src/AndroidAppHelper.cpp + ) + endif() +endif() + +if(CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE) + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiIrrlichtBaseApplication.cpp + ) +endif() + +if(CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiD3D11BaseApplication.cpp + ./src/DeviceReset_Direct3D11.cpp + ) +endif() + +if(CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE) + list(APPEND CORE_SOURCE_FILES + ./src/CEGuiDirectFBBaseApplication.cpp + ) +endif() + +if(CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) + include_directories(${DIRECTXSDK_INCLUDE_DIR}) + link_directories(${DIRECTXSDK_LIBRARY_DIR}) +endif() + + +# Combine the sample framework/browser's sources and headers with the common files of the samples +set(COMBINED_HEADER_FILES ${CORE_HEADER_FILES} ${COMMON_HEADER_FILES}) +set(COMBINED_SOURCE_FILES ${CORE_SOURCE_FILES} ${COMMON_SOURCE_FILES}) + +# We iterate through all added Samples and add the sources and headers to the combined headers and sources +foreach(CUR_SAMPLE_DIR_NAME ${SAMPLES_LIST}) + # We generate the Sample's variable names for the list of headers and list of sources, based on the directory name of the sample + + set(SAMPLE_HEADER_LIST_NAME "${CUR_SAMPLE_DIR_NAME}_SAMPLE_HEADERS") + set(SAMPLE_SOURCE_LIST_NAME "${CUR_SAMPLE_DIR_NAME}_SAMPLE_SOURCES") + + set(COMBINED_SOURCE_FILES ${COMBINED_SOURCE_FILES} ${${SAMPLE_SOURCE_LIST_NAME}}) + set(COMBINED_HEADER_FILES ${COMBINED_HEADER_FILES} ${${SAMPLE_HEADER_LIST_NAME}}) +endforeach() + +# add additional include directories; provided by sample +include_directories(${ADDITIONAL_INCLUDE_DIRS}) + +########################################################################### +# Statically Linked Executable +########################################################################### +if(CEGUI_BUILD_STATIC_CONFIGURATION) + if (ANDROID) + file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp "int x = 0;") + add_library(${CEGUI_TARGET_NAME}_Static STATIC ${CMAKE_CURRENT_BINARY_DIR}/dummy.cpp) + else() + add_executable(${CEGUI_TARGET_NAME}_Static ${COMBINED_SOURCE_FILES} ${COMBINED_HEADER_FILES}) + endif() + set_property(TARGET ${CEGUI_TARGET_NAME}_Static APPEND PROPERTY COMPILE_DEFINITIONS CEGUI_STATIC) + + # append the _d (or whatever) for debug builds as needed. + if(CEGUI_HAS_BUILD_SUFFIX AND CEGUI_BUILD_SUFFIX) + set_target_properties(${CEGUI_TARGET_NAME}_Static PROPERTIES + OUTPUT_NAME_DEBUG "${CEGUI_TARGET_NAME}_Static${CEGUI_BUILD_SUFFIX}" + ) + endif() + + # This works around an issue in the prebuilt deps and can be removed once those are fixed :) + if(WIN32) + set_target_properties(${CEGUI_TARGET_NAME}_Static PROPERTIES LINK_FLAGS_DEBUG /NODEFAULTLIB:freeglut.lib) + endif() + + if(APPLE) + cegui_apple_app_setup(${CEGUI_TARGET_NAME}_Static TRUE) + endif() + + if (ANDROID) + include(CEGUIAndroid) + set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/utils") + set(OGRE_TEMPLATES_DIR "${CMAKE_SOURCE_DIR}/cmake/templates") + file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/browserdummy.cpp "int x_dummy = 0;") + SET(ANDROID_PROJECT_TARGET "CEGUISampleBrowserAndroid") + ADD_LIBRARY(${ANDROID_PROJECT_TARGET} SHARED ${CMAKE_CURRENT_BINARY_DIR}/browserdummy.cpp) + target_link_libraries(${ANDROID_PROJECT_TARGET} ${CEGUI_TARGET_NAME}_Static) + #if cegui dependencies dir not supplied, then look in the provided prefix path + if (NOT CEGUI_DEPENDENCIES_DIR) + set(CEGUI_DEPENDENCIES_DIR ${CMAKE_PREFIX_PATH}) + endif() + create_android_proj(${ANDROID_PROJECT_TARGET}) + endif() +endif() + +########################################################################### +# Dynamically Linked Executable +########################################################################### +if(CEGUI_BUILD_DYNAMIC_CONFIGURATION) +add_executable(${CEGUI_TARGET_NAME} ${COMBINED_SOURCE_FILES} ${COMBINED_HEADER_FILES}) + +# additional dependencies from samples +add_dependencies(${CEGUI_TARGET_NAME} "${ADDITIONAL_LIBS}") + +# append the _d (or whatever) for debug builds as needed. +if(CEGUI_HAS_BUILD_SUFFIX AND CEGUI_BUILD_SUFFIX) + set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES + OUTPUT_NAME_DEBUG "${CEGUI_TARGET_NAME}${CEGUI_BUILD_SUFFIX}" + ) +endif() + +if(NOT APPLE AND CEGUI_INSTALL_WITH_RPATH) + set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CEGUI_LIB_INSTALL_DIR}" + ) +endif() + +if(APPLE) + # we add these to ensure the dynamically loaded modules we will be + # using are built before the .app's post build step that copies + # libs into the app bundle. + add_dependencies(${CEGUI_TARGET_NAME} ${CEGUI_CORE_WR_LIBNAME} + CEGUI${CEGUI_OPTION_DEFAULT_XMLPARSER} + CEGUI${CEGUI_OPTION_DEFAULT_IMAGECODEC} + ) + + cegui_apple_app_setup(${CEGUI_TARGET_NAME} FALSE) +endif() +endif(CEGUI_BUILD_DYNAMIC_CONFIGURATION) + +########################################################################### +# Setting up the source groups +########################################################################### + +source_group("Header Files\\browser" FILES ${CORE_HEADER_FILES}) +source_group("Source Files\\browser" FILES ${CORE_SOURCE_FILES}) + +source_group("Header Files\\common" FILES ${COMMON_HEADER_FILES}) +source_group("Source Files\\common" FILES ${COMMON_SOURCE_FILES}) + +# We iterate through all added Samples and add a source group for its sources and headers respectively +foreach(CUR_SAMPLE_DIR_NAME ${SAMPLES_LIST}) + # We generate the Sample's variable names for the list of headers and list of sources, based on the directory name of the sample + set(SAMPLE_HEADER_LIST_NAME "${CUR_SAMPLE_DIR_NAME}_SAMPLE_HEADERS") + set(SAMPLE_SOURCE_LIST_NAME "${CUR_SAMPLE_DIR_NAME}_SAMPLE_SOURCES") + + # We set the source group for the files + source_group("Header Files\\${CUR_SAMPLE_DIR_NAME}" FILES ${${SAMPLE_HEADER_LIST_NAME}}) + source_group("Source Files\\${CUR_SAMPLE_DIR_NAME}" FILES ${${SAMPLE_SOURCE_LIST_NAME}}) +endforeach() + +########################################################################### +# MSVC PROJ USER FILE TEMPLATES +########################################################################### +if(MSVC) + configure_file( + ${CMAKE_MODULE_PATH}/templates/VisualStudioUserFile.vcproj.user.in + ${CMAKE_CURRENT_BINARY_DIR}/${CEGUI_TARGET_NAME}.vcproj.user + @ONLY + ) + configure_file( + ${CMAKE_MODULE_PATH}/templates/VisualStudioUserFile.vcxproj.user.in + ${CMAKE_CURRENT_BINARY_DIR}/${CEGUI_TARGET_NAME}.vcxproj.user + @ONLY + ) +endif() + + +########################################################################### +# LIBRARY LINK SETUP +########################################################################### +if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME}) +endif() + +if(CEGUI_BUILD_STATIC_CONFIGURATION) + target_link_libraries(${CEGUI_TARGET_NAME}_Static + ${CEGUI_STATIC_XMLPARSER_MODULE}_Static + ${CEGUI_STATIC_IMAGECODEC_MODULE}_Static + ${CEGUI_CORE_WR_LIBNAME}_Static + ) +endif() + +########################################################################### +# BUILD DEPENDENCIES FOR THE SHARED LIBRARIES USED BY THE SAMPLEBROWSER +########################################################################### +if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + add_dependencies(${CEGUI_TARGET_NAME} ${CEGUI_CORE_WR_LIBNAME} + CEGUI${CEGUI_OPTION_DEFAULT_XMLPARSER} + CEGUI${CEGUI_OPTION_DEFAULT_IMAGECODEC}) + + if (CEGUI_SAMPLES_ENABLE_COMMON_DIALOGUES_DEMO) + add_dependencies(${CEGUI_TARGET_NAME} ${CEGUI_COMMON_DIALOGS_LIBNAME}) + endif() + +endif() + +########################################################################### +# INSTALLATION +########################################################################### +if (CEGUI_BUILD_DYNAMIC_CONFIGURATION) + install(TARGETS ${CEGUI_TARGET_NAME} + RUNTIME DESTINATION bin + LIBRARY DESTINATION ${CEGUI_LIB_INSTALL_DIR} + ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} + BUNDLE DESTINATION ${CEGUI_LIB_INSTALL_DIR} + ) +endif() + +if(CEGUI_BUILD_STATIC_CONFIGURATION) + install(TARGETS ${CEGUI_TARGET_NAME}_Static + RUNTIME DESTINATION bin + LIBRARY DESTINATION ${CEGUI_LIB_INSTALL_DIR} + ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} + BUNDLE DESTINATION ${CEGUI_LIB_INSTALL_DIR} +) +endif() + +if(CEGUI_BUILD_COMMON_DIALOGS) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_COMMON_DIALOGS_LIBNAME}) +endif() + +if (UNIX AND NOT APPLE AND NOT ANDROID) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${X11_LIBRARIES} ${X11_Xt_LIB} + ${XAW_LIBRARY} ${X11_Xrandr_LIB} pthread ${CMAKE_DL_LIBS}) +endif() + +if(CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE OR CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_OPENGL_RENDERER_LIBNAME}) +endif() + +if(CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE) + cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGL) + cegui_add_dependency(${CEGUI_TARGET_NAME} GLFW) +endif() + +if(CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE) + if (NOT ANDROID) # LINUX GLES depends on GLEW + cegui_add_dependency(${CEGUI_TARGET_NAME} GLEW) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} EGL) + endif() + if (CEGUI_BUILD_RENDERER_OPENGLES2_WITH_GLES3_SUPPORT) + cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGLES3) + else() + cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGLES2) + endif() +endif() + +if(CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) + cegui_add_dependency(${CEGUI_TARGET_NAME} OGRE) + if (UNIX AND NOT APPLE AND NOT ANDROID) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} GL ) + endif() + cegui_add_dependency(${CEGUI_TARGET_NAME} OIS) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_OGRE_RENDERER_LIBNAME}) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_OGRE_SAMPLES_EXTRALIBS} ) + if (OGRE_STATIC) #if ogre is static, then must include the static plugin libs + set(CORE_OGRE_COMPONENTS RenderSystem_Direct3D9 RenderSystem_Direct3D11 RenderSystem_GLES RenderSystem_GLES2 RenderSystem_GL RenderSystem_GL3Plus) + foreach (comp ${CORE_OGRE_COMPONENTS}) + if (${OGRE_${comp}_FOUND}) + include_directories(${OGRE_${comp}_INCLUDE_DIRS}) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${OGRE_${comp}_LIBRARIES}) + endif() + endforeach (comp) + endif() +endif() + +if(CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE) + cegui_add_dependency(${CEGUI_TARGET_NAME} IRRLICHT) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_IRRLICHT_RENDERER_LIBNAME}) +endif() + +if(CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) + cegui_add_dependency(${CEGUI_TARGET_NAME} DIRECTXSDK) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_DIRECT3D11_RENDERER_LIBNAME}) +endif() + +if(CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE) + cegui_add_dependency(${CEGUI_TARGET_NAME} DIRECTFB) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_DIRECTFB_RENDERER_LIBNAME}) +endif() + +if(CEGUI_SAMPLES_USE_GTK2) + cegui_add_dependency(${CEGUI_TARGET_NAME} GTK2) +endif() + +if(APPLE) + set (CEGUI_EXTRA_FRAMEWORKS "-framework Cocoa") + + if(CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) + set (CEGUI_EXTRA_FRAMEWORKS "${CEGUI_EXTRA_FRAMEWORKS} -framework IOKit -framework Carbon") + endif() + + set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES + LINK_FLAGS ${CEGUI_EXTRA_FRAMEWORKS} + ) +endif() + +if (UNIX AND NOT APPLE AND NOT ANDROID) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CMAKE_DL_LIBS}) +elseif (MINGW) + cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CMAKE_DL_LIBS}) +endif() + +cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME}) diff --git a/samples/browser/include/AndroidAppHelper.h b/samples/browser/include/AndroidAppHelper.h new file mode 100644 index 000000000..621c438a9 --- /dev/null +++ b/samples/browser/include/AndroidAppHelper.h @@ -0,0 +1,140 @@ +/*********************************************************************** + created: 28/9/2004 + author: David Reepmeyer +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _AndroidAppHelper_h_ +#define _AndroidAppHelper_h_ + +#ifndef __ANDROID__ +error: +only android builds should include this file +#endif + +#include "CEGUI/AndroidUtils.h" +#include + +#ifdef CEGUI_SAMPLES_ANDROID_GLES2 +class CEGuiEGLBaseApplication; +# include "SampleBrowserBase.h" +#elif defined(CEGUI_SAMPLES_ANDROID_OGRE) +# include +# include "OIS.h" +# include "Ogre.h" +# include "OgrePlatform.h" +# include "ANDROID/OgreAndroidEGLWindow.h" +# include "OgreFileSystemLayer.h" +# include "Android/OgreAPKFileSystemArchive.h" +# include "Android/OgreAPKZipArchive.h" +# include "OgreWindowEventUtilities.h" +# include "OgreBuildSettings.h" +#endif + +#ifdef CEGUI_SAMPLES_ANDROID_OGRE +class AndroidMultiTouch : public OIS::MultiTouch +{ +public: + AndroidMultiTouch(); + virtual void setBuffered (bool buffered); + virtual void capture(); + virtual OIS::Interface* queryInterface (OIS::Interface::IType type); + virtual void _initialize(); + OIS::MultiTouchState &getMultiTouchState (int i); +}; + +class AndroidKeyboard : public OIS::Keyboard +{ +public: + AndroidKeyboard(); + virtual void setBuffered (bool buffered); + virtual void capture(); + virtual OIS::Interface* queryInterface (OIS::Interface::IType type); + virtual void _initialize(); + virtual bool isKeyDown (OIS::KeyCode key) const; + virtual const std::string& getAsString (OIS::KeyCode kc); + virtual void copyKeyStates (char keys[256]) const; +}; + +class AndroidInputInjector +{ +private: + OIS::KeyListener* keyListener; + OIS::MultiTouchListener* touchListener; + AndroidMultiTouch* mTouch; + AndroidKeyboard* mKeyboard; + +public: + + AndroidInputInjector (OIS::KeyListener *keyListener, OIS::MultiTouchListener *touchListener, + AndroidMultiTouch* touch, AndroidKeyboard* keyboard); + + void injectKeyEvent (int action, int32_t keyCode); + void injectTouchEvent (int action, float x, float y, int pointerId = 0); +}; + +#endif //CEGUI_SAMPLES_ANDROID_OGRE + + +/*! +\brief + All static utility class containing helper / common functions used for the Win32 apps +*/ +class AndroidAppHelper +{ +public: + static bool createWindow(); + static bool processEvents(); + static int32_t handleInput(struct android_app* app, AInputEvent* event); + static void handleCmd(struct android_app* app, int32_t cmd); + + //Ogre specific +#ifdef CEGUI_SAMPLES_ANDROID_OGRE + static void shutdown(); + static void go(); + static Ogre::RenderWindow* getRenderWindow (); + static void initialiseFS(); + static bool initialiseOIS (OIS::KeyListener* keyListener, OIS::MultiTouchListener* mMultiTouchListener); +#endif + + +private: + static bool d_windowCreated; + static bool isWindowCreated(); + static void setWindowCreated(bool windowCreated); + + //OgreSpecific +#ifdef CEGUI_SAMPLES_ANDROID_OGRE + static Ogre::FileSystemLayer* mFSLayer; // File system abstraction layer + static AndroidInputInjector* mInputInjector; + static OIS::KeyListener* mKeyListener; + static OIS::MultiTouchListener* mMultiTouchListener; + static AndroidKeyboard* mKeyboard; + static AndroidMultiTouch* mTouch; + static Ogre::RenderWindow* mRenderWnd; +#endif + +}; + +#endif // end of guard _AndroidAppHelper_h_ + diff --git a/samples_framework/include/CEGuiBaseApplication.h b/samples/browser/include/CEGuiBaseApplication.h similarity index 89% rename from samples_framework/include/CEGuiBaseApplication.h rename to samples/browser/include/CEGuiBaseApplication.h index 86cdf94e1..acae53865 100644 --- a/samples_framework/include/CEGuiBaseApplication.h +++ b/samples/browser/include/CEGuiBaseApplication.h @@ -27,6 +27,8 @@ #ifndef _CEGuiBaseApplication_h_ #define _CEGuiBaseApplication_h_ +#include + // If this looks wanky, it's becase it is! Behold that this is not as fullblown // as it could be though. #ifndef PATH_MAX @@ -46,7 +48,7 @@ /************************************************************************* Forward refs *************************************************************************/ -class SamplesFrameworkBase; +class SampleBrowserBase; namespace CEGUI { class Renderer; @@ -91,7 +93,7 @@ class CEGuiBaseApplication - false if the application failed to initialise (cleanup function will not be called). */ - bool execute(SamplesFrameworkBase* sampleApp); + bool execute(SampleBrowserBase* sampleApp); /*! \brief @@ -127,7 +129,11 @@ class CEGuiBaseApplication /*! \brief - Registers the overlay handler for rendering the FPS for a specified GUIContext + Registers the overlay handler for rendering the FPS for a specified GUIContext. + This will be used to render the overlay for the specific samples. + + /param gui_context + The sample's GUIContext for which we will register the overlay rendering. */ void registerSampleOverlayHandler(CEGUI::GUIContext* gui_context); @@ -160,10 +166,12 @@ class CEGuiBaseApplication void updateFPS(const float elapsed); //! function that updates the logo rotation as needed. void updateLogo(const float elapsed); - //! function that positions the logo in the correct place. - void positionLogo(); - //! positions the FPS counter at the correct place. - void positionFPS(); + //! function that positions the logo GeometryBuffer at the correct place. + void updateLogoGeometry(); + //! function that positions the FPS GeometryBuffer at the correct place. + void updateFPSGeometry(); + //! function that updates the rotation of the logo. + void updateLogoGeometryRotation(); //! event handler function that draws the logo and FPS overlay elements. bool sampleBrowserOverlayHandler(const CEGUI::EventArgs& args); //! event handler function that draws the FPS overlay elements. @@ -172,7 +180,7 @@ class CEGuiBaseApplication bool resizeHandler(const CEGUI::EventArgs& args); //! SampleFramework base used in the application - static SamplesFrameworkBase* d_sampleApp; + static SampleBrowserBase* d_sampleApp; //! The window width the application should get created with at start static const int s_defaultWindowWidth = 1280; //! The window height the application should get created with at start @@ -187,9 +195,9 @@ class CEGuiBaseApplication //! ResourceProvider to use. Set in subclass constructor, may be 0. CEGUI::ResourceProvider* d_resourceProvider; //! GeometryBuffer used for drawing the spinning CEGUI logo - CEGUI::GeometryBuffer* d_logoGeometry; - //! GeometryBuffer used for drawing the FPS value. - CEGUI::GeometryBuffer* d_FPSGeometry; + std::vector d_logoGeometry; + //! GeometryBuffers used for drawing the FPS value. + std::vector d_FPSGeometry; //! Fraction of second elapsed (used for counting frames per second). float d_FPSElapsed; //! Number of frames drawn so far. diff --git a/samples_framework/include/CEGuiD3D11BaseApplication.h b/samples/browser/include/CEGuiD3D11BaseApplication.h similarity index 100% rename from samples_framework/include/CEGuiD3D11BaseApplication.h rename to samples/browser/include/CEGuiD3D11BaseApplication.h diff --git a/samples_framework/include/CEGuiDirectFBBaseApplication.h b/samples/browser/include/CEGuiDirectFBBaseApplication.h similarity index 100% rename from samples_framework/include/CEGuiDirectFBBaseApplication.h rename to samples/browser/include/CEGuiDirectFBBaseApplication.h diff --git a/samples/browser/include/CEGuiEGLBaseApplication.h b/samples/browser/include/CEGuiEGLBaseApplication.h new file mode 100644 index 000000000..0376305a7 --- /dev/null +++ b/samples/browser/include/CEGuiEGLBaseApplication.h @@ -0,0 +1,101 @@ +/*********************************************************************** + created: 25/9/2014 + author: David Reepmeyer +*************************************************************************/ +/*************************************************************************** +* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team +* +* Permission is hereby granted, free of charge, to any person obtaining +* a copy of this software and associated documentation files (the +* "Software"), to deal in the Software without restriction, including +* without limitation the rights to use, copy, modify, merge, publish, +* distribute, sublicense, and/or sell copies of the Software, and to +* permit persons to whom the Software is furnished to do so, subject to +* the following conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +* OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#ifndef _CEGuiEGLBaseApplication_h_ +#define _CEGuiEGLBaseApplication_h_ + +#include "CEGuiBaseApplication.h" +#include "CEGUI/Cursor.h" +#include "CEGUI/RendererModules/OpenGL/GL.h" +#include +#include +#include + +class SampleBrowserBase; + +#ifdef __ANDROID__ +# include "AndroidAppHelper.h" +#endif + +class CEGuiEGLBaseApplication : public CEGuiBaseApplication +{ +private: + //EGL configurations +#ifdef __ANDROID__ + ANativeWindow* d_window; +#elif defined(__unix__) + Display* x_display; + Window win; + NativeWindowType d_window; +#endif + EGLDisplay d_display; + EGLSurface d_surface; + EGLContext d_context; + EGLConfig d_config; + + int32_t d_width; + int32_t d_height; + int d_glesVersion; + + bool d_contextInitialised; + bool d_contextValid; + + bool initEGLSurface(); + bool initEGLContext(); + timespec start_timespec; + +public: + CEGuiEGLBaseApplication(); + virtual ~CEGuiEGLBaseApplication(); + +#ifdef __ANDROID__ + void setNativeWindow(ANativeWindow* window); +#endif + + void terminate(); + bool init(int openglesVersion); + EGLint swap(); + bool invalidate(); + void suspend(); + EGLint resume(); + SampleBrowserBase* getSampleApp(); + static CEGuiEGLBaseApplication& getSingleton(); + void clearFrame(); +protected: + // override from base class since + void initialiseResourceGroupDirectories(); + void run(); + virtual void destroyWindow(); + void beginRendering(const float elapsed); + void endRendering(); + void drawFrame(); + double getElapsedTime(); + static CEGuiEGLBaseApplication* d_appInstance; + bool d_windowSized; +}; + +#endif //end of guard _CEGuiEGLBaseApplication_h_ + diff --git a/samples_framework/include/CEGuiGLFWSharedBase.h b/samples/browser/include/CEGuiGLFWSharedBase.h similarity index 97% rename from samples_framework/include/CEGuiGLFWSharedBase.h rename to samples/browser/include/CEGuiGLFWSharedBase.h index a3beacc34..516cc7463 100644 --- a/samples_framework/include/CEGuiGLFWSharedBase.h +++ b/samples/browser/include/CEGuiGLFWSharedBase.h @@ -28,10 +28,12 @@ #define _CEGuiGLFWSharedBase_h_ #include "CEGuiBaseApplication.h" -#include "CEGUI/MouseCursor.h" +#include "CEGUI/Cursor.h" +#include "CEGUI/RendererModules/OpenGL/GL.h" + #include -class SamplesFrameworkBase; +class SampleBrowserBase; class CEGuiGLFWSharedBase : public CEGuiBaseApplication { diff --git a/samples_framework/include/CEGuiIrrlichtBaseApplication.h b/samples/browser/include/CEGuiIrrlichtBaseApplication.h similarity index 100% rename from samples_framework/include/CEGuiIrrlichtBaseApplication.h rename to samples/browser/include/CEGuiIrrlichtBaseApplication.h diff --git a/samples_framework/include/CEGuiOgreBaseApplication.h b/samples/browser/include/CEGuiOgreBaseApplication.h similarity index 81% rename from samples_framework/include/CEGuiOgreBaseApplication.h rename to samples/browser/include/CEGuiOgreBaseApplication.h index 914119fa2..a766ac468 100644 --- a/samples_framework/include/CEGuiOgreBaseApplication.h +++ b/samples/browser/include/CEGuiOgreBaseApplication.h @@ -1,6 +1,7 @@ /*********************************************************************** created: 9/3/2004 author: Paul D Turner + David Reepmeyer (modified for android) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team @@ -83,6 +84,8 @@ class CEGuiOgreBaseApplication : public CEGuiBaseApplication, public Ogre::Frame protected: // override from base class since we use a non-default resource provider. void initialiseResourceGroupDirectories(); + // retrieve the full path of the provided resource folder + CEGUI::String getResourcePath(CEGUI::String resource); // Implementation of base class abstract methods. void run(); @@ -107,6 +110,7 @@ class CEGuiOgreBaseApplication : public CEGuiBaseApplication, public Ogre::Frame CEGuiDemoFrameListener* d_frameListener; WndEvtListener* d_windowEventListener; + }; @@ -114,11 +118,16 @@ class CEGuiOgreBaseApplication : public CEGuiBaseApplication, public Ogre::Frame \brief Ogre FrameListener class where we deal with input processing and the like. */ -class CEGuiDemoFrameListener : public Ogre::FrameListener, public OIS::KeyListener, public OIS::MouseListener +class CEGuiDemoFrameListener : public Ogre::FrameListener, public OIS::KeyListener, +#ifdef __ANDROID__ + public OIS::MultiTouchListener +#else + public OIS::MouseListener +#endif { public: // Construction and Destruction - CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp, SamplesFrameworkBase*& sampleApp, Ogre::RenderWindow* win, Ogre::Camera* cam, bool useBufferedInputKeys = false, bool useBufferedInputMouse = false); + CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp, SampleBrowserBase*& sampleApp, Ogre::RenderWindow* win, Ogre::Camera* cam, bool useBufferedInputKeys = false, bool useBufferedInputMouse = false); ~CEGuiDemoFrameListener(); // Processing to be done at start and end of each frame. @@ -126,13 +135,21 @@ class CEGuiDemoFrameListener : public Ogre::FrameListener, public OIS::KeyListen bool frameEnded(const Ogre::FrameEvent& evt); // Raw input handlers that we care about - bool mouseMoved(const OIS::MouseEvent &e); bool keyPressed(const OIS::KeyEvent &e); bool keyReleased(const OIS::KeyEvent &e); + +#ifdef __ANDROID__ + virtual bool touchPressed (const OIS::MultiTouchEvent& evt); + virtual bool touchMoved (const OIS::MultiTouchEvent& evt); + virtual bool touchReleased (const OIS::MultiTouchEvent& evt); + virtual bool touchCancelled (const OIS::MultiTouchEvent & evt) {} +#else + bool mouseMoved(const OIS::MouseEvent &e); bool mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id); bool mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id); OIS::Mouse* getOISMouse(); +#endif protected: // convert an OIS mouse button into a CEGUI mouse button @@ -143,23 +160,44 @@ class CEGuiDemoFrameListener : public Ogre::FrameListener, public OIS::KeyListen *************************************************************************/ OIS::InputManager* d_inputManager; OIS::Keyboard* d_keyboard; + +#ifdef __ANDROID__ + OIS::MultiTouch* d_touch; +#else OIS::Mouse* d_mouse; +#endif Ogre::Camera* d_camera; Ogre::RenderWindow* d_window; CEGuiOgreBaseApplication* d_baseApp; - SamplesFrameworkBase*& d_sampleApp; + SampleBrowserBase*& d_sampleApp; }; //! window event listener class we use to hear abour window resizing class WndEvtListener : public Ogre::WindowEventListener { public: +#ifdef __ANDROID__ + WndEvtListener(); +#else WndEvtListener(OIS::Mouse* mouse); +#endif + + virtual void windowResized(Ogre::RenderWindow* rw) ; + virtual void windowClosed (Ogre::RenderWindow* rw) { + } + virtual bool windowClosing (Ogre::RenderWindow *rw) { + return true; + } + virtual void windowFocusChange (Ogre::RenderWindow *rw) { + } + virtual void windowMoved (Ogre::RenderWindow *rw) { + } - void windowResized(Ogre::RenderWindow* rw); protected: +#ifndef __ANDROID__ OIS::Mouse* d_mouse; +#endif }; diff --git a/samples_framework/include/CEGuiOpenGL3BaseApplication.h b/samples/browser/include/CEGuiOpenGL3BaseApplication.h similarity index 100% rename from samples_framework/include/CEGuiOpenGL3BaseApplication.h rename to samples/browser/include/CEGuiOpenGL3BaseApplication.h diff --git a/samples_framework/include/CEGuiOpenGLBaseApplication.h b/samples/browser/include/CEGuiOpenGLBaseApplication.h similarity index 100% rename from samples_framework/include/CEGuiOpenGLBaseApplication.h rename to samples/browser/include/CEGuiOpenGLBaseApplication.h diff --git a/samples_framework/include/CEGuiRendererSelector.h b/samples/browser/include/CEGuiRendererSelector.h similarity index 96% rename from samples_framework/include/CEGuiRendererSelector.h rename to samples/browser/include/CEGuiRendererSelector.h index 42dbfbb41..e2de61219 100644 --- a/samples_framework/include/CEGuiRendererSelector.h +++ b/samples/browser/include/CEGuiRendererSelector.h @@ -34,11 +34,10 @@ enum CEGuiRendererType { OgreGuiRendererType, //!< Renderer that uses the Ogre engine. - Direct3D9GuiRendererType, //!< Renderer that uses the Direct3D 9 API. - Direct3D10GuiRendererType, //!< Renderer that uses the Direct3D 10 API. Direct3D11GuiRendererType, //!< Renderer that uses the Direct3D 11 API. OpenGLGuiRendererType, //!< Renderer that uses the OpenGL API. OpenGL3GuiRendererType, //!< Renderer that uses the OpenGL3 API. + OpenGLES2GuiRendererType, //!< Renderer that uses the OpenGL API. IrrlichtGuiRendererType, //!< Renderer that uses the Irrlicht engine. DirectFBGuiRendererType, //!< Renderer that uses the DirectFB engine. RendererTypeCount, //!< Special value that equals the number of renderer types. diff --git a/samples_framework/include/CLICEGuiRendererSelector.h b/samples/browser/include/CLICEGuiRendererSelector.h similarity index 100% rename from samples_framework/include/CLICEGuiRendererSelector.h rename to samples/browser/include/CLICEGuiRendererSelector.h diff --git a/samples_framework/include/GTK2CEGuiRendererSelector.h b/samples/browser/include/GTK2CEGuiRendererSelector.h similarity index 100% rename from samples_framework/include/GTK2CEGuiRendererSelector.h rename to samples/browser/include/GTK2CEGuiRendererSelector.h diff --git a/samples_framework/include/MacCEGuiRendererSelector.h b/samples/browser/include/MacCEGuiRendererSelector.h similarity index 100% rename from samples_framework/include/MacCEGuiRendererSelector.h rename to samples/browser/include/MacCEGuiRendererSelector.h diff --git a/samples_framework/include/MetaDataWindowManager.h b/samples/browser/include/MetaDataWindowManager.h similarity index 95% rename from samples_framework/include/MetaDataWindowManager.h rename to samples/browser/include/MetaDataWindowManager.h index 197e28913..a15b39acb 100644 --- a/samples_framework/include/MetaDataWindowManager.h +++ b/samples/browser/include/MetaDataWindowManager.h @@ -32,7 +32,7 @@ namespace CEGUI class Window; } -class SampleData; +class SampleHandler; class MetaDataWindowManager { @@ -40,7 +40,7 @@ class MetaDataWindowManager MetaDataWindowManager(CEGUI::Window* metaDataWindow); virtual ~MetaDataWindowManager() {} - void setSampleInfo(SampleData* sampleData); + void setSampleInfo(SampleHandler* sampleData); CEGUI::Window* getWindow(); @@ -52,7 +52,6 @@ class MetaDataWindowManager CEGUI::Window* d_root; - CEGUI::Window* d_wndSampleType; CEGUI::Window* d_wndSummary; CEGUI::Window* d_wndDescription; CEGUI::Window* d_wndUsedFiles; diff --git a/samples_framework/include/SamplesFramework.h b/samples/browser/include/SampleBrowser.h similarity index 69% rename from samples_framework/include/SamplesFramework.h rename to samples/browser/include/SampleBrowser.h index 3fb890583..d8b5d3b73 100644 --- a/samples_framework/include/SamplesFramework.h +++ b/samples/browser/include/SampleBrowser.h @@ -24,41 +24,43 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Samples_Framework_h_ -#define _Samples_Framework_h_ +#ifndef _Samples_Browser_h_ +#define _Samples_Browser_h_ -#include "SamplesFrameworkBase.h" -#include "SampleData.h" +#include "SampleBrowserBase.h" +#include "SampleHandler.h" +#include "Sample.h" #include // forward declarations #include "CEGUI/ForwardRefs.h" -class SampleData; +using namespace CEGUI; + +class SampleHandler; class Sample; class MetaDataWindowManager; -class SamplesBrowserManager; - +class SampleBrowserManager; /*! \brief This is */ -class SamplesFramework : public SamplesFrameworkBase +class SampleBrowser : public SampleBrowserBase { public: - SamplesFramework(const CEGUI::String& xml_filename); - virtual ~SamplesFramework(); + SampleBrowser(); + virtual ~SampleBrowser(); + + typedef std::vector SampleList; static void setDefaultResourceGroup(const CEGUI::String& resourceGroup); bool initialise(); void deinitialise(); - void addSampleDataCppModule(CEGUI::String sampleName, CEGUI::String summary, - CEGUI::String description, - SampleType sampleTypeEnum, CEGUI::String credits); + void loadSamples(); void handleSampleSelection(CEGUI::Window* sampleWindow); void handleStartDisplaySample(CEGUI::Window* sampleWindow); @@ -69,7 +71,7 @@ class SamplesFramework : public SamplesFrameworkBase virtual void renderGUIContexts(); - SampleData* findSampleData(CEGUI::Window* sampleWindow); + SampleHandler* findSampleData(CEGUI::Window* sampleWindow); virtual bool injectKeyDown(const CEGUI::Key::Scan& ceguiKey); virtual bool injectKeyUp(const CEGUI::Key::Scan& ceguiKey); @@ -79,16 +81,10 @@ class SamplesFramework : public SamplesFrameworkBase virtual bool injectMouseWheelChange(float position); virtual bool injectMousePosition(float x, float y); - static const CEGUI::String XMLSchemaName; - protected: void initialiseLoadScreenLayout(); void initialiseSampleBrowserLayout(); - void loadSamplesDataFromXML(const CEGUI::String& filename); - void getSampleInstanceFromDLL(SampleData& sampleData); - - void addSample(SampleData* sampleData); bool initialiseSampleStepwise(int sampleNumber); @@ -107,24 +103,25 @@ class SamplesFramework : public SamplesFrameworkBase bool areWindowsIntersecting(CEGUI::Window* window1, CEGUI::Window* window2); - CEGUI::Window* d_root; + CEGUI::InputAggregator* getCurrentInputAggregator(); - CEGUI::PushButton* d_sampleExitButton; + CEGUI::Window* d_root; - std::vector d_samples; + CEGUI::PushButton* d_sampleExitButton; - MetaDataWindowManager* d_metaDataWinMgr; - SamplesBrowserManager* d_samplesWinMgr; + SampleList d_samples; - SampleData* d_selectedSampleData; + MetaDataWindowManager* d_metaDataWinMgr; + SampleBrowserManager* d_samplesWinMgr; - CEGUI::ProgressBar* d_loadingProgressBar; - CEGUI::Window* d_loadingScreenText; - CEGUI::Window* d_loadScreenChunkProgressText; + SampleHandler* d_selectedSampleData; - bool d_quittingSampleView; + CEGUI::ProgressBar* d_loadingProgressBar; + CEGUI::Window* d_loadingScreenText; + CEGUI::Window* d_loadScreenChunkProgressText; - CEGUI::String d_samplesXMLFilename; + bool d_quittingSampleView; + CEGUI::InputAggregator* d_systemInputAggregator; }; #endif diff --git a/samples_framework/include/SamplesFrameworkBase.h b/samples/browser/include/SampleBrowserBase.h similarity index 96% rename from samples_framework/include/SamplesFrameworkBase.h rename to samples/browser/include/SampleBrowserBase.h index f65caf035..c24ebd3da 100644 --- a/samples_framework/include/SamplesFrameworkBase.h +++ b/samples/browser/include/SampleBrowserBase.h @@ -24,8 +24,8 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _SamplesFrameworkBase_h_ -#define _SamplesFrameworkBase_h_ +#ifndef _SampleBrowserBase_h_ +#define _SampleBrowserBase_h_ // forward declarations class CEGuiBaseApplication; @@ -39,21 +39,21 @@ class CEGuiRendererSelector; Here we take care of common things such the renderer selection and application startup. */ -class SamplesFrameworkBase +class SampleBrowserBase { public: /*! \brief Constructor. */ - SamplesFrameworkBase(); + SampleBrowserBase(); /*! \brief Destructor. */ - virtual ~SamplesFrameworkBase(); + virtual ~SampleBrowserBase(); /*! @@ -214,4 +214,4 @@ class SamplesFrameworkBase int d_appWindowHeight; //!< Int defining the application window's height. }; -#endif // end of guard _SamplesFrameworkBase_h_ +#endif // end of guard _SampleBrowserBase_h_ diff --git a/samples_framework/include/SamplesBrowserManager.h b/samples/browser/include/SampleBrowserManager.h similarity index 84% rename from samples_framework/include/SamplesBrowserManager.h rename to samples/browser/include/SampleBrowserManager.h index 7738faa6b..40aea37e1 100644 --- a/samples_framework/include/SamplesBrowserManager.h +++ b/samples/browser/include/SampleBrowserManager.h @@ -24,8 +24,8 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _SamplesBrowserManager_h_ -#define _SamplesBrowserManager_h_ +#ifndef _SampleBrowserManager_h_ +#define _SampleBrowserManager_h_ #include #include @@ -35,13 +35,13 @@ author: Lukas E Meindl #include "CEGUI/ForwardRefs.h" -class SamplesFramework; +class SampleBrowser; -class SamplesBrowserManager +class SampleBrowserManager { public: - SamplesBrowserManager(SamplesFramework* owner, CEGUI::Window* samplesWindow); - virtual ~SamplesBrowserManager() {} + SampleBrowserManager(SampleBrowser* owner, CEGUI::Window* samplesWindow); + virtual ~SampleBrowserManager() {} CEGUI::Window* getWindow(); @@ -52,18 +52,18 @@ class SamplesBrowserManager void selectSampleWindow(CEGUI::Window* wnd); private: - SamplesBrowserManager(const SamplesBrowserManager&) {} + SampleBrowserManager(const SampleBrowserManager&) {} void init(); - SamplesBrowserManager& operator=(const SamplesBrowserManager&) {} + SampleBrowserManager& operator=(const SampleBrowserManager&) {} static const CEGUI::uint32 d_sampleWindowFrameNormal; static const CEGUI::uint32 d_sampleWindowFrameSelected; void updateWindows(); - bool handleMouseClickSampleWindow(const CEGUI::EventArgs& args); - bool handleMouseMoveSampleWindow(const CEGUI::EventArgs& args); + bool handlePointerActivateSampleWindow(const CEGUI::EventArgs& args); + bool handlePointerMoveSampleWindow(const CEGUI::EventArgs& args); bool handleLeaveSampleWindow(const CEGUI::EventArgs& args); bool handleSampleEnterButtonClicked(const CEGUI::EventArgs& args); @@ -74,7 +74,7 @@ class SamplesBrowserManager CEGUI::PushButton* createPreviewHeaderEnterButton(); CEGUI::HorizontalLayoutContainer* createPreviewHeader(); - SamplesFramework* d_owner; + SampleBrowser* d_owner; CEGUI::Window* d_root; CEGUI::VerticalLayoutContainer* d_verticalLayoutContainerSamples; diff --git a/samples_framework/include/SampleData.h b/samples/browser/include/SampleHandler.h similarity index 64% rename from samples_framework/include/SampleData.h rename to samples/browser/include/SampleHandler.h index 953df8015..8ebd0cc55 100644 --- a/samples_framework/include/SampleData.h +++ b/samples/browser/include/SampleHandler.h @@ -24,41 +24,35 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#ifndef _Sample_Data_h_ -#define _Sample_Data_h_ +#ifndef _Sample_Handler_h_ +#define _Sample_Handler_h_ #include "CEGUI/String.h" // forward declarations #include "CEGUI/ForwardRefs.h" +#include "Sample.h" + namespace CEGUI { - class BasicImage; + class BitmapImage; } -enum SampleType -{ - ST_Module, - ST_Lua, - ST_Python, - - ST_Count -}; - class Sample; -class SampleData +class SampleHandler { public: - SampleData(CEGUI::String sampleName, CEGUI::String summary, - CEGUI::String description, SampleType sampleTypeEnum, CEGUI::String credits); - virtual ~SampleData(); + SampleHandler(Sample* instance); + virtual ~SampleHandler(); virtual void initialise(int width, int height); + virtual void deinitialise(); virtual CEGUI::GUIContext* getGuiContext(); + virtual CEGUI::InputAggregator* getInputAggregator(); virtual void handleNewWindowSize(float width, float height); void setTextureTargetImageArea(float height, float width); @@ -67,53 +61,42 @@ class SampleData virtual void setGUIContextRTT(); virtual void clearRTTTexture(); - virtual void onEnteringSample() = 0; - virtual void update(float timeSinceLastUpdate) {}; + virtual void onEnteringSample(); + virtual void update(float timeSinceLastUpdate); void setSampleWindow(CEGUI::Window* sampleWindow); CEGUI::Window* getSampleWindow(); - CEGUI::String getName(); - CEGUI::String getSummary(); - CEGUI::String getSampleTypeString(); - CEGUI::String getDescription(); - CEGUI::String getUsedFilesString(); - CEGUI::String getCredits(); + CEGUI::String getNameText(); + CEGUI::String getSummaryText(); + CEGUI::String getDescriptionText(); + CEGUI::String getUsedFilesText(); + CEGUI::String getCreditsText(); + + const Sample* getSample() const; protected: - CEGUI::String d_name; - CEGUI::String d_summary; - CEGUI::String d_description; - SampleType d_type; + //! The Sample we are wrapping in this class + Sample* d_sample; + //! A string containing a list of files used for the sample CEGUI::String d_usedFilesString; - CEGUI::String d_credits; - + //! The root window of the sample CEGUI::Window* d_sampleWindow; - + //! The GUIContext created to contain the sample root CEGUI::GUIContext* d_guiContext; + //! The input aggregator which is created for the GUIContext + CEGUI::InputAggregator* d_inputAggregator; + //! A bool determining if the input aggregator of this sample is the default one or a manually created one + bool d_nonDefaultInputAggregator; + //! The texture target onto which the Sample will be rendered CEGUI::TextureTarget* d_textureTarget; - CEGUI::BasicImage* d_textureTargetImage; -}; - -class SampleDataModule : public SampleData -{ -public: - SampleDataModule(CEGUI::String sampleName, CEGUI::String summary, - CEGUI::String description, SampleType sampleTypeEnum, CEGUI::String credits); - virtual ~SampleDataModule(); - - virtual void getSampleInstanceFromDLL(); - - virtual void initialise(int width, int height); - virtual void deinitialise(); - - virtual void onEnteringSample(); - - virtual void update(float timeSinceLastUpdate); + //! The Bitmap image which is used to display the Sample as a rendered preview in connection with the texture target + CEGUI::BitmapImage* d_textureTargetImage; private: - CEGUI::DynamicModule* d_dynamicModule; - Sample* d_sample; + void initialiseSamplePreviewRenderTarget(int width, int height); + void initialiseSample(); + void initialiseInputAggregator(); }; #endif diff --git a/samples_framework/include/Win32AppHelper.h b/samples/browser/include/Win32AppHelper.h similarity index 95% rename from samples_framework/include/Win32AppHelper.h rename to samples/browser/include/Win32AppHelper.h index 13139eaf6..31fbb0d6d 100644 --- a/samples_framework/include/Win32AppHelper.h +++ b/samples/browser/include/Win32AppHelper.h @@ -31,6 +31,7 @@ # define WIN32_LEAN_AND_MEAN # include +#define DIRECTINPUT_VERSION 0x0800 #include // undefine Microsoft macro evilness @@ -43,7 +44,7 @@ # pragma comment(lib, "dxguid.lib") #endif -class SamplesFrameworkBase; +class SampleBrowserBase; /*! @@ -71,7 +72,7 @@ class Win32AppHelper static bool doWin32Events(bool& idle); static LRESULT CALLBACK wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - static void setSamplesFramework(SamplesFrameworkBase* samplesFramework); + static void setSampleBrowser(SampleBrowserBase* sampleBrowser); /************************************************************************* Constants @@ -90,7 +91,7 @@ class Win32AppHelper private: static bool s_mouseInWindow; - static SamplesFrameworkBase* s_samplesFramework; + static SampleBrowserBase* s_sampleBrowser; }; #endif // end of guard _Win32AppHelper_h_ diff --git a/samples_framework/include/Win32CEGuiRendererSelector.h b/samples/browser/include/Win32CEGuiRendererSelector.h similarity index 100% rename from samples_framework/include/Win32CEGuiRendererSelector.h rename to samples/browser/include/Win32CEGuiRendererSelector.h diff --git a/samples/browser/src/AndroidAppHelper.cpp b/samples/browser/src/AndroidAppHelper.cpp new file mode 100644 index 000000000..889a78f26 --- /dev/null +++ b/samples/browser/src/AndroidAppHelper.cpp @@ -0,0 +1,484 @@ +/*********************************************************************** + created: 28/9/2014 + author: David Reepmeyer +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include "AndroidAppHelper.h" +#ifdef CEGUI_SAMPLES_ANDROID_GLES2 +# include "CEGuiEGLBaseApplication.h" +# include "SampleBrowserBase.h" +#elif defined(CEGUI_SAMPLES_ANDROID_OGRE) +AndroidInputInjector* AndroidAppHelper::mInputInjector = NULL; +AndroidMultiTouch* AndroidAppHelper::mTouch = NULL; +AndroidKeyboard* AndroidAppHelper::mKeyboard = NULL; +Ogre::FileSystemLayer* AndroidAppHelper::mFSLayer; // File system abstraction layer +OIS::MultiTouchListener* AndroidAppHelper::mMultiTouchListener = NULL; +OIS::KeyListener* AndroidAppHelper::mKeyListener = NULL; +Ogre::RenderWindow* AndroidAppHelper::mRenderWnd = NULL; +#endif + +bool AndroidAppHelper::d_windowCreated = false; + +#ifdef CEGUI_SAMPLES_ANDROID_GLES2 +//----------------------------------------------------------------------------// +int32_t AndroidAppHelper::handleInput (struct android_app* app, AInputEvent* event) +{ + static int prev_x = -1; + static int prev_y = -1; + if (true) + { + if (AInputEvent_getType (event) == AINPUT_EVENT_TYPE_MOTION) + { + int action = (int) (AMOTION_EVENT_ACTION_MASK & AMotionEvent_getAction (event)); + float x = AMotionEvent_getRawX (event, 0); + float y = AMotionEvent_getRawY (event, 0); + if (action == AMOTION_EVENT_ACTION_MOVE) + { + if (prev_x > 0 || prev_y > 0) + { + float delta_x = x - prev_x; + float delta_y = y - prev_x; + CEGuiEGLBaseApplication::getSingleton().getSampleApp()->injectMousePosition ( + static_cast (x), static_cast (y)); + } + } + else if (action == AMOTION_EVENT_ACTION_DOWN) + { + CEGuiEGLBaseApplication::getSingleton().getSampleApp()->injectMousePosition (x, y); + CEGuiEGLBaseApplication::getSingleton().getSampleApp()->injectMouseButtonDown (CEGUI::LeftButton); + } + else if (action == AMOTION_EVENT_ACTION_UP) + { + CEGuiEGLBaseApplication::getSingleton().getSampleApp()->injectMouseButtonUp (CEGUI::LeftButton); + } + prev_x = x; + prev_y = y; + } + else if (AInputEvent_getType (event) == AINPUT_EVENT_TYPE_KEY) + { + //keyboard injection + } + + return 1; + } + return 0; + +} + +#elif defined(CEGUI_SAMPLES_ANDROID_OGRE) +int32_t AndroidAppHelper::handleInput (struct android_app* app, AInputEvent* event) +{ + if (mInputInjector) + { + if (AInputEvent_getType (event) == AINPUT_EVENT_TYPE_MOTION) + { + int action = (int) (AMOTION_EVENT_ACTION_MASK & AMotionEvent_getAction (event)); + + if (action == 0) + { + mInputInjector->injectTouchEvent (2, AMotionEvent_getRawX (event, 0), + AMotionEvent_getRawY (event, 0)); + } + mInputInjector->injectTouchEvent (action, AMotionEvent_getRawX (event, 0), + AMotionEvent_getRawY (event, 0)); + } + else + { + mInputInjector->injectKeyEvent (AKeyEvent_getAction (event), AKeyEvent_getKeyCode (event)); + } + + return 1; + } + return 0; +} + + +#endif + +#ifdef CEGUI_SAMPLES_ANDROID_GLES2 +//----------------------------------------------------------------------------// +void AndroidAppHelper::handleCmd (struct android_app* app, int32_t cmd) +{ + switch (cmd) + { + case APP_CMD_SAVE_STATE: + break; + case APP_CMD_INIT_WINDOW: + if (app->window != NULL) + { + if (!isWindowCreated()) + { + CEGuiEGLBaseApplication::getSingleton().setNativeWindow(app->window); +#ifdef CEGUI_GLES3_SUPPORT + CEGuiEGLBaseApplication::getSingleton().init (3); +#else + CEGuiEGLBaseApplication::getSingleton().init (2); +#endif + setWindowCreated (true); + } + else + { + CEGuiEGLBaseApplication::getSingleton().setNativeWindow(app->window); + CEGuiEGLBaseApplication::getSingleton().resume (); + } + } + break; + case APP_CMD_TERM_WINDOW: + CEGuiEGLBaseApplication::getSingleton().terminate(); + break; + case APP_CMD_GAINED_FOCUS: + CEGuiEGLBaseApplication::getSingleton().setNativeWindow(app->window); + CEGuiEGLBaseApplication::getSingleton().resume (); + break; + case APP_CMD_LOST_FOCUS: + CEGuiEGLBaseApplication::getSingleton().suspend(); + CEGuiEGLBaseApplication::getSingleton().clearFrame(); + break; + } +} +#elif defined(CEGUI_SAMPLES_ANDROID_OGRE) +//----------------------------------------------------------------------------// +void AndroidAppHelper::handleCmd (struct android_app* app, int32_t cmd) +{ + switch (cmd) + { + case APP_CMD_SAVE_STATE: + break; + case APP_CMD_INIT_WINDOW: + if (app->window && Ogre::Root::getSingletonPtr()) + { + AConfiguration* config = AConfiguration_new(); + AConfiguration_fromAssetManager (config, app->activity->assetManager); + + if (!mRenderWnd) + { + Ogre::NameValuePairList opt; + opt["externalWindowHandle"] = Ogre::StringConverter::toString ((int)app->window); + opt["androidConfig"] = Ogre::StringConverter::toString ((int)config); + mRenderWnd = Ogre::Root::getSingleton().createRenderWindow ( + "OgreWindow", 0, 0, false, &opt); + setWindowCreated (true); + } + else + { + static_cast (mRenderWnd)->_createInternalResources ( app->window, config); + } + AConfiguration_delete (config); + } + break; + case APP_CMD_TERM_WINDOW: + if (Ogre::Root::getSingletonPtr() && mRenderWnd) + static_cast (mRenderWnd)->_destroyInternalResources(); + break; + case APP_CMD_GAINED_FOCUS: + break; + case APP_CMD_LOST_FOCUS: + break; + case APP_CMD_CONFIG_CHANGED: + break; + } +} +#endif + +bool AndroidAppHelper::processEvents() +{ + int ident, events; + struct android_poll_source* source; + struct android_app* state = CEGUI::AndroidUtils::getAndroidApp(); + while ((ident = ALooper_pollAll (0, NULL, &events, (void**)&source)) >= 0) + { + if (source != NULL) + source->process (state, source); + if (state->destroyRequested != 0) + return false; + } + return true; +} +#ifdef CEGUI_SAMPLES_ANDROID_OGRE +void AndroidAppHelper::go() +{ + while (true) + { + bool processResult = processEvents(); + Ogre::WindowEventUtilities::messagePump(); + if (mRenderWnd != NULL && mRenderWnd->isActive()) + { + mRenderWnd->windowMovedOrResized(); + Ogre::Root::getSingletonPtr()->renderOneFrame(); + } + } +} +#endif + +//----------------------------------------------------------------------------// +bool AndroidAppHelper::createWindow() +{ + int ident, events; + struct android_poll_source* source; + struct android_app* state = CEGUI::AndroidUtils::getAndroidApp(); + state->onAppCmd = handleCmd; + while (!d_windowCreated) + { + //This will process until the android window is created. + while ((ident = ALooper_pollAll (0, NULL, &events, (void**)&source)) >= 0) + { + if (source) + source->process (state, source); + if (state->destroyRequested != 0) + { + return false; + } + } + } + state->onInputEvent = handleInput; + return true; +} + +//----------------------------------------------------------------------------// +bool AndroidAppHelper::isWindowCreated() +{ + return d_windowCreated; +} + +//----------------------------------------------------------------------------// +void AndroidAppHelper::setWindowCreated (bool windowCreated) +{ + d_windowCreated = windowCreated; +} + +#ifdef CEGUI_SAMPLES_ANDROID_OGRE +//----------------------------------------------------------------------------// +AndroidMultiTouch::AndroidMultiTouch(): OIS::MultiTouch ("Ogre", false, 0, 0) +{ +} + +//----------------------------------------------------------------------------// +void AndroidMultiTouch::setBuffered (bool buffered) +{ +} + +//----------------------------------------------------------------------------// +void AndroidMultiTouch::capture() {} + +//----------------------------------------------------------------------------// +OIS::Interface* AndroidMultiTouch::queryInterface (OIS::Interface::IType type) +{ + return 0; +} + +//----------------------------------------------------------------------------// +void AndroidMultiTouch::_initialize() {} + +//----------------------------------------------------------------------------// +OIS::MultiTouchState& AndroidMultiTouch::getMultiTouchState (int i) +{ + while (i >= mStates.size()) + { + Ogre::RenderWindow* pRenderWnd = + static_cast (Ogre::Root::getSingleton().getRenderTarget ("OgreWindow")); + if (pRenderWnd) + { + OIS::MultiTouchState state; + state.width = pRenderWnd->getWidth(); + state.height = pRenderWnd->getHeight(); + mStates.push_back (state); + } + } + return mStates[i]; +} + +//----------------------------------------------------------------------------// +AndroidKeyboard::AndroidKeyboard(): OIS::Keyboard ("Ogre", false, 1, 0) +{ +} + +//----------------------------------------------------------------------------// +void AndroidKeyboard::setBuffered (bool buffered) +{ +} + +//----------------------------------------------------------------------------// +void AndroidKeyboard::capture() +{ +} + +//----------------------------------------------------------------------------// +OIS::Interface* AndroidKeyboard::queryInterface (OIS::Interface::IType type) +{ + return 0; +} + +//----------------------------------------------------------------------------// +void AndroidKeyboard::_initialize() +{ +} + +//----------------------------------------------------------------------------// +bool AndroidKeyboard::isKeyDown (OIS::KeyCode key) const +{ + return false; +} + +//----------------------------------------------------------------------------// +const std::string& AndroidKeyboard::getAsString (OIS::KeyCode kc) +{ + static std::string defstr = ""; + return defstr; +} + +//----------------------------------------------------------------------------// +void AndroidKeyboard::copyKeyStates (char keys[256]) const +{ +} + +//----------------------------------------------------------------------------// +AndroidInputInjector::AndroidInputInjector (OIS::KeyListener *keyListener, OIS::MultiTouchListener *touchListener, + AndroidMultiTouch* touch, AndroidKeyboard* keyboard) + : keyListener (keyListener), touchListener (touchListener), mTouch (touch), mKeyboard (keyboard) +{ +} + +//----------------------------------------------------------------------------// +void AndroidInputInjector::injectKeyEvent (int action, int32_t keyCode) +{ + if (keyCode == AKEYCODE_BACK) + { + OIS::KeyEvent evt (mKeyboard, OIS::KC_ESCAPE, 0); + if (action == 0) + { + keyListener->keyPressed (evt); + } + else + { + keyListener->keyReleased (evt); + } + } +} + +//----------------------------------------------------------------------------// +void AndroidInputInjector::injectTouchEvent (int action, float x, float y, int pointerId) +{ + OIS::MultiTouchState &state = mTouch->getMultiTouchState (pointerId); + + switch (action) + { + case 0: + state.touchType = OIS::MT_Pressed; + break; + case 1: + state.touchType = OIS::MT_Released; + break; + case 2: + state.touchType = OIS::MT_Moved; + break; + case 3: + state.touchType = OIS::MT_Cancelled; + break; + default: + state.touchType = OIS::MT_None; + } + + if (state.touchType != OIS::MT_None) + { + int last = state.X.abs; + state.X.abs = (int)x; + state.X.rel = state.X.abs - last; + + last = state.Y.abs; + state.Y.abs = (int)y; + state.Y.rel = state.Y.abs - last; + + state.Z.abs = 0; + state.Z.rel = 0; + + OIS::MultiTouchEvent evt (mTouch, state); + + switch (state.touchType) + { + case OIS::MT_Pressed: + touchListener->touchPressed (evt); + break; + case OIS::MT_Released: + touchListener->touchReleased (evt); + break; + case OIS::MT_Moved: + touchListener->touchMoved (evt); + break; + case OIS::MT_Cancelled: + touchListener->touchCancelled (evt); + break; + default: + break; + } + } +} +//----------------------------------------------------------------------------// +void AndroidAppHelper::shutdown() +{ + OGRE_DELETE_T (mFSLayer, FileSystemLayer, Ogre::MEMCATEGORY_GENERAL); + mRenderWnd = NULL; + mKeyListener = NULL; + mMultiTouchListener = NULL; + + delete mTouch; + mTouch = NULL; + + delete mKeyboard; + mKeyboard = NULL; + + delete mInputInjector; + mInputInjector = NULL; +} + +void AndroidAppHelper::initialiseFS() +{ + mFSLayer = OGRE_NEW_T (Ogre::FileSystemLayer, Ogre::MEMCATEGORY_GENERAL) (OGRE_VERSION_NAME); + AAssetManager* assetManager = CEGUI::AndroidUtils::getAndroidApp()->activity->assetManager; + Ogre::APKFileSystemArchiveFactory* apk = new Ogre::APKFileSystemArchiveFactory (assetManager); + Ogre::APKZipArchiveFactory* zip = new Ogre::APKZipArchiveFactory (assetManager); + Ogre::ArchiveManager::getSingleton().addArchiveFactory (apk); + Ogre::ArchiveManager::getSingleton().addArchiveFactory (zip); +} + +bool AndroidAppHelper::initialiseOIS (OIS::KeyListener* keyListener, + OIS::MultiTouchListener* mMultiTouchListener) +{ + if (!mTouch) + mTouch = new AndroidMultiTouch(); + if (!mKeyboard) + mKeyboard = new AndroidKeyboard(); + if (!mInputInjector) + mInputInjector = new AndroidInputInjector (mKeyListener, mMultiTouchListener, mTouch, mKeyboard); +} +Ogre::RenderWindow* AndroidAppHelper::getRenderWindow () +{ + return mRenderWnd; +} + +#endif + +//----------------------------------------------------------------------------// + + diff --git a/samples_framework/src/CEGuiBaseApplication.cpp b/samples/browser/src/CEGuiBaseApplication.cpp similarity index 78% rename from samples_framework/src/CEGuiBaseApplication.cpp rename to samples/browser/src/CEGuiBaseApplication.cpp index 7c4d881aa..24aadd7d1 100644 --- a/samples_framework/src/CEGuiBaseApplication.cpp +++ b/samples/browser/src/CEGuiBaseApplication.cpp @@ -24,9 +24,13 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ +#ifdef __APPLE__ +# include +#endif + #include "CEGUISamplesConfig.h" #include "CEGuiBaseApplication.h" -#include "SamplesFramework.h" +#include "SampleBrowser.h" #include "CEGUI/System.h" #include "CEGUI/DefaultResourceProvider.h" #include "CEGUI/ImageManager.h" @@ -46,10 +50,6 @@ #include #include -#ifdef __APPLE__ -# include -#endif - // setup default-default path #ifndef CEGUI_SAMPLE_DATAPATH #define CEGUI_SAMPLE_DATAPATH "../datafiles" @@ -59,7 +59,7 @@ Static / Const data *************************************************************************/ const char CEGuiBaseApplication::DATAPATH_VAR_NAME[] = "CEGUI_SAMPLE_DATAPATH"; -SamplesFrameworkBase* CEGuiBaseApplication::d_sampleApp(0); +SampleBrowserBase* CEGuiBaseApplication::d_sampleApp(0); //----------------------------------------------------------------------------// CEGuiBaseApplication::CEGuiBaseApplication() : @@ -69,7 +69,7 @@ CEGuiBaseApplication::CEGuiBaseApplication() : d_resourceProvider(0), d_logoGeometry(0), d_FPSGeometry(0), - d_FPSElapsed(0.0f), + d_FPSElapsed(1.0f), d_FPSFrames(0), d_FPSValue(0), d_spinLogo(false) @@ -106,7 +106,7 @@ void CEGuiBaseApplication::renderSingleFrame(const float elapsed) } //----------------------------------------------------------------------------// -bool CEGuiBaseApplication::execute(SamplesFrameworkBase* sampleApp) +bool CEGuiBaseApplication::execute(SampleBrowserBase* sampleApp) { d_sampleApp = sampleApp; @@ -121,23 +121,18 @@ bool CEGuiBaseApplication::execute(SamplesFrameworkBase* sampleApp) initialiseResourceGroupDirectories(); initialiseDefaultResourceGroups(); - const CEGUI::Rectf scrn(CEGUI::Vector2f(0, 0), d_renderer->getDisplaySize()); - - // setup for FPS value - d_FPSGeometry = &d_renderer->createGeometryBuffer(); - d_FPSGeometry->setClippingRegion(scrn); - positionFPS(); - - // setup for spinning logo - d_logoGeometry = &d_renderer->createGeometryBuffer(); - d_logoGeometry->setPivot(CEGUI::Vector3f(91.5f, 44.5f, 0)); - positionLogo(); + const CEGUI::Rectf scrn(glm::vec2(0, 0), d_renderer->getDisplaySize()); // create logo imageset and draw the image (we only ever draw this once) - CEGUI::ImageManager::getSingleton().addFromImageFile("cegui_logo", + CEGUI::ImageManager::getSingleton().addBitmapImageFromFile("cegui_logo", "logo.png"); CEGUI::ImageManager::getSingleton().get("cegui_logo").render( - *d_logoGeometry, CEGUI::Rectf(0, 0, 183, 89), 0, CEGUI::ColourRect(0xFFFFFFFF)); + d_logoGeometry, CEGUI::Rectf(0, 0, 183, 89), 0, false, CEGUI::ColourRect(0xFFFFFFFF)); + + // initial position update of the logo + updateLogoGeometry(); + // setup for spinning logo + updateLogoGeometryRotation(); // clearing this queue actually makes sure it's created(!) CEGUI::System::getSingleton().getDefaultGUIContext().clearGeometry(CEGUI::RQ_OVERLAY); @@ -171,8 +166,17 @@ bool CEGuiBaseApplication::execute(SamplesFrameworkBase* sampleApp) void CEGuiBaseApplication::cleanup() { CEGUI::ImageManager::getSingleton().destroy("cegui_logo"); - d_renderer->destroyGeometryBuffer(*d_logoGeometry); - d_renderer->destroyGeometryBuffer(*d_FPSGeometry); + + const size_t logo_buffer_count = d_logoGeometry.size(); + for (size_t i = 0; i < logo_buffer_count; ++i) + d_renderer->destroyGeometryBuffer(*d_logoGeometry.at(i)); + d_logoGeometry.clear(); + + const size_t fps_buffer_count = d_FPSGeometry.size(); + for (size_t i = 0; i < fps_buffer_count; ++i) + d_renderer->destroyGeometryBuffer(*d_FPSGeometry.at(i)); + d_FPSGeometry.clear(); + CEGUI::System::destroy(); } @@ -201,9 +205,9 @@ void CEGuiBaseApplication::initialiseResourceGroupDirectories() sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/"); rp->setResourceGroupDirectory("lua_scripts", resourcePath); sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/"); - rp->setResourceGroupDirectory("schemas", resourcePath); + rp->setResourceGroupDirectory("schemas", resourcePath); sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations/"); - rp->setResourceGroupDirectory("animations", resourcePath); + rp->setResourceGroupDirectory("animations", resourcePath); } //----------------------------------------------------------------------------// @@ -263,9 +267,16 @@ bool CEGuiBaseApplication::sampleBrowserOverlayHandler(const CEGUI::EventArgs& a return false; // draw the logo - d_logoGeometry->draw(); + const size_t logo_buffer_count = d_logoGeometry.size(); + for (size_t i = 0; i < logo_buffer_count; ++i) + { + d_logoGeometry[i]->draw(); + } + // draw FPS value - d_FPSGeometry->draw(); + const size_t fps_buffer_count = d_FPSGeometry.size(); + for (size_t i = 0; i < fps_buffer_count; ++i) + d_FPSGeometry.at(i)->draw(); return true; } @@ -276,8 +287,10 @@ bool CEGuiBaseApplication::sampleOverlayHandler(const CEGUI::EventArgs& args) if (static_cast(args).queueID != CEGUI::RQ_OVERLAY) return false; - // draw FPS value - d_FPSGeometry->draw(); + // Draw FPS value + const size_t bufferCount = d_FPSGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + d_FPSGeometry.at(i)->draw(); return true; } @@ -302,15 +315,21 @@ void CEGuiBaseApplication::updateFPS(const float elapsed) char fps_textbuff[16]; sprintf(fps_textbuff , "FPS: %d", d_FPSValue); - d_FPSGeometry->reset(); - fnt->drawText(*d_FPSGeometry, fps_textbuff, CEGUI::Vector2f(0, 0), 0, - CEGUI::Colour(0xFFFFFFFF)); + const size_t bufferCount = d_FPSGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + d_renderer->destroyGeometryBuffer(*d_FPSGeometry.at(i)); + d_FPSGeometry.clear(); + + fnt->drawText(d_FPSGeometry, fps_textbuff, glm::vec2(0, 0), 0, false, + CEGUI::Colour(0xFFFFFFFF)); + + updateFPSGeometry(); } // reset counter state d_FPSFrames = 0; - float modValue = 1.f; + float modValue = 1.0f; d_FPSElapsed = std::modf(d_FPSElapsed, &modValue); } } @@ -322,29 +341,42 @@ void CEGuiBaseApplication::updateLogo(const float elapsed) return; static float rot = 0.0f; - d_logoGeometry->setRotation(CEGUI::Quaternion::eulerAnglesDegrees(rot, 0, 0)); + + const size_t bufferCount = d_logoGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + { + d_logoGeometry[i]->setRotation(glm::quat(glm::vec3(glm::radians(rot), 0, 0))); + } rot = fmodf(rot + 180.0f * elapsed, 360.0f); } //----------------------------------------------------------------------------// -void CEGuiBaseApplication::positionLogo() +void CEGuiBaseApplication::updateLogoGeometry() { const CEGUI::Rectf scrn(d_renderer->getDefaultRenderTarget().getArea()); + const glm::vec3 position(10.0f, scrn.getSize().d_height - 89.0f, 0.0f); - d_logoGeometry->setClippingRegion(scrn); - d_logoGeometry->setTranslation( - CEGUI::Vector3f(10.0f, scrn.getSize().d_height - 89.0f, 0.0f)); + const size_t bufferCount = d_logoGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + { + d_logoGeometry[i]->setClippingRegion(scrn); + d_logoGeometry[i]->setTranslation(position); + } } //----------------------------------------------------------------------------// -void CEGuiBaseApplication::positionFPS() +void CEGuiBaseApplication::updateFPSGeometry() { const CEGUI::Rectf scrn(d_renderer->getDefaultRenderTarget().getArea()); + const glm::vec3 position(scrn.getSize().d_width - 120.0f, 0.0f, 0.0f); - d_FPSGeometry->setClippingRegion(scrn); - d_FPSGeometry->setTranslation( - CEGUI::Vector3f(scrn.getSize().d_width - 120.0f, 0.0f, 0.0f)); + const size_t bufferCount = d_FPSGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + { + d_FPSGeometry[i]->setClippingRegion(scrn); + d_FPSGeometry[i]->setTranslation(position); + } } @@ -352,19 +384,24 @@ void CEGuiBaseApplication::positionFPS() bool CEGuiBaseApplication::resizeHandler(const CEGUI::EventArgs& /*args*/) { // clear FPS geometry and see that it gets recreated in the next frame - d_FPSGeometry->reset(); + const size_t bufferCount = d_FPSGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + d_renderer->destroyGeometryBuffer(*d_FPSGeometry.at(i)); + d_FPSGeometry.clear(); + d_FPSValue = 0; const CEGUI::Rectf& area(CEGUI::System::getSingleton().getRenderer()-> getDefaultRenderTarget().getArea()); d_sampleApp->handleNewWindowSize(area.getWidth(), area.getHeight()); - positionLogo(); + updateLogoGeometry(); + updateFPSGeometry(); + return true; } //----------------------------------------------------------------------------// - void CEGuiBaseApplication::registerSampleOverlayHandler(CEGUI::GUIContext* gui_context) { // clearing this queue actually makes sure it's created(!) @@ -376,5 +413,15 @@ void CEGuiBaseApplication::registerSampleOverlayHandler(CEGUI::GUIContext* gui_c this)); } +//----------------------------------------------------------------------------// +void CEGuiBaseApplication::updateLogoGeometryRotation() +{ + const size_t bufferCount = d_logoGeometry.size(); + for (size_t i = 0; i < bufferCount; ++i) + { + d_logoGeometry[i]->setPivot(glm::vec3(91.5f, 44.5f, 0)); + } +} -//----------------------------------------------------------------------------// \ No newline at end of file + +//----------------------------------------------------------------------------// diff --git a/samples_framework/src/CEGuiD3D11BaseApplication.cpp b/samples/browser/src/CEGuiD3D11BaseApplication.cpp similarity index 82% rename from samples_framework/src/CEGuiD3D11BaseApplication.cpp rename to samples/browser/src/CEGuiD3D11BaseApplication.cpp index 8db5471b0..dd2822ea8 100644 --- a/samples_framework/src/CEGuiD3D11BaseApplication.cpp +++ b/samples/browser/src/CEGuiD3D11BaseApplication.cpp @@ -30,12 +30,13 @@ #include "CEGuiD3D11BaseApplication.h" #include "CEGUI/RendererModules/Direct3D11/Renderer.h" -#include "SamplesFrameworkBase.h" +#include "SampleBrowserBase.h" #include "Win32AppHelper.h" #include "CEGUI/CEGUI.h" #include #include +#define DIRECTINPUT_VERSION 0x0800 #include //----------------------------------------------------------------------------// @@ -107,7 +108,7 @@ CEGuiD3D11BaseApplication::~CEGuiD3D11BaseApplication() void CEGuiD3D11BaseApplication::run() { d_sampleApp->initialise(); - Win32AppHelper::setSamplesFramework(d_sampleApp); + Win32AppHelper::setSampleBrowser(d_sampleApp); float clear_colour[4] = {0.0f, 0.0f, 0.0f, 0.0f}; @@ -190,15 +191,66 @@ bool CEGuiD3D11BaseApplication::initialiseDirect3D(unsigned int width, scd.SampleDesc.Quality = 0; scd.Windowed = windowed; + UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; + + +#if defined(DEBUG) || defined (_DEBUG) + creationFlags |= D3D11_CREATE_DEVICE_DEBUG; +#endif + + const D3D_FEATURE_LEVEL featureLevels[] = + { + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1, + }; + // initialise main parts of D3D res = D3D11CreateDeviceAndSwapChain(0, D3D_DRIVER_TYPE_HARDWARE, - 0, 0, 0, 0, D3D11_SDK_VERSION, + 0, creationFlags, featureLevels, + 6, D3D11_SDK_VERSION, &scd, &pimpl->d_swapChain, &pimpl->d_device, &pimpl->d_featureLevel, &pimpl->d_context); if (SUCCEEDED(res)) { + //Debugging stuff + ID3D11Debug* d3dDebug = 0; + if( SUCCEEDED( pimpl->d_device->QueryInterface( __uuidof(ID3D11Debug), (void**)&d3dDebug ) ) ) + { + ID3D11InfoQueue* d3dInfoQueue = 0; + if( SUCCEEDED( d3dDebug->QueryInterface( __uuidof(ID3D11InfoQueue), (void**)&d3dInfoQueue ) ) ) + { + #if defined(DEBUG) || defined (_DEBUG) + d3dInfoQueue->SetBreakOnSeverity( D3D11_MESSAGE_SEVERITY_CORRUPTION, true ); + d3dInfoQueue->SetBreakOnSeverity( D3D11_MESSAGE_SEVERITY_ERROR, true ); + #endif + + D3D11_MESSAGE_ID hide [] = + { + D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS, + // Add more message IDs here as needed + }; + + D3D11_INFO_QUEUE_FILTER filter; + memset( &filter, 0, sizeof(filter) ); + filter.DenyList.NumIDs = _countof(hide); + filter.DenyList.pIDList = hide; + d3dInfoQueue->AddStorageFilterEntries( &filter ); + d3dInfoQueue->Release(); + } + + d3dDebug->ReportLiveDeviceObjects(D3D11_RLDO_SUMMARY | D3D11_RLDO_DETAIL); + + d3dDebug->Release(); + } + + + // obtain handle to thr back buffer of the swap chain ID3D11Texture2D* back_buffer; res = pimpl->d_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), diff --git a/samples_framework/src/CEGuiDirectFBBaseApplication.cpp b/samples/browser/src/CEGuiDirectFBBaseApplication.cpp similarity index 100% rename from samples_framework/src/CEGuiDirectFBBaseApplication.cpp rename to samples/browser/src/CEGuiDirectFBBaseApplication.cpp diff --git a/samples/browser/src/CEGuiEGLBaseApplication.cpp b/samples/browser/src/CEGuiEGLBaseApplication.cpp new file mode 100644 index 000000000..20c64e634 --- /dev/null +++ b/samples/browser/src/CEGuiEGLBaseApplication.cpp @@ -0,0 +1,398 @@ +/*********************************************************************** + created: 28/9/2014 + author: David Reepmeyer +*************************************************************************/ +/*************************************************************************** + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) +# include +#endif + +#include "CEGUISamplesConfig.h" +#include "SampleBrowserBase.h" +#include "CEGUI/CEGUI.h" + +#include +#include + +#include +#include "CEGuiEGLBaseApplication.h" + +//----------------------------------------------------------------------------// +CEGuiEGLBaseApplication* CEGuiEGLBaseApplication::d_appInstance = 0; + +//----------------------------------------------------------------------------// +CEGuiEGLBaseApplication::CEGuiEGLBaseApplication() : + d_display(EGL_NO_DISPLAY), + d_surface(EGL_NO_SURFACE), + d_context(EGL_NO_CONTEXT), + d_width(0), + d_height(0), + d_contextInitialised(false), + d_contextValid(false), + d_glesVersion(0) +{ + if(d_appInstance) + throw CEGUI::InvalidRequestException("CEGuiEGLBaseApplication instance already exists!"); + + d_appInstance = this; +#ifdef __ANDROID__ + AndroidAppHelper::createWindow(); +#endif + d_renderer = &CEGUI::GLES2Renderer::create(); +} + +//----------------------------------------------------------------------------// +CEGuiEGLBaseApplication::~CEGuiEGLBaseApplication() +{ + terminate(); +} + +CEGuiEGLBaseApplication& CEGuiEGLBaseApplication::getSingleton() +{ + return (*d_appInstance); +} + + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::run() +{ + + d_sampleApp->initialise(); + + d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + + clock_gettime(CLOCK_MONOTONIC, &start_timespec); + + while(!d_sampleApp->isQuitting()) + { + drawFrame(); + +#ifdef __ANDROID__ + + if(!AndroidAppHelper::processEvents()) + { + d_sampleApp->setQuitting(true); + terminate(); + } + +#endif + if(d_windowSized) + { + d_windowSized = false; + //CEGUI::System::getSingleton().notifyDisplaySizeChanged( + //CEGUI::Sizef(static_cast(d_newWindowWidth), + //static_cast(d_newWindowHeight))); + } + + } + + d_sampleApp->deinitialise(); +} + +//----------------------------------------------------------------------------// +SampleBrowserBase* CEGuiEGLBaseApplication::getSampleApp() +{ + return d_sampleApp; +} + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::initialiseResourceGroupDirectories() +{ + // initialise the required dirs for the DefaultResourceProvider + CEGUI::DefaultResourceProvider* rp = + static_cast + (CEGUI::System::getSingleton().getResourceProvider()); +#ifdef __ANDROID__ + const char* dataPathPrefix = "datafiles"; +#else + const char* dataPathPrefix = getDataPathPrefix(); +#endif + char resourcePath[PATH_MAX]; + + // for each resource type, set a resource group directory + sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes"); + rp->setResourceGroupDirectory("schemes", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets"); + rp->setResourceGroupDirectory("imagesets", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts"); + rp->setResourceGroupDirectory("fonts", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts"); + rp->setResourceGroupDirectory("layouts", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel"); + rp->setResourceGroupDirectory("looknfeels", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts"); + rp->setResourceGroupDirectory("lua_scripts", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas"); + rp->setResourceGroupDirectory("schemas", resourcePath); + sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations"); + rp->setResourceGroupDirectory("animations", resourcePath); +} + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::destroyWindow() +{ + terminate(); +} + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::beginRendering(const float /*elapsed*/) +{ + clearFrame(); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, d_width, d_height); +} + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::endRendering() +{ + swap(); +} +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::clearFrame() +{ + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +} + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::drawFrame() +{ + d_appInstance->renderSingleFrame(static_cast(getElapsedTime())); +} + +double CEGuiEGLBaseApplication::getElapsedTime() +{ + timespec now_timespec; + clock_gettime(CLOCK_MONOTONIC, &now_timespec); + double elapsed = (now_timespec.tv_sec - start_timespec.tv_sec); + elapsed += ((double)(now_timespec.tv_nsec - start_timespec.tv_nsec)) / ((double) 1000000000L); + start_timespec = now_timespec; + return elapsed; +} + +//----------------------------------------------------------------------------// +bool CEGuiEGLBaseApplication::init(int openglesVersion) +{ + d_glesVersion = openglesVersion; + + if(d_contextInitialised) + return true; + + initEGLSurface(); + initEGLContext(); + + d_contextInitialised = true; + + return true; +} + +//----------------------------------------------------------------------------// +bool CEGuiEGLBaseApplication::initEGLSurface() +{ + + d_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + eglInitialize(d_display, 0, 0); + + const EGLint attribs[] = { EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES2_BIT, //Request opengl ES2.0 + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, + EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_NONE + }; + int32_t color_size_ = 8; + int32_t depth_size_ = 24; + + EGLint num_configs; + eglChooseConfig(d_display, attribs, &d_config, 1, &num_configs); + + if(!num_configs) + { + //Fall back to 16bit depth buffer + const EGLint attribs[] = { EGL_RENDERABLE_TYPE, + EGL_OPENGL_ES2_BIT, //Request opengl ES2.0 + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, + EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_NONE + }; + eglChooseConfig(d_display, attribs, &d_config, 1, &num_configs); + depth_size_ = 16; + } + + if(!num_configs) + { + return false; + } + + d_surface = eglCreateWindowSurface(d_display, d_config, d_window, NULL); + eglQuerySurface(d_display, d_surface, EGL_WIDTH, &d_width); + eglQuerySurface(d_display, d_surface, EGL_HEIGHT, &d_height); + EGLint format; + eglGetConfigAttrib(d_display, d_config, EGL_NATIVE_VISUAL_ID, &format); +#ifdef __ANDROID__ + ANativeWindow_setBuffersGeometry(d_window, 0, 0, format); +#endif + return true; +} + +//----------------------------------------------------------------------------// +bool CEGuiEGLBaseApplication::initEGLContext() +{ + const EGLint d_contextattribs[] = + { + EGL_CONTEXT_CLIENT_VERSION, d_glesVersion, //Request opengl es version (2/3) + EGL_NONE + }; + + d_context = eglCreateContext(d_display, d_config, NULL, d_contextattribs); + + if(eglMakeCurrent(d_display, d_surface, d_surface, d_context) == EGL_FALSE) + { + return false; + } + + d_contextValid = true; + return true; +} + +//----------------------------------------------------------------------------// +EGLint CEGuiEGLBaseApplication::swap() +{ + bool b = eglSwapBuffers(d_display, d_surface); + + if(!b) + { + EGLint err = eglGetError(); + + if(err == EGL_BAD_SURFACE) + { + //Recreate surface + initEGLSurface(); + return EGL_SUCCESS; //Still consider glContext is valid + } + else if(err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT) + { + //Context has been lost!! + d_contextValid = false; + terminate(); + initEGLContext(); + } + + return err; + } + + return EGL_SUCCESS; +} + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::terminate() +{ + if(d_display != EGL_NO_DISPLAY) + { + eglMakeCurrent(d_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + + if(d_context != EGL_NO_CONTEXT) + { + eglDestroyContext(d_display, d_context); + } + + if(d_surface != EGL_NO_SURFACE) + { + eglDestroySurface(d_display, d_surface); + } + + eglTerminate(d_display); + } + + d_display = EGL_NO_DISPLAY; + d_context = EGL_NO_CONTEXT; + d_surface = EGL_NO_SURFACE; + d_contextValid = false; + +} + +//----------------------------------------------------------------------------// +EGLint CEGuiEGLBaseApplication::resume() +{ + if(d_contextInitialised == false) + { + init(d_glesVersion); + return EGL_SUCCESS; + } + + int32_t original_widhth = d_width; + int32_t original_height = d_height; + + //Create surface + d_surface = eglCreateWindowSurface(d_display, d_config, d_window, NULL); + eglQuerySurface(d_display, d_surface, EGL_WIDTH, &d_width); + eglQuerySurface(d_display, d_surface, EGL_HEIGHT, &d_height); + + if(eglMakeCurrent(d_display, d_surface, d_surface, d_context) == EGL_TRUE) + return EGL_SUCCESS; + + EGLint err = eglGetError(); + + if(err == EGL_CONTEXT_LOST) + { + //Recreate context + initEGLContext(); + } + else + { + //Recreate surface + terminate(); + initEGLSurface(); + initEGLContext(); + } + + return err; +} + +//----------------------------------------------------------------------------// +#ifdef __ANDROID__ +void CEGuiEGLBaseApplication::setNativeWindow(ANativeWindow* window) +{ + d_window = window; +} +#endif + +//----------------------------------------------------------------------------// +void CEGuiEGLBaseApplication::suspend() +{ + if(d_surface != EGL_NO_SURFACE) + { + eglDestroySurface(d_display, d_surface); + d_surface = EGL_NO_SURFACE; + } +} + +//----------------------------------------------------------------------------// +bool CEGuiEGLBaseApplication::invalidate() +{ + terminate(); + + d_contextInitialised = false; + return true; +} + +//----------------------------------------------------------------------------// + diff --git a/samples_framework/src/CEGuiGLFWSharedBase.cpp b/samples/browser/src/CEGuiGLFWSharedBase.cpp similarity index 89% rename from samples_framework/src/CEGuiGLFWSharedBase.cpp rename to samples/browser/src/CEGuiGLFWSharedBase.cpp index f8406caff..1e498068a 100644 --- a/samples_framework/src/CEGuiGLFWSharedBase.cpp +++ b/samples/browser/src/CEGuiGLFWSharedBase.cpp @@ -30,7 +30,7 @@ author: Paul D Turner #include "CEGUISamplesConfig.h" #include "CEGuiGLFWSharedBase.h" -#include "SamplesFrameworkBase.h" +#include "SampleBrowserBase.h" #include "CEGUI/CEGUI.h" #include @@ -188,6 +188,33 @@ CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey) case GLFW_KEY_HOME : return CEGUI::Key::Home; case GLFW_KEY_END : return CEGUI::Key::End; case GLFW_KEY_KP_ENTER : return CEGUI::Key::NumpadEnter; + case GLFW_KEY_SPACE : return CEGUI::Key::Space; + case 'A' : return CEGUI::Key::A; + case 'B' : return CEGUI::Key::B; + case 'C' : return CEGUI::Key::C; + case 'D' : return CEGUI::Key::D; + case 'E' : return CEGUI::Key::E; + case 'F' : return CEGUI::Key::F; + case 'G' : return CEGUI::Key::G; + case 'H' : return CEGUI::Key::H; + case 'I' : return CEGUI::Key::I; + case 'J' : return CEGUI::Key::J; + case 'K' : return CEGUI::Key::K; + case 'L' : return CEGUI::Key::L; + case 'M' : return CEGUI::Key::M; + case 'N' : return CEGUI::Key::N; + case 'O' : return CEGUI::Key::O; + case 'P' : return CEGUI::Key::P; + case 'Q' : return CEGUI::Key::Q; + case 'R' : return CEGUI::Key::R; + case 'S' : return CEGUI::Key::S; + case 'T' : return CEGUI::Key::T; + case 'U' : return CEGUI::Key::U; + case 'V' : return CEGUI::Key::V; + case 'W' : return CEGUI::Key::W; + case 'X' : return CEGUI::Key::X; + case 'Y' : return CEGUI::Key::Y; + case 'Z' : return CEGUI::Key::Z; default : return CEGUI::Key::Unknown; } } @@ -306,7 +333,7 @@ void CEGuiGLFWSharedBase::initGLFW() //----------------------------------------------------------------------------// void CEGuiGLFWSharedBase::createGLFWWindow() { - if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 0, 0, 0, 0, 24, 8, GLFW_WINDOW) != GL_TRUE) + if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 8, 8, 8, 0, 24, 0, GLFW_WINDOW) != GL_TRUE) { CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window.")); glfwTerminate(); diff --git a/samples_framework/src/CEGuiIrrlichtBaseApplication.cpp b/samples/browser/src/CEGuiIrrlichtBaseApplication.cpp similarity index 99% rename from samples_framework/src/CEGuiIrrlichtBaseApplication.cpp rename to samples/browser/src/CEGuiIrrlichtBaseApplication.cpp index a5b27b72c..c82c16b3f 100644 --- a/samples_framework/src/CEGuiIrrlichtBaseApplication.cpp +++ b/samples/browser/src/CEGuiIrrlichtBaseApplication.cpp @@ -37,7 +37,7 @@ author: Paul D Turner #ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE #include "CEGuiIrrlichtBaseApplication.h" -#include "SamplesFrameworkBase.h" +#include "SampleBrowserBase.h" #include "CEGUI/RendererModules/Irrlicht/ImageCodec.h" #include "CEGUI/RendererModules/Irrlicht/ResourceProvider.h" #include "CEGUI/RendererModules/Irrlicht/Renderer.h" diff --git a/samples_framework/src/CEGuiOgreBaseApplication.cpp b/samples/browser/src/CEGuiOgreBaseApplication.cpp similarity index 66% rename from samples_framework/src/CEGuiOgreBaseApplication.cpp rename to samples/browser/src/CEGuiOgreBaseApplication.cpp index 625361ff7..b85908ade 100644 --- a/samples_framework/src/CEGuiOgreBaseApplication.cpp +++ b/samples/browser/src/CEGuiOgreBaseApplication.cpp @@ -25,11 +25,11 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H -# include "config.h" + #include "config.h" #endif #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) -# include +#include #endif // this controls conditional compile of file for Apple @@ -38,10 +38,25 @@ #include #include "CEGuiOgreBaseApplication.h" -#include "SamplesFrameworkBase.h" +#include "SampleBrowserBase.h" #include "CEGUI/RendererModules/Ogre/ImageCodec.h" #include "CEGUI/RendererModules/Ogre/ResourceProvider.h" +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 +#include +#include +#include +#include +#include +#include +#include +#include +#endif //CEGUI_USE_OGRE_COMPOSITOR2 + +#ifdef __ANDROID__ +# include "AndroidAppHelper.h" +#endif + //----------------------------------------------------------------------------// CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() : d_ogreRoot(0), @@ -59,7 +74,11 @@ CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() : #ifndef OGRE_STATIC_LIB d_ogreRoot = new Ogre::Root(pluginsFileName); #else - d_ogreRoot = new Ogre::Root(); +# ifdef __ANDROID__ + d_ogreRoot = new Ogre::Root("", "", "Ogre.log"); //this is needed to avoid looking for plugins.cfg +# else + d_ogreRoot = new Ogre::Root(); +# endif d_staticPluginLoader = new Ogre::StaticPluginLoader(); d_staticPluginLoader->load(); #endif @@ -68,26 +87,106 @@ CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() : if (d_ogreRoot->showConfigDialog()) { - // initialise system according to user options. +#ifdef __ANDROID__ + d_ogreRoot->setRenderSystem(d_ogreRoot->getAvailableRenderers().at (0)); + d_ogreRoot->initialise (false); + AndroidAppHelper::createWindow(); + d_window = AndroidAppHelper::getRenderWindow(); + AndroidAppHelper::initialiseFS(); +#else d_window = d_ogreRoot->initialise(true); +#endif +#if CEGUI_OGRE_VERSION_MAJOR < 2 // Create the scene manager SceneManager* sm = d_ogreRoot-> - createSceneManager(ST_GENERIC, "SampleSceneMgr"); + createSceneManager(ST_GENERIC, + "SampleSceneMgr"); +#else + // Create the scene manager + SceneManager* sm = d_ogreRoot-> + createSceneManager(ST_GENERIC, 2, INSTANCING_CULLING_SINGLETHREAD, + "SampleSceneMgr"); +#endif // Create and initialise the camera d_camera = sm->createCamera("SampleCam"); d_camera->setPosition(Vector3(0,0,500)); d_camera->lookAt(Vector3(0,0,-300)); d_camera->setNearClipDistance(5); +#ifdef CEGUI_USE_OGRE_COMPOSITOR2 + + Ogre::CompositorManager2* manager = d_ogreRoot->getCompositorManager2(); + + // The compositor has to be initialized + if (!manager) + { + assert(false && "No function to initialize Ogre::CompositorManager2..."); + manager = d_ogreRoot->getCompositorManager2(); + } + + // Create a full screen workspace that just clears the screen + + + // Define the workspace first + Ogre::CompositorWorkspaceDef* templatedworkspace = manager->addWorkspaceDefinition( + "Sample_workspace"); + + // Create a node for rendering on top of everything + Ogre::CompositorNodeDef* rendernode = manager->addNodeDefinition("SampleCleaner"); + + rendernode->addTextureSourceName("renderwindow", 0, + Ogre::TextureDefinitionBase::TEXTURE_INPUT); + + rendernode->setNumTargetPass(1); + // Pass for it + Ogre::CompositorTargetDef* targetpasses = rendernode->addTargetPass("renderwindow"); + targetpasses->setNumPasses(2); + + Ogre::CompositorPassClearDef* clearpass = + static_cast(targetpasses-> + addPass(Ogre::PASS_CLEAR)); + + // Only clear depth and stencil since we are rendering on top + // of an existing image + clearpass->mClearBufferFlags = Ogre::FBT_COLOUR | Ogre::FBT_DEPTH | + Ogre::FBT_STENCIL; + + // Set the same colour as in below + clearpass->mColourValue = ColourValue(0.f, 0.f, 0.f, 0.f); + // Other clear value defaults should be fine + + // Not sure if the samples want anything in their scenes so every group + // will be rendered + Ogre::CompositorPassSceneDef* scenepass = + static_cast(targetpasses-> + addPass(Ogre::PASS_SCENE)); + + // Just render the overlay group since it is the only one used + scenepass->mFirstRQ = Ogre::RENDER_QUEUE_BACKGROUND; + scenepass->mLastRQ = Ogre::RENDER_QUEUE_MAX; + + // Connect the main render target to the node + templatedworkspace->connectOutput("SampleCleaner", 0); + + // Create the workspace for rendering + + // This needs to be rendered first... + manager->addWorkspace(sm, d_window, d_camera, "Sample_workspace", + true, 0); + +#else // Create a viewport covering whole window Viewport* vp = d_window->addViewport(d_camera); vp->setBackgroundColour(ColourValue(0.0f, 0.0f, 0.0f, 0.0f)); // Update the camera aspect ratio to that of the viewport d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight())); +#endif // CEGUI_USE_OGRE_COMPOSITOR2 + + // create ogre renderer, image codec and resource provider. - CEGUI::OgreRenderer& renderer = CEGUI::OgreRenderer::create(); + CEGUI::OgreRenderer& renderer = CEGUI::OgreRenderer::create(*d_window); d_renderer = &renderer; d_imageCodec = &renderer.createOgreImageCodec(); d_resourceProvider = &renderer.createOgreResourceProvider(); @@ -96,12 +195,17 @@ CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() : d_frameListener= new CEGuiDemoFrameListener(this, d_sampleApp, d_window, d_camera); d_ogreRoot->addFrameListener(d_frameListener); +#ifdef __ANDROID__ + AndroidAppHelper::initialiseOIS(d_frameListener, d_frameListener); + d_windowEventListener = new WndEvtListener(); +#else // add a listener for OS framework window events (for resizing) d_windowEventListener = new WndEvtListener(d_frameListener->getOISMouse()); +#endif WindowEventUtilities::addWindowEventListener(d_window, d_windowEventListener); - + d_ogreRoot->addFrameListener(this); renderer.setRenderingEnabled(false); @@ -128,12 +232,12 @@ CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication() renderer.destroyOgreImageCodec( *static_cast(d_imageCodec)); CEGUI::OgreRenderer::destroy(renderer); + delete d_ogreRoot; + delete d_windowEventListener; #ifdef OGRE_STATIC_LIB d_staticPluginLoader->unload(); delete d_staticPluginLoader; #endif - delete d_ogreRoot; - delete d_windowEventListener; } //----------------------------------------------------------------------------// @@ -149,7 +253,11 @@ void CEGuiOgreBaseApplication::run() // start rendering via Ogre3D engine. CEGUI_TRY { +#ifdef __ANDROID__ + AndroidAppHelper::go(); +#else d_ogreRoot->startRendering(); +#endif } CEGUI_CATCH(...) {} @@ -192,32 +300,36 @@ void CEGuiOgreBaseApplication::initialiseResourceGroupDirectories() rgm.createResourceGroup("schemas"); rgm.createResourceGroup("samples"); - +#ifdef __ANDROID__ + const char* type= "APKFileSystem"; +#else // add CEGUI sample framework datafile dirs as resource locations ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem"); - - const char* dataPathPrefix = getDataPathPrefix(); - char resourcePath[PATH_MAX]; + const char* type= "FileSystem"; +#endif // for each resource type, set a resource group directory - sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "schemes"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "samples/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "samples"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "imagesets"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "fonts"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "layouts"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "looknfeels"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "lua_scripts"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "animations"); - sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas/"); - ResourceGroupManager::getSingleton().addResourceLocation(resourcePath, "FileSystem", "schemas"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("schemes").c_str(), type, "schemes"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("samples").c_str(), type, "samples"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("imagesets").c_str(), type, "imagesets"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("fonts").c_str(), type, "fonts"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("layouts").c_str(), type, "layouts"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("looknfeel").c_str(), type, "looknfeels"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("lua_scripts").c_str(), type, "lua_scripts"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("animations").c_str(), type, "animations"); + ResourceGroupManager::getSingleton().addResourceLocation(getResourcePath("schemas").c_str(), type, "schemas"); +} + +CEGUI::String CEGuiOgreBaseApplication::getResourcePath(CEGUI::String resource) { +#ifdef __ANDROID__ + const char* dataPathPrefix = "/datafiles"; + const char ext[]= ""; +#else + const char* dataPathPrefix = getDataPathPrefix(); + const char ext[]= "/"; +#endif + CEGUI::String path = CEGUI::String(dataPathPrefix)+ "/" + resource + CEGUI::String(ext); + return path; } //----------------------------------------------------------------------------// @@ -244,10 +356,10 @@ void CEGuiOgreBaseApplication::setupDefaultConfigIfNeeded() // Check if the config exists bool success = d_ogreRoot->restoreConfig(); - if(!success) + if (!success) { // If not we set our default values for all renderers if possible - const Ogre::RenderSystemList& renderSystems = d_ogreRoot->getAvailableRenderers(); + const Ogre::RenderSystemList& renderSystems = d_ogreRoot->getAvailableRenderers(); size_t renderSystemCount = renderSystems.size(); for(size_t i = 0; i < renderSystemCount; ++i) @@ -257,31 +369,31 @@ void CEGuiOgreBaseApplication::setupDefaultConfigIfNeeded() Ogre::ConfigOptionMap::iterator foundConfigIter; foundConfigIter = configOptions.find("Full Screen"); - if(foundConfigIter != configOptions.end()) - currentRenderSys->setConfigOption("Full Screen","No"); + if (foundConfigIter != configOptions.end()) + currentRenderSys->setConfigOption("Full Screen","No"); foundConfigIter = configOptions.find("Video Mode"); - if(foundConfigIter != configOptions.end()) + if (foundConfigIter != configOptions.end()) { Ogre::StringVector::iterator optionsIterCur = foundConfigIter->second.possibleValues.begin(); Ogre::StringVector::iterator optionsIterEnd = foundConfigIter->second.possibleValues.end(); while(optionsIterCur != optionsIterEnd) { - if(optionsIterCur->compare("1280 x 768 @ 32-bit colour") == 0) + if (optionsIterCur->compare("1280 x 768 @ 32-bit colour") == 0) { currentRenderSys->setConfigOption("Video Mode", *optionsIterCur); break; } ++optionsIterCur; } - if(optionsIterCur == optionsIterEnd) + if (optionsIterCur == optionsIterEnd) { optionsIterCur = foundConfigIter->second.possibleValues.begin(); while(optionsIterCur != optionsIterEnd) { - if(optionsIterCur->compare(0, 10, "1280 x 768") == 0) + if (optionsIterCur->compare(0, 10, "1280 x 768") == 0) { - currentRenderSys->setConfigOption("Video Mode", *optionsIterCur); + currentRenderSys->setConfigOption("Video Mode", *optionsIterCur); break; } ++optionsIterCur; @@ -292,7 +404,6 @@ void CEGuiOgreBaseApplication::setupDefaultConfigIfNeeded() } } - //----------------------------------------------------------------------------// //////////////////////////////////////////////////////////////////////////////// @@ -302,7 +413,7 @@ void CEGuiOgreBaseApplication::setupDefaultConfigIfNeeded() //////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------// -CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp, SamplesFrameworkBase*& sampleApp, +CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp, SampleBrowserBase*& sampleApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse) : d_baseApp(baseApp), d_sampleApp(sampleApp) @@ -319,6 +430,29 @@ CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp windowHndStr << (unsigned int)windowHnd; paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); + // Prevent the window from capturing mouse making debugging impossible + // (on Windows and Linux) +#if defined OIS_WIN32_PLATFORM + paramList.insert(std::make_pair(std::string("w32_mouse"), + std::string("DISCL_FOREGROUND" ))); + paramList.insert(std::make_pair(std::string("w32_mouse"), + std::string("DISCL_NONEXCLUSIVE"))); + paramList.insert(std::make_pair(std::string("w32_keyboard"), + std::string("DISCL_FOREGROUND"))); + paramList.insert(std::make_pair(std::string("w32_keyboard"), + std::string("DISCL_NONEXCLUSIVE"))); +#elif defined OIS_LINUX_PLATFORM + paramList.insert(std::make_pair(std::string("x11_mouse_grab"), + std::string("false"))); + paramList.insert(std::make_pair(std::string("x11_mouse_hide"), + std::string("false"))); + paramList.insert(std::make_pair(std::string("x11_keyboard_grab"), + std::string("false"))); + paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), + std::string("true"))); +#endif + + #if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID && OGRE_PLATFORM != OGRE_PLATFORM_WINRT && OGRE_PLATFORM != OGRE_PLATFORM_LINUX && defined (DEBUG) paramList.insert(std::make_pair("x11_keyboard_grab", "false")); paramList.insert(std::make_pair("x11_mouse_grab", "false")); @@ -327,6 +461,7 @@ CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp paramList.insert(std::make_pair("w32_mouse", "DISCL_NONEXCLUSIVE")); #endif +#ifndef __ANDROID__ // create input system d_inputManager = OIS::InputManager::createInputSystem(paramList); @@ -337,8 +472,10 @@ CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp if (d_inputManager->getNumberOfDevices(OIS::OISKeyboard) > 0) #endif { +#ifndef __ANDROID__ d_keyboard = static_cast(d_inputManager->createInputObject(OIS::OISKeyboard, true)); d_keyboard->setEventCallback(this); +#endif } // create buffered mouse @@ -359,6 +496,7 @@ CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiOgreBaseApplication* baseApp mouseState.width = width; mouseState.height = height; } +#endif // store inputs we want to make use of d_camera = camera; @@ -370,26 +508,30 @@ CEGuiDemoFrameListener::~CEGuiDemoFrameListener() { if (d_inputManager) { +#ifndef __ANDROID__ d_inputManager->destroyInputObject(d_mouse); d_inputManager->destroyInputObject(d_keyboard); OIS::InputManager::destroyInputSystem(d_inputManager); +#endif } } //----------------------------------------------------------------------------// bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt) { - if(d_window->isClosed() || d_sampleApp->isQuitting()) + if (d_window->isClosed() || d_sampleApp->isQuitting()) return false; static_cast(d_baseApp)-> doFrameUpdate(static_cast(evt.timeSinceLastFrame)); // update input system +#ifndef __ANDROID__ if (d_mouse) d_mouse->capture(); if (d_keyboard) d_keyboard->capture(); +#endif return true; } @@ -400,14 +542,26 @@ bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt) return true; } +#ifdef __ANDROID__ +//----------------------------------------------------------------------------// +bool CEGuiDemoFrameListener::touchMoved(const OIS::MultiTouchEvent &e) +{ + float x = static_cast (e.state.X.abs); + float y = static_cast (e.state.Y.abs); + d_sampleApp->injectMousePosition(x, y); + return true; +} + +#else //----------------------------------------------------------------------------// bool CEGuiDemoFrameListener::mouseMoved(const OIS::MouseEvent &e) { - d_sampleApp->injectMousePosition(e.state.X.abs, e.state.Y.abs); + d_sampleApp->injectMousePosition(static_cast(e.state.X.abs), static_cast(e.state.Y.abs)); d_sampleApp->injectMouseWheelChange(e.state.Z.rel / 120.0f); return true; } +#endif //----------------------------------------------------------------------------// bool CEGuiDemoFrameListener::keyPressed(const OIS::KeyEvent &e) @@ -418,7 +572,6 @@ bool CEGuiDemoFrameListener::keyPressed(const OIS::KeyEvent &e) return true; } - //----------------------------------------------------------------------------// bool CEGuiDemoFrameListener::keyReleased(const OIS::KeyEvent &e) { @@ -426,7 +579,25 @@ bool CEGuiDemoFrameListener::keyReleased(const OIS::KeyEvent &e) return true; } +#ifdef __ANDROID__ +//----------------------------------------------------------------------------// +bool CEGuiDemoFrameListener::touchPressed(const OIS::MultiTouchEvent &e) +{ + float x = static_cast (e.state.X.abs); + float y = static_cast (e.state.Y.abs); + d_sampleApp->injectMousePosition(x, y); + d_sampleApp->injectMouseButtonDown(CEGUI::LeftButton); + return true; +} + +//----------------------------------------------------------------------------// +bool CEGuiDemoFrameListener::touchReleased(const OIS::MultiTouchEvent &e) +{ + d_sampleApp->injectMouseButtonUp(CEGUI::LeftButton); + return true; +} +#else //----------------------------------------------------------------------------// bool CEGuiDemoFrameListener::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id) { @@ -466,7 +637,7 @@ OIS::Mouse* CEGuiDemoFrameListener::getOISMouse() { return d_mouse; } - +#endif //----------------------------------------------------------------------------// //////////////////////////////////////////////////////////////////////////////// @@ -476,8 +647,12 @@ OIS::Mouse* CEGuiDemoFrameListener::getOISMouse() //////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------// +#ifdef __ANDROID__ +WndEvtListener::WndEvtListener() +#else WndEvtListener::WndEvtListener(OIS::Mouse* mouse) : d_mouse(mouse) +#endif { } @@ -489,16 +664,13 @@ void WndEvtListener::windowResized(Ogre::RenderWindow* rw) sys->notifyDisplaySizeChanged( CEGUI::Sizef(static_cast(rw->getWidth()), static_cast(rw->getHeight()))); - - +#ifndef __ANDROID__ const OIS::MouseState& mouseState = d_mouse->getMouseState(); mouseState.width = rw->getWidth(); mouseState.height = rw->getHeight(); +#endif } //----------------------------------------------------------------------------// #endif - - - diff --git a/samples_framework/src/CEGuiOpenGL3BaseApplication.cpp b/samples/browser/src/CEGuiOpenGL3BaseApplication.cpp similarity index 100% rename from samples_framework/src/CEGuiOpenGL3BaseApplication.cpp rename to samples/browser/src/CEGuiOpenGL3BaseApplication.cpp diff --git a/samples_framework/src/CEGuiOpenGLBaseApplication.cpp b/samples/browser/src/CEGuiOpenGLBaseApplication.cpp similarity index 100% rename from samples_framework/src/CEGuiOpenGLBaseApplication.cpp rename to samples/browser/src/CEGuiOpenGLBaseApplication.cpp diff --git a/samples_framework/src/CEGuiRendererSelector.cpp b/samples/browser/src/CEGuiRendererSelector.cpp similarity index 100% rename from samples_framework/src/CEGuiRendererSelector.cpp rename to samples/browser/src/CEGuiRendererSelector.cpp diff --git a/samples_framework/src/CLICEGuiRendererSelector.cpp b/samples/browser/src/CLICEGuiRendererSelector.cpp similarity index 92% rename from samples_framework/src/CLICEGuiRendererSelector.cpp rename to samples/browser/src/CLICEGuiRendererSelector.cpp index 6dd9c40a0..93f061101 100644 --- a/samples_framework/src/CLICEGuiRendererSelector.cpp +++ b/samples/browser/src/CLICEGuiRendererSelector.cpp @@ -62,6 +62,12 @@ bool CLICEGuiRendererSelector::invokeDialog() last_available = OpenGL3GuiRendererType; std::cout << rendererNumber << ". OpenGL 3.2 Core Renderer." << std::endl; } + if (d_rendererAvailability[OpenGLES2GuiRendererType]) + { + ++rendererNumber; + last_available = OpenGLES2GuiRendererType; + std::cout << rendererNumber << ". OpenGLES 2.0 Renderer." << std::endl; + } if (d_rendererAvailability[IrrlichtGuiRendererType]) { ++rendererNumber; @@ -112,6 +118,10 @@ bool CLICEGuiRendererSelector::invokeDialog() { d_lastSelected = OpenGL3GuiRendererType; } + else if ((d_rendererAvailability[OpenGLES2GuiRendererType]) && (--selection == 0)) + { + d_lastSelected = OpenGLES2GuiRendererType; + } else if ((d_rendererAvailability[IrrlichtGuiRendererType]) && (--selection == 0)) { d_lastSelected = IrrlichtGuiRendererType; diff --git a/samples_framework/src/DeviceReset_Direct3D11.cpp b/samples/browser/src/DeviceReset_Direct3D11.cpp similarity index 92% rename from samples_framework/src/DeviceReset_Direct3D11.cpp rename to samples/browser/src/DeviceReset_Direct3D11.cpp index 9da186822..11e28c70b 100644 --- a/samples_framework/src/DeviceReset_Direct3D11.cpp +++ b/samples/browser/src/DeviceReset_Direct3D11.cpp @@ -61,10 +61,11 @@ void DeviceReset_Direct3D11(HWND window, CEGUI::Renderer* renderer) CEGUI::Direct3D11Renderer* d3d_renderer = static_cast(renderer); - IDevice11& d3d_device = d3d_renderer->getDirect3DDevice(); + ID3D11Device* d3d_device = d3d_renderer->getDirect3DDevice(); + ID3D11DeviceContext* d3d_deviceContext = d3d_renderer->getDirect3DDeviceContext(); ID3D11RenderTargetView* rtview; - d3d_device.d_context->OMGetRenderTargets(1, &rtview, 0); + d3d_deviceContext->OMGetRenderTargets(1, &rtview, 0); // we release once for the reference we just asked for rtview->Release(); @@ -95,7 +96,7 @@ void DeviceReset_Direct3D11(HWND window, CEGUI::Renderer* renderer) if (SUCCEEDED(res)) { // create render target view using the back buffer - res = d3d_device.d_device->CreateRenderTargetView(back_buffer, 0, &rtview); + res = d3d_device->CreateRenderTargetView(back_buffer, 0, &rtview); // release handle to buffer - we have done all we needed to with it. back_buffer->Release(); @@ -103,7 +104,7 @@ void DeviceReset_Direct3D11(HWND window, CEGUI::Renderer* renderer) if (SUCCEEDED(res)) { // bind the back-buffer render target to get the output. - d3d_device.d_context->OMSetRenderTargets(1, &rtview, 0); + d3d_deviceContext->OMSetRenderTargets(1, &rtview, 0); // set a basic viewport. D3D11_VIEWPORT view_port; @@ -113,7 +114,7 @@ void DeviceReset_Direct3D11(HWND window, CEGUI::Renderer* renderer) view_port.MaxDepth = 1.0f; view_port.TopLeftX = 0; view_port.TopLeftY = 0; - d3d_device.d_context->RSSetViewports(1, &view_port); + d3d_deviceContext->RSSetViewports(1, &view_port); // notify CEGUI of change. CEGUI::System::getSingleton().notifyDisplaySizeChanged( diff --git a/samples_framework/src/GTK2CEGuiRendererSelector.cpp b/samples/browser/src/GTK2CEGuiRendererSelector.cpp similarity index 92% rename from samples_framework/src/GTK2CEGuiRendererSelector.cpp rename to samples/browser/src/GTK2CEGuiRendererSelector.cpp index ec6fbc90b..8756fcd7e 100644 --- a/samples_framework/src/GTK2CEGuiRendererSelector.cpp +++ b/samples/browser/src/GTK2CEGuiRendererSelector.cpp @@ -65,6 +65,16 @@ bool GTK2CEGuiRendererSelector::invokeDialog() gtk_combo_box_append_text(GTK_COMBO_BOX(d_combobox1), OpenGLRendererName.c_str()); renderer_types[idx++] = OpenGLGuiRendererType; } + if (d_rendererAvailability[OpenGL3GuiRendererType]) + { + gtk_combo_box_append_text(GTK_COMBO_BOX(d_combobox1), OpenGL3RendererName.c_str()); + renderer_types[idx++] = OpenGL3GuiRendererType; + } + if (d_rendererAvailability[OpenGLES2GuiRendererType]) + { + gtk_combo_box_append_text(GTK_COMBO_BOX(d_combobox1), OpenGLES2RendererName.c_str()); + renderer_types[idx++] = OpenGLES2GuiRendererType; + } if (d_rendererAvailability[IrrlichtGuiRendererType]) { gtk_combo_box_append_text(GTK_COMBO_BOX(d_combobox1), IrrlichtRendererName.c_str()); diff --git a/samples_framework/src/MacCEGuiRendererSelector.mm b/samples/browser/src/MacCEGuiRendererSelector.mm similarity index 100% rename from samples_framework/src/MacCEGuiRendererSelector.mm rename to samples/browser/src/MacCEGuiRendererSelector.mm diff --git a/samples_framework/src/MetaDataWindowManager.cpp b/samples/browser/src/MetaDataWindowManager.cpp similarity index 71% rename from samples_framework/src/MetaDataWindowManager.cpp rename to samples/browser/src/MetaDataWindowManager.cpp index 5542d5eb5..521d55e0c 100644 --- a/samples_framework/src/MetaDataWindowManager.cpp +++ b/samples/browser/src/MetaDataWindowManager.cpp @@ -26,8 +26,9 @@ author: Lukas E Meindl ***************************************************************************/ #include "MetaDataWindowManager.h" -#include "SampleData.h" +#include "SampleHandler.h" +#include "CEGUI/widgets/Scrollbar.h" #include "CEGUI/Window.h" #include "CEGUI/SchemeManager.h" #include "CEGUI/WindowManager.h" @@ -42,7 +43,6 @@ MetaDataWindowManager::MetaDataWindowManager(CEGUI::Window* metaDataWindow) void MetaDataWindowManager::init() { - d_wndSampleType = d_root->getChild("SampleType"); d_wndSummary = d_root->getChild("Summary"); d_wndDescription = d_root->getChild("Description"); d_wndUsedFiles = d_root->getChild("UsedFiles"); @@ -55,12 +55,15 @@ CEGUI::Window* MetaDataWindowManager::getWindow() return d_root; } -void MetaDataWindowManager::setSampleInfo(SampleData* sampleData) +void MetaDataWindowManager::setSampleInfo(SampleHandler* sampleData) { - d_root->setText(sampleData->getName()); - d_wndSummary->setText(sampleData->getSummary()); - d_wndSampleType->setText(sampleData->getSampleTypeString()); - d_wndDescription->setText(sampleData->getDescription()); - d_wndUsedFiles->setText(sampleData->getUsedFilesString()); - d_wndCredits->setText(sampleData->getCredits()); + d_root->setText(sampleData->getNameText()); + d_wndSummary->setText(sampleData->getSummaryText()); + static_cast(d_wndSummary->getChild("__auto_vscrollbar__"))->setScrollPosition(0.f); + d_wndUsedFiles->setText(sampleData->getUsedFilesText()); + static_cast(d_wndDescription->getChild("__auto_vscrollbar__"))->setScrollPosition(0.f); + d_wndUsedFiles->setText(sampleData->getUsedFilesText()); + static_cast(d_wndUsedFiles->getChild("__auto_vscrollbar__"))->setScrollPosition(0.f); + d_wndCredits->setText(sampleData->getCreditsText()); + static_cast(d_wndCredits->getChild("__auto_vscrollbar__"))->setScrollPosition(0.f); } \ No newline at end of file diff --git a/samples_framework/src/SamplesFramework.cpp b/samples/browser/src/SampleBrowser.cpp similarity index 65% rename from samples_framework/src/SamplesFramework.cpp rename to samples/browser/src/SampleBrowser.cpp index b5b145c7d..945ed6649 100644 --- a/samples_framework/src/SamplesFramework.cpp +++ b/samples/browser/src/SampleBrowser.cpp @@ -24,39 +24,50 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "SamplesFramework.h" +#include "SampleBrowser.h" -#include "Samples_xmlHandler.h" #include "Sample.h" -#include "SampleData.h" +#include "SampleHandler.h" #include "CEGuiBaseApplication.h" #include "MetaDataWindowManager.h" -#include "SamplesBrowserManager.h" +#include "SampleBrowserManager.h" #include "CEGUI/CEGUI.h" #include "CEGUI/Logger.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/ProgressBar.h" +#include "samples.h" #include #include +#include using namespace CEGUI; //platform-dependant DLL delay-loading includes -#if (defined( __WIN32__ ) || defined( _WIN32 )) +#if (defined( __WIN32__ ) || defined( _WIN32 )) #include "windows.h" #endif -//----------------------------------------------------------------------------// -// Name of the xsd schema file used to validate samples XML files. -const String SamplesFramework::XMLSchemaName("Samples.xsd"); +#ifdef __ANDROID__ +# include "CEGUI/AndroidUtils.h" +#endif //----------------------------------------------------------------------------// +#ifdef __ANDROID__ +# include +void android_main(struct android_app* state) +{ + app_dummy(); // Make sure glue isn't stripped. + int argc = 0; + char* argv[0]; + AndroidUtils::setAndroidApp(state); +#else int main(int argc, char* argv[]) { +#endif // Basic start-up for the sample browser application. // Will remain in run() until quitting int argidx = 1; @@ -67,52 +78,65 @@ int main(int argc, char* argv[]) ++argidx; } #endif - - SamplesFramework sampleFramework(argc > 1 ? argv[argidx] : ""); - return sampleFramework.run(); + + SampleBrowser sampleBrowser; +#ifdef __ANDROID__ + sampleBrowser.run(); +#else + return sampleBrowser.run(); +#endif } //----------------------------------------------------------------------------// -SamplesFramework::SamplesFramework(const CEGUI::String& xml_filename) : +SampleBrowser::SampleBrowser() : d_sampleExitButton(0), d_metaDataWinMgr(0), d_samplesWinMgr(0), d_selectedSampleData(0), d_loadingProgressBar(0), - d_quittingSampleView(false), - d_samplesXMLFilename(xml_filename) + d_quittingSampleView(false) { } //----------------------------------------------------------------------------// -SamplesFramework::~SamplesFramework() +SampleBrowser::~SampleBrowser() { - if(d_metaDataWinMgr) + if (d_metaDataWinMgr) delete d_metaDataWinMgr; } - - //----------------------------------------------------------------------------// -bool SamplesFramework::initialise() +bool SampleBrowser::initialise() { using namespace CEGUI; initialiseLoadScreenLayout(); + loadSamples(); + + d_systemInputAggregator = new InputAggregator( + &CEGUI::System::getSingletonPtr()->getDefaultGUIContext()); + d_systemInputAggregator->initialise(); + // return true to signalize the initialisation was sucessful and run the - // SamplesFramework + // SampleBrowser return true; } //----------------------------------------------------------------------------// -void SamplesFramework::deinitialise() +void SampleBrowser::deinitialise() { unloadSamples(); + + if (d_systemInputAggregator != 0) + { + delete d_systemInputAggregator; + d_systemInputAggregator = 0; + } } //----------------------------------------------------------------------------// -void SamplesFramework::initialiseLoadScreenLayout() +void SampleBrowser::initialiseLoadScreenLayout() { CEGUI::Font& font = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); @@ -132,85 +156,52 @@ void SamplesFramework::initialiseLoadScreenLayout() d_loadScreenChunkProgressText = d_loadingScreenText->getChild("LoadScreenTextChunkProgress"); - d_loadingScreenText->setText("Parsing samples XML file..."); d_loadingProgressBar->setProgress(0.0f); } //----------------------------------------------------------------------------// -void SamplesFramework::unloadSamples() +void SampleBrowser::loadSamples() { - while (d_samples.size() > 0) - { - SampleData*& sampleData = d_samples.back(); - - sampleData->deinitialise(); - delete sampleData; - - d_samples.pop_back(); - } -} + #include "samples.inc" -//----------------------------------------------------------------------------// -void SamplesFramework::loadSamplesDataFromXML(const String& filename) -{ - if (filename.empty()) - CEGUI_THROW(InvalidRequestException( - "SamplesFramework::loadSamplesDataFromXML: " - "filename supplied for file loading must be valid.")); + std::vector::iterator iter = samples.begin(); + std::vector::iterator iterEnd = samples.end(); - Samples_xmlHandler handler(this); + std::sort(samples.begin(), samples.end(), SamplePointerCompare()); - // do parse (which uses handler to create actual data) - CEGUI_TRY + while (iter != iterEnd) { - System::getSingleton().getXMLParser()-> - parseXMLFile(handler, filename, XMLSchemaName, ""); - } - CEGUI_CATCH(...) - { - Logger::getSingleton().logEvent( - "SamplesFramework::loadSamplesDataFromXML: " - "loading of sample data from file '" + filename + "' has failed.", - Errors); + SampleHandler* sampleData = new SampleHandler(*iter); + d_samples.push_back(sampleData); - CEGUI_RETHROW; + ++iter; } -} +} //----------------------------------------------------------------------------// -void SamplesFramework::addSampleDataCppModule(CEGUI::String sampleName, - CEGUI::String summary, - CEGUI::String description, - SampleType sampleTypeEnum, - CEGUI::String credits) +void SampleBrowser::unloadSamples() { - SampleData* sampleData = new SampleDataModule(sampleName, summary, - description, sampleTypeEnum, - credits); + while (d_samples.size() > 0) + { + SampleHandler*& sampleData = d_samples.back(); - addSample(sampleData); + sampleData->deinitialise(); + delete sampleData; + + d_samples.pop_back(); + } } //----------------------------------------------------------------------------// -bool SamplesFramework::injectKeyDown(const CEGUI::Key::Scan& ceguiKey) +bool SampleBrowser::injectKeyDown(const CEGUI::Key::Scan& ceguiKey) { - if (d_selectedSampleData) - { - if (Key::Escape != ceguiKey) - return d_selectedSampleData->getGuiContext()->injectKeyDown(ceguiKey); - else - stopDisplaySample(); - } + if (Key::Escape != ceguiKey) + return getCurrentInputAggregator()->injectKeyDown(ceguiKey); else { - if (Key::Escape != ceguiKey) - { - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - return ceguiSystem->getDefaultGUIContext().injectKeyDown(ceguiKey); - else - return false; - } + if (d_selectedSampleData) + stopDisplaySample(); else setQuitting(true); } @@ -219,86 +210,63 @@ bool SamplesFramework::injectKeyDown(const CEGUI::Key::Scan& ceguiKey) } //----------------------------------------------------------------------------// -bool SamplesFramework::injectKeyUp(const CEGUI::Key::Scan& ceguiKey) +bool SampleBrowser::injectKeyUp(const CEGUI::Key::Scan& ceguiKey) { - if (d_selectedSampleData) - return d_selectedSampleData->getGuiContext()->injectKeyUp(ceguiKey); + if (getCurrentInputAggregator() == 0) + return false; - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - ceguiSystem->getDefaultGUIContext().injectKeyUp(ceguiKey); - - return false; + return getCurrentInputAggregator()->injectKeyUp(ceguiKey); } //----------------------------------------------------------------------------// -bool SamplesFramework::injectChar(int character) +bool SampleBrowser::injectChar(int character) { - if (d_selectedSampleData) - return d_selectedSampleData->getGuiContext()->injectChar(character); + if (getCurrentInputAggregator() == 0) + return false; - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - ceguiSystem->getDefaultGUIContext().injectChar(character); - - return false; + return getCurrentInputAggregator()->injectChar(character); } //----------------------------------------------------------------------------// -bool SamplesFramework::injectMouseButtonDown( +bool SampleBrowser::injectMouseButtonDown( const CEGUI::MouseButton& ceguiMouseButton) { - if (d_selectedSampleData) - return d_selectedSampleData->getGuiContext()-> - injectMouseButtonDown(ceguiMouseButton); + if (getCurrentInputAggregator() == 0) + return false; - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - ceguiSystem->getDefaultGUIContext(). - injectMouseButtonDown(ceguiMouseButton); - - return false; + return getCurrentInputAggregator()->injectMouseButtonDown(ceguiMouseButton); } //----------------------------------------------------------------------------// -bool SamplesFramework::injectMouseButtonUp( +bool SampleBrowser::injectMouseButtonUp( const CEGUI::MouseButton& ceguiMouseButton) { - if (d_selectedSampleData) - return d_selectedSampleData->getGuiContext()-> - injectMouseButtonUp(ceguiMouseButton); + if (getCurrentInputAggregator() == 0) + return false; - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - ceguiSystem->getDefaultGUIContext(). - injectMouseButtonUp(ceguiMouseButton); - - return false; + return getCurrentInputAggregator()->injectMouseButtonUp(ceguiMouseButton); } //----------------------------------------------------------------------------// -bool SamplesFramework::injectMouseWheelChange(float position) +bool SampleBrowser::injectMouseWheelChange(float position) { - if (d_selectedSampleData) - return d_selectedSampleData->getGuiContext()-> - injectMouseWheelChange(position); + if (getCurrentInputAggregator() == 0) + return false; - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - ceguiSystem->getDefaultGUIContext().injectMouseWheelChange(position); - - return false; + return getCurrentInputAggregator()->injectMouseWheelChange(position); } //----------------------------------------------------------------------------// -bool SamplesFramework::injectMousePosition(float x, float y) +bool SampleBrowser::injectMousePosition(float x, float y) { - if (d_selectedSampleData) - return d_selectedSampleData->getGuiContext()->injectMousePosition(x, y); + if (getCurrentInputAggregator() == 0) + return false; - if (CEGUI::System* ceguiSystem = CEGUI::System::getSingletonPtr()) - ceguiSystem->getDefaultGUIContext().injectMousePosition(x, y); - - return false; + return getCurrentInputAggregator()->injectMousePosition(x, y); } //----------------------------------------------------------------------------// -void SamplesFramework::update(float passedTime) +void SampleBrowser::update(float passedTime) { static bool init(false); @@ -334,16 +302,16 @@ void SamplesFramework::update(float passedTime) } //----------------------------------------------------------------------------// -void SamplesFramework::handleNewWindowSize(float width, float height) +void SampleBrowser::handleNewWindowSize(float width, float height) { d_appWindowWidth = static_cast(width); d_appWindowHeight = static_cast(height); - std::vector::iterator iter = d_samples.begin(); - std::vector::iterator end = d_samples.end(); + SampleList::iterator iter = d_samples.begin(); + SampleList::iterator end = d_samples.end(); for (; iter != end; ++iter) { - SampleData* sampleData = *iter; + SampleHandler* sampleData = *iter; sampleData->handleNewWindowSize(width, height); } @@ -353,13 +321,7 @@ void SamplesFramework::handleNewWindowSize(float width, float height) } //----------------------------------------------------------------------------// -void SamplesFramework::addSample(SampleData* sampleData) -{ - d_samples.push_back(sampleData); -} - -//----------------------------------------------------------------------------// -void SamplesFramework::renderGUIContexts() +void SampleBrowser::renderGUIContexts() { if (!d_selectedSampleData) { @@ -376,17 +338,17 @@ void SamplesFramework::renderGUIContexts() } //----------------------------------------------------------------------------// -void SamplesFramework::handleSampleSelection(CEGUI::Window* sampleWindow) +void SampleBrowser::handleSampleSelection(CEGUI::Window* sampleWindow) { - SampleData* correspondingSampleData = findSampleData(sampleWindow); + SampleHandler* correspondingSampleData = findSampleData(sampleWindow); d_metaDataWinMgr->setSampleInfo(correspondingSampleData); } //----------------------------------------------------------------------------// -void SamplesFramework::handleStartDisplaySample(CEGUI::Window* sampleWindow) +void SampleBrowser::handleStartDisplaySample(CEGUI::Window* sampleWindow) { - SampleData* correspondingSampleData = findSampleData(sampleWindow); + SampleHandler* correspondingSampleData = findSampleData(sampleWindow); CEGUI::RenderTarget& defaultRenderTarget = CEGUI::System::getSingleton().getRenderer()->getDefaultRenderTarget(); @@ -394,8 +356,8 @@ void SamplesFramework::handleStartDisplaySample(CEGUI::Window* sampleWindow) sampleContext->setRenderTarget(defaultRenderTarget); sampleContext->getRootWindow()->addChild(d_sampleExitButton); - sampleContext->getMouseCursor().setPosition( - CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor(). + sampleContext->getCursor().setPosition( + CEGUI::System::getSingleton().getDefaultGUIContext().getCursor(). getPosition()); d_selectedSampleData = correspondingSampleData; @@ -404,34 +366,35 @@ void SamplesFramework::handleStartDisplaySample(CEGUI::Window* sampleWindow) } //----------------------------------------------------------------------------// -void SamplesFramework::stopDisplaySample() +void SampleBrowser::stopDisplaySample() { GUIContext* sampleGUIContext = d_selectedSampleData->getGuiContext(); // Since we switch our contexts, the mouse release won't be injected if we // don't do it manually - sampleGUIContext->injectMouseButtonUp(CEGUI::LeftButton); + if (getCurrentInputAggregator() != 0) + getCurrentInputAggregator()->injectMouseButtonUp(CEGUI::LeftButton); sampleGUIContext->injectTimePulse(0.0f); sampleGUIContext->getRootWindow()->removeChild(d_sampleExitButton); d_selectedSampleData->setGUIContextRTT(); - CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor(). - setPosition(sampleGUIContext->getMouseCursor().getPosition()); + CEGUI::System::getSingleton().getDefaultGUIContext().getCursor(). + setPosition(sampleGUIContext->getCursor().getPosition()); d_selectedSampleData = 0; d_quittingSampleView = false; } //----------------------------------------------------------------------------// -SampleData* SamplesFramework::findSampleData(CEGUI::Window* sampleWindow) +SampleHandler* SampleBrowser::findSampleData(CEGUI::Window* sampleWindow) { //Find corresponding SampleData - std::vector::iterator iter = d_samples.begin(); - std::vector::iterator end = d_samples.end(); + SampleList::iterator iter = d_samples.begin(); + SampleList::iterator end = d_samples.end(); for (; iter != end; ++iter) { - SampleData* sampleData = *iter; + SampleHandler* sampleData = *iter; if (sampleData->getSampleWindow() == sampleWindow) return sampleData; @@ -441,7 +404,7 @@ SampleData* SamplesFramework::findSampleData(CEGUI::Window* sampleWindow) } //----------------------------------------------------------------------------// -bool SamplesFramework::handleSampleExitButtonClicked(const CEGUI::EventArgs& args) +bool SampleBrowser::handleSampleExitButtonClicked(const CEGUI::EventArgs& args) { d_quittingSampleView = true; @@ -449,7 +412,7 @@ bool SamplesFramework::handleSampleExitButtonClicked(const CEGUI::EventArgs& arg } //----------------------------------------------------------------------------// -bool SamplesFramework::initialiseSampleStepwise(int sampleNumber) +bool SampleBrowser::initialiseSampleStepwise(int sampleNumber) { if (static_cast(d_samples.size()) <= sampleNumber) return true; @@ -459,10 +422,10 @@ bool SamplesFramework::initialiseSampleStepwise(int sampleNumber) if (sampleNumber >= 0) { - SampleData* sampleData = d_samples[sampleNumber]; + SampleHandler* sampleData = d_samples[sampleNumber]; sampleData->initialise(d_appWindowWidth, d_appWindowHeight); CEGUI::FrameWindow* sampleWindow = d_samplesWinMgr->createSampleWindow( - sampleData->getName(), sampleData->getRTTImage()); + sampleData->getNameText(), sampleData->getRTTImage()); sampleData->setSampleWindow(sampleWindow); @@ -473,7 +436,7 @@ bool SamplesFramework::initialiseSampleStepwise(int sampleNumber) } //----------------------------------------------------------------------------// -void SamplesFramework::initialiseSampleBrowserLayout() +void SampleBrowser::initialiseSampleBrowserLayout() { CEGUI::FontManager::getSingleton(). createFreeTypeFont("DejaVuSans-14", 14.f, true, "DejaVuSans.ttf"); @@ -488,7 +451,7 @@ void SamplesFramework::initialiseSampleBrowserLayout() CEGUI::SchemeManager::getSingleton().createFromFile("Generic.scheme"); if (!ImageManager::getSingleton().isDefined("BackgroundSampleBrowser")) - ImageManager::getSingleton().addFromImageFile( + ImageManager::getSingleton().addBitmapImageFromFile( "BackgroundSampleBrowser", "BackgroundSampleBrowser.jpg"); d_root = winMgr.loadLayoutFromFile("SampleBrowser.layout"); @@ -500,7 +463,7 @@ void SamplesFramework::initialiseSampleBrowserLayout() CEGUI::Window* samplesScrollablePane = d_root->getChild( "SampleFrameWindowContainer/SamplesFrameWindow/SamplesScrollablePane"); - d_samplesWinMgr = new SamplesBrowserManager(this, samplesScrollablePane); + d_samplesWinMgr = new SampleBrowserManager(this, samplesScrollablePane); d_sampleExitButton = static_cast(winMgr.createWindow( "SampleBrowserSkin/Button", "SampleExitButton")); @@ -519,13 +482,13 @@ void SamplesFramework::initialiseSampleBrowserLayout() "PushedImage", "SampleBrowserSkin/ExitButtonClicked"); d_sampleExitButton->subscribeEvent( PushButton::EventClicked, - Event::Subscriber(&SamplesFramework::handleSampleExitButtonClicked, this)); + Event::Subscriber(&SampleBrowser::handleSampleExitButtonClicked, this)); d_sampleExitButton->setAlwaysOnTop(true); } //----------------------------------------------------------------------------// -bool SamplesFramework::updateInitialisationStep() +bool SampleBrowser::updateInitialisationStep() { static int step(0); @@ -533,11 +496,6 @@ bool SamplesFramework::updateInitialisationStep() { case 0: { - const String filename(d_samplesXMLFilename.empty() ? - String(d_baseApp->getDataPathPrefix()) + "/samples/samples.xml" : - d_samplesXMLFilename); - - loadSamplesDataFromXML(filename); ++step; displaySampleBrowserLayoutLoadProgress(); @@ -571,9 +529,9 @@ bool SamplesFramework::updateInitialisationStep() } //----------------------------------------------------------------------------// -void SamplesFramework::initialisationFinalisation() +void SampleBrowser::initialisationFinalisation() { - System::getSingleton().getDefaultGUIContext().getMouseCursor(). + System::getSingleton().getDefaultGUIContext().getCursor(). setDefaultImage("SampleBrowserSkin/MouseArrow"); d_samplesWinMgr->setWindowRatio(d_appWindowWidth / (float)d_appWindowHeight); @@ -590,13 +548,13 @@ void SamplesFramework::initialisationFinalisation() } //----------------------------------------------------------------------------// -void SamplesFramework::updateSamples(float passedTime) +void SampleBrowser::updateSamples(float passedTime) { - std::vector::iterator iter = d_samples.begin(); - std::vector::iterator end = d_samples.end(); + SampleList::iterator iter = d_samples.begin(); + SampleList::iterator end = d_samples.end(); for (; iter != end; ++iter) { - SampleData* sampleData = *iter; + SampleHandler* sampleData = *iter; GUIContext* guiContext = sampleData->getGuiContext(); guiContext->injectTimePulse(passedTime); @@ -606,13 +564,13 @@ void SamplesFramework::updateSamples(float passedTime) } //----------------------------------------------------------------------------// -void SamplesFramework::renderSampleGUIContexts() +void SampleBrowser::renderSampleGUIContexts() { - std::vector::iterator iter = d_samples.begin(); - std::vector::iterator end = d_samples.end(); + SampleList::iterator iter = d_samples.begin(); + SampleList::iterator end = d_samples.end(); for (; iter != end; ++iter) { - SampleData* sampleData = *iter; + SampleHandler* sampleData = *iter; if (!sampleData->getGuiContext()) continue; @@ -632,7 +590,7 @@ void SamplesFramework::renderSampleGUIContexts() } //----------------------------------------------------------------------------// -void SamplesFramework::displaySampleBrowserLayoutLoadProgress() +void SampleBrowser::displaySampleBrowserLayoutLoadProgress() { int totalNum = d_samples.size() + 2; @@ -647,12 +605,12 @@ void SamplesFramework::displaySampleBrowserLayoutLoadProgress() } //----------------------------------------------------------------------------// -void SamplesFramework::displaySampleLoadProgress(int sampleNumber) +void SampleBrowser::displaySampleLoadProgress(int sampleNumber) { - SampleData* sampleData = d_samples[sampleNumber + 1]; + SampleHandler* sampleData = d_samples[sampleNumber + 1]; int totalNum = d_samples.size() + 2; - CEGUI::String loadText = "Loading " + sampleData->getName() + " ..."; + CEGUI::String loadText = "Loading " + sampleData->getNameText() + " ..."; d_loadingScreenText->setText(loadText); CEGUI::String progressText = PropertyHelper::toString(sampleNumber + 3) + @@ -663,7 +621,7 @@ void SamplesFramework::displaySampleLoadProgress(int sampleNumber) } //----------------------------------------------------------------------------// -bool SamplesFramework::areWindowsIntersecting(CEGUI::Window* window1, +bool SampleBrowser::areWindowsIntersecting(CEGUI::Window* window1, CEGUI::Window* window2) { const CEGUI::Rectf& clipRect1 = window1->getOuterRectClipper(); @@ -676,4 +634,12 @@ bool SamplesFramework::areWindowsIntersecting(CEGUI::Window* window1, } //----------------------------------------------------------------------------// +CEGUI::InputAggregator* SampleBrowser::getCurrentInputAggregator() +{ + if (d_selectedSampleData != 0) + return d_selectedSampleData->getInputAggregator(); + return d_systemInputAggregator; +} + +//----------------------------------------------------------------------------// diff --git a/samples_framework/src/SamplesFrameworkBase.cpp b/samples/browser/src/SampleBrowserBase.cpp similarity index 87% rename from samples_framework/src/SamplesFrameworkBase.cpp rename to samples/browser/src/SampleBrowserBase.cpp index 7cdffe134..1c20de7d6 100644 --- a/samples_framework/src/SamplesFrameworkBase.cpp +++ b/samples/browser/src/SampleBrowserBase.cpp @@ -24,7 +24,7 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "SamplesFrameworkBase.h" +#include "SampleBrowserBase.h" #ifdef HAVE_CONFIG_H # include "config.h" @@ -63,23 +63,23 @@ # include "CEGuiDirectFBBaseApplication.h" #endif #if defined( __WIN32__ ) || defined( _WIN32 ) -# ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE -# include "CEGuiD3D9BaseApplication.h" -# endif -# ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE -# include "CEGuiD3D10BaseApplication.h" -# endif # ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE # include "CEGuiD3D11BaseApplication.h" # endif #endif + // now we include the base CEGuiBaseApplication just in case someone has managed to // get this far without any of the renderers. This ensures the framework will build, // although there will be no renderers available for selection in the samples. #include "CEGuiBaseApplication.h" - #include "CEGUI/CEGUI.h" +#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE +# include "CEGuiEGLBaseApplication.h" +#endif + +#include "CEGuiRendererSelector.h" + // Include iostream if not on windows. #if defined( __WIN32__ ) || defined( _WIN32 ) #else @@ -90,7 +90,7 @@ /************************************************************************* Constructor *************************************************************************/ -SamplesFrameworkBase::SamplesFrameworkBase() : +SampleBrowserBase::SampleBrowserBase() : d_rendererSelector(0), d_baseApp(0), d_quitting(false), @@ -102,7 +102,7 @@ SamplesFrameworkBase::SamplesFrameworkBase() : /************************************************************************* Destructor *************************************************************************/ -SamplesFrameworkBase::~SamplesFrameworkBase() +SampleBrowserBase::~SampleBrowserBase() { if (d_baseApp) { @@ -121,7 +121,7 @@ SamplesFrameworkBase::~SamplesFrameworkBase() /************************************************************************* Application entry point *************************************************************************/ -int SamplesFrameworkBase::run() +int SampleBrowserBase::run() { CEGUI_TRY { @@ -152,19 +152,14 @@ int SamplesFrameworkBase::run() /************************************************************************* Start the SamplesFramework application *************************************************************************/ -bool SamplesFrameworkBase::runApplication() +bool SampleBrowserBase::runApplication() { // Setup renderer selection dialog for Win32 #if defined( __WIN32__ ) || defined( _WIN32 ) d_rendererSelector = new Win32CEGuiRendererSelector; // enable renderer types supported for Win32 -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE - d_rendererSelector->setRendererAvailability(Direct3D9GuiRendererType); -#endif -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE - d_rendererSelector->setRendererAvailability(Direct3D10GuiRendererType); -#endif + #ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE d_rendererSelector->setRendererAvailability(Direct3D11GuiRendererType); #endif @@ -194,6 +189,9 @@ bool SamplesFrameworkBase::runApplication() d_rendererSelector->setRendererAvailability(OpenGL3GuiRendererType); #endif #endif +#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE + d_rendererSelector->setRendererAvailability(OpenGLES2GuiRendererType); +#endif #ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE d_rendererSelector->setRendererAvailability(IrrlichtGuiRendererType); #endif @@ -219,16 +217,6 @@ bool SamplesFrameworkBase::runApplication() break; #endif #if defined( __WIN32__ ) || defined( _WIN32 ) -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE - case Direct3D9GuiRendererType: - d_baseApp = new CEGuiD3D9BaseApplication(); - break; -#endif // DX9 -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE - case Direct3D10GuiRendererType: - d_baseApp = new CEGuiD3D10BaseApplication(); - break; -#endif // DX10 #ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE case Direct3D11GuiRendererType: d_baseApp = new CEGuiD3D11BaseApplication(); @@ -247,6 +235,11 @@ bool SamplesFrameworkBase::runApplication() break; #endif #endif +#ifdef CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE + case OpenGLES2GuiRendererType: + d_baseApp = new CEGuiEGLBaseApplication(); + break; +#endif #ifdef CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE case IrrlichtGuiRendererType: d_baseApp = new CEGuiIrrlichtBaseApplication(); @@ -287,7 +280,7 @@ bool SamplesFrameworkBase::runApplication() /************************************************************************* Cleanup the sample application. *************************************************************************/ -void SamplesFrameworkBase::cleanup() +void SampleBrowserBase::cleanup() { delete d_baseApp; d_baseApp = 0; @@ -305,7 +298,7 @@ void SamplesFrameworkBase::cleanup() /************************************************************************* Output a message to the user in some OS independant way. *************************************************************************/ -void SamplesFrameworkBase::outputExceptionMessage(const char* message) +void SampleBrowserBase::outputExceptionMessage(const char* message) { #if defined(__WIN32__) || defined(_WIN32) MessageBoxA(0, message, "CEGUI - Exception", MB_OK|MB_ICONERROR); @@ -315,18 +308,18 @@ void SamplesFrameworkBase::outputExceptionMessage(const char* message) #endif } -void SamplesFrameworkBase::setQuitting(bool quit) +void SampleBrowserBase::setQuitting(bool quit) { d_quitting = quit; } -bool SamplesFrameworkBase::isQuitting() +bool SampleBrowserBase::isQuitting() { return d_quitting; } -void SamplesFrameworkBase::setApplicationWindowSize(int width, int height) +void SampleBrowserBase::setApplicationWindowSize(int width, int height) { d_appWindowWidth = width; d_appWindowHeight = height; -} \ No newline at end of file +} diff --git a/samples_framework/src/SamplesBrowserManager.cpp b/samples/browser/src/SampleBrowserManager.cpp similarity index 69% rename from samples_framework/src/SamplesBrowserManager.cpp rename to samples/browser/src/SampleBrowserManager.cpp index 65dc4005d..d11537af1 100644 --- a/samples_framework/src/SamplesBrowserManager.cpp +++ b/samples/browser/src/SampleBrowserManager.cpp @@ -24,9 +24,9 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "SamplesBrowserManager.h" +#include "SampleBrowserManager.h" -#include "SamplesFramework.h" +#include "SampleBrowser.h" #include "CEGUI/Window.h" #include "CEGUI/SchemeManager.h" @@ -38,14 +38,15 @@ author: Lukas E Meindl #include "CEGUI/widgets/FrameWindow.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/Image.h" +#include "CEGUI/InputAggregator.h" #include "CEGUI/falagard/WidgetLookManager.h" using namespace CEGUI; -const CEGUI::uint32 SamplesBrowserManager::d_sampleWindowFrameNormal(0xFFFFFFFF); -const CEGUI::uint32 SamplesBrowserManager::d_sampleWindowFrameSelected(0xFF77FFB6); +const CEGUI::uint32 SampleBrowserManager::d_sampleWindowFrameNormal(0xFFFFFFFF); +const CEGUI::uint32 SampleBrowserManager::d_sampleWindowFrameSelected(0xFF77FFB6); -SamplesBrowserManager::SamplesBrowserManager(SamplesFramework* owner, CEGUI::Window* samplesWindow) +SampleBrowserManager::SampleBrowserManager(SampleBrowser* owner, CEGUI::Window* samplesWindow) : d_owner(owner), d_root(samplesWindow), d_childCount(0), @@ -56,12 +57,12 @@ SamplesBrowserManager::SamplesBrowserManager(SamplesFramework* owner, CEGUI::Win } -CEGUI::Window* SamplesBrowserManager::getWindow() +CEGUI::Window* SampleBrowserManager::getWindow() { return d_root; } -CEGUI::FrameWindow* SamplesBrowserManager::createSampleWindow(const CEGUI::String& name, const CEGUI::Image& image) +CEGUI::FrameWindow* SampleBrowserManager::createSampleWindow(const CEGUI::String& name, const CEGUI::Image& image) { CEGUI::VerticalLayoutContainer* root = createPreviewLayoutContainer(); @@ -88,14 +89,14 @@ CEGUI::FrameWindow* SamplesBrowserManager::createSampleWindow(const CEGUI::Strin return sampleWindow; } -void SamplesBrowserManager::setWindowRatio(float aspectRatio) +void SampleBrowserManager::setWindowRatio(float aspectRatio) { d_aspectRatio = aspectRatio; updateWindows(); } -void SamplesBrowserManager::updateWindows() +void SampleBrowserManager::updateWindows() { int max = d_sampleWindows.size(); for(int i = 0; i < max; ++i) @@ -109,7 +110,7 @@ void SamplesBrowserManager::updateWindows() d_root->setSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); } -bool SamplesBrowserManager::handleMouseClickSampleWindow(const CEGUI::EventArgs& args) +bool SampleBrowserManager::handlePointerActivateSampleWindow(const CEGUI::EventArgs& args) { const WindowEventArgs& winArgs(static_cast(args)); @@ -121,11 +122,11 @@ bool SamplesBrowserManager::handleMouseClickSampleWindow(const CEGUI::EventArgs& } -bool SamplesBrowserManager::handleMouseMoveSampleWindow(const CEGUI::EventArgs& args) +bool SampleBrowserManager::handlePointerMoveSampleWindow(const CEGUI::EventArgs& args) { - const MouseEventArgs& mouseArgs(static_cast(args)); + const CursorInputEventArgs& cursor_args(static_cast(args)); - CEGUI::Window* wnd(mouseArgs.window); + CEGUI::Window* wnd(cursor_args.window); if(d_selectedWindow != wnd) { @@ -136,47 +137,45 @@ bool SamplesBrowserManager::handleMouseMoveSampleWindow(const CEGUI::EventArgs& const CEGUI::String& lookNFeel(wnd->getLookNFeel()); CEGUI::Rectf innerRectangle = CEGUI::WidgetLookManager::getSingleton().getWidgetLook(lookNFeel).getNamedArea("InnerArea").getArea().getPixelRect(*wnd); - const CEGUI::Vector2f& mousePos(mouseArgs.position); + const glm::vec2& cursor_pos(cursor_args.position); const CEGUI::Rectf& windowDimensions(wnd->getUnclippedOuterRect().get()); - float relPosX = (mousePos.d_x - windowDimensions.left() - innerRectangle.getPosition().d_x) / innerRectangle.getWidth(); - float relPosY = (mousePos.d_y - windowDimensions.top() - innerRectangle.getPosition().d_y) / innerRectangle.getHeight(); + const float relPosX = (cursor_pos.x - windowDimensions.left() - innerRectangle.getPosition().d_x) / innerRectangle.getWidth(); + const float relPosY = (cursor_pos.y - windowDimensions.top() - innerRectangle.getPosition().d_y) / innerRectangle.getHeight(); - if(relPosX >= 0.0f && relPosX <= 1.0f && relPosY >= 0.0f && relPosY <= 1.0f) + if (relPosX >= 0.0f && relPosX <= 1.0f && relPosY >= 0.0f && relPosY <= 1.0f) { - SampleData* sampleData = d_owner->findSampleData(wnd); + SampleHandler* sampleData = d_owner->findSampleData(wnd); const CEGUI::Sizef& contextSize(sampleData->getGuiContext()->getSurfaceSize()); - float absPosX = relPosX * contextSize.d_width; - float absPosY = relPosY * contextSize.d_height; + const float absPosX = relPosX * contextSize.d_width; + const float absPosY = relPosY * contextSize.d_height; - - sampleData->getGuiContext()->injectMousePosition(absPosX, absPosY); + sampleData->getInputAggregator()->injectMousePosition(absPosX, absPosY); sampleData->getGuiContext()->markAsDirty(); - wnd->setMouseCursor("SampleBrowserSkin/MouseArrowHover"); + wnd->setCursor("SampleBrowserSkin/MouseArrowHover"); } else { - wnd->setMouseCursor("SampleBrowserSkin/MouseArrow"); + wnd->setCursor("SampleBrowserSkin/MouseArrow"); } return true; } +bool SampleBrowserManager::handleLeaveSampleWindow(const CEGUI::EventArgs& args) +{ + const CursorInputEventArgs& cursor_args(static_cast(args)); -bool SamplesBrowserManager::handleLeaveSampleWindow(const CEGUI::EventArgs& args) -{ - const MouseEventArgs& mouseArgs(static_cast(args)); - - CEGUI::Window* wnd(mouseArgs.window); - wnd->setMouseCursor("SampleBrowserSkin/MouseArrow"); + CEGUI::Window* wnd(cursor_args.window); + wnd->setCursor("SampleBrowserSkin/MouseArrow"); return true; } -void SamplesBrowserManager::selectSampleWindow(CEGUI::Window* wnd) +void SampleBrowserManager::selectSampleWindow(CEGUI::Window* wnd) { if(d_selectedWindow) { @@ -190,20 +189,20 @@ void SamplesBrowserManager::selectSampleWindow(CEGUI::Window* wnd) d_selectedWindow->setProperty("FrameColours", CEGUI::PropertyHelper::toString(colRectSelected)); } -void SamplesBrowserManager::init() +void SampleBrowserManager::init() { WindowManager& winMgr(WindowManager::getSingleton()); d_verticalLayoutContainerSamples = static_cast(winMgr.createWindow("VerticalLayoutContainer")); d_verticalLayoutContainerSamples->setMargin(CEGUI::UBox(cegui_reldim(0.0f), cegui_reldim(0.1f), cegui_absdim(14.f), cegui_reldim(0.1f))); - d_verticalLayoutContainerSamples->setMouseInputPropagationEnabled(true); + d_verticalLayoutContainerSamples->setCursorInputPropagationEnabled(true); d_root->addChild(d_verticalLayoutContainerSamples); } -CEGUI::DefaultWindow* SamplesBrowserManager::createPreviewHeaderNameWindow(const CEGUI::String& name) +CEGUI::DefaultWindow* SampleBrowserManager::createPreviewHeaderNameWindow(const CEGUI::String& name) { WindowManager& winMgr(WindowManager::getSingleton()); @@ -212,24 +211,24 @@ CEGUI::DefaultWindow* SamplesBrowserManager::createPreviewHeaderNameWindow(const windowName->setText(name); windowName->setFont("DejaVuSans-12-NoScale"); windowName->setProperty("HorzFormatting", "Centre"); - windowName->setMouseInputPropagationEnabled(true); + windowName->setCursorInputPropagationEnabled(true); return windowName; } -CEGUI::VerticalLayoutContainer* SamplesBrowserManager::createPreviewLayoutContainer() +CEGUI::VerticalLayoutContainer* SampleBrowserManager::createPreviewLayoutContainer() { WindowManager& winMgr(WindowManager::getSingleton()); CEGUI::VerticalLayoutContainer* root = static_cast(winMgr.createWindow("VerticalLayoutContainer")); root->setSize(CEGUI::USize(cegui_reldim(0.8f), cegui_reldim(1.0f))); - root->setMouseInputPropagationEnabled(true); + root->setCursorInputPropagationEnabled(true); root->setMargin(CEGUI::UBox(UDim(0.0f, 0.0f),UDim(0.0f, 0.0f),UDim(0.0f, 8.f), UDim(0.0f, 0.0f))); return root; } -CEGUI::FrameWindow* SamplesBrowserManager::createPreviewSampleWindow(const CEGUI::String& name, const CEGUI::Image &image) +CEGUI::FrameWindow* SampleBrowserManager::createPreviewSampleWindow(const CEGUI::String& name, const CEGUI::Image &image) { WindowManager& winMgr(WindowManager::getSingleton()); @@ -238,11 +237,11 @@ CEGUI::FrameWindow* SamplesBrowserManager::createPreviewSampleWindow(const CEGUI sampleWindow->setProperty("Image", imageName); sampleWindow->setSize(USize(UDim(1.0f, -10.0f), cegui_absdim(1.0f))); - sampleWindow->setMouseInputPropagationEnabled(true); + sampleWindow->setCursorInputPropagationEnabled(true); - sampleWindow->subscribeEvent(Window::EventMouseMove, Event::Subscriber(&SamplesBrowserManager::handleMouseMoveSampleWindow, this)); - sampleWindow->subscribeEvent(Window::EventMouseClick, Event::Subscriber(&SamplesBrowserManager::handleMouseClickSampleWindow, this)); - sampleWindow->subscribeEvent(Window::EventMouseLeavesArea, Event::Subscriber(&SamplesBrowserManager::handleLeaveSampleWindow, this)); + sampleWindow->subscribeEvent(Window::EventCursorMove, Event::Subscriber(&SampleBrowserManager::handlePointerMoveSampleWindow, this)); + sampleWindow->subscribeEvent(Window::EventCursorActivate, Event::Subscriber(&SampleBrowserManager::handlePointerActivateSampleWindow, this)); + sampleWindow->subscribeEvent(Window::EventCursorLeavesArea, Event::Subscriber(&SampleBrowserManager::handleLeaveSampleWindow, this)); CEGUI::ColourRect colRect((CEGUI::Colour(d_sampleWindowFrameNormal))); sampleWindow->setProperty("FrameColours", CEGUI::PropertyHelper::toString(colRect)); @@ -252,20 +251,20 @@ CEGUI::FrameWindow* SamplesBrowserManager::createPreviewSampleWindow(const CEGUI return sampleWindow; } -CEGUI::HorizontalLayoutContainer* SamplesBrowserManager::createPreviewHeader() +CEGUI::HorizontalLayoutContainer* SampleBrowserManager::createPreviewHeader() { WindowManager& winMgr(WindowManager::getSingleton()); CEGUI::HorizontalLayoutContainer* header = static_cast(winMgr.createWindow("HorizontalLayoutContainer")); header->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_absdim(40.0f))); - header->setMouseInputPropagationEnabled(true); + header->setCursorInputPropagationEnabled(true); header->setMargin(CEGUI::UBox(UDim(0.0f, 12.f),UDim(0.0f, 0.0f),UDim(0.0f, 0), UDim(0.0f, 0.0f))); header->setHorizontalAlignment(HA_CENTRE); return header; } -CEGUI::PushButton* SamplesBrowserManager::createPreviewHeaderEnterButton() +CEGUI::PushButton* SampleBrowserManager::createPreviewHeaderEnterButton() { WindowManager& winMgr(WindowManager::getSingleton()); @@ -275,11 +274,11 @@ CEGUI::PushButton* SamplesBrowserManager::createPreviewHeaderEnterButton() button->setAspectMode(AM_EXPAND); button->setAspectRatio(1.0f); button->setPosition(CEGUI::UVector2(cegui_absdim(-7.f), cegui_absdim(0.0f))); - button->setMouseInputPropagationEnabled(true); + button->setCursorInputPropagationEnabled(true); button->setProperty("NormalImage", "SampleBrowserSkin/EntryButtonNormal"); button->setProperty("HoverImage", "SampleBrowserSkin/EntryButtonHover"); button->setProperty("PushedImage", "SampleBrowserSkin/EntryButtonClicked"); - button->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&SamplesBrowserManager::handleSampleEnterButtonClicked, this)); + button->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&SampleBrowserManager::handleSampleEnterButtonClicked, this)); button->setAlwaysOnTop(true); button->setHorizontalAlignment(HA_RIGHT); button->setVerticalAlignment(VA_CENTRE); @@ -289,7 +288,7 @@ CEGUI::PushButton* SamplesBrowserManager::createPreviewHeaderEnterButton() } -bool SamplesBrowserManager::handleSampleEnterButtonClicked(const CEGUI::EventArgs& args) +bool SampleBrowserManager::handleSampleEnterButtonClicked(const CEGUI::EventArgs& args) { const WindowEventArgs& winArgs(static_cast(args)); diff --git a/samples_framework/src/SampleData.cpp b/samples/browser/src/SampleHandler.cpp similarity index 55% rename from samples_framework/src/SampleData.cpp rename to samples/browser/src/SampleHandler.cpp index 24d5948aa..144d3d794 100644 --- a/samples_framework/src/SampleData.cpp +++ b/samples/browser/src/SampleHandler.cpp @@ -24,125 +24,92 @@ author: Lukas E Meindl * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "SampleData.h" +#include "SampleHandler.h" #include "Sample.h" -#include "Samples_xmlHandler.h" - #include "CEGUI/DynamicModule.h" #include "CEGUI/Version.h" #include "CEGUI/Exceptions.h" #include "CEGUI/System.h" #include "CEGUI/TextureTarget.h" -#include "CEGUI/BasicImage.h" +#include "CEGUI/BitmapImage.h" #include "CEGUI/GUIContext.h" #include "CEGUI/Texture.h" #include "CEGUI/ImageManager.h" +#include "CEGUI/InputAggregator.h" #include "CEGUI/Window.h" #include "CEGUI/Vector.h" using namespace CEGUI; -#define S_(X) #X -#define STRINGIZE(X) S_(X) - -typedef Sample& (*getSampleInstance)(); -#define GetSampleInstanceFuncName "getSampleInstance" - -SampleData::SampleData(CEGUI::String sampleName, - CEGUI::String summary, - CEGUI::String description, - SampleType sampleTypeEnum, - CEGUI::String credits) - : d_name(sampleName) - , d_summary(summary) - , d_description(description) - , d_type(sampleTypeEnum) + +SampleHandler::SampleHandler(Sample* sample) + : d_sample(sample) , d_usedFilesString("") - , d_credits(credits) , d_sampleWindow(0) + , d_inputAggregator(0) + , d_nonDefaultInputAggregator(false) , d_guiContext(0) , d_textureTarget(0) , d_textureTargetImage(0) { } -SampleData::~SampleData() +SampleHandler::~SampleHandler() { - } -CEGUI::String SampleData::getName() +CEGUI::String SampleHandler::getNameText() { - return d_name; + return d_sample->getName(); } -CEGUI::String SampleData::getSummary() +CEGUI::String SampleHandler::getSummaryText() { - return "Summary:\n" + d_summary; + return "Summary:\n" + d_sample->getSummary(); } -CEGUI::String SampleData::getCredits() +CEGUI::String SampleHandler::getCreditsText() { - return "Credits:\n" + d_credits; + return "Credits:\n" + d_sample->getCredits(); } -CEGUI::String SampleData::getSampleTypeString() +CEGUI::String SampleHandler::getDescriptionText() { - switch(d_type) - { - case ST_Module: - return SampleDataHandler::SampleTypeCppModule; - break; - case ST_Lua: - return SampleDataHandler::SampleTypeLua; - break; - case ST_Python: - return SampleDataHandler::SampleTypePython; - default: - return ""; - } + return "Description:\n" + d_sample->getDescription(); } -CEGUI::String SampleData::getDescription() -{ - return "Description:\n" + d_description; -} - -CEGUI::String SampleData::getUsedFilesString() +CEGUI::String SampleHandler::getUsedFilesText() { return "Used files:\n" + d_usedFilesString; } -void SampleData::setSampleWindow(CEGUI::Window* sampleWindow) +void SampleHandler::setSampleWindow(CEGUI::Window* sampleWindow) { d_sampleWindow = sampleWindow; } -CEGUI::Window* SampleData::getSampleWindow() +CEGUI::Window* SampleHandler::getSampleWindow() { return d_sampleWindow; } -void SampleData::initialise(int width, int height) +void SampleHandler::initialise(int width, int height) { - CEGUI::System& system(System::getSingleton()); - - CEGUI::Sizef size(static_cast(width), static_cast(height)); + initialiseSamplePreviewRenderTarget(width, height); - d_textureTarget = system.getRenderer()->createTextureTarget(); - d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget); - d_textureTarget->declareRenderSize(size); - CEGUI::String imageName(d_textureTarget->getTexture().getName()); - d_textureTargetImage = static_cast(&CEGUI::ImageManager::getSingleton().create("BasicImage", "SampleBrowser/" + imageName)); - d_textureTargetImage->setTexture(&d_textureTarget->getTexture()); + initialiseInputAggregator(); - setTextureTargetImageArea(static_cast(height), static_cast(width)); + initialiseSample(); } -void SampleData::deinitialise() +void SampleHandler::deinitialise() { + if(d_sample) + d_sample->deinitialise(); + + CEGUI::System& system(System::getSingleton()); if(d_guiContext) @@ -151,6 +118,12 @@ void SampleData::deinitialise() d_guiContext = 0; } + if (d_inputAggregator && !d_nonDefaultInputAggregator) + { + delete d_inputAggregator; + d_inputAggregator = 0; + } + if(d_textureTarget) { system.getRenderer()->destroyTextureTarget(d_textureTarget); @@ -164,12 +137,17 @@ void SampleData::deinitialise() } } -GUIContext* SampleData::getGuiContext() +GUIContext* SampleHandler::getGuiContext() { return d_guiContext; } -void SampleData::handleNewWindowSize(float width, float height) +InputAggregator* SampleHandler::getInputAggregator() +{ + return d_inputAggregator; +} + +void SampleHandler::handleNewWindowSize(float width, float height) { setTextureTargetImageArea(height, width); @@ -182,22 +160,22 @@ void SampleData::handleNewWindowSize(float width, float height) } } -CEGUI::Image& SampleData::getRTTImage() +CEGUI::Image& SampleHandler::getRTTImage() { return *d_textureTargetImage; } -void SampleData::setGUIContextRTT() +void SampleHandler::setGUIContextRTT() { d_guiContext->setRenderTarget(*d_textureTarget); } -void SampleData::clearRTTTexture() +void SampleHandler::clearRTTTexture() { d_textureTarget->clear(); } -void SampleData::setTextureTargetImageArea(float height, float width) +void SampleHandler::setTextureTargetImageArea(float height, float width) { if(d_textureTarget) { @@ -210,64 +188,63 @@ void SampleData::setTextureTargetImageArea(float height, float width) if(d_textureTargetImage) - d_textureTargetImage->setArea(renderArea); + d_textureTargetImage->setImageArea(renderArea); } } -//----------------------------------------------------------------------------// -SampleDataModule::SampleDataModule(CEGUI::String sampleName, - CEGUI::String summary, - CEGUI::String description, - SampleType sampleTypeEnum, - CEGUI::String credits) - : SampleData(sampleName, summary, description, sampleTypeEnum, credits) - , d_sample(0) - , d_dynamicModule(0) +void SampleHandler::onEnteringSample() { + d_sample->onEnteringSample(); } -SampleDataModule::~SampleDataModule() +void SampleHandler::update(float timeSinceLastUpdate) { + d_sample->update(timeSinceLastUpdate); } -void SampleDataModule::initialise(int width, int height) +void SampleHandler::initialiseSample() { - SampleData::initialise(width, height); - - getSampleInstanceFromDLL(); - d_sample->initialise(d_guiContext); d_usedFilesString = d_sample->getUsedFilesString(); } -void SampleDataModule::deinitialise() +void SampleHandler::initialiseInputAggregator() { - if(d_sample) - d_sample->deinitialise(); - - SampleData::deinitialise(); + // If the sample has its own non-default InputAggregator, we will use that one, otherwise we create a default one + if (d_sample->getInputAggregator() != 0) + { + d_inputAggregator = d_sample->getInputAggregator(); + d_nonDefaultInputAggregator = true; + } + else + { + //! Creating the an input aggregator for this sample + d_inputAggregator = new CEGUI::InputAggregator(d_guiContext); + d_inputAggregator->initialise(); + } } -void SampleDataModule::getSampleInstanceFromDLL() +void SampleHandler::initialiseSamplePreviewRenderTarget(int width, int height) { - CEGUI::DynamicModule* sampleModule = new CEGUI::DynamicModule(d_name); - getSampleInstance functionPointerGetSample = (getSampleInstance)sampleModule->getSymbolAddress(CEGUI::String(GetSampleInstanceFuncName)); + CEGUI::System& system(System::getSingleton()); - if(functionPointerGetSample == 0) - { - CEGUI::String errorMessage = "The sample creation function is not defined in the dynamic library of " + d_name; - CEGUI_THROW(CEGUI::InvalidRequestException(errorMessage.c_str())); - } + CEGUI::Sizef size(static_cast(width), static_cast(height)); - d_sample = &(functionPointerGetSample()); -} + //! Creating a texcture target to render the GUIContext onto + d_textureTarget = system.getRenderer()->createTextureTarget(); + d_guiContext = &system.createGUIContext((RenderTarget&)*d_textureTarget); + d_textureTarget->declareRenderSize(size); -void SampleDataModule::onEnteringSample() -{ - d_sample->onEnteringSample(); + //! Creating an image based on the TextureTarget's texture, which allows us to use the rendered-to-texture inside CEGUI for previewing the sample + CEGUI::String imageName(d_textureTarget->getTexture().getName()); + d_textureTargetImage = static_cast(&CEGUI::ImageManager::getSingleton().create("BitmapImage", "SampleBrowser/" + imageName)); + d_textureTargetImage->setTexture(&d_textureTarget->getTexture()); + + //! Helper function to set the image's area + setTextureTargetImageArea(static_cast(height), static_cast(width)); } -void SampleDataModule::update(float timeSinceLastUpdate) +const Sample* SampleHandler::getSample() const { - d_sample->update(timeSinceLastUpdate); -} \ No newline at end of file + return d_sample; +} diff --git a/samples_framework/src/Win32AppHelper.cpp b/samples/browser/src/Win32AppHelper.cpp similarity index 86% rename from samples_framework/src/Win32AppHelper.cpp rename to samples/browser/src/Win32AppHelper.cpp index 56969ff80..aa36a9172 100644 --- a/samples_framework/src/Win32AppHelper.cpp +++ b/samples/browser/src/Win32AppHelper.cpp @@ -26,13 +26,13 @@ ***************************************************************************/ #include "CEGUISamplesConfig.h" -#if defined(CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE) || defined(CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE) || defined(CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) +#if defined(CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) #include "Win32AppHelper.h" #include "CEGUI/CEGUI.h" #include -#include "SamplesFrameworkBase.h" +#include "SampleBrowserBase.h" /************************************************************************* Static Data Definitions @@ -52,7 +52,7 @@ const TCHAR Win32AppHelper::CREATE_DEVICE_ERROR[] = _TEXT("Failed to create Di bool Win32AppHelper::s_mouseInWindow = false; // For input injection -SamplesFrameworkBase* Win32AppHelper::s_samplesFramework(0); +SampleBrowserBase* Win32AppHelper::s_sampleBrowser(0); /************************************************************************* Prototypes for internal helper functions a.k.a "The hacks section" @@ -60,8 +60,6 @@ SamplesFrameworkBase* Win32AppHelper::s_samplesFramework(0); we othereise would need multiple versions of the D3D headers included which is obviously a big no-no. *************************************************************************/ -void DeviceReset_Direct3D9(HWND window, CEGUI::Renderer* renderer); -void DeviceReset_Direct3D10(HWND window, CEGUI::Renderer* renderer); void DeviceReset_Direct3D11(HWND window, CEGUI::Renderer* renderer); /************************************************************************* @@ -117,7 +115,7 @@ LRESULT CALLBACK Win32AppHelper::wndProc(HWND hWnd, UINT message, WPARAM wParam, switch(message) { case WM_CHAR: - s_samplesFramework->injectChar((CEGUI::utf32)wParam); + s_sampleBrowser->injectChar((CEGUI::utf32)wParam); break; case WM_MOUSELEAVE: @@ -131,35 +129,35 @@ LRESULT CALLBACK Win32AppHelper::wndProc(HWND hWnd, UINT message, WPARAM wParam, case WM_MOUSEMOVE: mouseEnters(); - s_samplesFramework->injectMousePosition((float)(LOWORD(lParam)), (float)(HIWORD(lParam))); + s_sampleBrowser->injectMousePosition((float)(LOWORD(lParam)), (float)(HIWORD(lParam))); break; case WM_LBUTTONDOWN: - s_samplesFramework->injectMouseButtonDown(CEGUI::LeftButton); + s_sampleBrowser->injectMouseButtonDown(CEGUI::LeftButton); break; case WM_LBUTTONUP: - s_samplesFramework->injectMouseButtonUp(CEGUI::LeftButton); + s_sampleBrowser->injectMouseButtonUp(CEGUI::LeftButton); break; case WM_RBUTTONDOWN: - s_samplesFramework->injectMouseButtonDown(CEGUI::RightButton); + s_sampleBrowser->injectMouseButtonDown(CEGUI::RightButton); break; case WM_RBUTTONUP: - s_samplesFramework->injectMouseButtonUp(CEGUI::RightButton); + s_sampleBrowser->injectMouseButtonUp(CEGUI::RightButton); break; case WM_MBUTTONDOWN: - s_samplesFramework->injectMouseButtonDown(CEGUI::MiddleButton); + s_sampleBrowser->injectMouseButtonDown(CEGUI::MiddleButton); break; case WM_MBUTTONUP: - s_samplesFramework->injectMouseButtonUp(CEGUI::MiddleButton); + s_sampleBrowser->injectMouseButtonUp(CEGUI::MiddleButton); break; case 0x020A: // WM_MOUSEWHEEL: - s_samplesFramework->injectMouseWheelChange(static_cast((short)HIWORD(wParam)) / static_cast(120)); + s_sampleBrowser->injectMouseWheelChange(static_cast((short)HIWORD(wParam)) / static_cast(120)); break; case WM_DESTROY: @@ -181,14 +179,6 @@ LRESULT CALLBACK Win32AppHelper::wndProc(HWND hWnd, UINT message, WPARAM wParam, CEGUI::String id(renderer->getIdentifierString()); // invoke correct function based on the renderer we have ID'd -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE - if (id.find("Official Direct3D 9") != id.npos) - DeviceReset_Direct3D9(hWnd, renderer); -#endif -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE - if (id.find("Official Direct3D 10") != id.npos) - DeviceReset_Direct3D10(hWnd, renderer); -#endif #ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE if (id.find("Official Direct3D 11") != id.npos) DeviceReset_Direct3D11(hWnd, renderer); @@ -326,11 +316,11 @@ void Win32AppHelper::doDirectInputEvents(const Win32AppHelper::DirectInputState& { if (LOBYTE(devDat.dwData) & 0x80) { - s_samplesFramework->injectKeyDown((CEGUI::Key::Scan)devDat.dwOfs); + s_sampleBrowser->injectKeyDown((CEGUI::Key::Scan)devDat.dwOfs); } else { - s_samplesFramework->injectKeyUp((CEGUI::Key::Scan)devDat.dwOfs); + s_sampleBrowser->injectKeyUp((CEGUI::Key::Scan)devDat.dwOfs); } } @@ -373,9 +363,9 @@ bool Win32AppHelper::doWin32Events(bool& idle) } -void Win32AppHelper::setSamplesFramework(SamplesFrameworkBase* samplesFramework) +void Win32AppHelper::setSampleBrowser(SampleBrowserBase* sampleBrowser) { - s_samplesFramework = samplesFramework; + s_sampleBrowser = sampleBrowser; } #endif diff --git a/samples_framework/src/Win32CEGuiRendererSelector.cpp b/samples/browser/src/Win32CEGuiRendererSelector.cpp similarity index 98% rename from samples_framework/src/Win32CEGuiRendererSelector.cpp rename to samples/browser/src/Win32CEGuiRendererSelector.cpp index d2734c09d..199c612d4 100644 --- a/samples_framework/src/Win32CEGuiRendererSelector.cpp +++ b/samples/browser/src/Win32CEGuiRendererSelector.cpp @@ -389,8 +389,6 @@ INT_PTR CALLBACK Win32CEGuiRendererSelector::dialogProcedure(HWND hDlg, UINT mes obj->addComboboxOption(combo, "OpenGL 3.2 Core Renderer", OpenGL3GuiRendererType); obj->addComboboxOption(combo, "OpenGL Renderer", OpenGLGuiRendererType); obj->addComboboxOption(combo, "Ogre Engine Renderer", OgreGuiRendererType); - obj->addComboboxOption(combo, "Microsoft Direct3D 9 Renderer", Direct3D9GuiRendererType); - obj->addComboboxOption(combo, "Microsoft Direct3D 10 Renderer", Direct3D10GuiRendererType); obj->addComboboxOption(combo, "Microsoft Direct3D 11 Renderer", Direct3D11GuiRendererType); obj->addComboboxOption(combo, "Irrlicht Engine Renderer", IrrlichtGuiRendererType); } diff --git a/samples/common/NavigationStrategies.cpp b/samples/common/NavigationStrategies.cpp new file mode 100644 index 000000000..8623ebbf1 --- /dev/null +++ b/samples/common/NavigationStrategies.cpp @@ -0,0 +1,165 @@ +/*********************************************************************** + created: 25/08/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "NavigationStrategies.h" +#include "CEGUI/Window.h" + +#include + +using namespace CEGUI; +using namespace NavigationStrategiesPayloads; + +Window* LinearNavigationStrategy::getWindow(Window* neighbour, const String& payload) +{ + std::vector::const_iterator itor; + // start at the beginning + if (neighbour == 0) + return *d_windows.begin(); + else + itor = std::find(d_windows.begin(), d_windows.end(), neighbour); + + // no such neighbour window in here + if (itor == d_windows.end()) + return 0; + + if (payload == NAVIGATE_PREVIOUS) + { + // first item. wrap to end + if (itor == d_windows.begin()) + return *(d_windows.end() - 1); + + return *(itor - 1); + } + else if (payload == NAVIGATE_NEXT) + { + // last item. wrap to beginning + if (itor == d_windows.end() - 1) + return *d_windows.begin(); + + return *(itor + 1); + } + + // no payload handling, just return the same window + return neighbour; +} + +Window* MatrixNavigationStrategy::getWindow(Window* neighbour, const String& payload) +{ + size_t rows = d_windows.size(); + + for (size_t row = 0; row < rows; ++row) + { + std::vector column = d_windows.at(row); + size_t cols = column.size(); + + for (size_t col = 0; col < cols; ++col) + { + if (neighbour == column.at(col)) + { + // compute the new window (wrapping) + if (payload == NAVIGATE_RIGHT) + col = (col + 1) % cols; + else if (payload == NAVIGATE_DOWN) + row = (row + 1) % rows; + else if (payload == NAVIGATE_LEFT) + { + if (col == 0) + col = cols - 1; + else + col --; + } + else if (payload == NAVIGATE_UP) + { + if (row == 0) + row = rows - 1; + else + row --; + } + + return d_windows.at(row).at(col); + } + } + } + + // first button + return d_windows.at(0).at(0); +} + +CEGUI::Window* WindowChildrenNavigationStrategy::getWindow(CEGUI::Window* neighbour, const CEGUI::String& payload) +{ + if (d_targetWindow == 0) + return 0; + + size_t child_count = d_targetWindow->getChildCount(); + if (child_count == 0) + return 0; + + bool found = false; + size_t index = 0; + + for (size_t i = 0; i < child_count; ++i) + { + if (d_targetWindow->getChildAtIdx(i) == neighbour) + { + found = true; + index = i; + break; + } + } + + if (found) + { + if (payload == NAVIGATE_NEXT) + { + if (index >= child_count - 1) + index = 0; + else + index ++; + } + + if (payload == NAVIGATE_PREVIOUS) + { + if (index == 0) + index = child_count - 1; + else + index --; + } + } + + Window* child = d_targetWindow->getChildAtIdx(index); + + // start a new search + if (!child->canFocus()) + { + // prevent overflow + if (child != neighbour) + return getWindow(child, payload); + else + return 0; + } + + return child; +} diff --git a/samples/common/SamplesXmlFooter.xml b/samples/common/SamplesXmlFooter.xml deleted file mode 100644 index 34b5df9f0..000000000 --- a/samples/common/SamplesXmlFooter.xml +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/samples/common/SamplesXmlHeader.xml b/samples/common/SamplesXmlHeader.xml deleted file mode 100644 index 68c8d3d5f..000000000 --- a/samples/common/SamplesXmlHeader.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/samples/common/include/CEGUISamplesConfig.h.in b/samples/common/include/CEGUISamplesConfig.h.in index 8d18f664d..bf15a7184 100644 --- a/samples/common/include/CEGUISamplesConfig.h.in +++ b/samples/common/include/CEGUISamplesConfig.h.in @@ -55,13 +55,12 @@ Each item in here has a comment to describe what it's for. #cmakedefine CEGUI_BUILD_RENDERER_OPENGL3 #cmakedefine CEGUI_BUILD_RENDERER_OGRE #cmakedefine CEGUI_BUILD_RENDERER_IRRLICHT -#cmakedefine CEGUI_BUILD_RENDERER_DIRECT3D9 -#cmakedefine CEGUI_BUILD_RENDERER_DIRECT3D10 #cmakedefine CEGUI_BUILD_RENDERER_DIRECT3D11 #cmakedefine CEGUI_BUILD_RENDERER_DIRECTFB #cmakedefine CEGUI_SAMPLES_USE_GTK2 #cmakedefine CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE +#cmakedefine CEGUI_SAMPLES_RENDERER_OPENGLES2_ACTIVE #cmakedefine CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE #cmakedefine CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE #cmakedefine CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE diff --git a/samples/common/include/NavigationStrategies.h b/samples/common/include/NavigationStrategies.h new file mode 100644 index 000000000..39231f0af --- /dev/null +++ b/samples/common/include/NavigationStrategies.h @@ -0,0 +1,104 @@ +/*********************************************************************** + created: 25/08/2013 + author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUINavigationStrategies_h_ +#define _CEGUINavigationStrategies_h_ + +#include "CEGUI/String.h" +#include "CEGUI/WindowNavigator.h" +#include + +/*! +\brief + Payloads used by the navigation strategies defined in this file +*/ +namespace NavigationStrategiesPayloads +{ +static const CEGUI::String NAVIGATE_LEFT = "left"; +static const CEGUI::String NAVIGATE_RIGHT = "right"; +static const CEGUI::String NAVIGATE_UP = "up"; +static const CEGUI::String NAVIGATE_DOWN = "down"; +static const CEGUI::String NAVIGATE_NEXT = "next"; +static const CEGUI::String NAVIGATE_PREVIOUS = "previous"; +} + +/*! +\brief + A strategy that navigates between a specified window's children + + It uses the following navigation strategy payloads: + - NAVIGATE_NEXT + - NAVIGATE_PREVIOUS +*/ +class WindowChildrenNavigationStrategy : public CEGUI::NavigationStrategy +{ +public: + WindowChildrenNavigationStrategy(CEGUI::Window* target_window) : + d_targetWindow(target_window) + { + } + + CEGUI::Window* d_targetWindow; + + virtual CEGUI::Window* getWindow(CEGUI::Window* neighbour, const CEGUI::String& payload); +}; + +/*! +\brief + A linear strategy that navigates in the windows vector + + It uses the following navigation strategy payloads: + - NAVIGATE_NEXT + - NAVIGATE_PREVIOUS +*/ +class LinearNavigationStrategy : public CEGUI::NavigationStrategy +{ +public: + std::vector d_windows; + + virtual CEGUI::Window* getWindow(CEGUI::Window* neighbour, const CEGUI::String& payload); +}; + +/*! +\brief + A matrix navigation strategy which navigates in the windows matrix. + + It uses the following navigation strategy payloads: + - NAVIGATE_LEFT + - NAVIGATE_RIGHT + - NAVIGATE_UP + - NAVIGATE_DOWN +*/ +class MatrixNavigationStrategy : public CEGUI::NavigationStrategy +{ +public: + // matrix + std::vector< std::vector > d_windows; + + virtual CEGUI::Window* getWindow(CEGUI::Window* neighbour, const CEGUI::String& payload); +}; + +#endif diff --git a/samples/common/include/Sample.h b/samples/common/include/Sample.h index 57dfe2128..1977dba4a 100644 --- a/samples/common/include/Sample.h +++ b/samples/common/include/Sample.h @@ -36,6 +36,11 @@ author: Lukas E Meindl class Sample { public: + Sample(int priority = 0) : + d_inputAggregator(0), + d_priority(priority) + {} + virtual bool initialise(CEGUI::GUIContext* guiContext) = 0; virtual void deinitialise() = 0; @@ -43,9 +48,44 @@ class Sample virtual void update(float timeSinceLastUpdate) {} const CEGUI::String& getUsedFilesString() {return d_usedFiles;} + //! Get an explicit instance of input aggregator to be used with this sample + CEGUI::InputAggregator* getInputAggregator() { return d_inputAggregator; } + + //! Get the name of the sample + CEGUI::String getName() const { return d_name; } + //! Get the credits (author(s)) of the sample + CEGUI::String getCredits() const { return d_credits; } + //! Get the summary of what the samples wants to demonstrate + CEGUI::String getSummary() const { return d_summary; } + //! Get the description of how the sample achieves what it aims to demonstrate + CEGUI::String getDescription() const { return d_description; } + + //! Returns the priority of this sample in the browser + int getPriority() const { return d_priority; } + + //! Operator for sorting the samples in the browser after their priority + bool operator< (const Sample& other) const { return d_priority > other.getPriority(); } protected: - CEGUI::String d_usedFiles; + CEGUI::String d_usedFiles; + CEGUI::InputAggregator* d_inputAggregator; + + //! The name of the sample + CEGUI::String d_name; + //! The credits of the sample (author(s)) + CEGUI::String d_credits; + //! The summary of what the sample wants to demonstrate + CEGUI::String d_summary; + //! The summary of how the sample achieves what it aims to demonstrate + CEGUI::String d_description; + + //! The priority of display of this sample in the browser. Higher priority means earlier display + int d_priority; +}; + +struct SamplePointerCompare +{ + bool operator()(const Sample* left, const Sample* right) { return *left < *right; } }; #endif \ No newline at end of file diff --git a/samples_framework/CMakeLists.txt b/samples_framework/CMakeLists.txt deleted file mode 100644 index 014640df2..000000000 --- a/samples_framework/CMakeLists.txt +++ /dev/null @@ -1,303 +0,0 @@ -set( CEGUI_TARGET_NAME ${CEGUI_SAMPLEFRAMEWORK_EXENAME} ) - -set( CORE_SOURCE_FILES - ./src/SamplesFrameworkBase.cpp - ./src/SamplesFramework.cpp - ./src/CEGuiBaseApplication.cpp - ./src/CEGuiRendererSelector.cpp - ./src/Samples_xmlHandler.cpp - ./src/SampleData.cpp - ./src/MetaDataWindowManager.cpp - ./src/SamplesBrowserManager.cpp -) - -set( CORE_HEADER_FILES - ../samples/common/include/Sample.h - ./include/SamplesFrameworkBase.h - ./include/SamplesFramework.h - ./include/CEGuiBaseApplication.h - ./include/CEGuiRendererSelector.h - ./include/Samples_xmlHandler.h - ./include/SampleData.h - ./include/MetaDataWindowManager.h - ./include/SamplesBrowserManager.h -) - - -include_directories(${CMAKE_SOURCE_DIR}/samples_framework/include - ${CMAKE_BINARY_DIR}/samples/common/include - ${CMAKE_SOURCE_DIR}/samples/common/include - ${CMAKE_SOURCE_DIR}/cegui/include) - -if (WIN32) - list (APPEND CORE_SOURCE_FILES - ./src/Win32AppHelper.cpp - ./src/Win32CEGuiRendererSelector.cpp - ) -elseif (APPLE) - list (APPEND CORE_SOURCE_FILES - ./src/MacCEGuiRendererSelector.mm - ) -elseif (CEGUI_SAMPLES_USE_GTK2) - list (APPEND CORE_SOURCE_FILES - ./src/GTK2CEGuiRendererSelector.cpp - ) -else() - list (APPEND CORE_SOURCE_FILES - ./src/CLICEGuiRendererSelector.cpp - ) -endif() - - -if (CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE) - # Append OpenGL and OpenGL3 files - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiGLFWSharedBase.cpp - ) - - if (CEGUI_BUILD_RENDERER_OPENGL) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiOpenGLBaseApplication.cpp - ) - endif() - - if (CEGUI_BUILD_RENDERER_OPENGL3) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiOpenGL3BaseApplication.cpp - ) - endif() - -endif() - -if (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) - # this prevents the boost auto-link dis-feature - add_definitions(-DBOOST_ALL_NO_LIB) - - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiOgreBaseApplication.cpp - ) -endif() - -if (CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiIrrlichtBaseApplication.cpp - ) -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiD3D9BaseApplication.cpp - ./src/DeviceReset_Direct3D9.cpp - ) -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiD3D10BaseApplication.cpp - ./src/DeviceReset_Direct3D10.cpp - ) -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiD3D11BaseApplication.cpp - ./src/DeviceReset_Direct3D11.cpp - ) -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE) - list (APPEND CORE_SOURCE_FILES - ./src/CEGuiDirectFBBaseApplication.cpp - ) -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) - include_directories(${DIRECTXSDK_INCLUDE_DIR}) - link_directories(${DIRECTXSDK_LIBRARY_DIR}) -endif() - -########################################################################### -# Statically Linked Executable -########################################################################### -if (CEGUI_BUILD_STATIC_CONFIGURATION) - add_executable(${CEGUI_TARGET_NAME}_Static ${CORE_SOURCE_FILES} ${CORE_HEADER_FILES}) - set_property(TARGET ${CEGUI_TARGET_NAME}_Static APPEND PROPERTY COMPILE_DEFINITIONS CEGUI_STATIC) - - # append the _d (or whatever) for debug builds as needed. - if (CEGUI_HAS_BUILD_SUFFIX AND CEGUI_BUILD_SUFFIX) - set_target_properties(${CEGUI_TARGET_NAME}_Static PROPERTIES - OUTPUT_NAME_DEBUG "${CEGUI_TARGET_NAME}_Static${CEGUI_BUILD_SUFFIX}" - ) - endif() - - # This works around an issue in the prebuilt deps and can be removed once those are fixed :) - if (WIN32) - set_target_properties(${CEGUI_TARGET_NAME}_Static PROPERTIES LINK_FLAGS_DEBUG /NODEFAULTLIB:freeglut.lib) - endif() - - if (APPLE) - cegui_apple_app_setup(${CEGUI_TARGET_NAME}_Static TRUE) - endif() -endif() - -########################################################################### -# Dynamically Linked Executable -########################################################################### -add_executable(${CEGUI_TARGET_NAME} ${CORE_SOURCE_FILES} ${CORE_HEADER_FILES}) - -# append the _d (or whatever) for debug builds as needed. -if (CEGUI_HAS_BUILD_SUFFIX AND CEGUI_BUILD_SUFFIX) - set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES - OUTPUT_NAME_DEBUG "${CEGUI_TARGET_NAME}${CEGUI_BUILD_SUFFIX}" - ) -endif() - -if (NOT APPLE AND CEGUI_INSTALL_WITH_RPATH) - set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES - INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${CEGUI_LIB_INSTALL_DIR}" - ) -endif() - -if (APPLE) - # we add these to ensure the dynamically loaded modules we will be - # using are built before the .app's post build step that copies - # libs into the app bundle. - add_dependencies(${CEGUI_TARGET_NAME} ${CEGUI_CORE_WR_LIBNAME} - CEGUI${CEGUI_OPTION_DEFAULT_XMLPARSER} - CEGUI${CEGUI_OPTION_DEFAULT_IMAGECODEC} - ) - - cegui_apple_app_setup(${CEGUI_TARGET_NAME} FALSE) -endif() - -########################################################################### -# MSVC PROJ USER FILE TEMPLATES -########################################################################### -if (MSVC) - configure_file( - ${CMAKE_MODULE_PATH}/templates/VisualStudioUserFile.vcproj.user.in - ${CMAKE_CURRENT_BINARY_DIR}/${CEGUI_TARGET_NAME}.vcproj.user - @ONLY - ) - configure_file( - ${CMAKE_MODULE_PATH}/templates/VisualStudioUserFile.vcxproj.user.in - ${CMAKE_CURRENT_BINARY_DIR}/${CEGUI_TARGET_NAME}.vcxproj.user - @ONLY - ) -endif () - - -########################################################################### -# LIBRARY LINK SETUP -########################################################################### -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME}) - -if (CEGUI_BUILD_STATIC_CONFIGURATION) - target_link_libraries(${CEGUI_TARGET_NAME}_Static - ${CEGUI_STATIC_XMLPARSER_MODULE}_Static - ${CEGUI_STATIC_IMAGECODEC_MODULE}_Static - ${CEGUI_CORE_WR_LIBNAME}_Static - ) -endif() - -########################################################################### -# BUILD DEPENDENCIES FOR THE SHARED LIBRARIES USED BY THE SAMPLEBROWSER -########################################################################### - -add_dependencies(${CEGUI_TARGET_NAME} ${CEGUI_CORE_WR_LIBNAME} - CEGUI${CEGUI_OPTION_DEFAULT_XMLPARSER} - CEGUI${CEGUI_OPTION_DEFAULT_IMAGECODEC}) - -if (CEGUI_SAMPLES_ENABLE_COMMON_DIALOGUES_DEMO) - add_dependencies(${CEGUI_TARGET_NAME} ${CEGUI_COMMON_DIALOGS_LIBNAME}) -endif() - -########################################################################### -# INSTALLATION -########################################################################### -install(TARGETS ${CEGUI_TARGET_NAME} - RUNTIME DESTINATION bin - LIBRARY DESTINATION ${CEGUI_LIB_INSTALL_DIR} - ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} - BUNDLE DESTINATION ${CEGUI_LIB_INSTALL_DIR} -) - -if (CEGUI_BUILD_STATIC_CONFIGURATION) - install(TARGETS ${CEGUI_TARGET_NAME}_Static - RUNTIME DESTINATION bin - LIBRARY DESTINATION ${CEGUI_LIB_INSTALL_DIR} - ARCHIVE DESTINATION ${CEGUI_LIB_INSTALL_DIR} - BUNDLE DESTINATION ${CEGUI_LIB_INSTALL_DIR} -) -endif() - -if (CEGUI_SAMPLES_RENDERER_OPENGL_ACTIVE) - cegui_add_dependency(${CEGUI_TARGET_NAME} OPENGL) - cegui_add_dependency(${CEGUI_TARGET_NAME} GLFW) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_OPENGL_RENDERER_LIBNAME}) -endif() - -if (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) - cegui_add_dependency(${CEGUI_TARGET_NAME} OGRE) - cegui_add_dependency(${CEGUI_TARGET_NAME} OIS) - if (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) - if (OGRE_STATIC) #if ogre is static, then must include the static plugin libs - set(CORE_OGRE_COMPONENTS RenderSystem_Direct3D9 RenderSystem_Direct3D11 RenderSystem_GLES RenderSystem_GLES2 RenderSystem_GL RenderSystem_GL3Plus) - foreach (comp ${CORE_OGRE_COMPONENTS}) - if (${OGRE_${comp}_FOUND}) - include_directories(${OGRE_${comp}_INCLUDE_DIRS}) - target_link_libraries(${CEGUI_TARGET_NAME} ${OGRE_${comp}_LIBRARIES}) - if (CEGUI_BUILD_STATIC_CONFIGURATION) - target_link_libraries(${CEGUI_TARGET_NAME}_Static ${OGRE_${comp}_LIBRARIES}) - endif() - endif() - endforeach (comp) - endif() - endif() - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_OGRE_RENDERER_LIBNAME} ${CEGUI_OGRE_SAMPLES_EXTRALIBS}) -endif() - -if (CEGUI_SAMPLES_RENDERER_IRRLICHT_ACTIVE) - cegui_add_dependency(${CEGUI_TARGET_NAME} IRRLICHT) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_IRRLICHT_RENDERER_LIBNAME}) -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE OR CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} dxerr) - - if (CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_DIRECT3D9_RENDERER_LIBNAME} d3d9) - endif() - - if (CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_DIRECT3D10_RENDERER_LIBNAME} d3d10) - endif() - - if (CEGUI_SAMPLES_RENDERER_DIRECT3D11_ACTIVE) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_DIRECT3D11_RENDERER_LIBNAME} d3d11) - endif() - -endif() - -if (CEGUI_SAMPLES_RENDERER_DIRECTFB_ACTIVE) - cegui_add_dependency(${CEGUI_TARGET_NAME} DIRECTFB) - cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_DIRECTFB_RENDERER_LIBNAME}) -endif() - -if (CEGUI_SAMPLES_USE_GTK2) - cegui_add_dependency(${CEGUI_TARGET_NAME} GTK2) -endif() - -if (APPLE) - set (CEGUI_EXTRA_FRAMEWORKS "-framework Cocoa") - - if (CEGUI_SAMPLES_RENDERER_OGRE_ACTIVE) - set (CEGUI_EXTRA_FRAMEWORKS "${CEGUI_EXTRA_FRAMEWORKS} -framework IOKit -framework Carbon") - endif() - - set_target_properties(${CEGUI_TARGET_NAME} PROPERTIES - LINK_FLAGS ${CEGUI_EXTRA_FRAMEWORKS} - ) -endif() - -cegui_target_link_libraries(${CEGUI_TARGET_NAME} ${CEGUI_BASE_LIBNAME}) diff --git a/samples_framework/include/CEGuiD3D10BaseApplication.h b/samples_framework/include/CEGuiD3D10BaseApplication.h deleted file mode 100644 index 6be82e5a4..000000000 --- a/samples_framework/include/CEGuiD3D10BaseApplication.h +++ /dev/null @@ -1,78 +0,0 @@ -/*********************************************************************** - created: Sun May 25 2008 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGuiD3D10BaseApplication_h_ -#define _CEGuiD3D10BaseApplication_h_ - -#include "CEGuiBaseApplication.h" -#include "CEGUI/GeometryBuffer.h" - -#if defined( __WIN32__ ) || defined( _WIN32 ) -# define WIN32_LEAN_AND_MEAN -# include -#endif - -// forward declare struct that will hold D3D10 specifics -struct CEGuiBaseApplication10Impl; - -//! CEGuiBaseApplication implementation for Microsoft Direct3D 10 -class CEGuiD3D10BaseApplication : public CEGuiBaseApplication -{ -public: - //!Constructor. - CEGuiD3D10BaseApplication(); - - //! Destructor. - ~CEGuiD3D10BaseApplication(); - -protected: - /************************************************************************* - Implementation Methods - *************************************************************************/ - //! Initialises Direct3D system. - bool initialiseDirect3D(unsigned int width, unsigned int height, - bool windowed); - - //! cleanup D3D objects / interfaces - void cleanupDirect3D(); - - // Implementation of base class abstract methods. - void run(); - void destroyWindow(); - void beginRendering(const float elapsed); - void endRendering(); - - /************************************************************************* - Data fields - *************************************************************************/ - //! Pointer to the struct holding D3D specific fields. - CEGuiBaseApplication10Impl* pimpl; - - // counter used to track elapsed time - DWORD d_lastFrameTime; -}; - -#endif // end of guard _CEGuiD3D10BaseApplication_h_ diff --git a/samples_framework/include/CEGuiD3D9BaseApplication.h b/samples_framework/include/CEGuiD3D9BaseApplication.h deleted file mode 100644 index 49bd92b21..000000000 --- a/samples_framework/include/CEGuiD3D9BaseApplication.h +++ /dev/null @@ -1,89 +0,0 @@ -/*********************************************************************** - created: 24/9/2004 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _CEGuiD3D9BaseApplication_h_ -#define _CEGuiD3D9BaseApplication_h_ - -#include "CEGuiBaseApplication.h" -#include "CEGUI/GeometryBuffer.h" - -#if defined( __WIN32__ ) || defined( _WIN32 ) -# define WIN32_LEAN_AND_MEAN -# include - -// undefine Microsoft macro evilness -# undef min -# undef max -#endif - -struct CEGuiBaseApplication9Impl; - - -class CEGuiD3D9BaseApplication : public CEGuiBaseApplication -{ -public: - //! Constructor. - CEGuiD3D9BaseApplication(); - - //! Destructor. - ~CEGuiD3D9BaseApplication(); - -protected: - /************************************************************************* - Implementation Methods - *************************************************************************/ - /*! - \brief - Initialises Direct3D system. - */ - bool initialiseDirect3D(unsigned int width, unsigned int height, unsigned int adapter, bool windowed); - - /*! - \brief - Do reset of Direct3D device - - \return - - true if the device was reset successfully - - false if the device was not reset. - */ - bool resetDirect3D(void); - - // Implementation of base class abstract methods. - void run(); - void destroyWindow(); - void beginRendering(const float elapsed); - void endRendering(); - - /************************************************************************* - Data fields - *************************************************************************/ - CEGuiBaseApplication9Impl* pimpl; - - // counter used to track elapsed time - DWORD d_lastFrameTime; -}; - -#endif // end of guard _CEGuiD3D9BaseApplication_h_ diff --git a/samples_framework/include/Samples_xmlHandler.h b/samples_framework/include/Samples_xmlHandler.h deleted file mode 100644 index abd5d23ea..000000000 --- a/samples_framework/include/Samples_xmlHandler.h +++ /dev/null @@ -1,92 +0,0 @@ -/*********************************************************************** - created: 31/5/2012 - author: Lukas E Meindl -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#ifndef _Samples_xmlHandler_h_ -#define _Samples_xmlHandler_h_ - -#include "CEGUI/ChainedXMLHandler.h" -#include "CEGUI/String.h" - -class SamplesFramework; - -using namespace CEGUI; - -class Samples_xmlHandler : public ChainedXMLHandler -{ -public: - Samples_xmlHandler(SamplesFramework* samplesFramework); - virtual ~Samples_xmlHandler(); - - //! String holding the element handled by this class. - static const String ElementName; - - // XMLHandler overrides - const String& getSchemaName() const; - -protected: - // implement ChainedXMLHandler interface. - void elementStartLocal(const String& element, - const XMLAttributes& attributes); - void elementEndLocal(const String& element); - - SamplesFramework* d_samplesFramework; -}; - -//----------------------------------------------------------------------------// -//! Chained sub-handler for AnimationDefinition XML elements -class SampleDataHandler : public ChainedXMLHandler -{ -public: - //! String holding the element handled by this class. - static const String ElementName; - - static const String NameAttribute; - static const String SummaryAttribute; - static const String DescriptionAttribute; - static const String CreditsAttribute; - - static const String SampleTypeAttribute; - static const String SampleTypeCppModule; - static const String SampleTypeLua; - static const String SampleTypePython; - - - SampleDataHandler(const XMLAttributes& attributes, - const String& name_prefix, - SamplesFramework* samplesFramework); - virtual ~SampleDataHandler(); - -protected: - // implement ChainedXMLHandler interface. - void elementStartLocal(const String& element, - const XMLAttributes& attributes); - void elementEndLocal(const String& element); - - SamplesFramework* d_samplesFramework; -}; - -#endif - diff --git a/samples_framework/src/CEGuiD3D10BaseApplication.cpp b/samples_framework/src/CEGuiD3D10BaseApplication.cpp deleted file mode 100644 index bb422be2a..000000000 --- a/samples_framework/src/CEGuiD3D10BaseApplication.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/*********************************************************************** - created: Sun May 25 2008 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUISamplesConfig.h" - -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE - -#include "CEGuiD3D10BaseApplication.h" -#include "CEGUI/RendererModules/Direct3D10/Renderer.h" -#include "SamplesFrameworkBase.h" -#include "Win32AppHelper.h" -#include "CEGUI/CEGUI.h" - -#include -#include -#include - -//----------------------------------------------------------------------------// -struct CEGuiBaseApplication10Impl -{ - HWND d_window; - IDXGISwapChain* d_swapChain; - ID3D10Device* d_device; - Win32AppHelper::DirectInputState d_directInput; -}; - -//----------------------------------------------------------------------------// -CEGuiD3D10BaseApplication::CEGuiD3D10BaseApplication() : - pimpl(new CEGuiBaseApplication10Impl), - d_lastFrameTime(GetTickCount()) -{ - if (pimpl->d_window = Win32AppHelper::createApplicationWindow(s_defaultWindowWidth, s_defaultWindowHeight)) - { - if (initialiseDirect3D(s_defaultWindowWidth, s_defaultWindowHeight, true)) - { - // set the swap chain ptr into window data so we can get access - // later. This is a bit of a hack, but saved us redesigning the - // entire framework just for this. - SetWindowLongPtr(pimpl->d_window, - GWLP_USERDATA, - (LONG_PTR)pimpl->d_swapChain); - - if (Win32AppHelper::initialiseDirectInput(pimpl->d_window, - pimpl->d_directInput)) - { - d_renderer = &CEGUI::Direct3D10Renderer::create(pimpl->d_device); - return; - } - - cleanupDirect3D(); - } - - DestroyWindow(pimpl->d_window); - } - else - { - MessageBox(0, Win32AppHelper::CREATE_WINDOW_ERROR, - Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); - } - - CEGUI_THROW(std::runtime_error("Windows Direct3D 10 application failed to " - "initialise.")); -} - -//----------------------------------------------------------------------------// -CEGuiD3D10BaseApplication::~CEGuiD3D10BaseApplication() -{ - Win32AppHelper::mouseLeaves(); - - CEGUI::Direct3D10Renderer::destroy( - *static_cast(d_renderer)); - - Win32AppHelper::cleanupDirectInput(pimpl->d_directInput); - - cleanupDirect3D(); - - DestroyWindow(pimpl->d_window); - - delete pimpl; -} - -//----------------------------------------------------------------------------// -void CEGuiD3D10BaseApplication::run() -{ - d_sampleApp->initialise(); - Win32AppHelper::setSamplesFramework(d_sampleApp); - - float clear_colour[4] = {0.0f, 0.0f, 0.0f, 0.0f}; - - // - // This is basically a modified Win32 message pump - // - bool idle; - - while (Win32AppHelper::doWin32Events(idle)) - { - if (idle) - { - CEGUI::System& guiSystem = CEGUI::System::getSingleton(); - - // do time based updates - const DWORD thisTime = GetTickCount(); - const float elapsed = - static_cast(thisTime - d_lastFrameTime) / 1000.0f; - d_lastFrameTime = thisTime; - - Win32AppHelper::doDirectInputEvents(pimpl->d_directInput); - - // get render target view - // this is a bit wasteful, but done like this for now since the - // resize code can change the view from under us. - ID3D10RenderTargetView* rtview; - pimpl->d_device->OMGetRenderTargets(1, &rtview, 0); - - // clear display - pimpl->d_device->ClearRenderTargetView(rtview, clear_colour); - - renderSingleFrame(elapsed); - - pimpl->d_swapChain->Present(0, 0); - rtview->Release(); - } - - // check if the application is quitting, and break the loop next time - // around if so. - if (d_sampleApp->isQuitting()) - PostQuitMessage(0); - } -} - -//----------------------------------------------------------------------------// -void CEGuiD3D10BaseApplication::destroyWindow() -{ - -} - -//----------------------------------------------------------------------------// -void CEGuiD3D10BaseApplication::beginRendering(const float elapsed) -{ -} - -//----------------------------------------------------------------------------// -void CEGuiD3D10BaseApplication::endRendering() -{ -} - -//----------------------------------------------------------------------------// -bool CEGuiD3D10BaseApplication::initialiseDirect3D(unsigned int width, - unsigned int height, bool windowed) -{ - HRESULT res; - - // init sqap chain descriptor structure - DXGI_SWAP_CHAIN_DESC scd; - ZeroMemory(&scd, sizeof(scd)); - scd.BufferCount = 1; - scd.BufferDesc.Width = width; - scd.BufferDesc.Height = height; - scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - scd.BufferDesc.RefreshRate.Numerator = 60; - scd.BufferDesc.RefreshRate.Denominator = 1; - scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - scd.OutputWindow = pimpl->d_window; - scd.SampleDesc.Count = 1; - scd.SampleDesc.Quality = 0; - scd.Windowed = windowed; - - // initialise main parts of D3D - res = D3D10CreateDeviceAndSwapChain(0, D3D10_DRIVER_TYPE_HARDWARE, - 0, 0, D3D10_SDK_VERSION, - &scd, &pimpl->d_swapChain, - &pimpl->d_device); - if (SUCCEEDED(res)) - { - - // obtain handle to thr back buffer of the swap chain - ID3D10Texture2D* back_buffer; - res = pimpl->d_swapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), - (LPVOID*)&back_buffer); - - if (SUCCEEDED(res)) - { - ID3D10RenderTargetView* rtview; - - // create render target view using the back buffer - res = pimpl->d_device-> - CreateRenderTargetView(back_buffer, 0, &rtview); - - // release handle to buffer - we have done all we needed to with it. - back_buffer->Release(); - - if (SUCCEEDED(res)) - { - // bind the back-buffer render target to get the output. - pimpl->d_device-> - OMSetRenderTargets(1, &rtview, 0); - - // set a basic viewport. - D3D10_VIEWPORT view_port; - view_port.Width = width; - view_port.Height = height; - view_port.MinDepth = 0.0f; - view_port.MaxDepth = 1.0f; - view_port.TopLeftX = 0; - view_port.TopLeftY = 0; - pimpl->d_device->RSSetViewports(1, &view_port); - - // complete window initialisation - ShowWindow(pimpl->d_window, SW_NORMAL); - UpdateWindow(pimpl->d_window); - - return true; - } - - rtview->Release(); - } - - pimpl->d_swapChain->Release(); - pimpl->d_device->Release(); - pimpl->d_swapChain = 0; - pimpl->d_device = 0; - } - - MessageBox(0, "Failed to correctly initialise Direct3D 10", - Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); - - return false; -} - -//----------------------------------------------------------------------------// -void CEGuiD3D10BaseApplication::cleanupDirect3D() -{ - if (pimpl->d_device) - { - // get render target view - ID3D10RenderTargetView* rtview; - pimpl->d_device->OMGetRenderTargets(1, &rtview, 0); - - if (rtview) - { - // we release once for the reference we just asked for - rtview->Release(); - // we release again for the original reference made at creation. - rtview->Release(); - } - - pimpl->d_swapChain->Release(); - pimpl->d_device->Release(); - - pimpl->d_swapChain = 0; - pimpl->d_device = 0; - } -} - -#endif diff --git a/samples_framework/src/CEGuiD3D9BaseApplication.cpp b/samples_framework/src/CEGuiD3D9BaseApplication.cpp deleted file mode 100644 index 394cfc0e2..000000000 --- a/samples_framework/src/CEGuiD3D9BaseApplication.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/*********************************************************************** - created: 24/9/2004 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUISamplesConfig.h" - -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D9_ACTIVE - -#include "CEGuiD3D9BaseApplication.h" - -#include -#include -// undefine Microsoft macro evilness -#undef min -#undef max - -#include "CEGUI/RendererModules/Direct3D9/Renderer.h" -#include "SamplesFrameworkBase.h" -#include "Win32AppHelper.h" -#include "CEGUI/CEGUI.h" -#include - -//----------------------------------------------------------------------------// -struct CEGuiBaseApplication9Impl -{ - HWND d_window; - LPDIRECT3D9 d_D3D; - LPDIRECT3DDEVICE9 d_3DDevice; - D3DPRESENT_PARAMETERS d_ppars; - Win32AppHelper::DirectInputState d_directInput; -}; - -//----------------------------------------------------------------------------// -CEGuiD3D9BaseApplication::CEGuiD3D9BaseApplication() : -pimpl(new CEGuiBaseApplication9Impl), - d_lastFrameTime(GetTickCount()) -{ - if (pimpl->d_window = Win32AppHelper::createApplicationWindow(s_defaultWindowWidth, s_defaultWindowHeight)) - { - if (initialiseDirect3D(s_defaultWindowWidth, s_defaultWindowHeight, D3DADAPTER_DEFAULT, true)) - { - if (Win32AppHelper::initialiseDirectInput(pimpl->d_window, pimpl->d_directInput)) - { - d_renderer = &CEGUI::Direct3D9Renderer::create(pimpl->d_3DDevice); - return; - } - - // cleanup direct 3d systems - pimpl->d_3DDevice->Release(); - pimpl->d_D3D->Release(); - } - - DestroyWindow(pimpl->d_window); - } - else - { - MessageBox(0, Win32AppHelper::CREATE_WINDOW_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); - } - - CEGUI_THROW(std::runtime_error("Win32 DirectX 9 application failed to initialise.")); -} - -//----------------------------------------------------------------------------// -CEGuiD3D9BaseApplication::~CEGuiD3D9BaseApplication() -{ - Win32AppHelper::mouseLeaves(); - - CEGUI::Direct3D9Renderer::destroy( - *static_cast(d_renderer)); - - Win32AppHelper::cleanupDirectInput(pimpl->d_directInput); - - // cleanup direct 3d systems - pimpl->d_3DDevice->Release(); - pimpl->d_D3D->Release(); - - DestroyWindow(pimpl->d_window); - - delete pimpl; -} - -//----------------------------------------------------------------------------// -void CEGuiD3D9BaseApplication::run() -{ - d_sampleApp->initialise(); - Win32AppHelper::setSamplesFramework(d_sampleApp); - - // - // This is basically a modified Win32 message pump - // - bool idle; - HRESULT coop; - - while (Win32AppHelper::doWin32Events(idle)) - { - if (idle) - { - CEGUI::System& guiSystem = CEGUI::System::getSingleton(); - - // do time based updates - DWORD thisTime = GetTickCount(); - const float elapsed = - static_cast(thisTime - d_lastFrameTime) / 1000.0f; - d_lastFrameTime = thisTime; - - // handle D3D lost device stuff - coop = pimpl->d_3DDevice->TestCooperativeLevel(); - - if (coop == D3DERR_DEVICELOST) - { - Sleep(500); - continue; - } - else if (coop == D3DERR_DEVICENOTRESET) - { - if (!resetDirect3D()) - { - continue; - } - } - - Win32AppHelper::doDirectInputEvents(pimpl->d_directInput); - - // draw display - if (FAILED(pimpl->d_3DDevice->BeginScene())) - continue; - - renderSingleFrame(elapsed); - } - - // check if the application is quitting, and break the loop next time - // around if so. - if (d_sampleApp->isQuitting()) - PostQuitMessage(0); - } -} - -//----------------------------------------------------------------------------// -void CEGuiD3D9BaseApplication::destroyWindow() -{ - -} - -//----------------------------------------------------------------------------// -void CEGuiD3D9BaseApplication::beginRendering(const float elapsed) -{ - pimpl->d_3DDevice->Clear(0, 0, D3DCLEAR_TARGET, - D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0); -} - -//----------------------------------------------------------------------------// -void CEGuiD3D9BaseApplication::endRendering() -{ - pimpl->d_3DDevice->EndScene(); - pimpl->d_3DDevice->Present(0, 0, 0, 0); -} - -//----------------------------------------------------------------------------// -bool CEGuiD3D9BaseApplication::initialiseDirect3D(unsigned int width, unsigned int height, unsigned int adapter, bool windowed) -{ - pimpl->d_D3D = Direct3DCreate9(D3D_SDK_VERSION); - - // display error and exit if D3D creation failed - if (pimpl->d_D3D) - { - D3DDISPLAYMODE d3ddm; - pimpl->d_D3D->GetAdapterDisplayMode(adapter, &d3ddm); - - D3DFORMAT format = d3ddm.Format; - - // complete window initialisation - ShowWindow(pimpl->d_window, SW_NORMAL); - UpdateWindow(pimpl->d_window); - - ZeroMemory(&pimpl->d_ppars, sizeof(pimpl->d_ppars)); - pimpl->d_ppars.BackBufferFormat = format; - pimpl->d_ppars.hDeviceWindow = pimpl->d_window; - pimpl->d_ppars.SwapEffect = D3DSWAPEFFECT_DISCARD; - pimpl->d_ppars.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - pimpl->d_ppars.Windowed = windowed; - - if (!windowed) - { - pimpl->d_ppars.BackBufferWidth = width; - pimpl->d_ppars.BackBufferHeight = height; - pimpl->d_ppars.BackBufferCount = 1; - pimpl->d_ppars.MultiSampleType = D3DMULTISAMPLE_NONE; - pimpl->d_ppars.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; - } - - if (SUCCEEDED(pimpl->d_D3D->CreateDevice(adapter, D3DDEVTYPE_HAL, pimpl->d_window, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &pimpl->d_ppars, &pimpl->d_3DDevice))) - { - return true; - } - else - { - MessageBox(0, Win32AppHelper::CREATE_DEVICE_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); - } - - pimpl->d_D3D->Release(); - pimpl->d_D3D = 0; - } - else - { - MessageBox(0, Win32AppHelper::CREATE_D3D_ERROR, Win32AppHelper::APPLICATION_NAME, MB_ICONERROR|MB_OK); - } - - return false; -} - -//----------------------------------------------------------------------------// -bool CEGuiD3D9BaseApplication::resetDirect3D(void) -{ - // perform ops needed prior to reset - static_cast(d_renderer)->preD3DReset(); - - if (SUCCEEDED(pimpl->d_3DDevice->Reset(&pimpl->d_ppars))) - { - // re-build stuff now reset has been done. - static_cast(d_renderer)->postD3DReset(); - return true; - } - - return false; -} - -//----------------------------------------------------------------------------// - -#endif diff --git a/samples_framework/src/DeviceReset_Direct3D10.cpp b/samples_framework/src/DeviceReset_Direct3D10.cpp deleted file mode 100644 index 975050385..000000000 --- a/samples_framework/src/DeviceReset_Direct3D10.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/*********************************************************************** - created: 25/5/2008 - author: Paul D Turner -*************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2008 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "CEGUISamplesConfig.h" - -#ifdef CEGUI_SAMPLES_RENDERER_DIRECT3D10_ACTIVE - -#include "CEGUI/CEGUI.h" -#include "CEGUI/RendererModules/Direct3D10/Renderer.h" -#define WIN32_LEAN_AND_MEAN -#include -//----------------------------------------------------------------------------// -// The following function is basically a nasty hack; we just needed to do the -// preD3DReset call, the actual device reset, and then the postD3DReset call - -// the issue is that much of the information is not readily available here to us -// so we jump through a couple of hoops to obtain that information (and in the -// case of the D3DPRESENT_PARAMETERS recreate it from scratch). -// -// The reason this is in it's own file is that we need to be able to handle -// multiple different versions of this function for the D3D versions that the -// sample framework supports, though we can only include one main d3d header -// at a time, so these funcs live in their own files. -//----------------------------------------------------------------------------// - -//----------------------------------------------------------------------------// -void DeviceReset_Direct3D10(HWND window, CEGUI::Renderer* renderer) -{ - // this is the 'other side' of our earlier hack to save from having to - // totally rewrite the samples framework. - // - // Extract the pointer to the CEGuiD3D10BaseApplication from the window - //CEGuiD3D10BaseApplication* app = - // reinterpret_cast( - // GetWindowLongPtr(window,GWLP_USERDATA)); - - IDXGISwapChain* swap_chain = reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); - - // if the swap_chain pointer is 0, something obviously is amiss, so bail - if (!swap_chain) - return; - - CEGUI::Direct3D10Renderer* d3d_renderer = - static_cast(renderer); - - ID3D10Device& d3d_device = d3d_renderer->getDirect3DDevice(); - - ID3D10RenderTargetView* rtview; - d3d_device.OMGetRenderTargets(1, &rtview, 0); - - // we release once for the reference we just asked for - rtview->Release(); - // we release again for the original reference made at creation. - rtview->Release(); - - if (FAILED(swap_chain->ResizeBuffers(1, 0, 0, - DXGI_FORMAT_R8G8B8A8_UNORM, 0))) - { - CEGUI::Logger::getSingleton().logEvent("Direct3D 10: Failed to resize " - "swap chain buffers.", CEGUI::Errors); - - return; - } - - RECT wnd_rect; - GetClientRect(window, &wnd_rect); - - int width = wnd_rect.right;// - wnd_rect.left; - int height = wnd_rect.bottom;// - wnd_rect.top; - - HRESULT res; - // obtain handle to thr back buffer of the swap chain - ID3D10Texture2D* back_buffer; - res = swap_chain->GetBuffer(0, __uuidof(ID3D10Texture2D), - (LPVOID*)&back_buffer); - - if (SUCCEEDED(res)) - { - // create render target view using the back buffer - res = d3d_device.CreateRenderTargetView(back_buffer, 0, &rtview); - - // release handle to buffer - we have done all we needed to with it. - back_buffer->Release(); - - if (SUCCEEDED(res)) - { - // bind the back-buffer render target to get the output. - d3d_device.OMSetRenderTargets(1, &rtview, 0); - - // set a basic viewport. - D3D10_VIEWPORT view_port; - view_port.Width = width; - view_port.Height = height; - view_port.MinDepth = 0.0f; - view_port.MaxDepth = 1.0f; - view_port.TopLeftX = 0; - view_port.TopLeftY = 0; - d3d_device.RSSetViewports(1, &view_port); - - // notify CEGUI of change. - CEGUI::System::getSingleton().notifyDisplaySizeChanged( - CEGUI::Sizef((float)width, (float)height)); - } - } -} - -//----------------------------------------------------------------------------// - -#endif diff --git a/samples_framework/src/Samples_xmlHandler.cpp b/samples_framework/src/Samples_xmlHandler.cpp deleted file mode 100644 index 8c73195fe..000000000 --- a/samples_framework/src/Samples_xmlHandler.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/*********************************************************************** -created: 31/5/2012 -author: Lukas E Meindl -*************************************************************************/ -/*************************************************************************** -* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -* OTHER DEALINGS IN THE SOFTWARE. -***************************************************************************/ - -#include "Samples_xmlHandler.h" -#include "CEGUI/Exceptions.h" -#include "CEGUI/Logger.h" -#include "CEGUI/XMLAttributes.h" - -#include "SamplesFramework.h" -#include "Sample.h" -#include "SampleData.h" - -const String Samples_xmlHandler::ElementName("Samples"); - -const String SampleDataHandler::ElementName("SampleDefinition"); - -const String SampleDataHandler::NameAttribute("name"); -const String SampleDataHandler::SummaryAttribute("summary"); -const String SampleDataHandler::DescriptionAttribute("description"); -const String SampleDataHandler::CreditsAttribute("credits"); - - -const String SampleDataHandler::SampleTypeAttribute("type"); -const String SampleDataHandler::SampleTypeCppModule("C++ Module"); -const String SampleDataHandler::SampleTypeLua("Lua"); -const String SampleDataHandler::SampleTypePython("Python"); - - -//----------------------------------------------------------------------------// -Samples_xmlHandler::Samples_xmlHandler(SamplesFramework* samplesFramework) - : d_samplesFramework(samplesFramework) -{} - -//----------------------------------------------------------------------------// -Samples_xmlHandler::~Samples_xmlHandler() -{} - -//----------------------------------------------------------------------------// -const String& Samples_xmlHandler::getSchemaName() const -{ - return SamplesFramework::XMLSchemaName; -} - -//----------------------------------------------------------------------------// -void Samples_xmlHandler::elementStartLocal(const String& element, - const XMLAttributes& attributes) -{ - if (element == ElementName) - { - CEGUI_LOGINSANE("===== Begin Animations parsing ====="); - } - else if (element == SampleDataHandler::ElementName) - { - d_chainedHandler = new SampleDataHandler(attributes, "", d_samplesFramework); - } - else - Logger::getSingleton().logEvent("Animation_xmlHandler::elementStart: " - "<" + element + "> is invalid at this location.", Errors); -} - -//----------------------------------------------------------------------------// -void Samples_xmlHandler::elementEndLocal(const String& element) -{ - if (element == ElementName) - { - CEGUI_LOGINSANE("===== End Animations parsing ====="); - } - else - Logger::getSingleton().logEvent("Animation_xmlHandler::elementEnd: " - " is invalid at this location.", Errors); -} - -//----------------------------------------------------------------------------// -//----------------------------------------------------------------------------// -SampleDataHandler::SampleDataHandler( - const XMLAttributes& attributes, - const String& name_prefix, - SamplesFramework* samplesFramework) - : d_samplesFramework(samplesFramework) -{ - const String sampleName(attributes.getValueAsString(NameAttribute)); - const String summary(attributes.getValueAsString(SummaryAttribute)); - const String description(attributes.getValueAsString(DescriptionAttribute)); - const String sampleType(attributes.getValueAsString(SampleTypeAttribute)); - const String credits(attributes.getValueAsString(CreditsAttribute)); - - CEGUI_LOGINSANE( - "Defining sample named: " + - sampleName + - " Summary: " + - summary + - " Description: " + - description + - " Sample Type: " + - sampleType + - " Credits: " + - credits - ); - - SampleType sampleTypeEnum; - - if (sampleType == SampleTypeCppModule) - sampleTypeEnum = ST_Module; - else if(sampleType == SampleTypePython) - sampleTypeEnum = ST_Python; - else - sampleTypeEnum = ST_Lua; - - d_samplesFramework->addSampleDataCppModule(sampleName, summary, description, sampleTypeEnum, credits); -} - -//----------------------------------------------------------------------------// -SampleDataHandler::~SampleDataHandler() -{ -} - -//----------------------------------------------------------------------------// -void SampleDataHandler::elementStartLocal( - const String& element, - const XMLAttributes& attributes) -{ - Logger::getSingleton().logEvent( - "AnimationDefinitionHandler::elementStart: " - "<" + element + "> is invalid at this location.", Errors); -} - -void SampleDataHandler::elementEndLocal(const String& element) -{ - // set completed status when we encounter our own end element - if (element == ElementName) - d_completed = true; -} diff --git a/tests/README.md b/tests/README.md index 8d4a4b616..7ec061cd6 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,9 +10,20 @@ We use ctest which is part of cmake to run tests. You first need to enable the tests that you want to run. Enable `CEGUI_BUILD_TESTS` and/or `CEGUI_BUILD_DATAFILES_TEST` options in cmake. -Then run the tests using: +Then run the tests using the following commands, based on your operating system: + +* Linux / Mac OS X ```bash cd $cegui_folder cd build/ CEGUI_SAMPLE_DATAPATH=`pwd`/../datafiles/ ctest -V ``` + +* Windows +``` +cd +cd build/ +set CEGUI_SAMPLE_DATAPATH=%CD%/../datafiles/ +ctest -V -C +``` +Where `` is one of: `Debug`, `Release` or `RelWithDebInfo`, depending on what configuration you have built. \ No newline at end of file diff --git a/tests/performance/EventSet.cpp b/tests/performance/EventSet.cpp index 516fa7f81..ef72a348f 100644 --- a/tests/performance/EventSet.cpp +++ b/tests/performance/EventSet.cpp @@ -37,7 +37,7 @@ static const CEGUI::String EVENT_NAME("ExplicitlyAddedTestEvent"); class EventSetPerformanceTest : public PerformanceTest { public: - EventSetPerformanceTest(CEGUI::String const& test_name, CEGUI::EventSet& set) + EventSetPerformanceTest(CEGUI::String test_name, CEGUI::EventSet& set) : PerformanceTest(test_name), d_eventSet(set) { } diff --git a/tests/performance/ItemListbox.cpp b/tests/performance/ItemListbox.cpp deleted file mode 100644 index a538280b1..000000000 --- a/tests/performance/ItemListbox.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/*********************************************************************** - * created: Sat Aug 16 2014 - * author: Timotei Dolean - *************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ -#include "PerformanceTest.h" - -#include - -#include "CEGUI/WindowManager.h" -#include "CEGUI/widgets/ItemListbox.h" - -class ItemListboxPerformanceTest : public BaseListPerformanceTest -{ -public: - ItemListboxPerformanceTest(CEGUI::String const& windowType, CEGUI::String const& renderer) - : BaseListPerformanceTest(windowType, renderer) - { - } - - virtual void clearItems() - { - d_window->resetList(); - } - - CEGUI::ItemEntry* createItem(CEGUI::String id) - { - CEGUI::ItemEntry* item = static_cast( - CEGUI::WindowManager::getSingleton().createWindow( - "TaharezLook/ListboxItem", id)); - item->setText(id); - return item; - } - - virtual void addItems(size_t count) - { - // prevent adding already existing items. - size_t offset = d_window->getItemCount(); - for (size_t i = 0; i < count; ++i) - { - d_window->addItem(createItem( - CEGUI::PropertyHelper::toString(offset + i))); - } - } - - virtual void addItems(size_t count, size_t at_position) - { - // prevent adding already existing items. - size_t offset = d_window->getItemCount(); - const CEGUI::ItemEntry* item_at_pos = d_window->getItemFromIndex(at_position); - for (size_t i = 0; i < count; ++i) - { - d_window->insertItem( - createItem(CEGUI::PropertyHelper::toString(offset + i)), - item_at_pos); - } - } - - virtual void deleteFirstItems(size_t count) - { - for (size_t i = 0; i < count; ++i) - { - d_window->removeItem(d_window->getItemFromIndex(0)); - } - } - - virtual void deleteLastItems(size_t count) - { - size_t child_count = d_window->getItemCount(); - - for (size_t i = 0; i < count; ++i, --child_count) - { - d_window->removeItem(d_window->getItemFromIndex(child_count - 1)); - } - } - - virtual void sortItems() - { - d_window->setSortMode(CEGUI::ItemListBase::UserSort); - d_window->setSortMode(CEGUI::ItemListBase::Ascending); - } -}; - -BOOST_AUTO_TEST_SUITE(ItemListboxPerformance) - -BOOST_AUTO_TEST_CASE(Test) -{ - ItemListboxPerformanceTest item_listbox_performance_test( - "TaharezLook/ItemListbox", "Core/ItemListbox"); - item_listbox_performance_test.execute(); -} - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/performance/Listbox.cpp b/tests/performance/ListView.cpp similarity index 59% rename from tests/performance/Listbox.cpp rename to tests/performance/ListView.cpp index d314e9c27..6b6254ef6 100644 --- a/tests/performance/Listbox.cpp +++ b/tests/performance/ListView.cpp @@ -1,5 +1,5 @@ /*********************************************************************** - * created: Sat Aug 16 2014 + * created: Fri Aug 15 2014 * author: Timotei Dolean *************************************************************************/ /*************************************************************************** @@ -24,77 +24,83 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ +#include + #include "PerformanceTest.h" -#include +#include "CEGUI/views/StandardItemModel.h" +#include "CEGUI/views/ListView.h" +#include "CEGUI/Window.h" + +#include -#include "CEGUI/widgets/Listbox.h" -#include "CEGUI/widgets/ListboxTextItem.h" +using namespace CEGUI; -class ListBoxPerformanceTest : public BaseListPerformanceTest +class ListViewPerformanceTest : public BaseListPerformanceTest { public: - ListBoxPerformanceTest(CEGUI::String const& windowType, CEGUI::String const& renderer) - : BaseListPerformanceTest(windowType, renderer) + ListViewPerformanceTest(String windowType, String renderer) + : BaseListPerformanceTest(windowType, renderer) { + d_window->setModel(&d_model); } - virtual void clearItems() - { - d_window->resetList(); - } - - virtual void addItems(size_t count) + void addItems(size_t count) { for (size_t i = 0; i < count; ++i) { - d_window->addItem(new CEGUI::ListboxTextItem( - CEGUI::PropertyHelper::toString(i))); + d_model.addItem(PropertyHelper::toString(i)); } } - virtual void addItems(size_t count, size_t at_position) + void addItems(size_t count, size_t at_position) { - CEGUI::ListboxItem* item_at_pos = d_window->getListboxItemFromIndex(at_position); for (size_t i = 0; i < count; ++i) { - d_window->insertItem(new CEGUI::ListboxTextItem( - CEGUI::PropertyHelper::toString(i)), item_at_pos); + d_model.addItemAtPosition( + new StandardItem(PropertyHelper::toString(i)), at_position + i + 1); } } - virtual void deleteFirstItems(size_t count) + void deleteFirstItems(size_t count) { + ModelIndex root_index = d_model.getRootIndex(); for (size_t i = 0; i < count; ++i) { - d_window->removeItem(d_window->getListboxItemFromIndex(0)); + d_model.removeItem(d_model.makeIndex(0, root_index)); } } - virtual void deleteLastItems(size_t count) + void deleteLastItems(size_t count) { - size_t child_count = d_window->getItemCount(); + ModelIndex root_index = d_model.getRootIndex(); + size_t child_count = d_model.getChildCount(d_model.getRootIndex()); for (size_t i = 0; i < count; ++i, --child_count) { - d_window->removeItem(d_window->getListboxItemFromIndex(child_count - 1)); + d_model.removeItem(d_model.makeIndex(child_count - 1, root_index)); } } + virtual void clearItems() + { + d_model.clear(true); + } + virtual void sortItems() { - d_window->setSortingEnabled(false); - d_window->setSortingEnabled(true); + d_window->setSortMode(VSM_Ascending); } + + StandardItemModel d_model; }; -BOOST_AUTO_TEST_SUITE(ListBoxPerformance) +BOOST_AUTO_TEST_SUITE(ListViewPerformance) BOOST_AUTO_TEST_CASE(Test) { - ListBoxPerformanceTest list_box_performance_test( - "TaharezLook/Listbox", "Core/Listbox"); - list_box_performance_test.execute(); + ListViewPerformanceTest listview_test("TaharezLook/ListView", "Core/ListView"); + listview_test.execute(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/performance/Tree.cpp b/tests/performance/TreeView.cpp similarity index 60% rename from tests/performance/Tree.cpp rename to tests/performance/TreeView.cpp index 51f7f6b15..e34b1f4c8 100644 --- a/tests/performance/Tree.cpp +++ b/tests/performance/TreeView.cpp @@ -1,5 +1,5 @@ /*********************************************************************** - * created: Sat Aug 16 2014 + * created: Fri Aug 15 2014 * author: Timotei Dolean *************************************************************************/ /*************************************************************************** @@ -24,69 +24,72 @@ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ +#include + #include "PerformanceTest.h" -#include +#include "CEGUI/views/StandardItemModel.h" +#include "CEGUI/views/TreeView.h" +#include "CEGUI/Window.h" + +#include -#include "CEGUI/PropertyHelper.h" -// Easy way to access the tree's items - tree doesn't provide individual access -// to already added items by index :( -#define protected public -#include "CEGUI/widgets/Tree.h" -#include "CEGUI/widgets/TreeItem.h" +using namespace CEGUI; -class TreePerformanceTest : public WindowPerformanceTest + +class TreePerformanceTest : public WindowPerformanceTest { public: - TreePerformanceTest(CEGUI::String const& windowType, CEGUI::String const& renderer) - : WindowPerformanceTest(windowType, renderer) + TreePerformanceTest(String windowType, String renderer) + : WindowPerformanceTest(windowType, renderer) { + d_window->setModel(&d_model); } virtual void doTest() { - size_t root_items_count = 200; size_t id = 0; // 200 items with 50 children each - for (size_t parent = 0; parent < root_items_count; ++parent, ++id) + for (size_t parent = 0; parent < 200; ++parent, ++id) { - CEGUI::TreeItem* item = new CEGUI::TreeItem( - CEGUI::PropertyHelper::toString(id)); - d_window->addItem(item); + StandardItem* item = new StandardItem( + PropertyHelper::toString(id)); + d_model.addItem(item); + ModelIndex index = d_model.getIndexForItem(item); for (size_t child = 0; child < 50; ++child, ++id) { - item->addItem(new CEGUI::TreeItem( - CEGUI::PropertyHelper::toString(id))); + d_model.addItemAtPosition( + new StandardItem(PropertyHelper::toString(child)), + index, 0); d_window->render(); } } d_window->render(); - for (size_t i = 0; i < root_items_count; ++i) - { - d_window->d_listItems.at(i)->toggleIsOpen(); - } + d_window->expandAllSubtrees(); d_window->render(); + ModelIndex root = d_model.getRootIndex(); for (size_t i = 0; i < 30; ++i) { - d_window->removeItem(d_window->d_listItems.at(i)); + d_model.removeItem(d_model.makeIndex(i, root)); } d_window->render(); - d_window->setSortingEnabled(false); - d_window->setSortingEnabled(true); + d_window->setSortMode(VSM_Ascending); } + + StandardItemModel d_model; }; -BOOST_AUTO_TEST_SUITE(TreePerformance) +BOOST_AUTO_TEST_SUITE(TreeViewPerformance) BOOST_AUTO_TEST_CASE(Test) { - TreePerformanceTest tree_performance_test( - "TaharezLook/Tree", "Core/Tree"); - tree_performance_test.execute(); + TreePerformanceTest treeview_performance_test( + "TaharezLook/TreeView", "Core/TreeView"); + treeview_performance_test.execute(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 7a88e43a3..9017c7dc3 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -1 +1,10 @@ -cegui_add_test_executable(CEGUITests) +set(EXTRA_HEADER_FILES + ${CMAKE_SOURCE_DIR}/samples/ModelView/InventoryModel.h +) +set(EXTRA_SOURCE_FILES + ${CMAKE_SOURCE_DIR}/samples/ModelView/InventoryModel.cpp +) + +include_directories(${CMAKE_SOURCE_DIR}/samples/ModelView) + +cegui_add_test_executable_with_extra_files(CEGUITests "${EXTRA_HEADER_FILES}" "${EXTRA_SOURCE_FILES}") diff --git a/tests/unit/Clipboard.cpp b/tests/unit/Clipboard.cpp index 27b1ee0ba..51ec3ba8f 100644 --- a/tests/unit/Clipboard.cpp +++ b/tests/unit/Clipboard.cpp @@ -62,6 +62,7 @@ BOOST_AUTO_TEST_CASE(InternalClipboard) BOOST_CHECK_EQUAL(MIME_TYPE, retrievedMimeType); BOOST_CHECK_EQUAL(BUFFER_SIZE, retrievedBufferSize); BOOST_CHECK(memcmp(buffer, retrievedBuffer, BUFFER_SIZE) == 0); // 0 indicates that both blocks of memory are equal + delete[] buffer; } static CEGUI::String g_MimeType = ""; @@ -70,18 +71,25 @@ static size_t g_ClipboardSize = 0; class TestNativeClipboardProvider : public CEGUI::NativeClipboardProvider { +private: + std::vector d_allocatedMemory; public: virtual ~TestNativeClipboardProvider() - {} + { + for (std::vector::iterator itor = d_allocatedMemory.begin(); + itor != d_allocatedMemory.end(); ++itor) + { + delete[] *itor; + } + } virtual void sendToClipboard(const CEGUI::String& mimeType, void* buffer, size_t size) { - delete g_ClipboardBuffer; - g_MimeType = mimeType; g_ClipboardSize = size; g_ClipboardBuffer = new CEGUI::uint8[size]; memcpy(g_ClipboardBuffer, buffer, size); + d_allocatedMemory.push_back(g_ClipboardBuffer); } virtual void retrieveFromClipboard(CEGUI::String& mimeType, void*& buffer, size_t& size) @@ -92,6 +100,7 @@ class TestNativeClipboardProvider : public CEGUI::NativeClipboardProvider // we have to allocate buffer for the user of the native clipboard provider! buffer = new CEGUI::uint8[g_ClipboardSize]; memcpy(buffer, g_ClipboardBuffer, g_ClipboardSize); + d_allocatedMemory.push_back(buffer); } }; diff --git a/tests/unit/InputAggregator.cpp b/tests/unit/InputAggregator.cpp new file mode 100644 index 000000000..caa49d596 --- /dev/null +++ b/tests/unit/InputAggregator.cpp @@ -0,0 +1,496 @@ +/*********************************************************************** + * created: 10/7/2013 + * author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include + +#include +#include +#include + +#include "CEGUI/CEGUI.h" + +using namespace CEGUI; + +class MockInputEventReceiver : public InputEventReceiver +{ +public: + std::string d_text; + float d_totalScroll; + glm::vec2 d_cursorPosition; + std::vector d_semanticValues; + + MockInputEventReceiver() : + d_text(""), + d_cursorPosition(0.0f, 0.0f), + d_totalScroll(0) + {} + + ~MockInputEventReceiver() + { + for (HandlersMap::const_iterator itor = d_handlersMap.begin(); + itor != d_handlersMap.end(); ++ itor) + { + delete itor->second; + } + + for (HandlersMap::const_iterator itor = d_semanticEventsHandlersMap.begin(); + itor != d_semanticEventsHandlersMap.end(); ++itor) + { + delete itor->second; + } + } + + bool injectInputEvent(const InputEvent& event) + { + HandlersMap::const_iterator itor = d_handlersMap.find(event.d_eventType); + if (itor != d_handlersMap.end()) + { + return (*(*itor).second)(event); + } + else + { + std::cout << "No event handler for event type: " << event.d_eventType << std::endl; + return false; + } + } + + bool handleTextEvent(const TextInputEvent& event) + { + d_text += event.d_character; + return true; + } + + bool handleMovementEvent(const SemanticInputEvent& event) + { + d_cursorPosition = glm::vec2(event.d_payload.array[0], + event.d_payload.array[1]); + return true; + } + + bool handleScrollEvent(const SemanticInputEvent& event) + { + d_totalScroll += event.d_payload.single; + return true; + } + + bool handleSemanticEvent(const SemanticInputEvent& event) + { + HandlersMap::const_iterator itor = + d_semanticEventsHandlersMap.find(event.d_value); + if (itor != d_semanticEventsHandlersMap.end()) + { + return (*(*itor).second)(event); + } + else + { + d_semanticValues.push_back(event.d_value); + } + + return true; + } + + void initializeEventHandlers() + { + d_handlersMap.insert(std::make_pair(IET_TextInputEventType, + new InputEventHandlerSlot( + &MockInputEventReceiver::handleTextEvent, this))); + + d_handlersMap.insert(std::make_pair(IET_SemanticInputEventType, + new InputEventHandlerSlot( + &MockInputEventReceiver::handleSemanticEvent, this))); + } + + void initializeSemanticEventHandlers() + { + d_semanticEventsHandlersMap.insert(std::make_pair(SV_VerticalScroll, + new InputEventHandlerSlot( + &MockInputEventReceiver::handleScrollEvent, this))); + + d_semanticEventsHandlersMap.insert(std::make_pair(SV_CursorMove, + new InputEventHandlerSlot( + &MockInputEventReceiver::handleMovementEvent, this))); + } + +private: + typedef std::map*> HandlersMap; + HandlersMap d_semanticEventsHandlersMap; + HandlersMap d_handlersMap; +}; + +struct InputAggregatorFixture +{ + InputAggregatorFixture() + { + d_inputEventReceiver = new MockInputEventReceiver; + d_inputEventReceiver->initializeEventHandlers(); + d_inputEventReceiver->initializeSemanticEventHandlers(); + d_inputAggregator = new InputAggregator(d_inputEventReceiver); + d_inputAggregator->initialise(); + } + + ~InputAggregatorFixture() + { + delete d_inputEventReceiver; + delete d_inputAggregator; + } + + InputAggregator* d_inputAggregator; + MockInputEventReceiver* d_inputEventReceiver; +}; + +//----------------------------------------------------------------------------// + +BOOST_FIXTURE_TEST_SUITE(InputAggregator, InputAggregatorFixture) + +BOOST_AUTO_TEST_CASE(TextEventOneChar) +{ + d_inputAggregator->injectChar('a'); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_text, "a"); +} + +BOOST_AUTO_TEST_CASE(TextEventMultipleChars) +{ + d_inputAggregator->injectChar('a'); + d_inputAggregator->injectChar('b'); + d_inputAggregator->injectChar('c'); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_text, "abc"); +} + +BOOST_AUTO_TEST_CASE(MovementEventNoDelta) +{ + d_inputAggregator->injectMouseMove(0, 0); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 0); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 0); +} + +BOOST_AUTO_TEST_CASE(MovementEventSingleDelta) +{ + d_inputAggregator->injectMouseMove(0, 0); + d_inputAggregator->injectMouseMove(3, 5); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 3); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 5); +} + +BOOST_AUTO_TEST_CASE(MovementEventMultipleDeltas) +{ + d_inputAggregator->injectMouseMove(0, 0); + d_inputAggregator->injectMouseMove(3, 5); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 3); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 5); + + d_inputAggregator->injectMouseMove(3, -3); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 6); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 2); +} + +BOOST_AUTO_TEST_CASE(MovementEventZeroPosition) +{ + d_inputAggregator->injectMousePosition(0, 0); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 0); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 0); +} + +BOOST_AUTO_TEST_CASE(MovementEventNonZeroPosition) +{ + d_inputAggregator->injectMousePosition(30, 40); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 30); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 40); +} + +BOOST_AUTO_TEST_CASE(MovementEventMultiplePositions) +{ + d_inputAggregator->injectMousePosition(3, 5); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 3); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, 5); + + d_inputAggregator->injectMousePosition(3, -3); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.x, 3); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_cursorPosition.y, -3); +} + +BOOST_AUTO_TEST_CASE(ScrollEventNoDelta) +{ + d_inputAggregator->injectMouseWheelChange(0); + + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_totalScroll, 0); +} + +BOOST_AUTO_TEST_CASE(ScrollEventMultipleDelta) +{ + d_inputAggregator->injectMouseWheelChange(1); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_totalScroll, 1); + + d_inputAggregator->injectMouseWheelChange(3); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_totalScroll, 4); + + d_inputAggregator->injectMouseWheelChange(5); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_totalScroll, 9); + + d_inputAggregator->injectMouseWheelChange(-2); + BOOST_REQUIRE_EQUAL(d_inputEventReceiver->d_totalScroll, 7); +} + +BOOST_AUTO_TEST_CASE(CutRequestToCut) +{ + std::vector expected_values; + expected_values.push_back(SV_Cut); + + d_inputAggregator->injectCutRequest(); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(CopyRequestToCopy) +{ + std::vector expected_values; + expected_values.push_back(SV_Copy); + + d_inputAggregator->injectCopyRequest(); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(PasteRequestToPaste) +{ + std::vector expected_values; + expected_values.push_back(SV_Paste); + + d_inputAggregator->injectPasteRequest(); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseButtonDownToCursorHold) +{ + std::vector expected_values; + expected_values.push_back(SV_CursorPressHold); + + d_inputAggregator->injectMouseButtonDown(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseButtonDownAndControlToSelectCumulative) +{ + std::vector expected_values; + expected_values.push_back(SV_SelectCumulative); + + d_inputAggregator->injectKeyDown(Key::LeftControl); + d_inputAggregator->injectMouseButtonDown(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseButtonDownAndShiftToSelectMultiple) +{ + std::vector expected_values; + expected_values.push_back(SV_SelectRange); + + d_inputAggregator->injectKeyDown(Key::LeftShift); + d_inputAggregator->injectMouseButtonDown(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseButtonUpToCursorActivate) +{ + std::vector expected_values; + expected_values.push_back(SV_CursorActivate); + + d_inputAggregator->injectMouseButtonUp(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseButtonDownAndUpCombined) +{ + std::vector expected_values; + expected_values.push_back(SV_CursorPressHold); + expected_values.push_back(SV_CursorActivate); + + d_inputAggregator->injectMouseButtonDown(LeftButton); + d_inputAggregator->injectMouseButtonUp(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseClickToCursorActivate) +{ + std::vector expected_values; + expected_values.push_back(SV_CursorActivate); + + d_inputAggregator->injectMouseButtonClick(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseClickAndControlToSelectCumulative) +{ + std::vector expected_values; + expected_values.push_back(SV_SelectCumulative); + + d_inputAggregator->injectKeyDown(Key::LeftControl); + d_inputAggregator->injectMouseButtonClick(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseClickAndShiftToSelectMultipleItems) +{ + std::vector expected_values; + expected_values.push_back(SV_CursorActivate); + + d_inputAggregator->injectKeyDown(Key::LeftShift); + d_inputAggregator->injectMouseButtonClick(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseDoubleClickToSelectWord) +{ + std::vector expected_values; + expected_values.push_back(SV_SelectWord); + + d_inputAggregator->injectMouseButtonDoubleClick(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(MouseTripleClickToSelectAll) +{ + std::vector expected_values; + expected_values.push_back(SV_SelectAll); + + d_inputAggregator->injectMouseButtonTripleClick(LeftButton); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(KeyDownBackspaceToDeletePreviousCharacter) +{ + std::vector expected_values; + expected_values.push_back(SV_DeletePreviousCharacter); + + d_inputAggregator->injectKeyDown(Key::Backspace); + d_inputAggregator->injectKeyUp(Key::Backspace); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(KeyDownDeleteToDeleteNextCharacter) +{ + std::vector expected_values; + expected_values.push_back(SV_DeleteNextCharacter); + + d_inputAggregator->injectKeyDown(Key::Delete); + d_inputAggregator->injectKeyUp(Key::Delete); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(KeyDownLeftArrowToGoToPreviousCharacter) +{ + std::vector expected_values; + expected_values.push_back(SV_GoToPreviousCharacter); + + d_inputAggregator->injectKeyDown(Key::ArrowLeft); + d_inputAggregator->injectKeyUp(Key::ArrowLeft); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(KeyDownLeftArrowAndShiftToSelectPreviousCharacter) +{ + std::vector expected_values; + expected_values.push_back(SV_SelectPreviousCharacter); + + d_inputAggregator->injectKeyDown(Key::LeftShift); + d_inputAggregator->injectKeyDown(Key::ArrowLeft); + d_inputAggregator->injectKeyUp(Key::ArrowLeft); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_CASE(KeyDownLeftArrowAndControlToGoToPreviousWord) +{ + std::vector expected_values; + expected_values.push_back(SV_GoToPreviousWord); + + d_inputAggregator->injectKeyDown(Key::LeftControl); + d_inputAggregator->injectKeyDown(Key::ArrowLeft); + d_inputAggregator->injectKeyUp(Key::ArrowLeft); + + BOOST_REQUIRE_EQUAL_COLLECTIONS(expected_values.begin(), expected_values.end(), + d_inputEventReceiver->d_semanticValues.begin(), + d_inputEventReceiver->d_semanticValues.end()); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/InputInjection.cpp b/tests/unit/InputInjection.cpp new file mode 100644 index 000000000..d74feea7a --- /dev/null +++ b/tests/unit/InputInjection.cpp @@ -0,0 +1,283 @@ +/*********************************************************************** + * created: 21/5/2013 + * author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ + +#include + +#include +#include + +#include "CEGUI/CEGUI.h" + +using namespace CEGUI; + +struct InputInjectionFixture +{ + InputInjectionFixture() : + d_buttonHandledCount(0), + d_windowHandledCount(0), + d_guiContext(&System::getSingleton().getDefaultGUIContext()), + d_inputAggregator(new InputAggregator(d_guiContext)) + { + d_inputAggregator->initialise(); + // reset the cursor to (0,0) + d_guiContext->getCursor().setPosition(glm::vec2(0, 0)); + + System::getSingleton().notifyDisplaySizeChanged(Sizef(100, 100)); + Rectf constraint_area(0, 0, 100, 100); + d_guiContext->getCursor().setConstraintArea(&constraint_area); + + d_window = WindowManager::getSingleton().createWindow("DefaultWindow"); + d_window->setPosition(UVector2(cegui_reldim(0.0f), cegui_reldim(0.0f))); + d_window->setSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); + + d_button = WindowManager::getSingleton().createWindow("CEGUI/PushButton"); + d_button->setPosition(UVector2(cegui_reldim(0.2f), cegui_reldim(0.2f))); + d_button->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); + + d_editbox = static_cast(WindowManager::getSingleton().createWindow("TaharezLook/Editbox")); + d_editbox->setPosition(UVector2(cegui_reldim(0.9f), cegui_reldim(0.9f))); + d_editbox->setSize(USize(cegui_reldim(0.1f), cegui_reldim(0.1f))); + + d_window->addChild(d_editbox); + d_window->addChild(d_button); + + System::getSingleton().getDefaultGUIContext().setRootWindow(d_window); + + d_windowConnections.push_back( + d_window->subscribeEvent(Window::EventCursorActivate, + Event::Subscriber(&InputInjectionFixture::handleWindowEvent, this)) + ); + d_buttonConnections.push_back( + d_button->subscribeEvent(PushButton::EventClicked, + Event::Subscriber(&InputInjectionFixture::handleButtonEvent, this)) + ); + } + + ~InputInjectionFixture() + { + disconnectConnections(d_windowConnections); + disconnectConnections(d_buttonConnections); + + delete d_inputAggregator; + + System::getSingleton().getDefaultGUIContext().setRootWindow(0); + + WindowManager::getSingleton().destroyWindow(d_window); + } + + bool handleButtonEvent(const EventArgs& e) + { + ++d_buttonHandledCount; + return true; + } + + bool handleWindowEvent(const EventArgs& e) + { + ++d_windowHandledCount; + return true; + } + + void disconnectConnections(std::vector& connections) + { + for(std::vector::iterator itor = connections.begin(); + itor != connections.end(); ++itor) + { + (*itor)->disconnect(); + } + } + + int d_buttonHandledCount; + int d_windowHandledCount; + + Window* d_window; + Window* d_button; + Editbox* d_editbox; + + GUIContext* d_guiContext; + InputAggregator* d_inputAggregator; + + std::vector d_windowConnections; + std::vector d_buttonConnections; +}; + +//----------------------------------------------------------------------------// +static void doClick(InputAggregator* input_aggregator, float position_x, float position_y) +{ + BOOST_REQUIRE_EQUAL(input_aggregator->injectMousePosition(position_x, position_y), true); + BOOST_REQUIRE_EQUAL(input_aggregator->injectMouseButtonDown(LeftButton), true); + BOOST_REQUIRE_EQUAL(input_aggregator->injectMouseButtonUp(LeftButton), true); +} + +static void pressKey(InputAggregator* input_aggregator, Key::Scan key) +{ + BOOST_REQUIRE_EQUAL(input_aggregator->injectKeyDown(key), true); + BOOST_REQUIRE_EQUAL(input_aggregator->injectKeyUp(key), true); +} + +//----------------------------------------------------------------------------// +BOOST_FIXTURE_TEST_SUITE(InputInjection, InputInjectionFixture) + +BOOST_AUTO_TEST_CASE(OneClickOnWindow) +{ + // we check for both: a) being handled, b) have the expected final result + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectMouseButtonClick(LeftButton), true); + + BOOST_REQUIRE_EQUAL(d_windowHandledCount, 1); + BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 0); +} + +BOOST_AUTO_TEST_CASE(MultipleClicksOnWindow) +{ + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectMouseButtonClick(LeftButton), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectMouseButtonClick(LeftButton), true); + + BOOST_REQUIRE_EQUAL(d_windowHandledCount, 2); + BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 0); +} + +BOOST_AUTO_TEST_CASE(OneClickOnButton) +{ + doClick(d_inputAggregator, 30.0f, 30.0f); + + BOOST_REQUIRE_EQUAL(d_windowHandledCount, 0); + BOOST_REQUIRE_EQUAL(d_buttonHandledCount, 1); +} + +BOOST_AUTO_TEST_CASE(InsertSimpleText) +{ + // focus the editbox + doClick(d_inputAggregator, 91.0f, 91.0f); + + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('W'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('o'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('W'), true); + + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW"); +} + +BOOST_AUTO_TEST_CASE(DeleteTextWithBackspace) +{ + // focus the editbox + doClick(d_inputAggregator, 91.0f, 91.0f); + + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('W'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('o'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('k'), true); + pressKey(d_inputAggregator, Key::Backspace); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('W'), true); + + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW"); +} + +BOOST_AUTO_TEST_CASE(DeleteTextWithDelete) +{ + // focus the editbox + doClick(d_inputAggregator, 91.0f, 91.0f); + + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('W'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('o'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('k'), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectChar('W'), true); + pressKey(d_inputAggregator, Key::ArrowLeft); + pressKey(d_inputAggregator, Key::ArrowLeft); + pressKey(d_inputAggregator, Key::Delete); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectKeyDown(Key::Delete), true); + + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW"); +} + +BOOST_AUTO_TEST_CASE(MouseSelectAllTextCopyAndPaste) +{ + // focus the editbox + doClick(d_inputAggregator, 91.0f, 91.0f); + + d_editbox->setText("WoW rocks"); + + // select all text + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectMouseButtonTripleClick(LeftButton), true); + BOOST_REQUIRE_EQUAL(d_editbox->getSelectionLength(), 9); + + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectCopyRequest(), true); + + // deselect the text + d_editbox->setSelection(0, 0); + + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectPasteRequest(), true); + + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "WoW rocksWoW rocks"); +} + +BOOST_AUTO_TEST_CASE(MouseSelectWordAndDelete) +{ + // focus the editbox + doClick(d_inputAggregator, 92.0f, 92.0f); + + d_editbox->setText("WoW rocks"); + + // select all text + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectMouseButtonDoubleClick(LeftButton), true); + BOOST_REQUIRE_EQUAL(d_editbox->getSelectionLength(), 4); + pressKey(d_inputAggregator, Key::Delete); + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "rocks"); +} + +BOOST_AUTO_TEST_CASE(KeyboardSelectCharactersAndDelete) +{ + // focus the editbox + doClick(d_inputAggregator, 91.0f, 91.0f); + + d_editbox->setText("WoW rocks"); + + // select 'WoW' + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectKeyDown(Key::LeftShift), true); + pressKey(d_inputAggregator, Key::ArrowRight); + pressKey(d_inputAggregator, Key::ArrowRight); + pressKey(d_inputAggregator, Key::ArrowRight); + pressKey(d_inputAggregator, Key::ArrowRight); + + BOOST_REQUIRE_EQUAL(d_editbox->getSelectionLength(), 4); + pressKey(d_inputAggregator, Key::Delete); + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "rocks"); +} + +BOOST_AUTO_TEST_CASE(KeyboardSelectWordAndDelete) +{ + // focus the editbox + doClick(d_inputAggregator, 91.0f, 91.0f); + + d_editbox->setText("WoW rocks"); + + // select 'WoW' + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectKeyDown(Key::LeftShift), true); + BOOST_REQUIRE_EQUAL(d_inputAggregator->injectKeyDown(Key::LeftControl), true); + pressKey(d_inputAggregator, Key::ArrowRight); + + BOOST_REQUIRE_EQUAL(d_editbox->getSelectionLength(), 4); + pressKey(d_inputAggregator, Key::Delete); + BOOST_REQUIRE_EQUAL(d_editbox->getText(), "rocks"); +} +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/Quaternion.cpp b/tests/unit/ItemModel.cpp similarity index 75% rename from tests/unit/Quaternion.cpp rename to tests/unit/ItemModel.cpp index fcecf2c40..18fabb84c 100644 --- a/tests/unit/Quaternion.cpp +++ b/tests/unit/ItemModel.cpp @@ -1,9 +1,9 @@ /*********************************************************************** - * created: 5/9/2012 - * author: Martin Preisler + * created: Tue May 20 2014 + * author: Timotei Dolean *************************************************************************/ /*************************************************************************** - * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -25,16 +25,19 @@ * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ -#include "CEGUI/Quaternion.h" - #include -BOOST_AUTO_TEST_SUITE(Quaternion) +#include "CEGUI/views/ItemModel.h" + +using namespace CEGUI; + +BOOST_AUTO_TEST_SUITE(ModelIndexTestSuite) -BOOST_AUTO_TEST_CASE(Constants) +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(Ctor_Default_InitialisesDefaultValues) { - BOOST_CHECK_EQUAL(CEGUI::Quaternion::ZERO, CEGUI::Quaternion(0, 0, 0, 0)); - BOOST_CHECK_EQUAL(CEGUI::Quaternion::IDENTITY, CEGUI::Quaternion(1, 0, 0, 0)); + ModelIndex modelIndex; + BOOST_CHECK(modelIndex.d_modelData == 0); } BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/ItemModelStub.cpp b/tests/unit/ItemModelStub.cpp new file mode 100644 index 000000000..2fc181bfc --- /dev/null +++ b/tests/unit/ItemModelStub.cpp @@ -0,0 +1,93 @@ +/*********************************************************************** + * created: Sat Jun 07 2014 + * author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include "ItemModelStub.h" +#include +#include + +using namespace CEGUI; + +//----------------------------------------------------------------------------// +bool ItemModelStub::isValidIndex(const ModelIndex& model_index) const +{ + return model_index.d_modelData != 0; +} + +//----------------------------------------------------------------------------// +ModelIndex ItemModelStub::makeIndex(size_t child, const ModelIndex& model_index) +{ + assert(child < d_items.size()); + return ModelIndex(&d_items.at(child)); +} + +//----------------------------------------------------------------------------// +size_t ItemModelStub::getChildCount(const ModelIndex& model_index) const +{ + return d_items.size(); +} + +//----------------------------------------------------------------------------// +ModelIndex ItemModelStub::getParentIndex(const ModelIndex& model_index) const +{ + return ModelIndex(); +} + +//----------------------------------------------------------------------------// +ModelIndex ItemModelStub::getRootIndex() const +{ + return ModelIndex(); +} + +//----------------------------------------------------------------------------// +String ItemModelStub::getData(const ModelIndex& model_index, ItemDataRole role /*= IDR_Text*/) +{ + assert(model_index.d_modelData != 0); + return *(static_cast(model_index.d_modelData)); +} + +//----------------------------------------------------------------------------// +bool ItemModelStub::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const +{ + return index1.d_modelData == index2.d_modelData; +} + +//----------------------------------------------------------------------------// +int ItemModelStub::compareIndices(const ModelIndex& index1, const ModelIndex& index2) const +{ + return (*static_cast(index1.d_modelData)).compare( + *static_cast(index2.d_modelData)); +} + +//----------------------------------------------------------------------------// +int ItemModelStub::getChildId(const ModelIndex& model_index) const +{ + String* str = static_cast(model_index.d_modelData); + std::vector::const_iterator itor = std::find(d_items.begin(), d_items.end(), *str); + if (itor == d_items.end()) + return -1; + + return std::distance(d_items.begin(), itor); +} diff --git a/tests/unit/ItemModelStub.h b/tests/unit/ItemModelStub.h new file mode 100644 index 000000000..401ff7a74 --- /dev/null +++ b/tests/unit/ItemModelStub.h @@ -0,0 +1,49 @@ +/*********************************************************************** + * created: Sat Jun 07 2014 + * author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#ifndef _CEGUITestsItemModelStub_h_ +#define _CEGUITestsItemModelStub_h_ + +#include "CEGUI/views/ItemModel.h" +#include + +class ItemModelStub : public CEGUI::ItemModel +{ +public: + virtual bool isValidIndex(const CEGUI::ModelIndex& model_index) const; + virtual CEGUI::ModelIndex makeIndex(size_t child, const CEGUI::ModelIndex& model_index); + virtual bool areIndicesEqual(const CEGUI::ModelIndex& index1, const CEGUI::ModelIndex& index2) const; + virtual int compareIndices(const CEGUI::ModelIndex& index1, const CEGUI::ModelIndex& index2) const; + virtual CEGUI::ModelIndex getParentIndex(const CEGUI::ModelIndex& model_index) const; + virtual int getChildId(const CEGUI::ModelIndex& model_index) const; + virtual size_t getChildCount(const CEGUI::ModelIndex& model_index) const; + virtual CEGUI::String getData(const CEGUI::ModelIndex& model_index, CEGUI::ItemDataRole role = CEGUI::IDR_Text); + virtual CEGUI::ModelIndex getRootIndex() const; + + std::vector d_items; +}; + +#endif diff --git a/tests/unit/ItemView.cpp b/tests/unit/ItemView.cpp new file mode 100644 index 000000000..34a3e3d1c --- /dev/null +++ b/tests/unit/ItemView.cpp @@ -0,0 +1,196 @@ +/*********************************************************************** + * created: Sun May 25 2014 + * author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include + +#include "CEGUI/views/ListView.h" +#include "CEGUI/WindowManager.h" +#include "ItemModelStub.h" + +using namespace CEGUI; + +//----------------------------------------------------------------------------// +struct ItemViewFixture +{ + ItemViewFixture() + { + view = static_cast(WindowManager::getSingleton().createWindow("TaharezLook/ListView", "lv")); + view->setWindowRenderer("Core/ListView"); + view->setModel(&model); + } + + ItemModelStub model; + ItemView* view; +}; + +BOOST_FIXTURE_TEST_SUITE(ItemViewTestSuite, ItemViewFixture) + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetModel_SetsTheModel) +{ + BOOST_CHECK_EQUAL(&model, view->getModel()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetModel_SameModel_DoesNotSetDirtyState) +{ + view->setIsDirty(false); + + view->setModel(&model); + + BOOST_CHECK(!view->isDirty()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetModel_DifferentModel_SetsDirtyState) +{ + ItemModelStub model2; + view->setIsDirty(false); + + view->setModel(&model2); + + BOOST_CHECK(view->isDirty()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetModel_ModelHasNewChildren_SetsDirtyState) +{ + model.d_items.push_back("item"); + + { + view->setIsDirty(false); + model.notifyChildrenAdded(model.getRootIndex(), 0, 1); + + BOOST_CHECK(view->isDirty()); + } + + { + model.notifyChildrenWillBeRemoved(model.getRootIndex(), 0, 1); + view->setIsDirty(false); + model.notifyChildrenRemoved(model.getRootIndex(), 0, 1); + + BOOST_CHECK(view->isDirty()); + } +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetModel_DifferentModel_UnhooksPreviousModelEvents) +{ + model.d_items.push_back("item"); + + ItemModelStub model2; + view->setModel(&model2); + + view->setIsDirty(false); + model.notifyChildrenAdded(model.getRootIndex(), 0, 1); + + BOOST_CHECK(!view->isDirty()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetModel_DifferentModel_RemovesSelection) +{ + model.d_items.push_back("item"); + view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); + + BOOST_CHECK_EQUAL(1, view->getIndexSelectionStates().size()); + + ItemModelStub model2; + view->setModel(&model2); + BOOST_REQUIRE_EQUAL(0, view->getIndexSelectionStates().size()); +} + +BOOST_AUTO_TEST_CASE(ClearSelection) +{ + model.d_items.push_back("item"); + + view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); + + view->clearSelections(); + + BOOST_REQUIRE_EQUAL(0, view->getIndexSelectionStates().size()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetSelectedItem_ReplacesSelection) +{ + model.d_items.push_back("item1"); + model.d_items.push_back("item2"); + view->setModel(&model); + + view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); + BOOST_CHECK_EQUAL(1, view->getIndexSelectionStates().size()); + + view->setSelectedIndex(model.makeIndex(1, model.getRootIndex())); + BOOST_REQUIRE_EQUAL(1, view->getIndexSelectionStates().size()); + BOOST_REQUIRE_EQUAL("item2", + *(static_cast( + view->getIndexSelectionStates().at(0).d_selectedIndex.d_modelData))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetItemSelectionState_MultiSelectToggled_ModifiesSelectionAccordingly) +{ + model.d_items.push_back("item1"); + model.d_items.push_back("item2"); + view->setModel(&model); + view->setMultiSelectEnabled(true); + + view->setIndexSelectionState(model.makeIndex(0, model.getRootIndex()), true); + view->setIndexSelectionState(model.makeIndex(1, model.getRootIndex()), true); + + BOOST_REQUIRE_EQUAL(2, view->getIndexSelectionStates().size()); + BOOST_REQUIRE_EQUAL("item2", + *(static_cast( + view->getIndexSelectionStates().at(1).d_selectedIndex.d_modelData))); + + view->setMultiSelectEnabled(false); + BOOST_REQUIRE_EQUAL(1, view->getIndexSelectionStates().size()); + BOOST_REQUIRE_EQUAL("item1", + *(static_cast( + view->getIndexSelectionStates().at(0).d_selectedIndex.d_modelData))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(EnsureItemIsVisible_ScrollsHorizontallyAndVertically) +{ + for (int i = 0; i < 10; ++i) + model.d_items.push_back("1"); + model.d_items.push_back(String(100, 'x')); + + view->setSize(USize(cegui_absdim(10), cegui_absdim(10))); + view->prepareForRender(); + + view->getVertScrollbar()->setScrollPosition(view->getRenderedTotalHeight()); + view->getHorzScrollbar()->setScrollPosition(view->getRenderedMaxWidth()); + + view->ensureIndexIsVisible(model.makeIndex(0, model.getRootIndex())); + + BOOST_REQUIRE_CLOSE(0.0f, view->getVertScrollbar()->getScrollPosition(), 1.0f); + BOOST_REQUIRE_CLOSE(0.0f, view->getHorzScrollbar()->getScrollPosition(), 1.0f); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/ListView.cpp b/tests/unit/ListView.cpp new file mode 100644 index 000000000..be0ff2638 --- /dev/null +++ b/tests/unit/ListView.cpp @@ -0,0 +1,281 @@ +/*********************************************************************** + * created: Sun May 25 2014 + * author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include + +#include "ItemModelStub.h" +#include "CEGUI/Font.h" +#include "CEGUI/WindowManager.h" +#include "CEGUI/widgets/Scrollbar.h" + +// Yup. We need this in order to easily inject/call event handlers without having +// to go through GUIContext, or inherit from widgets in order to test them. +#define protected public +#include "CEGUI/views/ListView.h" + +using namespace CEGUI; + +//----------------------------------------------------------------------------// +static const String ITEM1 = "ITEM 1"; +static const String ITEM2 = "ITEM 2"; +static const String ITEM3 = "ITEM 3"; +static const String ITEM_WITH_6LINES = "THIS\nIS\nA\nMULTILINE\nLINE\n"; + +//----------------------------------------------------------------------------// +struct ListViewFixture +{ + ListViewFixture() + { + System::getSingleton().notifyDisplaySizeChanged(Sizef(100, 100)); + + view = static_cast(WindowManager::getSingleton().createWindow("TaharezLook/ListView", "lv")); + view->setWindowRenderer("Core/ListView"); + view->setModel(&model); + font_height = view->getFont()->getFontHeight(); + } + + ListView* view; + ItemModelStub model; + float font_height; +}; + +BOOST_FIXTURE_TEST_SUITE(ListViewTestSuite, ListViewFixture) + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_NoItems_ReturnsInvalidIndex) +{ + ModelIndex index = view->indexAt(glm::vec2(1, 0)); + + BOOST_REQUIRE(index.d_modelData == 0); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideSingleObject_ReturnsCorrectIndex) +{ + model.d_items.push_back(ITEM1); + + ModelIndex index = view->indexAt(glm::vec2(1, font_height / 2.0f)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL(ITEM1, *(static_cast(index.d_modelData))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideSingleObjectListWithOffset_ReturnsCorrectIndex) +{ + float x_offset = 500; + float y_offset = 354; + view->setPosition(UVector2(cegui_absdim(x_offset), cegui_absdim(y_offset))); + model.d_items.push_back(ITEM1); + + ModelIndex index = view->indexAt(glm::vec2( + x_offset + 1, + y_offset + font_height / 2.0f)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL(ITEM1, *(static_cast(index.d_modelData))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideSingleObjectListWithScrollbar_ReturnsCorrectIndex) +{ + for (int i = 0; i < 100; ++i) + model.d_items.push_back(" item .." + PropertyHelper::toString(i)); + model.d_items.push_back(ITEM1); + view->setSize(USize(cegui_absdim(100), cegui_absdim(font_height * 10))); + view->prepareForRender(); + view->getVertScrollbar()->setUnitIntervalScrollPosition(1.0f); + + ModelIndex index = view->indexAt(glm::vec2(1, 9 * font_height + font_height / 2.0f)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL(ITEM1, *(static_cast(index.d_modelData))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionOutsideSingleObject_ReturnsInvalidIndex) +{ + model.d_items.push_back(ITEM1); + + ModelIndex index = view->indexAt(glm::vec2(1, font_height * 2)); + + BOOST_REQUIRE(index.d_modelData == 0); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideSecondObject_ReturnsCorrectIndex) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + + ModelIndex index = view->indexAt(glm::vec2(1, font_height * 2)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL(ITEM2, *(static_cast(index.d_modelData))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetSelectedItem_InitialSelection_SelectsFirstObject) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + + bool selected = view->setSelectedIndex(ModelIndex(&model.d_items.at(0))); + view->prepareForRender(); + + BOOST_REQUIRE(selected); + BOOST_REQUIRE(view->getItems().at(0)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetSelectedItem_SecondSelection_SelectsSecondObject) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + view->setSelectedIndex(ModelIndex(&model.d_items.at(0))); + view->prepareForRender(); + + bool selected = view->setSelectedIndex(ModelIndex(&model.d_items.at(1))); + view->prepareForRender(); + + BOOST_REQUIRE(selected); + BOOST_REQUIRE(!view->getItems().at(0)->d_isSelected); + BOOST_REQUIRE(view->getItems().at(1)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemAdded_ProperSelectionIsPersisted) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + view->setSelectedIndex(ModelIndex(&model.d_items.at(1))); + view->prepareForRender(); + + model.d_items.insert(model.d_items.begin() + 1, 1, ITEM3); + model.notifyChildrenAdded(model.getRootIndex(), 1, 1); + + view->prepareForRender(); + + BOOST_REQUIRE(!view->getItems().at(0)->d_isSelected); + BOOST_REQUIRE(!view->getItems().at(1)->d_isSelected); + BOOST_REQUIRE(view->getItems().at(2)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemRemoved_RenderingHeightIsUpdated) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + model.d_items.push_back(ITEM3); + view->prepareForRender(); + + model.notifyChildrenWillBeRemoved(model.getRootIndex(), 0, 3); + model.d_items.clear(); + model.notifyChildrenRemoved(model.getRootIndex(), 0, 3); + + view->prepareForRender(); + + BOOST_REQUIRE(view->getRenderedTotalHeight() <= 0.01f); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemRemoved_NothingIsSelectedAndRenderingHeightIsUpdated) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + model.d_items.push_back(ITEM3); + view->setSelectedIndex(ModelIndex(&model.d_items.at(1))); + view->prepareForRender(); + + float itemSize = view->getRenderedTotalHeight() / 3; + + model.notifyChildrenWillBeRemoved(model.getRootIndex(), 1, 1); + model.d_items.erase(model.d_items.begin() + 1); + model.notifyChildrenRemoved(model.getRootIndex(), 1, 1); + + view->prepareForRender(); + + BOOST_REQUIRE(view->getItems().size() == 2); + BOOST_REQUIRE(!view->getItems().at(0)->d_isSelected); + BOOST_REQUIRE(!view->getItems().at(1)->d_isSelected); + BOOST_REQUIRE(view->getRenderedTotalHeight() <= (itemSize * 2 + 0.01f)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemNameChanged_UpdatesRenderedString) +{ + model.d_items.push_back(ITEM1); + view->prepareForRender(); + BOOST_CHECK_EQUAL(1, view->getItems().at(0)->d_string.getLineCount()); + + model.notifyChildrenDataWillChange(model.getRootIndex(), 0, 1); + model.d_items.at(0) = ITEM_WITH_6LINES; + model.notifyChildrenDataChanged(model.getRootIndex(), 0, 1); + + view->prepareForRender(); + BOOST_REQUIRE_EQUAL(6, view->getItems().at(0)->d_string.getLineCount()); +} + +//----------------------------------------------------------------------------// +void triggerSelectRangeEvent(glm::vec2 position, ItemView* view) +{ + SemanticEventArgs args(view); + args.d_semanticValue = SV_SelectRange; + view->getGUIContext().getCursor().setPosition(position); + view->onSemanticInputEvent(args); +} + +BOOST_AUTO_TEST_CASE(SelectRange) +{ + model.d_items.push_back(ITEM1); + model.d_items.push_back(ITEM2); + model.d_items.push_back(ITEM3); + view->prepareForRender(); + view->setMultiSelectEnabled(true); + + view->setSelectedIndex(ModelIndex(&model.d_items.at(0))); + + triggerSelectRangeEvent(glm::vec2(1, font_height * 2.0f + font_height / 2.0f), view); + + BOOST_REQUIRE_EQUAL(3, view->getIndexSelectionStates().size()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SortEnabled_IsEnabled_ListIsSorted) +{ + model.d_items.push_back(ITEM3); + model.d_items.push_back(ITEM2); + model.d_items.push_back(ITEM1); + view->prepareForRender(); + + view->setSortMode(VSM_Ascending); + view->prepareForRender(); + + ModelIndex index = view->indexAt(glm::vec2(1, font_height * 2.0f + font_height / 2.0f)); + BOOST_REQUIRE_EQUAL(ITEM3, *(static_cast(index.d_modelData))); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/ListWidget.cpp b/tests/unit/ListWidget.cpp new file mode 100644 index 000000000..0140c8f84 --- /dev/null +++ b/tests/unit/ListWidget.cpp @@ -0,0 +1,160 @@ +/*********************************************************************** + * created: Sun May 25 2014 + * author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include + +#include "CEGUI/widgets/ListWidget.h" +#include "CEGUI/WindowManager.h" + +using namespace CEGUI; + +struct ListWidgetFixture +{ + ListWidgetFixture() + { + view = static_cast( + WindowManager::getSingleton().createWindow("TaharezLook/ListWidget", "lw")); + view->setWindowRenderer("Core/ListView"); + } + + ListWidget* view; +}; + +BOOST_FIXTURE_TEST_SUITE(ListWidgetTestSuite, ListWidgetFixture) + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(GetFirstSelectedItem_NoSelection_ReturnsNull) +{ + BOOST_REQUIRE_EQUAL(static_cast(0), view->getFirstSelectedItem()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(GetFirstSelectedItem_OneItem_ReturnsSelection) +{ + view->addItem("item1"); + + view->setIndexSelectionState(static_cast(0), true); + + BOOST_REQUIRE_EQUAL(view->getItemAtIndex(0), view->getFirstSelectedItem()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(GetFirstSelectedItem_MultipleSelectedItemsUnordered_ReturnsFirst) +{ + view->addItem("item1"); + view->addItem("item2"); + view->addItem("item3"); + view->setMultiSelectEnabled(true); + + view->setIndexSelectionState(2, true); + view->setIndexSelectionState(1, true); + + BOOST_REQUIRE_EQUAL(2, view->getSelectedItemsCount()); + BOOST_REQUIRE_EQUAL(view->getItemAtIndex(1), view->getFirstSelectedItem()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(GetNextSelectedItem_OneItem_NullStartItem_ReturnsFirstSelectedItem) +{ + view->addItem("item1"); + + view->setIndexSelectionState(static_cast(0), true); + + BOOST_REQUIRE_EQUAL(view->getItemAtIndex(0), view->getNextSelectedItem(0)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(GetNextSelectedItem_HappyFlow_ReturnsExpectedItem) +{ + view->addItem("item1"); + view->addItem("item2"); + view->addItem("item3"); + view->setMultiSelectEnabled(true); + + view->setIndexSelectionState(2, true); + view->setIndexSelectionState(1, true); + + BOOST_REQUIRE_EQUAL(2, view->getSelectedItemsCount()); + BOOST_REQUIRE_EQUAL(view->getItemAtIndex(1), + view->getNextSelectedItem(view->getItemAtIndex(0))); + BOOST_REQUIRE_EQUAL(view->getItemAtIndex(2), + view->getNextSelectedItem(view->getItemAtIndex(1))); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(RemoveItem_IsRemoved) +{ + view->addItem("item1"); + view->addItem("item2"); + + view->prepareForRender(); + + BOOST_REQUIRE_EQUAL(2, view->getItems().size()); + + view->removeItem(view->getItemAtIndex(0)); + view->prepareForRender(); + + BOOST_REQUIRE_EQUAL(1, view->getItems().size()); + BOOST_REQUIRE_EQUAL("item2", view->getItems().at(0)->d_text); +} + + +//----------------------------------------------------------------------------// +struct OnListSelectionQueriesFirstSelectedItemTestFixture : public ListWidgetFixture +{ + OnListSelectionQueriesFirstSelectedItemTestFixture() + { + view->subscribeEvent(ListWidget::EventSelectionChanged, + Event::Subscriber( + &OnListSelectionQueriesFirstSelectedItemTestFixture::onSelectionChanged, + this)); + } + + bool onSelectionChanged(const EventArgs& args) + { + d_firstSelectedItem = view->getFirstSelectedItem(); + return true; + } + + StandardItem* d_firstSelectedItem; +}; + +BOOST_FIXTURE_TEST_CASE( + ClearList_ViewWithSelectionChangedHandler_SelectedItemEqualsToNull, + OnListSelectionQueriesFirstSelectedItemTestFixture) +{ + view->addItem("ichi"); + view->addItem("ni"); + view->addItem("san"); + + view->setIndexSelectionState(1, true); + + view->clearList(); + + BOOST_REQUIRE_EQUAL(static_cast(0), d_firstSelectedItem); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/StandardItemModel.cpp b/tests/unit/StandardItemModel.cpp new file mode 100644 index 000000000..d359f6a0b --- /dev/null +++ b/tests/unit/StandardItemModel.cpp @@ -0,0 +1,79 @@ +/*********************************************************************** + * created: Wed Jul 30 2014 + * author: Timotei Dolean + *************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + ***************************************************************************/ +#include + +#include "CEGUI/views/StandardItemModel.h" + +using namespace CEGUI; + +BOOST_AUTO_TEST_SUITE(StandardItemModelTestSuite) + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(Insert_NullPosition_InsertsAtBeginning) +{ + StandardItemModel model; + model.addItem("i1"); + + model.insertItem(new StandardItem("i2"), 0); + + BOOST_REQUIRE_EQUAL(2, model.getChildCount(model.getRootIndex())); + BOOST_REQUIRE_EQUAL("i2", model.getData(model.makeIndex(0, model.getRootIndex()), IDR_Text)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(Insert_NonNullPosition_InsertsBefore) +{ + StandardItemModel model; + model.addItem("i1"); + model.addItem("i2"); + + model.insertItem(new StandardItem("i3"), model.getItemForIndex(model.makeIndex(1, model.getRootIndex()))); + + BOOST_REQUIRE_EQUAL(3, model.getChildCount(model.getRootIndex())); + BOOST_REQUIRE_EQUAL("i3", model.getData(model.makeIndex(1, model.getRootIndex()), IDR_Text)); +} + +BOOST_AUTO_TEST_CASE(Insert_ChildOfNode_InsertsBefore) +{ + StandardItemModel model; + model.addItem("i1"); + model.addItem("i2"); + + ModelIndex i1_index = model.makeIndex(0, model.getRootIndex()); + StandardItem* i1_child1 = new StandardItem("i1-child1"); + model.addItemAtPosition(i1_child1, i1_index, 0); + + BOOST_REQUIRE_EQUAL(1, model.getChildCount(i1_index)); + BOOST_REQUIRE_EQUAL(i1_child1->getText(), model.getData(model.makeIndex(0, i1_index), IDR_Text)); + + model.insertItem(new StandardItem("i1-child2"), i1_child1); + BOOST_REQUIRE_EQUAL(2, model.getChildCount(i1_index)); + BOOST_REQUIRE_EQUAL("i1-child2", model.getData(model.makeIndex(0, i1_index), IDR_Text)); + BOOST_REQUIRE_EQUAL(i1_child1->getText(), model.getData(model.makeIndex(1, i1_index), IDR_Text)); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/TreeView.cpp b/tests/unit/TreeView.cpp new file mode 100644 index 000000000..64d5da2e1 --- /dev/null +++ b/tests/unit/TreeView.cpp @@ -0,0 +1,565 @@ +/*********************************************************************** + * created: Fri Jun 13 2014 + * author: Timotei Dolean +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. +***************************************************************************/ +#include + +#include "InventoryModel.h" +#include "CEGUI/Event.h" +#include "CEGUI/Font.h" +#include "CEGUI/WindowManager.h" + +// Yup. We need this in order to easily inject/call event handlers without having +// to go through GUIContext, or inherit from widgets in order to test them. +#define protected public +#include "CEGUI/views/TreeView.h" + +using namespace CEGUI; +#define BOOST_REQUIRE_INDICES_EQUAL(i1, i2) BOOST_REQUIRE_EQUAL(i1.d_modelData, i2.d_modelData) + +//----------------------------------------------------------------------------// +struct TreeViewFixture +{ + TreeViewFixture() + { + System::getSingleton().notifyDisplaySizeChanged(Sizef(100, 100)); + + view = static_cast( + WindowManager::getSingleton().createWindow("TaharezLook/TreeView", "tv")); + view->setModel(&model); + view->setItemTooltipsEnabled(true); + font_height = view->getFont()->getFontHeight(); + expander_width = view->getViewRenderer()->getSubtreeExpanderSize().d_width; + + view->subscribeEvent(TreeView::EventSubtreeExpanded, + Event::Subscriber(&TreeViewFixture::onSubtreeExpanded, this)); + view->subscribeEvent(TreeView::EventSubtreeCollapsed, + Event::Subscriber(&TreeViewFixture::onSubtreeCollapsed, this)); + } + + bool onSubtreeExpanded(const EventArgs& args) + { + expanded_nodes.push_back( + static_cast(args).d_index); + return true; + } + + bool onSubtreeCollapsed(const EventArgs& args) + { + collapsed_nodes.push_back( + static_cast(args).d_index); + return true; + } + + + TreeView* view; + InventoryModel model; + float font_height; + float expander_width; + + std::vector expanded_nodes; + std::vector collapsed_nodes; +}; + +//----------------------------------------------------------------------------// +CursorInputEventArgs createCursorEventArgs(float x, float y, TreeView* view) +{ + CursorInputEventArgs args(view); + + args.source = CIS_Left; + args.position = glm::vec2(x, y); + + return args; +} + +BOOST_FIXTURE_TEST_SUITE(TreeViewTestSuite, TreeViewFixture) + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_NoItems_ReturnsInvalidIndex) +{ + ModelIndex index = view->indexAt(glm::vec2(1, 0)); + + BOOST_REQUIRE(index.d_modelData == 0); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideObject_ReturnsCorrectIndex) +{ + // we do this on purpose: we need to skip the root from selection & related. + // if it has a name then we need not to render it. + model.getRoot().setText("Root"); + model.addRandomItemWithChildren(model.getRootIndex(), 0); + + ModelIndex index = view->indexAt(glm::vec2(expander_width * 2, font_height / 2.0f)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL( + model.getRoot().getChildren().at(0), + static_cast(index.d_modelData)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideObjectTreeWithOffset_ReturnsCorrectIndex) +{ + float x_offset = 500; + float y_offset = 354; + view->setPosition(UVector2(cegui_absdim(x_offset), cegui_absdim(y_offset))); + model.addRandomItemWithChildren(model.getRootIndex(), 0); + + ModelIndex index = view->indexAt(glm::vec2( + x_offset + expander_width * 2, + y_offset + font_height / 2.0f)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL( + model.getRoot().getChildren().at(0), + static_cast(index.d_modelData)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideSingleObjectTreeWithScrollbar_ReturnsCorrectIndex) +{ + for (int i = 0; i < 50; ++i) + model.addRandomItemWithChildren(model.getRootIndex(), 0); + + view->setSize(USize(cegui_absdim(200), cegui_absdim(font_height * 10))); + view->prepareForRender(); + view->getVertScrollbar()->setUnitIntervalScrollPosition(1.0f); + + ModelIndex index = view->indexAt(glm::vec2( + expander_width * 2, + 9 * font_height + font_height / 2.0f)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL( + model.getRoot().getChildren().at(49), + static_cast(index.d_modelData)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionOutsideObject_ReturnsInvalidIndex) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0); + + ModelIndex index = view->indexAt(glm::vec2(expander_width * 2, font_height * 3)); + + BOOST_REQUIRE(index.d_modelData == 0); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(IndexAt_PositionInsideSecondObject_ReturnsCorrectIndex) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0); + model.addRandomItemWithChildren(model.getRootIndex(), 0); + + ModelIndex index = view->indexAt(glm::vec2( + expander_width * 2, + font_height + font_height / 2)); + + BOOST_REQUIRE(index.d_modelData != 0); + BOOST_REQUIRE_EQUAL( + model.getRoot().getChildren().at(1), + static_cast(index.d_modelData)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetSelectedItem_InitialSelection_SelectsFirstObject) +{ + model.load(); + + bool selected = view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); + view->prepareForRender(); + + BOOST_REQUIRE(selected); + BOOST_REQUIRE(view->getRootItemState().d_renderedChildren.at(0)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(SetSelectedItem_SecondSelection_SelectsSecondObject) +{ + model.load(); + view->setSelectedIndex(model.makeIndex(0, model.getRootIndex())); + view->prepareForRender(); + + bool selected = view->setSelectedIndex(model.makeIndex(1, model.getRootIndex())); + view->prepareForRender(); + + BOOST_REQUIRE(selected); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(!children.at(0)->d_isSelected); + BOOST_REQUIRE(children.at(1)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemAdded_ProperSelectionIsPersisted) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0); + model.addRandomItemWithChildren(model.getRootIndex(), 0); + view->setSelectedIndex(model.makeIndex(1, model.getRootIndex())); + view->prepareForRender(); + + model.addRandomItemWithChildren(model.getRootIndex(), 0); + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(!children.at(0)->d_isSelected); + BOOST_REQUIRE(!children.at(1)->d_isSelected); + BOOST_REQUIRE(children.at(2)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemAdded_ProperChildSelectionIsPersisted) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0); + model.addRandomItemWithChildren(model.getRootIndex(), 0); + view->prepareForRender(); + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height * 3 / 2, view); + view->onCursorPressHold(args); + // first child + view->setSelectedIndex(model.makeIndex(0, model.makeIndex(1, model.getRootIndex()))); + + model.addRandomItemWithChildren(model.getRootIndex(), 0); + view->prepareForRender(); + + const std::vector& children = view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(!children.at(0)->d_isSelected); + BOOST_REQUIRE(!children.at(1)->d_isSelected); + BOOST_REQUIRE(!children.at(2)->d_isSelected); + BOOST_REQUIRE(children.at(2)->d_renderedChildren.at(0)->d_isSelected); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemAdded_InExpandedSubtree_IsRendered) +{ + ModelIndex root_index = model.getRootIndex(); + model.addRandomItemWithChildren(root_index, 0, 0); + + ModelIndex child_index = model.makeIndex(0, root_index); + model.addRandomItemWithChildren(child_index, 0); + view->prepareForRender(); + + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height / 2, view); + view->onCursorPressHold(args); + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE_EQUAL(1, children.at(0)->d_renderedChildren.size()); + + model.addRandomItemWithChildren(child_index, 0); + view->prepareForRender(); + BOOST_REQUIRE_EQUAL(2, children.at(0)->d_renderedChildren.size()); + BOOST_REQUIRE_EQUAL(2, children.at(0)->d_totalChildCount); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(ItemRemoved_NothingIsSelectedAndRenderingHeightIsUpdated) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0, 0); + model.addRandomItemWithChildren(model.getRootIndex(), 0, 0); + view->setSelectedIndex(model.makeIndex(1, model.getRootIndex())); + view->prepareForRender(); + + float itemSize = view->getRenderedTotalHeight() / 2; + + model.removeItem(model.makeIndex(1, model.getRootIndex())); + + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE_EQUAL(1, view->getRootItemState().d_renderedChildren.size()); + BOOST_REQUIRE_EQUAL(1, view->getRootItemState().d_totalChildCount); + BOOST_REQUIRE(!children.at(0)->d_isSelected); + BOOST_REQUIRE(view->getRenderedTotalHeight() <= (itemSize + 0.01f)); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(InitialState_NoSubtreesOpenedAndCountIsComputedRight) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0); + model.addRandomItemWithChildren(model.getRootIndex(), 0); + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(!children.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(1, children.at(0)->d_totalChildCount); + BOOST_REQUIRE(!children.at(1)->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(1, children.at(1)->d_totalChildCount); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(CursorMoved_OverSubtreeExpander_DoesNotTriggerExpanding) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + view->prepareForRender(); + + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height / 2, view); + view->onCursorMove(args); + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(!children.at(0)->d_subtreeIsExpanded); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(CursorPressed_ExpandAndCollapseEventsFired) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + view->prepareForRender(); + + BOOST_REQUIRE_EQUAL(3, view->getRootItemState().d_renderedChildren.at(0)->d_totalChildCount); + + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height / 2, view); + ModelIndex target_node = model.makeIndex(0, model.getRootIndex()); + view->onCursorPressHold(args); + BOOST_REQUIRE_INDICES_EQUAL(target_node, expanded_nodes.at(0)); + BOOST_REQUIRE(collapsed_nodes.empty()); + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(children.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(3, children.at(0)->d_renderedChildren.size()); + + // collapse + view->onCursorPressHold(args); + BOOST_REQUIRE_INDICES_EQUAL(target_node, expanded_nodes.at(0)); + BOOST_REQUIRE_INDICES_EQUAL(target_node, collapsed_nodes.at(0)); + BOOST_REQUIRE(!children.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(0, children.at(0)->d_renderedChildren.size()); +} + +//----------------------------------------------------------------------------// +BOOST_AUTO_TEST_CASE(CursorPressed_ExpandChild) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + model.addRandomItemWithChildren(model.makeIndex(0, model.getRootIndex()), 0, 3); + view->prepareForRender(); + + CursorInputEventArgs args = createCursorEventArgs(expander_width / 2, font_height / 2, view); + view->onCursorPressHold(args); + + args = createCursorEventArgs( + view->getViewRenderer()->getSubtreeExpanderXIndent(1) + expander_width / 2, + font_height + font_height / 2, view); + view->onCursorPressHold(args); + ModelIndex first_node = model.makeIndex(0, model.getRootIndex()); + BOOST_REQUIRE_INDICES_EQUAL(first_node, expanded_nodes.at(0)); + BOOST_REQUIRE_INDICES_EQUAL(model.makeIndex(0, first_node), expanded_nodes.at(1)); + BOOST_REQUIRE(collapsed_nodes.empty()); + + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(children.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(4, children.at(0)->d_renderedChildren.size()); + BOOST_REQUIRE(children.at(0)->d_renderedChildren.at(0)->d_subtreeIsExpanded); +} + +BOOST_AUTO_TEST_CASE(SubtreeExpanded_SelectionChanges_DoesNotChangeExpandedState) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + view->prepareForRender(); + + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height / 2, view); + view->onCursorPressHold(args); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(children.at(0)->d_subtreeIsExpanded); + + view->setSelectedIndex(model.makeIndex(1, model.getRootIndex())); + view->prepareForRender(); + + BOOST_REQUIRE(children.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE(children.at(1)->d_isSelected); +} + +BOOST_AUTO_TEST_CASE(SetSelectedItem_ChildInExpandedSubtree_SelectsChild) +{ + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + model.addRandomItemWithChildren(model.getRootIndex(), 0, 3); + view->prepareForRender(); + + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height / 2, view); + view->onCursorPressHold(args); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE(children.at(0)->d_subtreeIsExpanded); + + view->setSelectedIndex(model.makeIndex(0, model.makeIndex(0, model.getRootIndex()))); + view->prepareForRender(); + + BOOST_REQUIRE(children.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE(children.at(0)->d_renderedChildren.at(0)->d_isSelected); +} + +BOOST_AUTO_TEST_CASE(ExpandAll) +{ + ModelIndex root = model.getRootIndex(); + model.addRandomItemWithChildren(root, 0, 3); + model.addRandomItemWithChildren(root, 0, 3); + model.addRandomItemWithChildren(model.makeIndex(0, model.makeIndex(0, root)), 0, 2); + model.addRandomItemWithChildren(model.makeIndex(0, model.makeIndex(1, root)), 0, 2); + + view->prepareForRender(); + view->expandAllSubtrees(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + + const TreeViewItemRenderingState* first_child = children.at(0); + BOOST_REQUIRE(first_child->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(3, first_child->d_renderedChildren.size()); + BOOST_REQUIRE(children.at(1)->d_subtreeIsExpanded); + + BOOST_REQUIRE(first_child->d_renderedChildren.at(0)->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(1, first_child->d_renderedChildren.at(0)->d_renderedChildren.size()); + + const TreeViewItemRenderingState* child2 = + first_child->d_renderedChildren.at(0)->d_renderedChildren.at(0); + BOOST_REQUIRE(child2->d_subtreeIsExpanded); + BOOST_REQUIRE_EQUAL(2, child2->d_renderedChildren.size()); +} + +BOOST_AUTO_TEST_CASE(GetTreeViewItemForIndex) +{ + ModelIndex root_index = model.getRootIndex(); + + /* + ROOT + Index0 + Index0_Child + A + B + C + D + */ + model.addRandomItemWithChildren(root_index, 0); + model.addRandomItemWithChildren(root_index, 0); + model.addRandomItemWithChildren(root_index, 0); + + ModelIndex index0 = model.makeIndex(0, root_index); + model.addRandomItemWithChildren(index0, 0); + model.addRandomItemWithChildren(index0, 0); + + ModelIndex index0_child = model.makeIndex(0, index0); + model.addRandomItemWithChildren(index0_child, 0); + view->prepareForRender(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + + BOOST_REQUIRE_EQUAL(&view->getRootItemState(), view->getTreeViewItemForIndex(root_index)); + BOOST_REQUIRE_EQUAL(children.at(0), view->getTreeViewItemForIndex(index0)); + BOOST_REQUIRE_EQUAL(children.at(1), view->getTreeViewItemForIndex(model.makeIndex(1, root_index))); + + // subtree not opened now. + BOOST_REQUIRE_EQUAL( + static_cast(0), + view->getTreeViewItemForIndex(index0_child)); + CursorInputEventArgs args = + createCursorEventArgs(expander_width / 2, font_height / 2, view); + view->onCursorPressHold(args); + view->prepareForRender(); + + BOOST_REQUIRE_EQUAL(children.at(0)->d_renderedChildren.at(0), + view->getTreeViewItemForIndex(index0_child)); +} + +BOOST_AUTO_TEST_CASE(SortEnabled_IsEnabled_TreeIsSorted) +{ + InventoryItem* i1 = InventoryItem::make("C", 1, &model.getRoot()); + InventoryItem* i2 = InventoryItem::make("B", 1, &model.getRoot()); + InventoryItem* i3 = InventoryItem::make("A", 1, &model.getRoot()); + + InventoryItem* i1_child1 = InventoryItem::make("Z3", 1, i1); + InventoryItem* i1_child2 = InventoryItem::make("Z1", 1, i1); + i1->getChildren().push_back(i1_child1); + i1->getChildren().push_back(i1_child2); + + InventoryItem* i_leaf1 = InventoryItem::make("Z", 1, i1_child1); + InventoryItem* i_leaf2 = InventoryItem::make("A", 1, i1_child1); + InventoryItem* i_leaf3 = InventoryItem::make("B", 1, i1_child1); + i1_child1->getChildren().push_back(i_leaf1); + i1_child1->getChildren().push_back(i_leaf2); + i1_child1->getChildren().push_back(i_leaf3); + + model.getRoot().getChildren().push_back(i1); + model.getRoot().getChildren().push_back(i2); + model.getRoot().getChildren().push_back(i3); + view->prepareForRender(); + + view->setSortMode(VSM_Ascending); + view->prepareForRender(); + view->expandAllSubtrees(); + + const std::vector& children = + view->getRootItemState().d_renderedChildren; + BOOST_REQUIRE_EQUAL(2, children.at(0)->d_childId); + BOOST_REQUIRE_EQUAL(1, children.at(1)->d_childId); + BOOST_REQUIRE_EQUAL(0, children.at(2)->d_childId); + + BOOST_REQUIRE_EQUAL(1, children.at(2)->d_renderedChildren.at(0)->d_childId); + + BOOST_REQUIRE_EQUAL(0, + children.at(2)->d_renderedChildren.at(1)->d_renderedChildren.at(2)->d_childId); +} + +BOOST_AUTO_TEST_CASE(MultipleLevelsHierarchy_RenderedMaxWidthGreaterThanViewSize) +{ + view->setSize(USize(cegui_absdim(10), cegui_absdim(10))); + InventoryItem* parent = &model.getRoot(); + for (size_t i = 0; i < 100; ++i) + { + InventoryItem* item = InventoryItem::make("level " + PropertyHelper::toString(i), 0, parent); + + parent->getChildren().push_back(item); + parent = item; + } + view->prepareForRender(); + + view->expandAllSubtrees(); + + BOOST_REQUIRE(view->getRenderedMaxWidth() > 100); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/Vector.cpp b/tests/unit/Vector.cpp deleted file mode 100644 index 18ffb8b5e..000000000 --- a/tests/unit/Vector.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/*********************************************************************** - * created: 5/7/2011 - * author: Martin Preisler - *************************************************************************/ -/*************************************************************************** - * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - ***************************************************************************/ - -#include "CEGUI/Vector.h" - -#include - -BOOST_AUTO_TEST_SUITE(Vector) - -BOOST_AUTO_TEST_CASE(ConstructionAssignment2) -{ - CEGUI::Vector2f a(1, 0); - CEGUI::Vector2f b(0, 1); - CEGUI::Vector2f c(2, 2); - CEGUI::Vector2f d(2, 1); - CEGUI::Vector2f e(1, 2); - - BOOST_CHECK_EQUAL(a + b, CEGUI::Vector2f(1, 1)); - BOOST_CHECK_EQUAL(a - b, CEGUI::Vector2f(1, -1)); - - BOOST_CHECK_EQUAL(a * c, CEGUI::Vector2f(2, 0)); - BOOST_CHECK_EQUAL(b * c, CEGUI::Vector2f(0, 2)); - BOOST_CHECK_EQUAL(c * d, CEGUI::Vector2f(4, 2)); - BOOST_CHECK_EQUAL(c * e, CEGUI::Vector2f(2, 4)); - - BOOST_CHECK_EQUAL(a * 2, CEGUI::Vector2f(2, 0)); - BOOST_CHECK_EQUAL(b * 2, CEGUI::Vector2f(0, 2)); -} - -BOOST_AUTO_TEST_CASE(ConstructionAssignment3) -{ - CEGUI::Vector3f a(1, 0, 0); - CEGUI::Vector3f b(0, 1, 0); - CEGUI::Vector3f c(0, 0, 1); - - BOOST_CHECK_EQUAL(a + b, CEGUI::Vector3f(1, 1, 0)); - BOOST_CHECK_EQUAL(a - b, CEGUI::Vector3f(1, -1, 0)); - - BOOST_CHECK_EQUAL(a * 2, CEGUI::Vector3f(2, 0, 0)); - BOOST_CHECK_EQUAL(b * 2, CEGUI::Vector3f(0, 2, 0)); - BOOST_CHECK_EQUAL(c * 2, CEGUI::Vector3f(0, 0, 2)); - - BOOST_CHECK_EQUAL(CEGUI::Vector3f::one(), CEGUI::Vector3f::one_x() + CEGUI::Vector3f::one_y() + CEGUI::Vector3f::one_z()); -} - -BOOST_AUTO_TEST_CASE(Constants2) -{ - BOOST_CHECK_EQUAL(CEGUI::Vector2f::zero(), CEGUI::Vector2f(0, 0)); - BOOST_CHECK_EQUAL(CEGUI::Vector2f::one(), CEGUI::Vector2f(1, 1)); - BOOST_CHECK_EQUAL(CEGUI::Vector2f::one_x(), CEGUI::Vector2f(1, 0)); - BOOST_CHECK_EQUAL(CEGUI::Vector2f::one_y(), CEGUI::Vector2f(0, 1)); - - BOOST_CHECK_EQUAL(CEGUI::UVector2::zero(), CEGUI::UVector2(CEGUI::UDim(0, 0), CEGUI::UDim(0, 0))); - BOOST_CHECK_EQUAL(CEGUI::UVector2::one(), CEGUI::UVector2(CEGUI::UDim(1, 0), CEGUI::UDim(1, 0))); - BOOST_CHECK_EQUAL(CEGUI::UVector2::one_x(), CEGUI::UVector2(CEGUI::UDim(1, 0), CEGUI::UDim(0, 0))); - BOOST_CHECK_EQUAL(CEGUI::UVector2::one_y(), CEGUI::UVector2(CEGUI::UDim(0, 0), CEGUI::UDim(1, 0))); - - // test if it works with the UDim zero and relative - BOOST_CHECK_EQUAL(CEGUI::UVector2::zero(), CEGUI::UVector2(CEGUI::UDim::zero(), CEGUI::UDim::zero())); - BOOST_CHECK_EQUAL(CEGUI::UVector2::one(), CEGUI::UVector2(CEGUI::UDim::relative(), CEGUI::UDim::relative())); - BOOST_CHECK_EQUAL(CEGUI::UVector2::one_x(), CEGUI::UVector2(CEGUI::UDim::relative(), CEGUI::UDim::zero())); - BOOST_CHECK_EQUAL(CEGUI::UVector2::one_y(), CEGUI::UVector2(CEGUI::UDim::zero(), CEGUI::UDim::relative())); -} - -BOOST_AUTO_TEST_CASE(Constants3) -{ - BOOST_CHECK_EQUAL(CEGUI::Vector3f::zero(), CEGUI::Vector3f(0, 0, 0)); - BOOST_CHECK_EQUAL(CEGUI::Vector3f::one(), CEGUI::Vector3f(1, 1, 1)); - - BOOST_CHECK_EQUAL(CEGUI::Vector3f::one_x(), CEGUI::Vector3f(1, 0, 0)); - BOOST_CHECK_EQUAL(CEGUI::Vector3f::one_y(), CEGUI::Vector3f(0, 1, 0)); - BOOST_CHECK_EQUAL(CEGUI::Vector3f::one_z(), CEGUI::Vector3f(0, 0, 1)); -} - -BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/unit/Window.cpp b/tests/unit/Window.cpp index 1700390f9..209d06af8 100644 --- a/tests/unit/Window.cpp +++ b/tests/unit/Window.cpp @@ -127,16 +127,16 @@ BOOST_AUTO_TEST_CASE(HitTesting) * We know where the windows are so lets check whether CEGUI reports correct hits for them */ - BOOST_CHECK(d_insideInsideRoot->isHit(CEGUI::Vector2f(300, 150))); + BOOST_CHECK(d_insideInsideRoot->isHit(glm::vec2(300, 150))); d_insideInsideRoot->setDisabled(true); - BOOST_CHECK(!d_insideInsideRoot->isHit(CEGUI::Vector2f(300, 150), false)); - BOOST_CHECK(d_insideInsideRoot->isHit(CEGUI::Vector2f(300, 150), true)); + BOOST_CHECK(!d_insideInsideRoot->isHit(glm::vec2(300, 150), false)); + BOOST_CHECK(d_insideInsideRoot->isHit(glm::vec2(300, 150), true)); d_insideInsideRoot->setDisabled(false); d_root->setDisabled(true); - BOOST_CHECK(!d_insideInsideRoot->isHit(CEGUI::Vector2f(300, 150), false)); - BOOST_CHECK(d_insideInsideRoot->isHit(CEGUI::Vector2f(300, 150), true)); + BOOST_CHECK(!d_insideInsideRoot->isHit(glm::vec2(300, 150), false)); + BOOST_CHECK(d_insideInsideRoot->isHit(glm::vec2(300, 150), true)); d_root->setDisabled(false); }