From 7472c87afc7f10794fc57dff31786215c2e42bf2 Mon Sep 17 00:00:00 2001 From: Rick Gleason Date: Sat, 2 Sep 2023 10:36:58 -0400 Subject: [PATCH 01/73] 1.15.4.0 fix macos wx315 --- CMakeLists.txt | 14 +++++++------- ci/circleci-build-macos.sh | 12 ++++++------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e194ed4..9693a769 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ ## * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, * ## * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx * #----------------------------------------------------------------------------- -# Frontend2 Author: Jon Gough TP v1.0.253.0 07/08/2023 DD/MM/YYYY format +# Frontend2 Author: Jon Gough TP v1.0.253.0 07/08/2023 DD/MM/YYYY format # buildCI:yes useODAPI:no validateJSON:no # --------------------------------------------------------------------------- ## ----- When changing this file do NOT change the order in which sections occur ----- ## @@ -50,13 +50,13 @@ set(TITLE_NAME "weatherrouting") set(PACKAGE_CONTACT "Sean d'Epagnier") set(PACKAGE "weather_routing_pi") set(SHORT_DESCRIPTION "Compute optimal routes based on weather and constraints.") -set(LONG_DESCRIPTION "WR features include: optimal routing subject to various constraints based on weather data, automatic boat polar computation.") +set(LONG_DESCRIPTION "WR features include: optimal routing subject to various constraints based on weather data, automatic boat polar computation.") set(VERSION_MAJOR "1") set(VERSION_MINOR "15") -set(VERSION_PATCH "3") +set(VERSION_PATCH "4") set(VERSION_TWEAK "0") -set(VERSION_DATE "31/08/2023")#DD/MM/YYYY format +set(VERSION_DATE "02/09/2023")#DD/MM/YYYY format set(OCPN_MIN_VERSION "ov58") set(OCPN_API_VERSION_MAJOR "1") set(OCPN_API_VERSION_MINOR "16") @@ -82,7 +82,7 @@ set(CLOUDSMITH_USER "opencpn") #set(CLOUDSMITH_USER "rick-gleason") # Set Plugin info-url, summary and description -set(XML_INFO_URL "https://opencpn.org/OpenCPN/plugins/weatherroute.html") +set(XML_INFO_URL "https://opencpn.org/OpenCPN/plugins/weatherroute.html") set(XML_SUMMARY ${SHORT_DESCRIPTION}) set(XML_DESCRIPTION ${LONG_DESCRIPTION}) @@ -197,8 +197,8 @@ SET (HDRS set(EXTSRC ) -set(EXTINCLUDE - extinclude/ODAPI.h +set(EXTINCLUDE + extinclude/ODAPI.h extinclude/ODJSONSchemas.h ) diff --git a/ci/circleci-build-macos.sh b/ci/circleci-build-macos.sh index 914a7687..7f60db31 100755 --- a/ci/circleci-build-macos.sh +++ b/ci/circleci-build-macos.sh @@ -23,12 +23,12 @@ if [ -n "$WX_VER" ] && [ "$WX_VER" -eq "32" ]; then WX_CONFIG="--prefix=/tmp/wx321_opencpn50_macos1010" MACOSX_DEPLOYMENT_TARGET=10.10 else - echo "Building for WXVERSION 312"; - WX_URL=https://download.opencpn.org/s/rwoCNGzx6G34tbC/download - WX_DOWNLOAD=/tmp/wx312B_opencpn50_macos109.tar.xz - WX_EXECUTABLE=/tmp/wx312B_opencpn50_macos109/bin/wx-config - WX_CONFIG="--prefix=/tmp/wx312B_opencpn50_macos109" - MACOSX_DEPLOYMENT_TARGET=10.9 + echo "Building for WXVERSION 315"; + WX_URL=https://download.opencpn.org/s/MCiRiq4fJcKD56r/download + WX_DOWNLOAD=/tmp/wx315_opencpn50_macos1010.tar.xz + WX_EXECUTABLE=/tmp/wx315_opencpn50_macos1010/bin/wx-config + WX_CONFIG="--prefix=/tmp/wx315_opencpn50_macos1010" + MACOSX_DEPLOYMENT_TARGET=10.10 fi # Download required binaries using wget, since curl causes an issue with Xcode 13.1 and some specific certificates. From f0e865ea1412e399782c34d26f756aef6043b737 Mon Sep 17 00:00:00 2001 From: Rick Gleason Date: Sat, 2 Sep 2023 13:24:27 -0400 Subject: [PATCH 02/73] 1.15.4.1 macos target darwin-wx315 --- .circleci/config.yml | 2 +- CMakeLists.txt | 2 +- cmake/PluginSetup.cmake | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 39312b18..73625cc0 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -310,7 +310,7 @@ jobs: - OCPN_TARGET: macos - CLOUDSMITH_PKG_EXT: pkg - DEPLOY_USE_ORB: true - - WX_VER: 312 + - WX_VER: 315 steps: - checkout - run: chmod a+x ci/*.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index 9693a769..7fb68b48 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -55,7 +55,7 @@ set(LONG_DESCRIPTION "WR features include: optimal routing subject to various co set(VERSION_MAJOR "1") set(VERSION_MINOR "15") set(VERSION_PATCH "4") -set(VERSION_TWEAK "0") +set(VERSION_TWEAK "1") set(VERSION_DATE "02/09/2023")#DD/MM/YYYY format set(OCPN_MIN_VERSION "ov58") set(OCPN_API_VERSION_MAJOR "1") diff --git a/cmake/PluginSetup.cmake b/cmake/PluginSetup.cmake index 69a6005b..6e104b44 100644 --- a/cmake/PluginSetup.cmake +++ b/cmake/PluginSetup.cmake @@ -99,7 +99,8 @@ elseif(APPLE) if("$ENV{WX_VER}" STREQUAL "32") set(PKG_TARGET "darwin-wx$ENV{WX_VER}") else() - set(PKG_TARGET "${PKG_BUILD_TARGET}") +## set(PKG_TARGET "${PKG_BUILD_TARGET}") + set(PKG_TARGET "darwin-wx315") endif() execute_process(COMMAND "sw_vers" "-productVersion" OUTPUT_VARIABLE PKG_TARGET_VERSION) elseif(_wx_selected_config MATCHES "androideabi-qt-arm64") From 0a643e0d956c3c7a0adb2b7865acb342da049afd Mon Sep 17 00:00:00 2001 From: Rick Gleason Date: Sun, 3 Sep 2023 08:01:03 -0400 Subject: [PATCH 03/73] 1.15.6.0 + Old + pluginGL --- CMakeLists.txt | 39 +- .travis.yml => OLD/.travis.yml | 0 OLD/CMakeLists.txt.bak | 348 +++ Frontend2.md => OLD/Frontend2.md | 0 Read-Build.md => OLD/Read-Build.md | 0 OLD/buildwin/zlib1.lib | Bin 0 -> 17152 bytes {ci => OLD/ci}/circleci-build-macos-new.sh | 0 {ci => OLD/ci}/circleci-build-trusty.sh | 0 .../ci}/travis-build-raspbian-armhf-part1.sh | 0 .../ci}/travis-build-raspbian-armhf-part2.sh | 0 {cmake => OLD/cmake}/FindGTK3.cmake | 0 {cmake => OLD/cmake}/FindTinyXML.cmake | 0 {cmake => OLD/cmake}/PluginSetup.cmake.bak | 0 {extinclude => OLD/extinclude}/GLES2/gl2.h | 0 {extinclude => OLD/extinclude}/GLES2/gl2ext.h | 0 .../extinclude}/GLES2/gl2platform.h | 0 {extinclude => OLD/extinclude}/ODAPI.h | 0 .../extinclude}/ODJSONSchemas.h | 0 .../extinclude}/nlohmann/json-schema.hpp | 0 .../extinclude}/nlohmann/json.hpp | 0 libs/ODAPI/ODAPI.h | 224 ++ libs/ODAPI/ODJSONSchemas.h | 340 +++ libs/pluginDC/CMakeLists.txt | 119 + libs/pluginDC/include/TexFont.h | 77 + libs/pluginDC/include/linmath.h | 574 +++++ libs/pluginDC/include/pi_shaders.h | 47 + libs/pluginDC/include/pidc.h | 176 ++ libs/pluginDC/include/qtstylesheet.h | 3 + libs/pluginDC/src/TexFont.cpp | 411 ++++ libs/pluginDC/src/pi_shaders.cpp | 664 ++++++ libs/pluginDC/src/pidc.cpp | 1965 +++++++++++++++++ libs/pluginDC/src/qtstylesheet.cpp | 177 ++ po/POTFILES.in | 2 + po/POTFILES.in.test | 2 + 34 files changed, 5150 insertions(+), 18 deletions(-) rename .travis.yml => OLD/.travis.yml (100%) create mode 100644 OLD/CMakeLists.txt.bak rename Frontend2.md => OLD/Frontend2.md (100%) rename Read-Build.md => OLD/Read-Build.md (100%) create mode 100644 OLD/buildwin/zlib1.lib rename {ci => OLD/ci}/circleci-build-macos-new.sh (100%) rename {ci => OLD/ci}/circleci-build-trusty.sh (100%) rename {ci => OLD/ci}/travis-build-raspbian-armhf-part1.sh (100%) rename {ci => OLD/ci}/travis-build-raspbian-armhf-part2.sh (100%) rename {cmake => OLD/cmake}/FindGTK3.cmake (100%) rename {cmake => OLD/cmake}/FindTinyXML.cmake (100%) rename {cmake => OLD/cmake}/PluginSetup.cmake.bak (100%) rename {extinclude => OLD/extinclude}/GLES2/gl2.h (100%) rename {extinclude => OLD/extinclude}/GLES2/gl2ext.h (100%) rename {extinclude => OLD/extinclude}/GLES2/gl2platform.h (100%) rename {extinclude => OLD/extinclude}/ODAPI.h (100%) rename {extinclude => OLD/extinclude}/ODJSONSchemas.h (100%) rename {extinclude => OLD/extinclude}/nlohmann/json-schema.hpp (100%) rename {extinclude => OLD/extinclude}/nlohmann/json.hpp (100%) create mode 100644 libs/ODAPI/ODAPI.h create mode 100644 libs/ODAPI/ODJSONSchemas.h create mode 100644 libs/pluginDC/CMakeLists.txt create mode 100644 libs/pluginDC/include/TexFont.h create mode 100644 libs/pluginDC/include/linmath.h create mode 100644 libs/pluginDC/include/pi_shaders.h create mode 100644 libs/pluginDC/include/pidc.h create mode 100644 libs/pluginDC/include/qtstylesheet.h create mode 100644 libs/pluginDC/src/TexFont.cpp create mode 100644 libs/pluginDC/src/pi_shaders.cpp create mode 100644 libs/pluginDC/src/pidc.cpp create mode 100644 libs/pluginDC/src/qtstylesheet.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7fb68b48..4cfa00aa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,9 +54,9 @@ set(LONG_DESCRIPTION "WR features include: optimal routing subject to various co set(VERSION_MAJOR "1") set(VERSION_MINOR "15") -set(VERSION_PATCH "4") -set(VERSION_TWEAK "1") -set(VERSION_DATE "02/09/2023")#DD/MM/YYYY format +set(VERSION_PATCH "6") +set(VERSION_TWEAK "0") +set(VERSION_DATE "03/09/2023")#DD/MM/YYYY format set(OCPN_MIN_VERSION "ov58") set(OCPN_API_VERSION_MAJOR "1") set(OCPN_API_VERSION_MINOR "16") @@ -195,12 +195,12 @@ SET (HDRS include/navobj_util.h ) -set(EXTSRC -) -set(EXTINCLUDE - extinclude/ODAPI.h - extinclude/ODJSONSchemas.h -) +#set(EXTSRC +#) +#set(EXTINCLUDE +# extinclude/ODAPI.h +# extinclude/ODJSONSchemas.h +#) set(LIBSSRC libs/wxJSON/src/jsonreader.cpp libs/wxJSON/src/jsonval.cpp libs/wxJSON/src/jsonwriter.cpp) @@ -216,7 +216,7 @@ set(LIBHDRS add_definitions(-DPLUGIN_USE_SVG) -set(EXTINCLUDE_DIR ${EXTINCLUDE_DIR} extinclude libs/ocpn-api/) +#set(EXTINCLUDE_DIR ${EXTINCLUDE_DIR} extinclude libs/ocpn-api/) # ----- If using JSON validation in plugin section below is needed ----- ## @@ -233,9 +233,8 @@ set(EXTINCLUDE_DIR ${EXTINCLUDE_DIR} extinclude libs/ocpn-api/) ## This add_library can be used in conditionals below. ##================================================================================ - - -SET(SRC ${SRCS} ${HDRS} ${SRC_LIBTESS2} ) +SET(SRC ${SRCS} ${HDRS}) +##SET(SRC ${SRCS} ${HDRS} ${SRC_LIBTESS2} ) @@ -247,22 +246,24 @@ SET(SRC ${SRCS} ${HDRS} ${SRC_LIBTESS2} ) ##============================================================= include_directories(BEFORE ${PROJECT_SOURCE_DIR}/include) -include_directories(BEFORE ${PROJECT_SOURCE_DIR}/ocpninclude) +#include_directories(BEFORE ${PROJECT_SOURCE_DIR}/ocpninclude) #include_directories(BEFORE ${PROJECT_SOURCE_DIR}/ocpnsrc/glu/include) -include_directories(BEFORE ${PROJECT_SOURCE_DIR}/${EXTINCLUDE_DIR}) +#include_directories(BEFORE ${PROJECT_SOURCE_DIR}/${EXTINCLUDE_DIR}) + include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/) include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/GL) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/glu) #added with plugDC include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/ocpn-api) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/ODAPI) + include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/wxJSON/include) include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/pugixml) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/pluginDC) ## ## ----- Change above to match project requirements for android build ----- ## ## -#if(QT_ANDROID) -# include_directories( ${PROJECT_SOURCE_DIR}/extinclude/GLES2) -#endif(QT_ANDROID) ##================================================= target_sources(${PACKAGE_NAME} PUBLIC ${SRC}) @@ -275,8 +276,10 @@ if(NOT OCPN_FLATPAK_CONFIG) message(STATUS "${CMLOC}Adding target link libraries to ${PACKAGE_NAME}") add_subdirectory(libs/tinyxml) + add_subdirectory(libs/pluginDC) target_link_libraries(${PACKAGE_NAME} ocpn::tinyxml) + target_link_libraries(${PACKAGE_NAME} ocpn::pluginDC) endif(NOT OCPN_FLATPAK_CONFIG) add_definitions(-DTIXML_USE_STL) diff --git a/.travis.yml b/OLD/.travis.yml similarity index 100% rename from .travis.yml rename to OLD/.travis.yml diff --git a/OLD/CMakeLists.txt.bak b/OLD/CMakeLists.txt.bak new file mode 100644 index 00000000..2b1a99f4 --- /dev/null +++ b/OLD/CMakeLists.txt.bak @@ -0,0 +1,348 @@ +##--------------------------------------------------------------------------- +## Author: Sean d'Epagnier +##*************************************************************************** +## * Copyright (C) 2010 by Sean d'Epagnier * +## * This program is free software; you can redistribute it and/or modify * +## * it under the terms of the GNU General Public License as published by * +## * the Free Software Foundation; either version 2 of the License, or * +## * (at your option) any later version. * +## * * +## * This program is distributed in the hope that it will be useful, * +## * but WITHOUT ANY WARRANTY; without even the implied warranty of * +## * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +## * GNU General Public License for more details. * +## * * +## * You should have received a copy of the GNU General Public License * +## * along with this program; if not, write to the * +## * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, * +## * xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx * +#----------------------------------------------------------------------------- +# Frontend2 Author: Jon Gough TP v1.0.238.0 09/06/2023 DD/MM/YYYY format +# buildCI:yes useODAPI:no validateJSON:no +# --------------------------------------------------------------------------- +## ----- When changing this file do NOT change the order in which sections occur ----- ## +## ----- Changes should only be made between the section blocks that identify where ----- ## +## ----- these changes should be. The whole configuration process relies on this ----- ## +## ----- sequence to be successful ----- ## + +##----- Modify section below to include all the details for your plugin ----- ## + +set(CMLOC "CMakeLists: ") + +# define minimum cmake version +cmake_minimum_required(VERSION 3.5.1) +if(COMMAND cmake_policy) + if(POLICY CMP0043) + cmake_policy(SET CMP0043 NEW) + endif(POLICY CMP0043) + cmake_policy(SET CMP0048 NEW) +# Need cmake 3.13 to implement this, but raspbian builds are at 3.7.2 and bionic at 3.10 and xenial builds at 3.5.1 +# cmake_policy(SET CMP0076 NEW) + if(POLICY CMP0077) + cmake_policy(SET CMP0077 NEW) + endif(POLICY CMP0077) +endif(COMMAND cmake_policy) + +# define plugin name, owner and versions +set(VERBOSE_NAME "WeatherRouting") +set(COMMON_NAME "WeatherRouting") # Search "getcommonname"in .cpp +set(TITLE_NAME "weatherrouting") +set(PACKAGE_CONTACT "Sean d'Epagnier") +set(PACKAGE "weather_routing_pi") +set(SHORT_DESCRIPTION "Compute optimal routes based on weather and constraints.") +set(LONG_DESCRIPTION "WR features include: optimal routing subject to various constraints based on weather data, automatic boat polar computation.") + +set(VERSION_MAJOR "1") +set(VERSION_MINOR "14") +set(VERSION_PATCH "1") +set(VERSION_TWEAK "0") +set(VERSION_DATE "11/06/2023")#DD/MM/YYYY format +set(OCPN_MIN_VERSION "ov571") +set(OCPN_API_VERSION_MAJOR "1") +set(OCPN_API_VERSION_MINOR "16") +set(TP_COMMENT " * Release for O571 or o58 using CI") + +set(PARENT "opencpn") + +#Used to set up a local webserver with git loaded, for testing purposes. +#Now set in plugin configure, needed to build flatpak, also locally. +#set(GIT_REPOSITORY_SERVER "github.com") + +## Specifies Cloudsmith upload repository suffix for each catalog +set(PROD "prod") #Standard Repos +set(BETA "beta") #Standard Repos +set(ALPHA "alpha") #Standard Repos + +# Set if Cloudsmith Base Repository name does not match your Git Repository name. +#set(CLOUDSMITH_BASE_REPOSITORY "${GIT_REPOSITORY_NAME}") +#set(CLOUDSMITH_BASE_REPOSITORY "opencpn-plugins") #Ricks's customization +set(CLOUDSMITH_BASE_REPOSITORY "weather-routing") #without the _pi + +set(CLOUDSMITH_USER "opencpn") +#set(CLOUDSMITH_USER "rick-gleason") + +# Set Plugin info-url, summary and description +set(XML_INFO_URL "https://opencpn.org/OpenCPN/plugins/weatherroute.html") +set(XML_SUMMARY ${SHORT_DESCRIPTION}) +set(XML_DESCRIPTION ${LONG_DESCRIPTION}) + +## ----- Modify section above to include all the details for your plugin ----- ## +## ----- Modify section below if there are special requirements for the plugin ----- ## + +option(PLUGIN_USE_SVG "Use SVG graphics" ON) + +set(CMAKE_CXX_STANDARD 11) + +# Use local version of GLU library +# requires libs/glu directory +set(USE_LOCAL_GLU TRUE) +# Prefer libGL.so to libOpenGL.so, see CMP0072 +set(OpenGL_GL_PREFERENCE "LEGACY") #not operational +# Don't use local version of GLU library +#set(USE_LOCAL_GLU FALSE) #not operational + +option(USE_GL "Enable OpenGL support" ON) #WxRoute requires on +message(STATUS "${CMLOC}USE_GL: ${USE_GL}") + +if("${CMAKE_BUILD_TYPE}" STREQUAL "") + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose the type of build" FORCE) +endif("${CMAKE_BUILD_TYPE}" STREQUAL "") +set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "" "Debug" "Release" "RelWithDebInfo" "MinSizeRel") +message(STATUS "${CMLOC}Build type: ${CMAKE_BUILD_TYPE}") + +## ----- The statements below are used to setup standard variables that are required by the CMAKE process - do not remove ----- ## + +project(${PACKAGE}) + +set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") + +#======================================================== +include("PluginSetup") +#======================================================== +## ----- The above is used to setup standard variables that are required by the CMAKE process - do not remove ----- ## +## ----- Modify section below if there are special requirements for the plugin ----- ## + +set(CMAKE_VERBOSE_MAKEFILE "Activate verbose mode for make files" ON) + +option(Plugin_CXX11 "Use c++11" OFF) + +## ----- Modify section above if there are special requirements for the plugin ----- ## +## ----- do not change next section - needed to configure build process ----- ## +#=========================================================== +include("PluginConfigure") +#=========================================================== +## ----- do not change section above - needed to configure build process ----- ## +## ----- Change below to match project requirements for source, headers, etc. ----- ## + +add_definitions(-DUSE_S57) + +#======== Below from cmakelists.txt weather_routing_pi +# ----Remember to Add your project Set(SRCS and set(HDRS etc.. + +SET(SRCS + src/weather_routing_pi.cpp + src/WeatherRouting.cpp + src/ConfigurationDialog.cpp + src/SettingsDialog.cpp + src/PlotDialog.cpp + src/BoatDialog.cpp + src/StatisticsDialog.cpp + src/ReportDialog.cpp + src/FilterRoutesDialog.cpp + src/ConfigurationBatchDialog.cpp + src/EditPolarDialog.cpp + src/AboutDialog.cpp + src/Polar.cpp + src/Boat.cpp + src/RouteMap.cpp + src/RouteMapOverlay.cpp + src/Utilities.cpp + src/LineBufferOverlay.cpp + src/PolygonRegion.cpp + src/WeatherRoutingUI.cpp + src/icons.cpp + src/zuFile.cpp + src/georef.c + src/GribRecord.cpp +) + +SET (HDRS + include/weather_routing_pi.h + include/WeatherRouting.h + include/ConfigurationDialog.h + include/SettingsDialog.h + include/PlotDialog.h + include/BoatDialog.h + include/StatisticsDialog.h + include/ReportDialog.h + include/FilterRoutesDialog.h + include/ConfigurationBatchDialog.h + include/EditPolarDialog.h + include/AboutDialog.h + include/Polar.h + include/Boat.h + include/RouteMap.h + include/RouteMapOverlay.h + include/Utilities.h + include/LineBufferOverlay.h + include/PolygonRegion.h + include/WeatherRoutingUI.h + include/icons.h + include/zuFile.h + include/georef.h + include/GribRecord.h +) + +set(EXTSRC +) +set(EXTINCLUDE + extinclude/ODAPI.h + extinclude/ODJSONSchemas.h +) + +set(LIBSSRC libs/wxJSON/src/jsonreader.cpp libs/wxJSON/src/jsonval.cpp libs/wxJSON/src/jsonwriter.cpp) + +set(LIBHDRS + libs/GL/gl.h + libs/GL/gl_private.h + libs/GL/glext.h + libs/GL/glu.h + libs/wxJSON/include/json_defs.h + libs/wxJSON/include/jsonreader.h + libs/wxJSON/include/jsonval.h + libs/wxJSON/include/jsonwriter.h) + +add_definitions(-DPLUGIN_USE_SVG) + +set(EXTINCLUDE_DIR ${EXTINCLUDE_DIR} extinclude libs/ocpn-api/) + + +# ----- If using JSON validation in plugin section below is needed ----- ## + + +# Do not need Json Schema Validation + + +# ----- If using JSON validation in plugin section above is needed ----- ## + + +##================================================================================ +## Required to collect all the set( headers and SRCS - Adjust as required +## This add_library can be used in conditionals below. +##================================================================================ + + + +SET(SRC ${SRCS} ${HDRS} ${SRC_LIBTESS2} ) + + + +##========================================= + + +##============================================================= +# Modify/configure 'Include' Directories below for the Plugin +##============================================================= + +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/include) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/ocpninclude) +#include_directories(BEFORE ${PROJECT_SOURCE_DIR}/ocpnsrc/glu/include) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/${EXTINCLUDE_DIR}) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/GL) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/ocpn-api) +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/wxJSON/include) + +## +## ----- Change above to match project requirements for android build ----- ## +## + +#if(QT_ANDROID) +# include_directories( ${PROJECT_SOURCE_DIR}/extinclude/GLES2) +#endif(QT_ANDROID) + +##================================================= +target_sources(${PACKAGE_NAME} PUBLIC ${SRC}) +##================================================= + + + +if(NOT OCPN_FLATPAK_CONFIG) + # Build environment not available when flatpak is being configured so following statements will not work + message(STATUS "${CMLOC}Adding target link libraries to ${PACKAGE_NAME}") + + add_subdirectory(libs/tinyxml) + + target_link_libraries(${PACKAGE_NAME} ocpn::tinyxml) +endif(NOT OCPN_FLATPAK_CONFIG) + +add_definitions(-DTIXML_USE_STL) + +# +# ----- If using JSON validation in plugin section below is needed ----- ## +# + +# Do not need Json Schema Validation + + +# ----- If using JSON validation in plugin section above is needed ----- ## +# + +## +## ----- Change above to match project requirements ----- ## +## + +## +## ----- do not change next section - needed to configure build process ----- ## +## + +IF(NOT UNIX) + include_directories(src/zlib-1.2.3) + include_directories(libs/bzip2) + add_subdirectory(libs/bzip2) + target_link_libraries(${PACKAGE_NAME} ocpn::bzip2) +ENDIF(NOT UNIX) + +IF(WIN32) + IF(MSVC) + include_directories(${PROJECT_SOURCE_DIR}/buildwin/include) + target_link_libraries(${PACKAGE_NAME} "${PROJECT_SOURCE_DIR}/buildwin/zlib1.lib") + ELSE() + # MINGW + target_link_libraries(${PACKAGE_NAME} "-lz") + ENDIF() +ENDIF() + +#------- Change below to match project requirements -------------- + +# Needed for android builds +if(QT_ANDROID) + include_directories(BEFORE ${qt_android_include}) +endif(QT_ANDROID) + +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/jsoncpp) +add_subdirectory(libs/jsoncpp) +target_link_libraries(${PACKAGE_NAME} ${PACKAGE_NAME}_LIB_PLUGINJSON) + +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/plugingl/include) +add_subdirectory(libs/plugingl) +target_link_libraries(${PACKAGE_NAME} ocpn::plugingl) + +include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/libtess2/include) +add_subdirectory(libs/libtess2) +target_link_libraries(${PACKAGE_NAME} ocpn::libtess2) + +# Needed for all builds +# ----- Do not change - needed to build app ----- ## +#======================================================== +include("PluginInstall") +include("PluginLocalization") +include("PluginPackage") +#======================================================== +## ----- do not change section above - needed to configure build process ----- ## +## +message(STATUS "${CMLOC}include directories: ") +get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES) +foreach(dir ${dirs}) + message(STATUS "${CMLOC}dir='${dir}'") +endforeach() diff --git a/Frontend2.md b/OLD/Frontend2.md similarity index 100% rename from Frontend2.md rename to OLD/Frontend2.md diff --git a/Read-Build.md b/OLD/Read-Build.md similarity index 100% rename from Read-Build.md rename to OLD/Read-Build.md diff --git a/OLD/buildwin/zlib1.lib b/OLD/buildwin/zlib1.lib new file mode 100644 index 0000000000000000000000000000000000000000..bd6ba8824e509df085bd0787a681587e0538efd4 GIT binary patch literal 17152 zcmdU0%Ws@T5-&SIz=RM&c;!Lt#CbW18N+FLf_5Fri-v51ve4!JEthy!ro4`7q6`l_lQ-;A4?eD+~SDtC8v zb^pHZuCA`??{m}9Txs&^@rFZ<{_kMBU)EBaWI8iFy_~($004gn*m4VC+g*U|>i`Dd zWorHgfM|C;Q|}o7qQiHX_I(OKwEHU4uJ-_l_Ws1Q=VJh(mUozTbznWx-c3R`Fhy!< zVLJXj0MU_VrW2z8M29ak9s2-)=r}$z(Xqo!N52IiI&zb#_Y-_hq&~zU8a%+%bPs@N z$Ar+Am?HK6&NP60qK@@U2fqLy+K=NS>iU%_a|M9t&^S}ij{ro6ZZmcE0uc4!*oZn2 zlc?kIi{{Rv45oQTTJaAVZTUC*eB6Wd{&~y*O;16ABc7$4pH;#OpSN2 z9%<)IragnW-blOeG95*^m;h6xz8g$!m=XCv9qJ&7sj$n#ll28WV0iehKI|m;csz0*N&gL zG;%IGG%!AZ@`Y=2*|_oLs5D=godLhV_4#P3m|KV-Ycd}H)J)z~#d)qR%t$Mf@%XW% zR5`5#;$pNgRG3`AC(4!HFufP z#hW$ZozIp2V*22M*8`4GXH{A_98YpEH)(s~LRr1LD@erI8MK8@&R&}<6r-1lxoK3p zat`-5iBhF#9wltfufbW-D$M$IqJmoQY2@OJvLWl{xd+R^PQ3!xPcO~RMQCC)Rc>C{ zl2QJ|;?xvr>-3W5v<5fkob0{nC8wbECDe0j$Ek9slr0(MUoRENx=k-hM)^~wLUUR( zS1QabOi>ffY0Y1iF}-B6S~s`2fNO$n;#9fQ5py|JF3RBch-EQVF3QAQPL;bjqkPS2 z%~Wx5{wj4N8RgGM5vn3h9i_@GMb`^ti)h|Br!@;vu}FMQl{-5%g>z4Q&1p?E8&6K0 zC@)_qMU%0#=Co$AI6EKDzhpdqHdcVRhO&O$bpq!)%xYa!D$T~NB%}PvVw5W(j~i)T zYe@;aGx2C7r!_Q7T%$Ryq50q%&1ntKi1ZiF6Xm%!moG-8&JNmw6NQ4UpmF=rm2Tbr`+f)8VdvO zaHQX8fhIe_#qxW*0DjsF@bMmicUsV&#_}dC-$0_c?EB;B>mLCa zJpphT+kJ2hpaFS@G5r>u`kPqy3HG_E4`U9*xz_|Ru>;^sq~H57KLD^EV}>sdBHn(0 zU%LRVWB|qw0sPnla2wO!PQ=6fJxqUS19%_Pt(a~`-fyiKOJJMNsZBS)P&+;s@+Ppq zjsy72NWUY!g}kq^|2f2Z6XkEA>_;Sv&vS1lz-x^-518-3{OdRucd&dD^Mg3LQ&_37&y>JXVVIS;= zb{K_2&;x_e3@6}KH~?+X3VWdoGSClupc@9D0}et9tc9(x4KBcCcorUoO|S(<;5=-G z7vMQ~9{vPR!!s}j<8TRfz)pAtUWAAKuby=c+P0cwJO5Bo>sV&5dE+J6=+B!tsllW5lkm_2Y!{pVI z-Bw1@mrJ+;sR_SSp$Ii4SD-to50a-l+A(j0B!Jj(o!3lM~7G zr!Kv=X5ZW?IoN*0k@TZ|e>>?-RtRK#hdb$HCf)tAh{FqL+C&q@0O zhr!*LBI;~R;Z)q1w$4{{;rkobVH$-HUWI6V)V&uGF>hnKJY(uyCc8l1%v9X1(uS`& zd~xd&di+23fBW!DY(6w1`w1dcHh z;ec19vxphkrCsiCo#$svm(mc19Z5;Luu<#0{R>lX6Sq+K^@5GmuDoYra^NAn%Xf)@6FTi~WJ_*d7Ok0utUn=f(^-=$#YEiFje4;uzsDF)6pW8}iWO_=->=|56l zgK0mseI{}kLGiBvlm8;A9C7=h@w0kNH()$NzsJm=_Q2B{)*^>`qu+XrdVa}oJYSeB z&CbtGEi~>O+t)aJcH|sa`+wJAks4A5fZ+<|HsIffh9lHFp{Sq zJy<>HaQgw`N4=_?cwmIGMmZUhK?WF^F3TbQi}Xi+)H}YglM*HM7U9dCqz=WxML%2*Ar*dCmg63hx~FM@mS$%KbUJ3hy!aM{@ttf}|@rx7Exi-VrVL zF0|I!?Cg`tL=6PgKY(G}nD_5L9gpl$<3)k#7;4t?OiyJD8b%#j!{oJbDy(J3Ln>Hb z0Siy%G$S+LYxuMG45F=Z(Uwx7=;t4aHKJYq5TU4->VTL*RcVPbfss7yVstnlwQGVN zh>4NBfFpUtMPWzT45D_O>s&_Xo3@M#P zhwMRv#Y&~mA&kcfL&A$xbEbzxLerkdIa}voBo)mlM78^-v$Ab_4so7vaN=0cbY8nY zXF4k5Jc~H%9USuVEsV)kIhw9zP#O{CNe9J`9}J2`t`aY_hc-BP5{Foz+AU8&AD&7e zW$id@ZUsiP(ZP{;J@L!)T?=J$)s87Jcbi#f&Ui;hyaGr5+ zIJ!)MqfU3iHf+V2qc<{Yf9%D`gJXqu)N>A&9|Au(o(U)_jO}?JPh$NPSOMGjf`b)b z6Iqzr_io^%-Ap)m`QzL`r9ldKT3ccyz1*@OCRgolTE@nbCEv;z=Gx5kUGrWFow3^# zg}zs@5VfyMz-N5X!N3n*RtaUhi*h{`N?_$18AWa=?NCgv%9RhTNt0m2-;kM(YxfgE ze(w&(plj7M2+KrR6fy1;g!smGl`xtagD-6Ahu3D{H z<}}-g>#>J1&^}H&OI|ZVV8!=Z1lMh<*_Lz$MzPOe%%>PdXf0Y8LEgBU`LSqKu0_a8 z-|u30L7Ks<5+yWO2Ly%Q44Zy!u1bW^TphFssYVgPXtfylPG)t+afmVGZO?;agjSa_^zW-D;Q_A!RMay3t1vtEVnMh`QF zezIagYG04QDSL!blCHvvVjLw5d6R0VsCExD6VTsd4o3WTJH>ou0{0)s6FBK^#X>Rl zi3AeAlDES$xoY>!GJX)>`;Wz5B0=jqF!HGXIF`YkvH45A*o^f#a z`xOgha@CF}fOFQtNqu)2(1e$hIO*Qi1@!w|5-I+i$IO{E7FEt(Xzva?SSxl*8nArl zT|D}SPCKmHEni>`M-n*vb&~}%xhm%{bV^-tu + +enum { + EXCLUSION_BOUNDARY = 0, + INCLUSION_BOUNDARY, + NEITHER_BOUNDARY +}; + +enum { + TEXTPOINT_DISPLAY_TEXT_SHOW_ALWAYS = 0, + TEXTPOINT_DISPLAY_TEXT_SHOW_ON_ROLLOVER, + TEXTPOINT_DISPLAY_TEXT_SHOW_NEVER, + TEXTPOINT_DISPLAY_TEXT_SHOW_DEFAULT, + + TEXTPOINT_DISPLAY_TEXT_SHOW_LAST +}; + +enum { + TEXT_TOP = 0, + TEXT_CENTRE_TOP, + TEXT_BOTTOM, + TEXT_CENTRE_BOTTOM, + TEXT_CENTRE, + TEXT_RIGHT, + TEXT_LEFT, + TEXT_DEFAULT, + + TEXT_POSTION_LAST +}; + +enum { + TEXTPOINT_TEXT_BACKGROUND_TRANSPARANCY_DEFAULT = -1 +}; + +struct ODAPIVersion_t { + int ODAPIVersionMajor; + int ODAPIVersionMinor; + ODAPIVersion_t() : ODAPIVersionMajor(ODAPI_VERSION_MAJOR), ODAPIVersionMinor(ODAPI_VERSION_MINOR) {} +}; + +struct HyperLinkList_t { + wxString sDescription; + wxString sLink; + wxString sType; +}; + +struct FindPointInAnyBoundary_t { + double dLat; + double dLon; + wxString sBoundaryType; + wxString sBoundaryState; + wxString sName; + wxString sDescription; + wxString sGUID; + wxString sBoundaryObjectType; +}; + +struct FindClosestBoundaryLineCrossing_t { + double dStartLat; + double dStartLon; + double dEndLat; + double dEndLon; + double dCrossingLat; + double dCrossingLon; + double dCrossingDistance; + wxString sBoundaryType; + wxString sBoundaryState; + wxString sName; + wxString sDescription; + wxString sGUID; + wxString sBoundaryObjectType; +}; + +struct CreateBoundaryPoint_t : public ODAPIVersion_t { + wxString name; + wxString iconname; + double lat; + double lon; + int type; + bool visible; + bool ringsvisible; + int ringsnumber; + double ringssteps; + int ringsunits; + bool defaultRingColour; + wxColour ringscolour; + wxString GUID; + std::list BoundaryPointHyperLinkList; +}; + +struct DeleteBoundaryPoint_t : public ODAPIVersion_t { + wxString GUID; +}; + +struct CreateBoundary_t : public ODAPIVersion_t { + wxString name; + int type; + bool pathIsActive; + bool visible; + bool defaultLineColour; + wxColour lineColour; + bool defaultFillColour; + wxColour fillColour; + wxString GUID; + bool temporary; + std::list BoundaryPointsList; +}; + +struct DeleteBoundary_t : public ODAPIVersion_t { + wxString GUID; +}; + +struct CreateTextPoint_t : public ODAPIVersion_t{ + wxString name; //Point name + wxString iconname; //Icon Name + double lat; + double lon; + wxString description; + wxString TextToDisplay; + bool Visible; //Point visible + bool ShowName; //Show name + int TextPosition; //enum, i.e. TEXT_CENTRE + wxString TextColour; + wxString BackgroundColour; + int BackgroundTransparancy; + bool defaultFont; + wxFont TextFont; + int TextPointDisplayTextWhen; + bool defaultRangeRings; + bool ringsvisible; + int ringsnumber; + double ringssteps; + int ringsunits; + bool defaultRingColour; + wxString ringscolour; + wxString GUID; + std::list TextPointHyperLinkList; + bool temporary; +}; + +struct DeleteTextPoint_t : public ODAPIVersion_t { + wxString GUID; +}; + +struct AddPointIcon_t : ODAPIVersion_t { + wxBitmap PointIcon; + wxString PointIconName; + wxString PointIconDescription; +}; + +struct DeletePointIcon_t :ODAPIVersion_t { + wxString PointIconName; +}; + +class ODAPI +{ +public: + ODAPI(); + ~ODAPI(); + static bool OD_FindPathByGUID( wxString sGUID, wxString *sName, wxString *sDescription ); + static bool OD_FindPointInAnyBoundary( FindPointInAnyBoundary_t *pFPIAB ); + static bool OD_FindClosestBoundaryLineCrossing( FindClosestBoundaryLineCrossing_t *pFCBLC ); + static bool OD_FindFirstBoundaryLineCrossing( FindClosestBoundaryLineCrossing_t *pFCBLC ); + static bool OD_CreateBoundary( CreateBoundary_t *pCB ); + static bool OD_CreateBoundaryPoint( CreateBoundaryPoint_t *pCBP ); + static bool OD_CreateTextPoint( CreateTextPoint_t *pCTP ); + static bool OD_AddPointIcon( AddPointIcon_t *pAPI ); + static bool OD_DeletePointIcon( DeletePointIcon_t *pDPI ); + static bool OD_DeleteBoundary( DeleteBoundary_t *pDB ); + static bool OD_DeleteBoundaryPoint( DeleteBoundaryPoint_t *pDBP ); + static bool OD_DeleteTextPoint( DeleteTextPoint_t *pDTP ); + +protected: + +private: + +}; + +typedef bool (*OD_FindPathByGUID) (wxString, wxString *, wxString *); +typedef bool (*OD_FindPointInAnyBoundary) (FindPointInAnyBoundary_t *); +typedef bool (*OD_FindClosestBoundaryLineCrossing) (FindClosestBoundaryLineCrossing_t *); +typedef bool (*OD_FindFirstBoundaryLineCrossing) (FindClosestBoundaryLineCrossing_t *); +typedef bool (*OD_CreateBoundary) (CreateBoundary_t *); +typedef bool (*OD_CreateBoundaryPoint) (CreateBoundaryPoint_t *); +typedef bool (*OD_CreateTextPoint) (CreateTextPoint_t *); +typedef bool (*OD_AddPointIcon) (AddPointIcon_t *); +typedef bool (*OD_DeletePointIcon) (DeletePointIcon_t *); +typedef bool (*OD_DeleteBoundary) (DeleteBoundary_t *); +typedef bool (*OD_DeleteBoundaryPoint) (DeleteBoundaryPoint_t *); +typedef bool (*OD_DeleteTextPoint) (DeleteTextPoint_t *); + +#endif //_ODAPI_H_ diff --git a/libs/ODAPI/ODJSONSchemas.h b/libs/ODAPI/ODJSONSchemas.h new file mode 100644 index 00000000..0410d50c --- /dev/null +++ b/libs/ODAPI/ODJSONSchemas.h @@ -0,0 +1,340 @@ +/****************************************************************************** + * $Id: ocpn_draw_pi.h,v 1.0 2015/01/28 01:54:37 jongough Exp $ + * + * Project: OpenCPN + * Purpose: OpenCPN General Drawing Plugin + * Author: Jon Gough + * + *************************************************************************** + * Copyright (C) 2010 by David S. Register * + * $EMAIL$ * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + *************************************************************************** + */ + +/* The header file contains the schema for the JSON messages that are being used. However it relies on Draf7 of the JSON schema + * which is not fully implemented yet in a C++ library. The code is defined out that will use this as the implementation changes the + * ABI code of the executable and is then not compatible with OpenCPN. There is basic checking for schema compliance but + * it is not robust and it is possible to crash OpenCPN if the values are not valid. + * + */ + +static json jSchema = R"( +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "OD Schemas", + "definitions": { + "schemahead": { + "description": "Standalone for simple queries or required for complex internactions as a part of the message", + "type": "object", + "properties": { + "Msg": { + "description": "Message Name", + "enum": ["Version", "GetAPIAddresses", "CreateBoundaryPoint", "CreateBoundary", "CreateTextPoint", "DeleteTextPoint", "DeleteBoundaryPoint", "DeleteBoundary"] + }, + "Type": { + "description": "Type of Message", + "enum": ["Request","Response"] + }, + "Source": { + "description": "Source of message", + "type": "string" + }, + "MsgId": { + "description": "Message Name", + "type": "string" + } + }, + "required": ["Msg", "Type", "Source", "MsgId"], + "addtionalProperties": false + }, + "ODPoint": { + "description": "Generic OD Point", + "type": "object", + "properties" : { + "Name": { + "description": "Boundary Point Name", + "type": "string" + }, + "Lat": { + "description": "Latitude of Boundary Point", + "type": "number", + "minimum": -90, + "maximum": 90 + }, + "Lon": { + "description": "Longitude of Boundary Point", + "type": "number", + "minimum": -180, + "maximum": 180 + }, + "IconName": { + "description": "Boundary Point Icon Name", + "type": "string" + }, + "Visible": { + "description": "Visibility of Boundary Point", + "type": "boolean", + "default": false + }, + "RingsVisible": { + "description": "Visibility of Boundary Point Range Rings", + "type": "boolean", + "default": false + }, + "RingsNumber": { + "description": "Number of Boundary Point Rings", + "type": "number", + "minimum": 0, + "maximum": 10 + }, + "RingsSteps": { + "description": "Steps between Boundary Point Rings", + "type": "number", + "minimum": 0.0 + }, + "RingUnits": { + "description": "Boundary Point Range Ring Step Units", + "enum": [0,1,2,3,4,5,6,7,8,9,10] + }, + "RingsColour": { + "description": "Boundary Point Range Rings Colour", + "type": "string" + }, + "HyperLinks": { + "description": "Array of hyperlinks to local or internet documents", + "type": "array", + "Items": { + "allOf" : [ + { + "LinkDescription": { + "description": "Text description of hyper link", + "type": "string" + } + }, + { + "LinkURL": { + "description": "Actual Hyperlink", + "type": "string" + } + } + ] + } + } + }, + "required": [ + "Lat", + "Lon" + ] + }, + "boundarypoint": { + "description": "Used to create a boundary point", + "type": "object", + "properties": { + "items": { + "$ref": "#/definitions/ODPoint" + }, + "BoundaryPointType": { + "description": "Boundary Point Type", + "enum": ["Exclusion", "Inclusion", "Neither"] + } + }, + "required": [ + "BoundaryPointType" + ] + }, + "textpoint": { + "description": "Used to create a text point", + "type": "object", + "properties": { + "items": { + "$ref": "#/definitions/ODPoint" + }, + "Temporary": { + "description": "Text point life, false - exists over restart, true - non persistent", + "type": "boolean", + "default": false + }, + "GUID": { + "description": "GUID of Text Point", + "type": "string", + "optional": true + }, + "TextToDisplay": { + "description": "Text Point Text", + "type": "string" + }, + "TextPosition": { + "description": "Text Point Text Position", + "enum": [0,1,2,3,4,5,6] + }, + "TextColour": { + "description": "Text Point Text Colour", + "type": "string" + }, + "BackgroundColour": { + "description": "Text Point Text BackgroundColour", + "type": "string" + }, + "BackgroundTransparancy": { + "description": "Text Point Text BackgroundTransparancy", + "type": "number", + "minimum": 0, + "maximum": 255 + }, + "TextFont": { + "description": "Text Point Font", + "type": "string" + }, + "TextPointDisplayTextWhen": { + "description": "Text Point When To Display", + "type": "string" + } + } + }, + "ODObject": { + "description": "Used to delete an object", + "type": "object", + "properties": { + "GUID": { + "description": "GUID of object", + "type": "string" + } + }, + "required": [ + "GUID" + ] + }, + "PointIcon": { + "description": "Used to delete add an point icon", + "type": "object", + "properties": { + "PointIcon": { + "description": "Point Icon in Base64", + "type": "string", + "optional": false + }, + "PointIconName": { + "description": "Point Icon name", + "type": "string", + "optional": false + }, + "PointIconDescription": { + "description": "Point Icon Description", + "type": "string", + "optional": false + } + }, + "required": [ + "PointIcon", + "PointIconName", + "PointIconDescription" + ] + }, + "boundary": { + "description": "Used to create or modify a boundary", + "type": "object", + "properties": { + "BoundaryName": { + "description": "Boundary Name", + "type": "string" + }, + "BoundaryType": { + "description": "Boundary Type", + "enum": ["Exclusion","Inclusion","Neither"] + }, + "Active": { + "description": "Is Boundary Active", + "type": "boolean", + "boolean": true + }, + "Visible": { + "description": "Visibility of Boundary", + "type": "boolean", + "default": true + }, + "Temporary": { + "description": "Boundary life, false - exists over restart, true - non persistent", + "type": "boolean", + "default": false + }, + "BoundaryPoints": { + "description": "Array of boundary points needed to define a boundary", + "type": "array", + "items": { + "$ref": "#/definitions/boundarypoint" + }, + "minItems": 3, + "additionalItems": false + } + }, + "required": [ + "BoundaryPoints", + "BoundaryType" + ] + } + }, + "type": "object", + "allOf": [ + {"$ref": "#/definitions/schemahead"}, + { + "if": { "properties": {"Msg": {"const": "CreateBoundary"}} + }, + "then": { + "$ref": "#/definitions/boundary" + } + }, + { + "if": { "properties": {"Msg": {"const": "CreateBoundaryPoint"}} + }, + "then": { + "$ref": "#/definitions/boundarypoint" + } + }, + { + "if": { "properties": {"Msg": {"const": "CreateTextPoint"}} + }, + "then": { + "$ref": "#/definitions/textpoint" + } + }, + { + "if": { "properties": {"Msg": {"const": "DeleteTextPoint"}} + }, + "then": { + "$ref": "#/definitions/ODObject" + } + }, + { + "if": { "properties": {"Msg": {"const": "DeleteBoundaryPoint"}} + }, + "then": { + "$ref": "#/definitions/ODObject" + } + }, + { + "if": { "properties": {"Msg": {"const": "DeleteBoundary"}} + }, + "then": { + "$ref": "#/definitions/ODObject" + } + } + + ] +} +)"_json; + diff --git a/libs/pluginDC/CMakeLists.txt b/libs/pluginDC/CMakeLists.txt new file mode 100644 index 00000000..cb71999d --- /dev/null +++ b/libs/pluginDC/CMakeLists.txt @@ -0,0 +1,119 @@ +##--------------------------------------------------------------------------- +## Author: Sean D'Epagnier +## Copyright: +## License: GPLv3 +##--------------------------------------------------------------------------- + +if (TARGET ocpn::pluginDC) + return () +endif () + +set(SAVE_CMLOC_PLUGINDCL ${CMLOC}) +set(CMLOC "CMakeLists_PLUGINDC: ") + +message(STATUS "${CMLOC}Building PluginDC") +SET(SRC_PLUGINDC + src/pidc.cpp + src/pi_shaders.cpp + src/TexFont.cpp + src/qtstylesheet.cpp + ) + +if(UNIX) + add_definitions("-fpic") +endif(UNIX) + +# Needed for android builds +if (QT_ANDROID) + +# include_directories(BEFORE ${qt_android_include}) + message(STATUS "${CMLOC}Building PluginDC: qt_android_include: ${qt_android_include}") +# include_directories(${qt_android_include}) +# There is probably a much simpler way to do this... + IF(_wx_selected_config MATCHES "androideabi-qt-arm64") + # from bdbcat changes +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtCore") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtWidgets") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtGui") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtOpenGL") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtTest") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/wxWidgets/libarm64/wx/include/arm-linux-androideabi-qt-unicode-static-3.1") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/wxWidgets/include") + +# suggested by JG + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtCore") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtWidgets") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtGui") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtOpenGL") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/include/QtTest") + + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/wxWidgets/libarm64/wx/include/arm-linux-androideabi-qt-unicode-static-3.1") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/wxWidgets/include") + + SET(wxWidgets_LIBRARIES + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/lib/libQt5Core.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/lib/libQt5OpenGL.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/lib/libQt5Widgets.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/lib/libQt5Gui.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm64_O3/qtbase/lib/libQt5AndroidExtras.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/opencpn/API-117/libarm64/libgorp.so + + -lc++_shared + -lz + libGLESv2.so + libEGL.so + ) + + ELSE(_wx_selected_config MATCHES "androideabi-qt-arm64") +# from bdbcat changes +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtCore") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtWidgets") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtGui") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtOpenGL") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtTest") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/wxWidgets/libarmhf/wx/include/arm-linux-androideabi-qt-unicode-static-3.1") +# include_directories( "${CMAKE_SOURCE_DIR}/${OCPN_Android_Common}/wxWidgets/include") + + ADD_DEFINITIONS( -DOCPN_ARMHF ) + + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtCore") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtWidgets") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtGui") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtOpenGL") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/include/QtTest") + + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/wxWidgets/libarmhf/wx/include/arm-linux-androideabi-qt-unicode-static-3.1") + set(qt_android_include ${qt_android_include} "${OCPN_Android_Common}/wxWidgets/include") + + ADD_DEFINITIONS( -DOCPN_ARMHF ) + + SET(wxWidgets_LIBRARIES + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/lib/libQt5Core.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/lib/libQt5OpenGL.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/lib/libQt5Widgets.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/lib/libQt5Gui.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/qt5/build_arm32_19_O3/qtbase/lib/libQt5AndroidExtras.so + ${CMAKE_CURRENT_SOURCE_DIR}/${OCPN_Android_Common}/opencpn/API-117/libarmhf/libgorp.so + + -lc++_shared + -lz + libGLESv2.so + libEGL.so + ) + + ENDIF(_wx_selected_config MATCHES "androideabi-qt-arm64") + + + include_directories(${qt_android_include}) +endif(QT_ANDROID) + + +ADD_LIBRARY(${PACKAGE_NAME}_LIB_PLUGINDC STATIC ${SRC_PLUGINDC}) +target_include_directories(${PACKAGE_NAME}_LIB_PLUGINDC PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +add_library(ocpn::pluginDC ALIAS ${PACKAGE_NAME}_LIB_PLUGINDC) + +set(CMLOC ${SAVE_CMLOC_PLUGINDC}) diff --git a/libs/pluginDC/include/TexFont.h b/libs/pluginDC/include/TexFont.h new file mode 100644 index 00000000..74687ceb --- /dev/null +++ b/libs/pluginDC/include/TexFont.h @@ -0,0 +1,77 @@ +/*************************************************************************** + * + * Project: OpenCPN + * Purpose: OpenGL text rendering + * Author: Sean D'Epagnier + * + *************************************************************************** + * Copyright (C) 2014 Sean D'Epagnier * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + **************************************************************************/ + +#ifndef __TEXFONT_H__ +#define __TEXFONT_H__ + +/* support ascii plus degree symbol for now pack font in a single texture 16x8 */ +#define DEGREE_GLYPH 127 +#define MIN_GLYPH 32 +#define MAX_GLYPH 128 + +#define NUM_GLYPHS (MAX_GLYPH - MIN_GLYPH) + +#define COLS_GLYPHS 16 +#define ROWS_GLYPHS ((NUM_GLYPHS / COLS_GLYPHS)+1) + +struct TexGlyphInfo { + int x, y, width, height; + float advance; +}; + +class TexFont { +public: + TexFont(); + ~TexFont(); + + void Build( wxFont &font, bool blur = false ); + void Delete(); + + void GetTextExtent( const wxString &string, int *width, int *height); + void RenderString( const char *string, int x=0, int y=0 ); + void RenderString( const wxString &string, int x=0, int y=0 ); + bool IsBuilt(){ return m_built; } + void SetColor(wxColor &color){ m_color = color;} + +private: + void GetTextExtent( const char *string, int *width, int *height); + void RenderGlyph( int c ); + + wxFont m_font; + bool m_blur; + + TexGlyphInfo tgi[MAX_GLYPH]; + + unsigned int texobj; + int tex_w, tex_h; + int m_maxglyphw; + int m_maxglyphh; + bool m_built; + + float m_dx; + float m_dy; + wxColor m_color; +}; +#endif //guard diff --git a/libs/pluginDC/include/linmath.h b/libs/pluginDC/include/linmath.h new file mode 100644 index 00000000..5732a76a --- /dev/null +++ b/libs/pluginDC/include/linmath.h @@ -0,0 +1,574 @@ +#ifndef LINMATH_H +#define LINMATH_H + +#include + +#ifdef _MSC_VER +#define inline __inline +#endif + +#define LINMATH_H_DEFINE_VEC(n) \ +typedef float vec##n[n]; \ +static inline void vec##n##_add(vec##n r, vec##n const a, vec##n const b) \ +{ \ + int i; \ + for(i=0; i 1e-4) { + mat4x4 T, C, S; + + vec3_norm(u, u); + mat4x4_from_vec3_mul_outer(T, u, u); + + S[1][2] = u[0]; + S[2][1] = -u[0]; + S[2][0] = u[1]; + S[0][2] = -u[1]; + S[0][1] = u[2]; + S[1][0] = -u[2]; + + mat4x4_scale(S, S, s); + + mat4x4_identity(C); + mat4x4_sub(C, C, T); + + mat4x4_scale(C, C, c); + + mat4x4_add(T, T, C); + mat4x4_add(T, T, S); + + T[3][3] = 1.; + mat4x4_mul(R, M, T); + } else { + mat4x4_dup(R, M); + } +} +static inline void mat4x4_rotate_X(mat4x4 Q, mat4x4 M, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = { + {1.f, 0.f, 0.f, 0.f}, + {0.f, c, s, 0.f}, + {0.f, -s, c, 0.f}, + {0.f, 0.f, 0.f, 1.f} + }; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_rotate_Y(mat4x4 Q, mat4x4 M, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = { + { c, 0.f, s, 0.f}, + { 0.f, 1.f, 0.f, 0.f}, + { -s, 0.f, c, 0.f}, + { 0.f, 0.f, 0.f, 1.f} + }; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = { + { c, s, 0.f, 0.f}, + { -s, c, 0.f, 0.f}, + { 0.f, 0.f, 1.f, 0.f}, + { 0.f, 0.f, 0.f, 1.f} + }; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_invert(mat4x4 T, mat4x4 M) +{ + float idet; + float s[6]; + float c[6]; + s[0] = M[0][0]*M[1][1] - M[1][0]*M[0][1]; + s[1] = M[0][0]*M[1][2] - M[1][0]*M[0][2]; + s[2] = M[0][0]*M[1][3] - M[1][0]*M[0][3]; + s[3] = M[0][1]*M[1][2] - M[1][1]*M[0][2]; + s[4] = M[0][1]*M[1][3] - M[1][1]*M[0][3]; + s[5] = M[0][2]*M[1][3] - M[1][2]*M[0][3]; + + c[0] = M[2][0]*M[3][1] - M[3][0]*M[2][1]; + c[1] = M[2][0]*M[3][2] - M[3][0]*M[2][2]; + c[2] = M[2][0]*M[3][3] - M[3][0]*M[2][3]; + c[3] = M[2][1]*M[3][2] - M[3][1]*M[2][2]; + c[4] = M[2][1]*M[3][3] - M[3][1]*M[2][3]; + c[5] = M[2][2]*M[3][3] - M[3][2]*M[2][3]; + + /* Assumes it is invertible */ + idet = 1.0f/( s[0]*c[5]-s[1]*c[4]+s[2]*c[3]+s[3]*c[2]-s[4]*c[1]+s[5]*c[0] ); + + T[0][0] = ( M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; + T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; + T[0][2] = ( M[3][1] * s[5] - M[3][2] * s[4] + M[3][3] * s[3]) * idet; + T[0][3] = (-M[2][1] * s[5] + M[2][2] * s[4] - M[2][3] * s[3]) * idet; + + T[1][0] = (-M[1][0] * c[5] + M[1][2] * c[2] - M[1][3] * c[1]) * idet; + T[1][1] = ( M[0][0] * c[5] - M[0][2] * c[2] + M[0][3] * c[1]) * idet; + T[1][2] = (-M[3][0] * s[5] + M[3][2] * s[2] - M[3][3] * s[1]) * idet; + T[1][3] = ( M[2][0] * s[5] - M[2][2] * s[2] + M[2][3] * s[1]) * idet; + + T[2][0] = ( M[1][0] * c[4] - M[1][1] * c[2] + M[1][3] * c[0]) * idet; + T[2][1] = (-M[0][0] * c[4] + M[0][1] * c[2] - M[0][3] * c[0]) * idet; + T[2][2] = ( M[3][0] * s[4] - M[3][1] * s[2] + M[3][3] * s[0]) * idet; + T[2][3] = (-M[2][0] * s[4] + M[2][1] * s[2] - M[2][3] * s[0]) * idet; + + T[3][0] = (-M[1][0] * c[3] + M[1][1] * c[1] - M[1][2] * c[0]) * idet; + T[3][1] = ( M[0][0] * c[3] - M[0][1] * c[1] + M[0][2] * c[0]) * idet; + T[3][2] = (-M[3][0] * s[3] + M[3][1] * s[1] - M[3][2] * s[0]) * idet; + T[3][3] = ( M[2][0] * s[3] - M[2][1] * s[1] + M[2][2] * s[0]) * idet; +} +static inline void mat4x4_orthonormalize(mat4x4 R, mat4x4 M) +{ + float s = 1.; + vec3 h; + + mat4x4_dup(R, M); + vec3_norm(R[2], R[2]); + + s = vec3_mul_inner(R[1], R[2]); + vec3_scale(h, R[2], s); + vec3_sub(R[1], R[1], h); + vec3_norm(R[2], R[2]); + + s = vec3_mul_inner(R[1], R[2]); + vec3_scale(h, R[2], s); + vec3_sub(R[1], R[1], h); + vec3_norm(R[1], R[1]); + + s = vec3_mul_inner(R[0], R[1]); + vec3_scale(h, R[1], s); + vec3_sub(R[0], R[0], h); + vec3_norm(R[0], R[0]); +} + +static inline void mat4x4_frustum(mat4x4 M, float l, float r, float b, float t, float n, float f) +{ + M[0][0] = 2.f*n/(r-l); + M[0][1] = M[0][2] = M[0][3] = 0.f; + + M[1][1] = 2.f*n/(t-b); + M[1][0] = M[1][2] = M[1][3] = 0.f; + + M[2][0] = (r+l)/(r-l); + M[2][1] = (t+b)/(t-b); + M[2][2] = -(f+n)/(f-n); + M[2][3] = -1.f; + + M[3][2] = -2.f*(f*n)/(f-n); + M[3][0] = M[3][1] = M[3][3] = 0.f; +} +static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, float n, float f) +{ + M[0][0] = 2.f/(r-l); + M[0][1] = M[0][2] = M[0][3] = 0.f; + + M[1][1] = 2.f/(t-b); + M[1][0] = M[1][2] = M[1][3] = 0.f; + + M[2][2] = -2.f/(f-n); + M[2][0] = M[2][1] = M[2][3] = 0.f; + + M[3][0] = -(r+l)/(r-l); + M[3][1] = -(t+b)/(t-b); + M[3][2] = -(f+n)/(f-n); + M[3][3] = 1.f; +} +static inline void mat4x4_perspective(mat4x4 m, float y_fov, float aspect, float n, float f) +{ + /* NOTE: Degrees are an unhandy unit to work with. + * linmath.h uses radians for everything! */ + float const a = 1.f / (float) tan(y_fov / 2.f); + + m[0][0] = a / aspect; + m[0][1] = 0.f; + m[0][2] = 0.f; + m[0][3] = 0.f; + + m[1][0] = 0.f; + m[1][1] = a; + m[1][2] = 0.f; + m[1][3] = 0.f; + + m[2][0] = 0.f; + m[2][1] = 0.f; + m[2][2] = -((f + n) / (f - n)); + m[2][3] = -1.f; + + m[3][0] = 0.f; + m[3][1] = 0.f; + m[3][2] = -((2.f * f * n) / (f - n)); + m[3][3] = 0.f; +} +static inline void mat4x4_look_at(mat4x4 m, vec3 eye, vec3 center, vec3 up) +{ + /* Adapted from Android's OpenGL Matrix.java. */ + /* See the OpenGL GLUT documentation for gluLookAt for a description */ + /* of the algorithm. We implement it in a straightforward way: */ + + /* TODO: The negation of of can be spared by swapping the order of + * operands in the following cross products in the right way. */ + vec3 f; + vec3 s; + vec3 t; + + vec3_sub(f, center, eye); + vec3_norm(f, f); + + vec3_mul_cross(s, f, up); + vec3_norm(s, s); + + vec3_mul_cross(t, s, f); + + m[0][0] = s[0]; + m[0][1] = t[0]; + m[0][2] = -f[0]; + m[0][3] = 0.f; + + m[1][0] = s[1]; + m[1][1] = t[1]; + m[1][2] = -f[1]; + m[1][3] = 0.f; + + m[2][0] = s[2]; + m[2][1] = t[2]; + m[2][2] = -f[2]; + m[2][3] = 0.f; + + m[3][0] = 0.f; + m[3][1] = 0.f; + m[3][2] = 0.f; + m[3][3] = 1.f; + + mat4x4_translate_in_place(m, -eye[0], -eye[1], -eye[2]); +} + +typedef float quat[4]; +static inline void quat_identity(quat q) +{ + q[0] = q[1] = q[2] = 0.f; + q[3] = 1.f; +} +static inline void quat_add(quat r, quat a, quat b) +{ + int i; + for(i=0; i<4; ++i) + r[i] = a[i] + b[i]; +} +static inline void quat_sub(quat r, quat a, quat b) +{ + int i; + for(i=0; i<4; ++i) + r[i] = a[i] - b[i]; +} +static inline void quat_mul(quat r, quat p, quat q) +{ + vec3 w; + vec3_mul_cross(r, p, q); + vec3_scale(w, p, q[3]); + vec3_add(r, r, w); + vec3_scale(w, q, p[3]); + vec3_add(r, r, w); + r[3] = p[3]*q[3] - vec3_mul_inner(p, q); +} +static inline void quat_scale(quat r, quat v, float s) +{ + int i; + for(i=0; i<4; ++i) + r[i] = v[i] * s; +} +static inline float quat_inner_product(quat a, quat b) +{ + float p = 0.f; + int i; + for(i=0; i<4; ++i) + p += b[i]*a[i]; + return p; +} +static inline void quat_conj(quat r, quat q) +{ + int i; + for(i=0; i<3; ++i) + r[i] = -q[i]; + r[3] = q[3]; +} +static inline void quat_rotate(quat r, float angle, vec3 axis) { + int i; + vec3 v; + vec3_scale(v, axis, sinf(angle / 2)); + for(i=0; i<3; ++i) + r[i] = v[i]; + r[3] = cosf(angle / 2); +} +#define quat_norm vec4_norm +static inline void quat_mul_vec3(vec3 r, quat q, vec3 v) +{ +/* + * Method by Fabian 'ryg' Giessen (of Farbrausch) +t = 2 * cross(q.xyz, v) +v' = v + q.w * t + cross(q.xyz, t) + */ + vec3 t = {q[0], q[1], q[2]}; + vec3 u = {q[0], q[1], q[2]}; + + vec3_mul_cross(t, t, v); + vec3_scale(t, t, 2); + + vec3_mul_cross(u, u, t); + vec3_scale(t, t, q[3]); + + vec3_add(r, v, t); + vec3_add(r, r, u); +} +static inline void mat4x4_from_quat(mat4x4 M, quat q) +{ + float a = q[3]; + float b = q[0]; + float c = q[1]; + float d = q[2]; + float a2 = a*a; + float b2 = b*b; + float c2 = c*c; + float d2 = d*d; + + M[0][0] = a2 + b2 - c2 - d2; + M[0][1] = 2.f*(b*c + a*d); + M[0][2] = 2.f*(b*d - a*c); + M[0][3] = 0.f; + + M[1][0] = 2*(b*c - a*d); + M[1][1] = a2 - b2 + c2 - d2; + M[1][2] = 2.f*(c*d + a*b); + M[1][3] = 0.f; + + M[2][0] = 2.f*(b*d + a*c); + M[2][1] = 2.f*(c*d - a*b); + M[2][2] = a2 - b2 - c2 + d2; + M[2][3] = 0.f; + + M[3][0] = M[3][1] = M[3][2] = 0.f; + M[3][3] = 1.f; +} + +static inline void mat4x4o_mul_quat(mat4x4 R, mat4x4 M, quat q) +{ +/* XXX: The way this is written only works for othogonal matrices. */ +/* TODO: Take care of non-orthogonal case. */ + quat_mul_vec3(R[0], q, M[0]); + quat_mul_vec3(R[1], q, M[1]); + quat_mul_vec3(R[2], q, M[2]); + + R[3][0] = R[3][1] = R[3][2] = 0.f; + R[3][3] = 1.f; +} +static inline void quat_from_mat4x4(quat q, mat4x4 M) +{ + float r=0.f; + int i; + + int perm[] = { 0, 1, 2, 0, 1 }; + int *p = perm; + + for(i = 0; i<3; i++) { + float m = M[i][i]; + if( m < r ) + continue; + m = r; + p = &perm[i]; + } + + r = (float) sqrt(1.f + M[p[0]][p[0]] - M[p[1]][p[1]] - M[p[2]][p[2]] ); + + if(r < 1e-6) { + q[0] = 1.f; + q[1] = q[2] = q[3] = 0.f; + return; + } + + q[0] = r/2.f; + q[1] = (M[p[0]][p[1]] - M[p[1]][p[0]])/(2.f*r); + q[2] = (M[p[2]][p[0]] - M[p[0]][p[2]])/(2.f*r); + q[3] = (M[p[2]][p[1]] - M[p[1]][p[2]])/(2.f*r); +} + +#endif diff --git a/libs/pluginDC/include/pi_shaders.h b/libs/pluginDC/include/pi_shaders.h new file mode 100644 index 00000000..9a7bacdc --- /dev/null +++ b/libs/pluginDC/include/pi_shaders.h @@ -0,0 +1,47 @@ +/*************************************************************************** + * + * Project: OpenCPN + * + *************************************************************************** + * Copyright (C) 2017 by David S. Register * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + **************************************************************************/ + +#ifndef __PISHADERS_H__ +#define __PISHADERS_H__ + +#include "wx/wxprec.h" +#ifndef WX_PRECOMP +#include "wx/wx.h" +#endif //precompiled headers + +#ifdef USE_ANDROID_GLES2 +#include "GLES2/gl2.h" +#endif + + extern GLint pi_color_tri_shader_program; + extern GLint pi_colorv_tri_shader_program; + extern GLint pi_texture_2D_shader_program; + extern GLint pi_texture_2DA_shader_program; + extern GLint pi_texture_text_shader_program; + extern GLint pi_circle_filled_shader_program; + + +bool pi_loadShaders(); +void configureShaders(float width, float height); + +#endif diff --git a/libs/pluginDC/include/pidc.h b/libs/pluginDC/include/pidc.h new file mode 100644 index 00000000..9d91f35a --- /dev/null +++ b/libs/pluginDC/include/pidc.h @@ -0,0 +1,176 @@ +/****************************************************************************** + * + * Project: OpenCPN + * Purpose: Layer to use wxDC or opengl + * Author: Sean D'Epagnier + * + *************************************************************************** + * Copyright (C) 2011 by Sean D'Epagnier * + * sean at depagnier dot com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + *************************************************************************** + * + *f + */ + + +#ifndef __PIDC_H__ +#define __PIDC_H__ + +#include +#include "linmath.h" + +#include "TexFont.h" +#include "ocpn_plugin.h" + + +#ifdef ocpnUSE_GL +#include +#endif + +#ifndef DECL_EXP +#ifdef __WXMSW__ +# define DECL_EXP __declspec(dllexport) +#else +# ifdef __GNUC__ +# define DECL_EXP __attribute__((visibility("default"))) +#else +# define DECL_EXP +# endif +#endif +#endif + +void DrawGLThickLine( float x1, float y1, float x2, float y2, wxPen pen, bool b_hiqual ); + +//---------------------------------------------------------------------------- +// piDC +//---------------------------------------------------------------------------- + +class wxGLCanvas; +class GLUtesselator; + +class piDC +{ +public: + piDC(wxGLCanvas &canvas); + piDC(wxDC &pdc); + piDC(); + + ~piDC(); + + void SetBackground( const wxBrush &brush ); + void SetPen( const wxPen &pen); + void SetBrush( const wxBrush &brush); + void SetTextForeground(const wxColour &colour); + void SetTextBackground(const wxColour &colour); + void SetFont(const wxFont& font); + static void SetGLAttrs( bool highQuality ); + void SetGLStipple() const; + void SetVP(PlugIn_ViewPort *vp); + void SetDC(wxDC *dc_in){dc = dc_in;} + + const wxPen& GetPen() const; + const wxBrush& GetBrush() const; + const wxFont& GetFont() const; + + void GetSize(wxCoord *width, wxCoord *height) const; + + void DrawLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, bool b_hiqual = true); + void DrawLines( int n, wxPoint points[], wxCoord xoffset = 0, wxCoord yoffset = 0, bool b_hiqual = true); + + void StrokeLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2); + void StrokeLine( wxPoint a, wxPoint b) { StrokeLine(a.x, a.y, b.x, b.y); } + void StrokeLines( int n, wxPoint *points); + + void Clear(); + void DrawRectangle( wxCoord x, wxCoord y, wxCoord w, wxCoord h ); + void DrawRoundedRectangle( wxCoord x, wxCoord y, wxCoord w, wxCoord h, wxCoord rr ); + void DrawCircle(wxCoord x, wxCoord y, wxCoord radius); + void DrawCircle(const wxPoint &pt, wxCoord radius) { DrawCircle(pt.x, pt.y, radius); } + void StrokeCircle(wxCoord x, wxCoord y, wxCoord radius); + + void DrawEllipse(wxCoord x, wxCoord y, wxCoord width, wxCoord height); + void DrawPolygon(int n, wxPoint points[], wxCoord xoffset = 0, wxCoord yoffset = 0, float scale =1.0, float angle = 0.0); + void StrokePolygon(int n, wxPoint points[], wxCoord xoffset = 0, wxCoord yoffset = 0, float scale = 1.0); + + void DrawBitmap(const wxBitmap &bitmap, wxCoord x, wxCoord y, bool usemask); + + void DrawText(const wxString &text, wxCoord x, wxCoord y); + void GetTextExtent(const wxString &string, wxCoord *w, wxCoord *h, wxCoord *descent = NULL, + wxCoord *externalLeading = NULL, wxFont *font = NULL); + + void ResetBoundingBox(); + void CalcBoundingBox(wxCoord x, wxCoord y); + + void DestroyClippingRegion() {} + + wxDC *GetDC() const { return dc; } + + void DrawGLLineArray( int n, float *vertex_array, unsigned char *color_array, bool b_hiqual ); + void DrawGLLineArray( int n, float *vertex_array, float *color_array, bool b_hiqual ); + +#ifdef ocpnUSE_GL + GLfloat *s_odc_tess_work_buf; +#endif + + #ifdef USE_ANDROID_GLES2 + int s_odc_tess_vertex_idx; + int s_odc_tess_vertex_idx_this; + int s_odc_tess_buf_len; + GLenum s_odc_tess_mode; + int s_odc_nvertex; + vec4 s_odc_tess_color; + //ViewPort *s_odc_tessVP; + GLUtesselator *m_tobj; + + #endif + +protected: + bool ConfigurePen(); + bool ConfigureBrush(); + + void GLDrawBlendData(wxCoord x, wxCoord y, wxCoord w, wxCoord h, + int format, const unsigned char *data); + + void drawrrhelperGLES2( wxCoord x0, wxCoord y0, wxCoord r, int quadrant, int steps ); + + wxGLCanvas *glcanvas; + wxDC *dc; + wxPen m_pen; + wxBrush m_brush; + wxColour m_textforegroundcolour; + wxColour m_textbackgroundcolour; + wxFont m_font; + +#ifdef ocpnUSE_GL + TexFont m_texfont; +#endif + bool m_buseTex; + +#if wxUSE_GRAPHICS_CONTEXT + wxGraphicsContext *pgc; +#endif + + float *workBuf; + size_t workBufSize; + unsigned int workBufIndex; + + wxSize m_vpSize; + +}; + +#endif diff --git a/libs/pluginDC/include/qtstylesheet.h b/libs/pluginDC/include/qtstylesheet.h new file mode 100644 index 00000000..c2315572 --- /dev/null +++ b/libs/pluginDC/include/qtstylesheet.h @@ -0,0 +1,3 @@ +#ifdef __OCPN__ANDROID__ +extern QString qtStyleSheet; +#endif diff --git a/libs/pluginDC/src/TexFont.cpp b/libs/pluginDC/src/TexFont.cpp new file mode 100644 index 00000000..df988beb --- /dev/null +++ b/libs/pluginDC/src/TexFont.cpp @@ -0,0 +1,411 @@ +/*************************************************************************** + * + * Project: OpenCPN + * Purpose: texture OpenGL text rendering built from wxFont + * Author: Sean D'Epagnier + * + *************************************************************************** + * Copyright (C) 2014 Sean D'Epagnier * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + **************************************************************************/ +#include + +#ifdef __OCPN__ANDROID__ +#include "qdebug.h" +#endif + +#include "TexFont.h" + +#if ocpnUSE_GL + +#ifdef USE_ANDROID_GLES2 +#include "GLES2/gl2.h" +#include "linmath.h" +#include "pi_shaders.h" +#else +#include "GL/gl.h" +#endif + +TexFont::TexFont( ) +{ + texobj = 0; + m_blur = false; + m_built = false; + m_color = wxColor(0,0,0); +} + +TexFont::~TexFont( ) +{ + Delete( ); +} + + +void TexFont::Build( wxFont &font, bool blur ) +{ + /* avoid rebuilding if the parameters are the same */ + if(font == m_font && blur == m_blur) + return; + + m_font = font; + m_blur = blur; + + m_maxglyphw = 0; + m_maxglyphh = 0; + + wxScreenDC sdc; + + sdc.SetFont( font ); + + for( int i = MIN_GLYPH; i < MAX_GLYPH; i++ ) { + wxCoord gw, gh; + wxString text; + if(i == DEGREE_GLYPH) + text = wxString::Format(_T("%c"), 0x00B0); //_T("°"); + else + text = wxString::Format(_T("%c"), i); + wxCoord descent, exlead; + sdc.GetTextExtent( text, &gw, &gh, &descent, &exlead, &font ); // measure the text + + tgi[i].width = gw; + tgi[i].height = gh; + + tgi[i].advance = gw; + + + m_maxglyphw = wxMax(tgi[i].width, m_maxglyphw); + m_maxglyphh = wxMax(tgi[i].height, m_maxglyphh); + } + + /* add extra pixel to give a border between rows of characters + without this, in some cases a faint line can be see on the edge + from the character above */ + m_maxglyphh++; + + int w = COLS_GLYPHS * m_maxglyphw; + int h = ROWS_GLYPHS * m_maxglyphh; + + wxASSERT(w < 2048 && h < 2048); + + /* make power of 2 */ + for(tex_w = 1; tex_w < w; tex_w *= 2); + for(tex_h = 1; tex_h < h; tex_h *= 2); + + wxBitmap tbmp(tex_w, tex_h); + wxMemoryDC dc; + dc.SelectObject(tbmp); + dc.SetFont( font ); + + /* fill bitmap with black */ + dc.SetBackground( wxBrush( wxColour( 0, 0, 0 ) ) ); + dc.Clear(); + + /* draw the text white */ + dc.SetTextForeground( wxColour( 255, 255, 255 ) ); + + /* wxPen pen(wxColour( 255, 255, 255 )); + wxBrush brush(wxColour( 255, 255, 255 ), wxTRANSPARENT); + dc.SetPen(pen); + dc.SetBrush(brush); + */ + int row = 0, col = 0; + for( int i = MIN_GLYPH; i < MAX_GLYPH; i++ ) { + if(col == COLS_GLYPHS) { + col = 0; + row++; + } + + tgi[i].x = col * m_maxglyphw; + tgi[i].y = row * m_maxglyphh; + + wxString text; + if(i == DEGREE_GLYPH) + text = wxString::Format(_T("%c"), 0x00B0); //_T("°"); + else + text = wxString::Format(_T("%c"), i); + + dc.DrawText(text, tgi[i].x, tgi[i].y ); + +// dc.DrawRectangle(tgi[i].x, tgi[i].y, tgi[i].advance, tgi[i].height); + col++; + } + + dc.SelectObject(wxNullBitmap); + + wxImage image = tbmp.ConvertToImage(); + + GLuint format, internalformat; + int stride; + + format = GL_ALPHA; + internalformat = format; + stride = 1; + + if( m_blur ) + image = image.Blur(1); + + unsigned char *imgdata = image.GetData(); + + if(imgdata){ + unsigned char *teximage = (unsigned char *) malloc( stride * tex_w * tex_h ); + + for( int j = 0; j < tex_w*tex_h; j++ ) + for( int k = 0; k < stride; k++ ) + teximage[j * stride + k] = imgdata[3*j]; + + Delete(); + + glGenTextures( 1, &texobj ); + glBindTexture( GL_TEXTURE_2D, texobj ); + + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST/*GL_LINEAR*/ ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + + glTexImage2D( GL_TEXTURE_2D, 0, internalformat, tex_w, tex_h, 0, + format, GL_UNSIGNED_BYTE, teximage ); + + free(teximage); + } + + m_built = true; +} + +void TexFont::Delete( ) +{ + if (texobj) { + glDeleteTextures(1, &texobj); + texobj = 0; + } +} + +void TexFont::GetTextExtent(const char *string, int *width, int *height) +{ + int w=0, h=0; + + for(int i = 0; string[i]; i++ ) { + unsigned char c = string[i]; + if(c == '\n') { + h += tgi[(int)'A'].height; + continue; + } + if(c == 0xc2 && (unsigned char)string[i+1] == 0xb0) { + c = DEGREE_GLYPH; + i++; + } + if( c < MIN_GLYPH || c >= MAX_GLYPH) + continue; + + TexGlyphInfo &tgisi = tgi[c]; + w += tgisi.advance; + if(tgisi.height > h) + h = tgisi.height; + } + if(width) *width = w; + if(height) *height = h; +} + +void TexFont::GetTextExtent(const wxString &string, int *width, int *height) +{ + GetTextExtent((const char*)string.ToUTF8(), width, height); +} + +void TexFont::RenderGlyph( int c ) +{ + + if( c < MIN_GLYPH || c >= MAX_GLYPH) + return; + + TexGlyphInfo &tgic = tgi[c]; + + int x = tgic.x, y = tgic.y; + float w = m_maxglyphw, h = m_maxglyphh; + float tx1 = (float)x / (float)tex_w; + float tx2 = (float)(x + w) / (float)tex_w; + float ty1 = (float)y / (float)tex_h; + float ty2 = (float)(y + h) / (float)tex_h; + +#ifndef USE_ANDROID_GLES2 + + glBegin( GL_QUADS ); + + glTexCoord2f( tx1, ty1 ); glVertex2i( 0, 0 ); + glTexCoord2f( tx2, ty1 ); glVertex2i( w, 0 ); + glTexCoord2f( tx2, ty2 ); glVertex2i( w, h ); + glTexCoord2f( tx1, ty2 ); glVertex2i( 0, h ); + + glEnd(); + glTranslatef( tgic.advance, 0.0, 0.0 ); +#else + + float uv[8]; + float coords[8]; + + //normal uv + uv[0] = tx1; uv[1] = ty1; uv[2] = tx2; uv[3] = ty1; + uv[4] = tx2; uv[5] = ty2; uv[6] = tx1; uv[7] = ty2; + + // pixels + coords[0] = 0; coords[1] = 0; coords[2] = w; coords[3] = 0; + coords[4] = w; coords[5] = h; coords[6] = 0; coords[7] = h; + + glUseProgram( pi_texture_text_shader_program ); + + // Get pointers to the attributes in the program. + GLint mPosAttrib = glGetAttribLocation( pi_texture_text_shader_program, "aPos" ); + GLint mUvAttrib = glGetAttribLocation( pi_texture_text_shader_program, "aUV" ); + + // Set up the texture sampler to texture unit 0 + GLint texUni = glGetUniformLocation( pi_texture_text_shader_program, "uTex" ); + glUniform1i( texUni, 0 ); + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + // Set the attribute mPosAttrib with the vertices in the screen coordinates... + glVertexAttribPointer( mPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, coords ); + // ... and enable it. + glEnableVertexAttribArray( mPosAttrib ); + + float colorv[4]; + colorv[0] = m_color.Red() / 255.0f; + colorv[1] = m_color.Green() / 255.0f; + colorv[2] = m_color.Blue() / 255.0f; + colorv[3] = m_color.Alpha() / 255.0f; + + GLint colloc = glGetUniformLocation(pi_texture_text_shader_program, "color"); + glUniform4fv(colloc, 1, colorv); + + // Set the attribute mUvAttrib with the vertices in the GL coordinates... + glVertexAttribPointer( mUvAttrib, 2, GL_FLOAT, GL_FALSE, 0, uv ); + // ... and enable it. + glEnableVertexAttribArray( mUvAttrib ); + + // Rotate + float angle = 0; + mat4x4 I, Q; + mat4x4_identity(I); + mat4x4_rotate_Z(Q, I, angle); + + // Translate + Q[3][0] = m_dx; + Q[3][1] = m_dy; + + GLint matloc = glGetUniformLocation(pi_texture_text_shader_program, "TransformMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)Q); + + // Select the active texture unit. + glActiveTexture( GL_TEXTURE0 ); + + // For some reason, glDrawElements is busted on Android + // So we do this a hard ugly way, drawing two triangles... + #if 0 + GLushort indices1[] = {0,1,3,2}; + glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_SHORT, indices1); + #else + + float co1[8]; + co1[0] = coords[0]; + co1[1] = coords[1]; + co1[2] = coords[2]; + co1[3] = coords[3]; + co1[4] = coords[6]; + co1[5] = coords[7]; + co1[6] = coords[4]; + co1[7] = coords[5]; + + float tco1[8]; + tco1[0] = uv[0]; + tco1[1] = uv[1]; + tco1[2] = uv[2]; + tco1[3] = uv[3]; + tco1[4] = uv[6]; + tco1[5] = uv[7]; + tco1[6] = uv[4]; + tco1[7] = uv[5]; + + glVertexAttribPointer( mPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, co1 ); + glVertexAttribPointer( mUvAttrib, 2, GL_FLOAT, GL_FALSE, 0, tco1 ); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + #endif + m_dx += tgic.advance; +#endif +} + +void TexFont::RenderString( const char *string, int x, int y ) +{ + +#ifndef USE_ANDROID_GLES2 + + glPushMatrix(); + glTranslatef(x, y, 0); + + glPushMatrix(); + glBindTexture( GL_TEXTURE_2D, texobj); + + for( int i = 0; string[i]; i++ ) { + if(string[i] == '\n') { + glPopMatrix(); + glTranslatef(0, tgi[(int)'A'].height, 0); + glPushMatrix(); + continue; + } + /* degree symbol */ + if((unsigned char)string[i] == 0xc2 && + (unsigned char)string[i+1] == 0xb0) { + RenderGlyph( DEGREE_GLYPH ); + i++; + continue; + } + RenderGlyph( string[i] ); + } + + glPopMatrix(); + glPopMatrix(); +#else + m_dx = x; + m_dy = y; + + glBindTexture( GL_TEXTURE_2D, texobj); + + for( int i = 0; string[i]; i++ ) { + if(string[i] == '\n') { + m_dy += tgi[(int)'A'].height; + continue; + } + /* degree symbol */ + if((unsigned char)string[i] == 0xc2 && + (unsigned char)string[i+1] == 0xb0) { + RenderGlyph( DEGREE_GLYPH ); + i++; + continue; + } + RenderGlyph( string[i] ); + } + +#endif +} + +void TexFont::RenderString( const wxString &string, int x, int y ) +{ + RenderString((const char*)string.ToUTF8(), x, y); +} + +#endif //#ifdef ocpnUSE_GL diff --git a/libs/pluginDC/src/pi_shaders.cpp b/libs/pluginDC/src/pi_shaders.cpp new file mode 100644 index 00000000..8fc7859b --- /dev/null +++ b/libs/pluginDC/src/pi_shaders.cpp @@ -0,0 +1,664 @@ +/*************************************************************************** + * + * Project: OpenCPN + * + *************************************************************************** + * Copyright (C) 2017 by David S. Register * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + **************************************************************************/ + +#ifdef USE_ANDROID_GLES2 +#include "qdebug.h" + +#include "GLES2/gl2.h" +#include "pi_shaders.h" +#include "linmath.h" + +// Simple colored triangle shader + +static const GLchar* color_tri_vertex_shader_source = + "attribute vec2 position;\n" + "uniform mat4 MVMatrix;\n" + "uniform mat4 TransformMatrix;\n" + "uniform vec4 color;\n" + "varying vec4 fragColor;\n" + "void main() {\n" + " fragColor = color;\n" + " gl_Position = MVMatrix * TransformMatrix * vec4(position, 0.0, 1.0);\n" + "}\n"; + + static const GLchar* color_tri_fragment_shader_source = + "precision lowp float;\n" + "varying vec4 fragColor;\n" + "void main() {\n" + " gl_FragColor = fragColor;\n" + "}\n"; + +// Array colored triangle shader + static const GLchar* colorv_tri_vertex_shader_source = + "attribute vec2 position;\n" + "attribute vec4 colorv;\n" + "uniform mat4 MVMatrix;\n" + "uniform mat4 TransformMatrix;\n" + "varying vec4 fragColor;\n" + "void main() {\n" + " fragColor = colorv;\n" + " gl_Position = MVMatrix * TransformMatrix * vec4(position, 0.0, 1.0);\n" + "}\n"; + + static const GLchar* colorv_tri_fragment_shader_source = + "precision lowp float;\n" + "varying vec4 fragColor;\n" + "void main() {\n" + " gl_FragColor = fragColor;\n" + "}\n"; + + // Simple 2D texture shader +static const GLchar* texture_2D_vertex_shader_source = + "attribute vec2 aPos;\n" + "attribute vec2 aUV;\n" + "uniform mat4 MVMatrix;\n" + "uniform mat4 TransformMatrix;\n" + "varying vec2 varCoord;\n" + "void main() {\n" + " gl_Position = MVMatrix * TransformMatrix * vec4(aPos, 0.0, 1.0);\n" + " varCoord = aUV;\n" + "}\n"; + +static const GLchar* texture_2D_fragment_shader_source = + "precision lowp float;\n" + "uniform sampler2D uTex;\n" + "varying vec2 varCoord;\n" + "void main() {\n" + " gl_FragColor = texture2D(uTex, varCoord);\n" + "}\n"; + + // Alpah 2D texture shader +static const GLchar* pi_texture_2DA_vertex_shader_source = + "attribute vec2 aPos;\n" + "attribute vec2 aUV;\n" + "uniform mat4 MVMatrix;\n" + "uniform mat4 TransformMatrix;\n" + "varying vec2 varCoord;\n" + "void main() {\n" + " gl_Position = MVMatrix * TransformMatrix * vec4(aPos, 0.0, 1.0);\n" + " varCoord = aUV;\n" + "}\n"; + +static const GLchar* pi_texture_2DA_fragment_shader_source = + "precision lowp float;\n" + "uniform sampler2D uTex;\n" + "varying vec2 varCoord;\n" + "uniform vec4 color;\n" + "void main() {\n" + " gl_FragColor = texture2D(uTex, varCoord) + color;\n" + "}\n"; + +static const GLchar* pi_texture_text_vertex_shader_source = + "attribute vec2 aPos;\n" + "attribute vec2 aUV;\n" + "uniform mat4 MVMatrix;\n" + "uniform mat4 TransformMatrix;\n" + "varying vec2 varCoord;\n" + "void main() {\n" + " gl_Position = MVMatrix * TransformMatrix * vec4(aPos, 0.0, 1.0);\n" + " varCoord = aUV;\n" + "}\n"; + +static const GLchar* pi_texture_text_fragment_shader_source = + "precision lowp float;\n" + "uniform sampler2D uTex;\n" + "varying vec2 varCoord;\n" + "uniform vec4 color;\n" + "void main() {\n" + " gl_FragColor = vec4(color.r, color.g, color.b, color.a * texture2D(uTex, varCoord).a);\n" + "}\n"; + + + // Fade Texture shader +static const GLchar* fade_texture_2D_vertex_shader_source = + "precision highp float;\n" + "attribute vec2 aPos;\n" + "attribute vec2 aUV;\n" + "attribute vec2 aUV2;\n" + "uniform mat4 MVMatrix;\n" + "varying vec2 varCoord;\n" + "varying vec2 varCoord2;\n" + "void main() {\n" + " gl_Position = MVMatrix * vec4(aPos, 0.0, 1.0);\n" + " varCoord = aUV.st;\n" + " varCoord2 = aUV2.st;\n" + "}\n"; + +static const GLchar* fade_texture_2D_fragment_shader_source = + "precision highp float;\n" + "uniform sampler2D uTex;\n" + "uniform sampler2D uTex2;\n" + "uniform lowp float texAlpha;\n" + "varying vec2 varCoord;\n" + "varying vec2 varCoord2;\n" + "void main() {\n" + " mediump vec4 texColor = texture2D(uTex, varCoord);\n" + " mediump vec4 texTwoColor = texture2D(uTex2, varCoord2);\n" + " gl_FragColor = ((texTwoColor * (1.0 - texAlpha)) + (texColor * texAlpha));\n" + "}\n"; + + + + // Circle shader + +static const GLchar* circle_filled_vertex_shader_source = + "precision highp float;\n" + "attribute vec2 aPos;\n" + "uniform mat4 MVMatrix;\n" + "uniform mat4 TransformMatrix;\n" + "void main() {\n" + " gl_Position = MVMatrix * TransformMatrix * vec4(aPos, 0.0, 1.0);\n" + "}\n"; + +static const GLchar* circle_filled_fragment_shader_source = + "precision highp float;\n" + "uniform float border_width;\n" + "uniform float circle_radius;\n" + "uniform vec4 circle_color;\n" + "uniform vec4 border_color;\n" + "uniform vec2 circle_center;\n" + "void main(){\n" + "float d = distance(gl_FragCoord.xy, circle_center);\n" + "if (d < (circle_radius - border_width)) { gl_FragColor = circle_color; }\n" + "else if (d < circle_radius) { gl_FragColor = border_color; }\n" + "else { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); }\n" + "}\n"; + + + // 2D texture shader for FBOs + static const GLchar* FBO_texture_2D_vertex_shader_source = + "attribute vec2 aPos;\n" + "attribute vec2 aUV;\n" + "uniform mat4 MVMatrix;\n" + "varying vec2 varCoord;\n" + "void main() {\n" + " gl_Position = MVMatrix * vec4(aPos, 0.0, 1.0);\n" + " varCoord = aUV;\n" + "}\n"; + + static const GLchar* FBO_texture_2D_fragment_shader_source = + "precision lowp float;\n" + "uniform sampler2D uTex;\n" + "varying vec2 varCoord;\n" + "void main() {\n" + " gl_FragColor = texture2D(uTex, varCoord);\n" + "}\n"; + + + GLint pi_color_tri_fragment_shader; + GLint pi_color_tri_shader_program; + GLint pi_color_tri_vertex_shader; + + GLint pi_colorv_tri_fragment_shader; + GLint pi_colorv_tri_shader_program; + GLint pi_colorv_tri_vertex_shader; + + GLint pi_texture_2D_fragment_shader; + GLint pi_texture_2D_shader_program; + GLint pi_texture_2D_vertex_shader; + + GLint pi_texture_2DA_fragment_shader; + GLint pi_texture_2DA_shader_program; + GLint pi_texture_2DA_vertex_shader; + + GLint pi_texture_text_fragment_shader; + GLint pi_texture_text_shader_program; + GLint pi_texture_text_vertex_shader; + +// GLint fade_texture_2D_fragment_shader; +// GLint fade_texture_2D_shader_program; +// GLint fade_texture_2D_vertex_shader; + + GLint pi_circle_filled_shader_program; + GLint pi_circle_filled_vertex_shader; + GLint pi_circle_filled_fragment_shader; + +// GLint FBO_texture_2D_fragment_shader; +// GLint FBO_texture_2D_shader_program; +// GLint FBO_texture_2D_vertex_shader; + +bool pi_loadShaders() +{ + + bool ret_val = true; + GLint success; + + enum Consts {INFOLOG_LEN = 512}; + GLchar infoLog[INFOLOG_LEN]; + + // Are the shaders ready? + + // Simple colored triangle shader + + if(!pi_color_tri_vertex_shader){ + /* Vertex shader */ + pi_color_tri_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(pi_color_tri_vertex_shader, 1, &color_tri_vertex_shader_source, NULL); + glCompileShader(pi_color_tri_vertex_shader); + glGetShaderiv(pi_color_tri_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_color_tri_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!pi_color_tri_fragment_shader){ + /* Fragment shader */ + pi_color_tri_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(pi_color_tri_fragment_shader, 1, &color_tri_fragment_shader_source, NULL); + glCompileShader(pi_color_tri_fragment_shader); + glGetShaderiv(pi_color_tri_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_color_tri_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!pi_color_tri_shader_program){ + /* Link shaders */ + pi_color_tri_shader_program = glCreateProgram(); + glAttachShader(pi_color_tri_shader_program, pi_color_tri_fragment_shader); + glAttachShader(pi_color_tri_shader_program, pi_color_tri_vertex_shader); + glLinkProgram(pi_color_tri_shader_program); + glGetProgramiv(pi_color_tri_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(pi_color_tri_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + // Array colored triangle shader + + if(!pi_colorv_tri_vertex_shader){ + /* Vertex shader */ + pi_colorv_tri_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(pi_colorv_tri_vertex_shader, 1, &colorv_tri_vertex_shader_source, NULL); + glCompileShader(pi_colorv_tri_vertex_shader); + glGetShaderiv(pi_colorv_tri_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_colorv_tri_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!pi_colorv_tri_fragment_shader){ + /* Fragment shader */ + pi_colorv_tri_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(pi_colorv_tri_fragment_shader, 1, &colorv_tri_fragment_shader_source, NULL); + glCompileShader(pi_colorv_tri_fragment_shader); + glGetShaderiv(pi_colorv_tri_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_colorv_tri_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!pi_colorv_tri_shader_program){ + /* Link shaders */ + pi_colorv_tri_shader_program = glCreateProgram(); + glAttachShader(pi_colorv_tri_shader_program, pi_colorv_tri_fragment_shader); + glAttachShader(pi_colorv_tri_shader_program, pi_colorv_tri_vertex_shader); + glLinkProgram(pi_colorv_tri_shader_program); + glGetProgramiv(pi_colorv_tri_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(pi_colorv_tri_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + // Simple 2D texture shader + + if(!pi_texture_2D_vertex_shader){ + /* Vertex shader */ + pi_texture_2D_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(pi_texture_2D_vertex_shader, 1, &texture_2D_vertex_shader_source, NULL); + glCompileShader(pi_texture_2D_vertex_shader); + glGetShaderiv(pi_texture_2D_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_texture_2D_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!pi_texture_2D_fragment_shader){ + /* Fragment shader */ + pi_texture_2D_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(pi_texture_2D_fragment_shader, 1, &texture_2D_fragment_shader_source, NULL); + glCompileShader(pi_texture_2D_fragment_shader); + glGetShaderiv(pi_texture_2D_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_texture_2D_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!pi_texture_2D_shader_program){ + /* Link shaders */ + pi_texture_2D_shader_program = glCreateProgram(); + glAttachShader(pi_texture_2D_shader_program, pi_texture_2D_vertex_shader); + glAttachShader(pi_texture_2D_shader_program, pi_texture_2D_fragment_shader); + glLinkProgram(pi_texture_2D_shader_program); + glGetProgramiv(pi_texture_2D_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(pi_texture_2D_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + // 2D Alpha color texture shader + + if(!pi_texture_2DA_vertex_shader){ + /* Vertex shader */ + pi_texture_2DA_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(pi_texture_2DA_vertex_shader, 1, &pi_texture_2DA_vertex_shader_source, NULL); + glCompileShader(pi_texture_2DA_vertex_shader); + glGetShaderiv(pi_texture_2DA_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_texture_2DA_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + if(!pi_texture_2DA_fragment_shader){ + /* Fragment shader */ + pi_texture_2DA_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(pi_texture_2DA_fragment_shader, 1, &pi_texture_2DA_fragment_shader_source, NULL); + glCompileShader(pi_texture_2DA_fragment_shader); + glGetShaderiv(pi_texture_2DA_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_texture_2DA_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + if(!pi_texture_2DA_shader_program){ + /* Link shaders */ + pi_texture_2DA_shader_program = glCreateProgram(); + glAttachShader(pi_texture_2DA_shader_program, pi_texture_2DA_vertex_shader); + glAttachShader(pi_texture_2DA_shader_program, pi_texture_2DA_fragment_shader); + glLinkProgram(pi_texture_2DA_shader_program); + glGetProgramiv(pi_texture_2DA_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(pi_texture_2DA_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + + + if(!pi_texture_text_vertex_shader){ + /* Vertex shader */ + pi_texture_text_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(pi_texture_text_vertex_shader, 1, &pi_texture_text_vertex_shader_source, NULL); + glCompileShader(pi_texture_text_vertex_shader); + glGetShaderiv(pi_texture_text_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_texture_text_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + if(!pi_texture_text_fragment_shader){ + /* Fragment shader */ + pi_texture_text_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(pi_texture_text_fragment_shader, 1, &pi_texture_text_fragment_shader_source, NULL); + glCompileShader(pi_texture_text_fragment_shader); + glGetShaderiv(pi_texture_text_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_texture_text_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + if(!pi_texture_text_shader_program){ + /* Link shaders */ + pi_texture_text_shader_program = glCreateProgram(); + glAttachShader(pi_texture_text_shader_program, pi_texture_text_vertex_shader); + glAttachShader(pi_texture_text_shader_program, pi_texture_text_fragment_shader); + glLinkProgram(pi_texture_text_shader_program); + glGetProgramiv(pi_texture_text_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(pi_texture_text_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + +#if 0 + + // Fade texture shader + if(!fade_texture_2D_vertex_shader){ + /* Vertex shader */ + fade_texture_2D_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(fade_texture_2D_vertex_shader, 1, &fade_texture_2D_vertex_shader_source, NULL); + glCompileShader(fade_texture_2D_vertex_shader); + glGetShaderiv(fade_texture_2D_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(fade_texture_2D_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!fade_texture_2D_fragment_shader){ + /* Fragment shader */ + fade_texture_2D_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(fade_texture_2D_fragment_shader, 1, &fade_texture_2D_fragment_shader_source, NULL); + glCompileShader(fade_texture_2D_fragment_shader); + glGetShaderiv(fade_texture_2D_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(fade_texture_2D_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!fade_texture_2D_shader_program){ + /* Link shaders */ + fade_texture_2D_shader_program = glCreateProgram(); + glAttachShader(fade_texture_2D_shader_program, fade_texture_2D_vertex_shader); + glAttachShader(fade_texture_2D_shader_program, fade_texture_2D_fragment_shader); + glLinkProgram(fade_texture_2D_shader_program); + glGetProgramiv(fade_texture_2D_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(fade_texture_2D_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + +#endif + // Circle shader + if(!pi_circle_filled_vertex_shader){ + /* Vertex shader */ + pi_circle_filled_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(pi_circle_filled_vertex_shader, 1, &circle_filled_vertex_shader_source, NULL); + glCompileShader(pi_circle_filled_vertex_shader); + glGetShaderiv(pi_circle_filled_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_circle_filled_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + if(!pi_circle_filled_fragment_shader){ + /* Fragment shader */ + pi_circle_filled_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(pi_circle_filled_fragment_shader, 1, &circle_filled_fragment_shader_source, NULL); + glCompileShader(pi_circle_filled_fragment_shader); + glGetShaderiv(pi_circle_filled_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(pi_circle_filled_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + + if(!pi_circle_filled_shader_program){ + /* Link shaders */ + pi_circle_filled_shader_program = glCreateProgram(); + glAttachShader(pi_circle_filled_shader_program, pi_circle_filled_vertex_shader); + glAttachShader(pi_circle_filled_shader_program, pi_circle_filled_fragment_shader); + glLinkProgram(pi_circle_filled_shader_program); + glGetProgramiv(pi_circle_filled_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(pi_circle_filled_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + qDebug() << infoLog; + ret_val = false; + } + } + +#if 0 + // FBO 2D texture shader + + if(!FBO_texture_2D_vertex_shader){ + /* Vertex shader */ + FBO_texture_2D_vertex_shader = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(FBO_texture_2D_vertex_shader, 1, &FBO_texture_2D_vertex_shader_source, NULL); + glCompileShader(FBO_texture_2D_vertex_shader); + glGetShaderiv(FBO_texture_2D_vertex_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(FBO_texture_2D_vertex_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!FBO_texture_2D_fragment_shader){ + /* Fragment shader */ + FBO_texture_2D_fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(FBO_texture_2D_fragment_shader, 1, &FBO_texture_2D_fragment_shader_source, NULL); + glCompileShader(FBO_texture_2D_fragment_shader); + glGetShaderiv(FBO_texture_2D_fragment_shader, GL_COMPILE_STATUS, &success); + if (!success) { + glGetShaderInfoLog(FBO_texture_2D_fragment_shader, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s\n", infoLog); + ret_val = false; + } + } + + if(!FBO_texture_2D_shader_program){ + /* Link shaders */ + FBO_texture_2D_shader_program = glCreateProgram(); + glAttachShader(FBO_texture_2D_shader_program, FBO_texture_2D_vertex_shader); + glAttachShader(FBO_texture_2D_shader_program, FBO_texture_2D_fragment_shader); + glLinkProgram(FBO_texture_2D_shader_program); + glGetProgramiv(FBO_texture_2D_shader_program, GL_LINK_STATUS, &success); + if (!success) { + glGetProgramInfoLog(FBO_texture_2D_shader_program, INFOLOG_LEN, NULL, infoLog); + printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s\n", infoLog); + ret_val = false; + } + } +#endif + + //qDebug() << "pi_loadShaders: " << ret_val; + return ret_val; +} + + +void configureShaders(float width, float height) +{ + // Set the shader viewport transform matrix + float vp_transform[16]; + mat4x4 m; + mat4x4_identity(m); + mat4x4_scale_aniso((float (*)[4])vp_transform, m, 2.0 / width, -2.0 / height, 1.0); + mat4x4_translate_in_place((float (*)[4])vp_transform, -width/2, -height/2, 0); + + mat4x4 I; + mat4x4_identity(I); + + glUseProgram(pi_color_tri_shader_program); + GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"MVMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)vp_transform); + GLint transloc = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( transloc, 1, GL_FALSE, (const GLfloat*)I); + + //qDebug() << pi_color_tri_shader_program << transloc; + + glUseProgram(pi_circle_filled_shader_program); + matloc = glGetUniformLocation(pi_circle_filled_shader_program,"MVMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)vp_transform); + transloc = glGetUniformLocation(pi_circle_filled_shader_program,"TransformMatrix"); + glUniformMatrix4fv( transloc, 1, GL_FALSE, (const GLfloat*)I); + + //qDebug() << pi_circle_filled_shader_program << transloc; + + glUseProgram(pi_texture_2D_shader_program); + matloc = glGetUniformLocation(pi_texture_2D_shader_program,"MVMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)vp_transform); + transloc = glGetUniformLocation(pi_texture_2D_shader_program,"TransformMatrix"); + glUniformMatrix4fv( transloc, 1, GL_FALSE, (const GLfloat*)I); + + glUseProgram(pi_texture_2DA_shader_program); + matloc = glGetUniformLocation(pi_texture_2DA_shader_program,"MVMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)vp_transform); + transloc = glGetUniformLocation(pi_texture_2DA_shader_program,"TransformMatrix"); + glUniformMatrix4fv( transloc, 1, GL_FALSE, (const GLfloat*)I); + + glUseProgram(pi_texture_text_shader_program); + matloc = glGetUniformLocation(pi_texture_text_shader_program,"MVMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)vp_transform); + transloc = glGetUniformLocation(pi_texture_text_shader_program,"TransformMatrix"); + glUniformMatrix4fv( transloc, 1, GL_FALSE, (const GLfloat*)I); + + //qDebug() << pi_texture_2D_shader_program << transloc; + + glUseProgram(pi_colorv_tri_shader_program); + matloc = glGetUniformLocation(pi_colorv_tri_shader_program,"MVMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)vp_transform); + transloc = glGetUniformLocation(pi_colorv_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( transloc, 1, GL_FALSE, (const GLfloat*)I); + +} +#else +bool pi_loadShaders() { return true; } +void configureShaders(float width, float height) {} + +#endif diff --git a/libs/pluginDC/src/pidc.cpp b/libs/pluginDC/src/pidc.cpp new file mode 100644 index 00000000..bc9a43a1 --- /dev/null +++ b/libs/pluginDC/src/pidc.cpp @@ -0,0 +1,1965 @@ +/****************************************************************************** + * + * Project: OpenCPN + * Purpose: Layer to perform wxDC drawing using wxDC or opengl + * Author: Sean D'Epagnier + * + *************************************************************************** + * Copyright (C) 2011 by Sean D'Epagnier * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * + *************************************************************************** + * + */ + +#include "wx/wxprec.h" + +#ifndef WX_PRECOMP +#include "wx/wx.h" +#endif + +#include "ocpn_plugin.h" + +#ifdef __MSVC__ +#include +#endif + +#ifdef ocpnUSE_GL +#include +#endif + +#include +#include + +#include + +#include "pidc.h" + +#ifdef __OCPN__ANDROID__ +#include +#include "GL/gl_private.h" +#else +#include "GL/gl.h" +#include "GL/glu.h" +#endif + +#include "linmath.h" +#include "pi_shaders.h" + +#ifdef __OCPN__ANDROID__ +#include "qdebug.h" +#endif + +static float GLMinSymbolLineWidth; +static wxArrayPtrVoid pi_gTesselatorVertices; + +#ifdef USE_ANDROID_GLES2 +extern GLint pi_color_tri_shader_program; +extern GLint pi_circle_filled_shader_program; +#endif + +//---------------------------------------------------------------------------- +/* pass the dc to the constructor, or NULL to use opengl */ +piDC::piDC( wxGLCanvas &canvas ) : + glcanvas( &canvas ), dc( NULL ), m_pen( wxNullPen ), m_brush( wxNullBrush ) +{ +#if wxUSE_GRAPHICS_CONTEXT + pgc = NULL; +#endif +#ifdef ocpnUSE_GL + m_textforegroundcolour = wxColour( 0, 0, 0 ); + m_textbackgroundcolour = wxTransparentColour; + wxFont font = wxFont(20, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, "Roboto"); + SetFont(font); +#endif + m_buseTex = GetLocaleCanonicalName().IsSameAs(_T("en_US")); + workBuf = NULL; + workBufSize = 0; + +#ifdef USE_ANDROID_GLES2 + s_odc_tess_work_buf = NULL; + s_odc_tess_vertex_idx = 0; + s_odc_tess_vertex_idx_this = 0; + s_odc_tess_buf_len = 0; + + s_odc_tess_work_buf = (GLfloat *)malloc( 100 * sizeof(GLfloat)); + s_odc_tess_buf_len = 100; + + pi_loadShaders(); + +#endif + +} + +piDC::piDC( wxDC &pdc ) : + glcanvas( NULL ), dc( &pdc ), m_pen( wxNullPen ), m_brush( wxNullBrush ) +{ +#if wxUSE_GRAPHICS_CONTEXT + pgc = NULL; + wxMemoryDC *pmdc = wxDynamicCast(dc, wxMemoryDC); + if( pmdc ) pgc = wxGraphicsContext::Create( *pmdc ); + else { + wxClientDC *pcdc = wxDynamicCast(dc, wxClientDC); + if( pcdc ) pgc = wxGraphicsContext::Create( *pcdc ); + } +#endif + m_textforegroundcolour = wxColour( 0, 0, 0 ); + m_buseTex = GetLocaleCanonicalName().IsSameAs(_T("en_US")); + workBuf = NULL; + workBufSize = 0; +#ifdef USE_ANDROID_GLES2 + s_odc_tess_work_buf = NULL; +#endif + +} + +piDC::piDC() : + glcanvas( NULL ), dc( NULL ), m_pen( wxNullPen ), m_brush( wxNullBrush ) +{ +#if wxUSE_GRAPHICS_CONTEXT + pgc = NULL; +#endif +#ifdef ocpnUSE_GL + m_textforegroundcolour = wxColour( 0, 0, 0 ); + m_textbackgroundcolour = wxTransparentColour; + wxFont font = wxFont(20, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, "Roboto"); + SetFont(font); +#endif + m_buseTex = GetLocaleCanonicalName().IsSameAs(_T("en_US")); + workBuf = NULL; + workBufSize = 0; +#ifdef USE_ANDROID_GLES2 + s_odc_tess_work_buf = NULL; +#endif + + GLint parms[2]; + glGetIntegerv( GL_SMOOTH_LINE_WIDTH_RANGE, &parms[0] ); + GLMinSymbolLineWidth = wxMax(parms[0], 1); + + pi_loadShaders(); + +} + +piDC::~piDC() +{ +#if wxUSE_GRAPHICS_CONTEXT + if( pgc ) delete pgc; +#endif + free(workBuf); +#ifdef USE_ANDROID_GLES2 + free(s_odc_tess_work_buf); +#endif +} + +void piDC::SetVP(PlugIn_ViewPort *vp) +{ + configureShaders(vp->pix_width, vp->pix_height); + m_vpSize = wxSize(vp->pix_width, vp->pix_height); +} + + +void piDC::Clear() +{ + if( dc ) dc->Clear(); + else { +#ifdef ocpnUSE_GL + wxBrush tmpBrush = m_brush; + int w, h; + SetBrush( wxBrush( glcanvas->GetBackgroundColour() ) ); + glcanvas->GetSize( &w, &h ); + DrawRectangle( 0, 0, w, h ); + SetBrush( tmpBrush ); +#endif + } +} + +void piDC::SetBackground( const wxBrush &brush ) +{ + if( dc ) + dc->SetBackground( brush ); + else { +#ifdef ocpnUSE_GL + glcanvas->SetBackgroundColour( brush.GetColour() ); +#endif + } +} + +void piDC::SetPen( const wxPen &pen ) +{ + if( dc ) { + if( pen == wxNullPen ) dc->SetPen( *wxTRANSPARENT_PEN ); + else + dc->SetPen( pen ); + } else + m_pen = pen; +} + +void piDC::SetBrush( const wxBrush &brush ) +{ + if( dc ) dc->SetBrush( brush ); + else + m_brush = brush; +} + +void piDC::SetTextForeground( const wxColour &colour ) +{ + if( dc ) dc->SetTextForeground( colour ); + else + m_textforegroundcolour = colour; +} + +void piDC::SetTextBackground( const wxColour &colour ) +{ + if( dc ) dc->SetTextBackground( colour ); + else + m_textbackgroundcolour = colour; +} + +void piDC::SetFont( const wxFont& font ) +{ + if( dc ) dc->SetFont( font ); + else + m_font = font; +} + +const wxPen& piDC::GetPen() const +{ + if( dc ) return dc->GetPen(); + return m_pen; +} + +const wxBrush& piDC::GetBrush() const +{ + if( dc ) return dc->GetBrush(); + return m_brush; +} + +const wxFont& piDC::GetFont() const +{ + if( dc ) return dc->GetFont(); + return m_font; +} + +void piDC::GetSize( wxCoord *width, wxCoord *height ) const +{ + if( dc ) + dc->GetSize( width, height ); + else { +#ifdef ocpnUSE_GL + glcanvas->GetSize( width, height ); +#endif + } +} + +void piDC::SetGLAttrs( bool highQuality ) +{ +#ifdef ocpnUSE_GL + glEnable( GL_BLEND ); + + // Enable anti-aliased polys, at best quality + if( highQuality ) { + glEnable( GL_LINE_SMOOTH ); + glEnable( GL_POLYGON_SMOOTH ); + } else { + glDisable(GL_LINE_SMOOTH); + glDisable( GL_POLYGON_SMOOTH ); + } +#endif +} + +void piDC::SetGLStipple() const +{ +#ifdef ocpnUSE_GL + +#ifndef USE_ANDROID_GLES2 + switch( m_pen.GetStyle() ) { + case wxDOT: { + glLineStipple( 1, 0x3333 ); + glEnable( GL_LINE_STIPPLE ); + break; + } + case wxLONG_DASH: { + glLineStipple( 1, 0xFFF8 ); + glEnable( GL_LINE_STIPPLE ); + break; + } + case wxSHORT_DASH: { + glLineStipple( 1, 0x3F3F ); + glEnable( GL_LINE_STIPPLE ); + break; + } + case wxDOT_DASH: { + glLineStipple( 1, 0x8FF1 ); + glEnable( GL_LINE_STIPPLE ); + break; + } + default: break; + } +#endif +#endif +} + +#ifdef ocpnUSE_GL +/* draw a half circle using triangles */ +void piDrawEndCap(float x1, float y1, float t1, float angle) +{ +#ifndef USE_ANDROID_GLES2 + const int steps = 16; + float xa, ya; + bool first = true; + for(int i = 0; i <= steps; i++) { + float a = angle + M_PI/2 + M_PI/steps*i; + + float xb = x1 + t1 / 2 * cos( a ); + float yb = y1 + t1 / 2 * sin( a ); + if(first) + first = false; + else { + glVertex2f( x1, y1 ); + glVertex2f( xa, ya ); + glVertex2f( xb, yb ); + } + xa = xb, ya = yb; + } +#endif +} +#endif + +// Draws a line between (x1,y1) - (x2,y2) with a start thickness of t1 +void piDrawGLThickLine( float x1, float y1, float x2, float y2, wxPen pen, bool b_hiqual ) +{ +#ifdef ocpnUSE_GL + + float angle = atan2f( y2 - y1, x2 - x1 ); + float t1 = pen.GetWidth(); + float t2sina1 = t1 / 2 * sinf( angle ); + float t2cosa1 = t1 / 2 * cosf( angle ); + +#ifndef USE_ANDROID_GLES2 + glBegin( GL_TRIANGLES ); + + // n.b. The dwxDash interpretation for GL only allows for 2 elements in the dash table. + // The first is assumed drawn, second is assumed space + wxDash *dashes; + int n_dashes = pen.GetDashes( &dashes ); + if( n_dashes ) { + float lpix = sqrtf( powf( (float) (x1 - x2), 2) + powf( (float) (y1 - y2), 2) ); + float lrun = 0.; + float xa = x1; + float ya = y1; + float ldraw = t1 * dashes[0]; + float lspace = t1 * dashes[1]; + + while( lrun < lpix ) { + // Dash + float xb = xa + ldraw * cosf( angle ); + float yb = ya + ldraw * sinf( angle ); + + if( ( lrun + ldraw ) >= lpix ) // last segment is partial draw + { + xb = x2; + yb = y2; + } + + glVertex2f( xa + t2sina1, ya - t2cosa1 ); + glVertex2f( xb + t2sina1, yb - t2cosa1 ); + glVertex2f( xb - t2sina1, yb + t2cosa1 ); + + glVertex2f( xb - t2sina1, yb + t2cosa1 ); + glVertex2f( xa - t2sina1, ya + t2cosa1 ); + glVertex2f( xa + t2sina1, ya - t2cosa1 ); + + xa = xb; + ya = yb; + lrun += ldraw; + + // Space + xb = xa + lspace * cos( angle ); + yb = ya + lspace * sin( angle ); + + xa = xb; + ya = yb; + lrun += lspace; + } + } else { + glVertex2f( x1 + t2sina1, y1 - t2cosa1 ); + glVertex2f( x2 + t2sina1, y2 - t2cosa1 ); + glVertex2f( x2 - t2sina1, y2 + t2cosa1 ); + + glVertex2f( x2 - t2sina1, y2 + t2cosa1 ); + glVertex2f( x1 - t2sina1, y1 + t2cosa1 ); + glVertex2f( x1 + t2sina1, y1 - t2cosa1 ); + + /* wx draws a nice rounded end in dc mode, so replicate + this for opengl mode, should this be done for the dashed mode case? */ + if(pen.GetCap() == wxCAP_ROUND) { + piDrawEndCap( x1, y1, t1, angle); + piDrawEndCap( x2, y2, t1, angle + M_PI); + } + + } + + glEnd(); +#else + + // n.b. The dwxDash interpretation for GL only allows for 2 elements in the dash table. + // The first is assumed drawn, second is assumed space + wxDash *dashes; + int n_dashes = pen.GetDashes( &dashes ); + if( n_dashes ) { + float lpix = sqrtf( powf( (float) (x1 - x2), 2) + powf( (float) (y1 - y2), 2) ); + float lrun = 0.; + float xa = x1; + float ya = y1; + float ldraw = t1 * dashes[0]; + float lspace = t1 * dashes[1]; + + glUseProgram(pi_color_tri_shader_program); + + float vert[12]; + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + GLint pos = glGetAttribLocation(pi_color_tri_shader_program, "position"); + glEnableVertexAttribArray(pos); + glVertexAttribPointer(pos, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), vert); + + // Build Transform matrix + mat4x4 I; + mat4x4_identity(I); + + GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)I); + + wxColor c = pen.GetColour(); + float colorv[4]; + colorv[0] = c.Red() / 255.0f; + colorv[1] = c.Green() / 255.0f; + colorv[2] = c.Blue() / 255.0f; + colorv[3] = c.Alpha() / 255.0f; + + GLint colloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(colloc, 1, colorv); + + while( lrun < lpix ) { + // Dash + float xb = xa + ldraw * cosf( angle ); + float yb = ya + ldraw * sinf( angle ); + + if( ( lrun + ldraw ) >= lpix ) // last segment is partial draw + { + xb = x2; + yb = y2; + } + + vert[0] = xa + t2sina1; vert[1] = ya - t2cosa1; vert[2] = xb + t2sina1; vert[3] = yb - t2cosa1; vert[4] = xb - t2sina1; vert[5] = yb + t2cosa1; + vert[6] = xb - t2sina1; vert[7] = yb + t2cosa1; vert[8] = xa - t2sina1; vert[9] = ya + t2cosa1; vert[10] = xa + t2sina1; vert[11] = ya - t2cosa1; + + glDrawArrays(GL_TRIANGLES, 0, 6); + + + xa = xb; + ya = yb; + lrun += ldraw; + + // Space + xb = xa + lspace * cos( angle ); + yb = ya + lspace * sin( angle ); + + xa = xb; + ya = yb; + lrun += lspace; + } + } else { + + float vert[12]; + vert[0] = x1 + t2sina1; vert[1] = y1 - t2cosa1; vert[2] = x2 + t2sina1; vert[3] = y2 - t2cosa1; vert[4] = x2 - t2sina1; vert[5] = y2 + t2cosa1; + vert[6] = x2 - t2sina1; vert[7] = y2 + t2cosa1; vert[8] = x1 - t2sina1; vert[9] = y1 + t2cosa1; vert[10] = x1 + t2sina1; vert[11] = y1 - t2cosa1; + + glUseProgram(pi_color_tri_shader_program); + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + GLint pos = glGetAttribLocation(pi_color_tri_shader_program, "position"); + glEnableVertexAttribArray(pos); + glVertexAttribPointer(pos, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), vert); + + // Build Transform matrix + mat4x4 I; + mat4x4_identity(I); + + GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)I); + + wxColor c = pen.GetColour(); + float colorv[4]; + colorv[0] = c.Red() / 255.0f; + colorv[1] = c.Green() / 255.0f; + colorv[2] = c.Blue() / 255.0f; + colorv[3] = c.Alpha() / 255.0f; + + GLint colloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(colloc, 1, colorv); + + glDrawArrays(GL_TRIANGLES, 0, 6); + + + /* wx draws a nice rounded end in dc mode, so replicate + * this for opengl mode, should this be done for the dashed mode case? */ +// if(pen.GetCap() == wxCAP_ROUND) { +// DrawEndCap( x1, y1, t1, angle); +// DrawEndCap( x2, y2, t1, angle + M_PI); +// } +// + } + +#endif + +#endif +} + +void piDC::DrawLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2, bool b_hiqual ) +{ + + if( dc ) + dc->DrawLine( x1, y1, x2, y2 ); +#ifdef ocpnUSE_GL + else if( ConfigurePen() ) { + bool b_draw_thick = false; + + float pen_width = wxMax(GLMinSymbolLineWidth, m_pen.GetWidth()); + + // Enable anti-aliased lines, at best quality + if( b_hiqual ) { + SetGLStipple(); + + glEnable( GL_BLEND ); +#ifndef __WXQT__ + glEnable( GL_LINE_SMOOTH ); +#endif + + if( pen_width > 1.0 ) { + GLint parms[2]; + glGetIntegerv( GL_SMOOTH_LINE_WIDTH_RANGE, &parms[0] ); + if(glGetError()) + glGetIntegerv( GL_ALIASED_LINE_WIDTH_RANGE, &parms[0] ); + if( pen_width > parms[1] ) + b_draw_thick = true; + else + glLineWidth( pen_width ); + } else + glLineWidth( pen_width ); + } else { + if( pen_width > 1 ) { + GLint parms[2]; + glGetIntegerv( GL_ALIASED_LINE_WIDTH_RANGE, &parms[0] ); + if( pen_width > parms[1] ) b_draw_thick = true; + else + glLineWidth( pen_width ); + } else + glLineWidth( pen_width ); + } + + +#ifdef USE_ANDROID_GLES2 + if( b_draw_thick ) + piDrawGLThickLine( x1, y1, x2, y2, m_pen, b_hiqual ); + else { + glUseProgram(pi_color_tri_shader_program); + + float fBuf[4]; + GLint pos = glGetAttribLocation(pi_color_tri_shader_program, "position"); + glVertexAttribPointer(pos, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), fBuf); + glEnableVertexAttribArray(pos); + +// GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"MVMatrix"); +// glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)cc1->GetpVP()->vp_transform); + + float colorv[4]; + colorv[0] = m_pen.GetColour().Red() / 255.0f; + colorv[1] = m_pen.GetColour().Green() / 255.0f; + colorv[2] = m_pen.GetColour().Blue() / 255.0f; + colorv[3] = m_pen.GetColour().Alpha() / 255.0f; + + GLint colloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(colloc, 1, colorv); + + wxDash *dashes; + int n_dashes = m_pen.GetDashes( &dashes ); + if( n_dashes ) { + float angle = atan2f( (float) ( y2 - y1 ), (float) ( x2 - x1 ) ); + float cosa = cosf( angle ); + float sina = sinf( angle ); + float t1 = m_pen.GetWidth(); + + float lpix = sqrtf( powf(x1 - x2, 2) + powf(y1 - y2, 2) ); + float lrun = 0.; + float xa = x1; + float ya = y1; + float ldraw = t1 * dashes[0]; + float lspace = t1 * dashes[1]; + + ldraw = wxMax(ldraw, 4.0); + lspace = wxMax(lspace, 4.0); + lpix = wxMin(lpix, 2000.0); + + while( lrun < lpix ) { + // Dash + float xb = xa + ldraw * cosa; + float yb = ya + ldraw * sina; + + if( ( lrun + ldraw ) >= lpix ) // last segment is partial draw + { + xb = x2; + yb = y2; + } + + fBuf[0] = xa; + fBuf[1] = ya; + fBuf[2] = xb; + fBuf[3] = yb; + + glDrawArrays(GL_LINES, 0, 2); + + xa = xa + ( lspace + ldraw ) * cosa; + ya = ya + ( lspace + ldraw ) * sina; + lrun += lspace + ldraw; + + } + } else // not dashed + { + fBuf[0] = x1; + fBuf[1] = y1; + fBuf[2] = x2; + fBuf[3] = y2; + + glDrawArrays(GL_LINES, 0, 2); + } + } + +#else + if( b_draw_thick ) + piDrawGLThickLine( x1, y1, x2, y2, m_pen, b_hiqual ); + else { + wxDash *dashes; + int n_dashes = m_pen.GetDashes( &dashes ); + if( n_dashes ) { + float angle = atan2f( (float) ( y2 - y1 ), (float) ( x2 - x1 ) ); + float cosa = cosf( angle ); + float sina = sinf( angle ); + float t1 = m_pen.GetWidth(); + + float lpix = sqrtf( powf(x1 - x2, 2) + powf(y1 - y2, 2) ); + float lrun = 0.; + float xa = x1; + float ya = y1; + float ldraw = t1 * dashes[0]; + float lspace = t1 * dashes[1]; + + ldraw = wxMax(ldraw, 4.0); + lspace = wxMax(lspace, 4.0); + lpix = wxMin(lpix, 2000.0); + + glBegin( GL_LINES ); + while( lrun < lpix ) { + // Dash + float xb = xa + ldraw * cosa; + float yb = ya + ldraw * sina; + + if( ( lrun + ldraw ) >= lpix ) // last segment is partial draw + { + xb = x2; + yb = y2; + } + + glVertex2f( xa, ya ); + glVertex2f( xb, yb ); + + xa = xa + ( lspace + ldraw ) * cosa; + ya = ya + ( lspace + ldraw ) * sina; + lrun += lspace + ldraw; + + } + glEnd(); + } else // not dashed + { + glBegin( GL_LINES ); + glVertex2i( x1, y1 ); + glVertex2i( x2, y2 ); + glEnd(); + } + } +#endif + glDisable( GL_LINE_STIPPLE ); + + if( b_hiqual ) + glDisable( GL_LINE_SMOOTH ); + glDisable( GL_BLEND ); + } +#endif +} + +// Draws thick lines from triangles +void piDrawGLThickLines( int n, wxPoint points[],wxCoord xoffset, + wxCoord yoffset, wxPen pen, bool b_hiqual ) +{ +#ifdef ocpnUSE_GL + if(n < 2) + return; + +#ifdef USE_ANDROID_GLES2 + wxPoint p0 = points[0]; + for( int i = 1; i < n; i++ ) { + piDrawGLThickLine( p0.x + xoffset, p0.y + yoffset, points[i].x + xoffset, + points[i].y + yoffset, pen, b_hiqual ); + p0 = points[i]; + } + return; +#else + + /* for dashed case, for now just draw thick lines */ + wxDash *dashes; + if( pen.GetDashes( &dashes ) ) + { + wxPoint p0 = points[0]; + for( int i = 1; i < n; i++ ) { + piDrawGLThickLine( p0.x + xoffset, p0.y + yoffset, points[i].x + xoffset, + points[i].y + yoffset, pen, b_hiqual ); + p0 = points[i]; + } + return; + } + + /* cull zero segments */ + wxPoint *cpoints = new wxPoint[n]; + cpoints[0] = points[0]; + int c = 1; + for( int i = 1; i < n; i++ ) { + if(points[i].x != points[i-1].x || points[i].y != points[i-1].y) + cpoints[c++] = points[i]; + } + + /* nicer than than rendering each segment separately, this is because thick + line segments drawn as rectangles which have different angles have + rectangles which overlap and also leave a gap. + This code properly calculates vertexes for adjoining segments */ + float t1 = pen.GetWidth(); + + float x0 = cpoints[0].x, y0 = cpoints[0].y, x1 = cpoints[1].x, y1 = cpoints[1].y; + float a0 = atan2f( y1 - y0, x1 - x0 ); + + // It is also possible to use triangle strip, (and triangle fan for endcap) + // to reduce vertex count.. is it worth it? + glBegin( GL_TRIANGLES ); + + float t2sina0 = t1 / 2 * sinf( a0 ); + float t2cosa0 = t1 / 2 * cosf( a0 ); + + for( int i = 1; i < c; i++ ) { + float x2, y2; + float a1; + + if(i < c - 1) { + x2 = cpoints[i + 1].x, y2 = cpoints[i + 1].y; + a1 = atan2f( y2 - y1, x2 - x1 ); + } else { + x2 = x1, y2 = y1; + a1 = a0; + } + + float aa = (a0 + a1) / 2; + float diff = fabsf(a0 - a1); + if(diff > M_PI) + diff -= 2 * (float)M_PI; + float rad = t1 / 2 / wxMax(cosf(diff / 2), .4); + + float t2sina1 = rad * sinf( aa ); + float t2cosa1 = rad * cosf( aa ); + + glVertex2f( x1 + t2sina1, y1 - t2cosa1 ); + glVertex2f( x1 - t2sina1, y1 + t2cosa1 ); + glVertex2f( x0 + t2sina0, y0 - t2cosa0 ); + + glVertex2f( x0 - t2sina0, y0 + t2cosa0 ); + glVertex2f( x0 + t2sina0, y0 - t2cosa0 ); + + float dot = t2sina0 * t2sina1 + t2cosa0 * t2cosa1; + if(dot > 0) + glVertex2f( x1 - t2sina1, y1 + t2cosa1 ); + else + glVertex2f( x1 + t2sina1, y1 - t2cosa1 ); + + x0 = x1, x1 = x2; + y0 = y1, y1 = y2; + a0 = a1; + t2sina0 = t2sina1, t2cosa0 = t2cosa1; + } + + if(pen.GetCap() == wxCAP_ROUND) { + piDrawEndCap( x0, y0, t1, a0); + piDrawEndCap( x0, y0, t1, a0 + M_PI); + } + + glEnd(); + + glPopAttrib(); + + delete [] cpoints; + #endif + #endif + } + + void piDC::DrawLines( int n, wxPoint points[], wxCoord xoffset, wxCoord yoffset, bool b_hiqual ) +{ + if( dc ) + dc->DrawLines( n, points, xoffset, yoffset ); +#ifdef ocpnUSE_GL + else if( ConfigurePen() ) { + +#ifdef __WXQT__ + SetGLAttrs( false ); // Some QT platforms (Android) have trouble with GL_BLEND / GL_LINE_SMOOTH +#else + SetGLAttrs( b_hiqual ); +#endif + bool b_draw_thick = false; + + glDisable( GL_LINE_STIPPLE ); + SetGLStipple(); + + // Enable anti-aliased lines, at best quality + if( b_hiqual ) { + if( m_pen.GetWidth() > 1 ) { + GLint parms[2]; + glGetIntegerv( GL_SMOOTH_LINE_WIDTH_RANGE, &parms[0] ); + if(glGetError()) + glGetIntegerv( GL_ALIASED_LINE_WIDTH_RANGE, &parms[0] ); + + if( m_pen.GetWidth() > parms[1] ) + b_draw_thick = true; + else + glLineWidth( wxMax(GLMinSymbolLineWidth, m_pen.GetWidth()) ); + } else + glLineWidth( wxMax(GLMinSymbolLineWidth, 1) ); + } else { + if( m_pen.GetWidth() > 1 ) { + GLint parms[2]; + glGetIntegerv( GL_ALIASED_LINE_WIDTH_RANGE, &parms[0] ); + if( m_pen.GetWidth() > parms[1] ) b_draw_thick = true; + else + glLineWidth( wxMax(GLMinSymbolLineWidth, m_pen.GetWidth()) ); + } else + glLineWidth( wxMax(GLMinSymbolLineWidth, 1) ); + } + + if( b_draw_thick) { + piDrawGLThickLines( n, points, xoffset, yoffset, m_pen, b_hiqual ); + + if( b_hiqual ) { + glDisable( GL_LINE_STIPPLE ); + glDisable( GL_POLYGON_SMOOTH ); + } + + return; + } + +#ifndef USE_ANDROID_GLES2 + + glBegin( GL_LINE_STRIP ); + for( int i = 0; i < n; i++ ) + glVertex2i( points[i].x + xoffset, points[i].y + yoffset ); + glEnd(); + +#else + + // Grow the work buffer as necessary + if( workBufSize < (size_t)n*2 ){ + workBuf = (float *)realloc(workBuf, (n*4) * sizeof(float)); + workBufSize = n*4; + } + + for( int i = 0; i < n; i++ ){ + workBuf[i*2] = points[i].x + xoffset; + workBuf[(i*2) + 1] = points[i].y + yoffset; + } + + glUseProgram(pi_color_tri_shader_program); + + GLint pos = glGetAttribLocation(pi_color_tri_shader_program, "position"); + glVertexAttribPointer(pos, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), workBuf); + glEnableVertexAttribArray(pos); +// GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"MVMatrix"); +// glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)cc1->GetpVP()->vp_transform); + + float colorv[4]; + colorv[0] = m_pen.GetColour().Red() / 255.0f; + colorv[1] = m_pen.GetColour().Green() / 255.0f; + colorv[2] = m_pen.GetColour().Blue() / 255.0f; + colorv[3] = m_pen.GetColour().Alpha() / 255.0f; + + GLint colloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(colloc, 1, colorv); + + glDrawArrays(GL_LINE_STRIP, 0, n); + + +#endif + + + if( b_hiqual ) { + glDisable( GL_LINE_STIPPLE ); + glDisable( GL_POLYGON_SMOOTH ); + } + } +#endif +} + +void piDC::StrokeLine( wxCoord x1, wxCoord y1, wxCoord x2, wxCoord y2 ) +{ +#if wxUSE_GRAPHICS_CONTEXT + if( pgc ) { + pgc->SetPen( dc->GetPen() ); + pgc->StrokeLine( x1, y1, x2, y2 ); + + dc->CalcBoundingBox( x1, y1 ); + dc->CalcBoundingBox( x2, y2 ); + } else +#endif + DrawLine( x1, y1, x2, y2, true ); +} + +void piDC::StrokeLines( int n, wxPoint *points) { + if(n < 2) /* optimization and also to avoid assertion in pgc->StrokeLines */ + return; + +#if wxUSE_GRAPHICS_CONTEXT + if( pgc ) { + wxPoint2DDouble* dPoints = (wxPoint2DDouble*) malloc( n * sizeof( wxPoint2DDouble ) ); + for( int i=0; iSetPen( dc->GetPen() ); + pgc->StrokeLines( n, dPoints ); + free( dPoints ); + } else +#endif + DrawLines( n, points, 0, 0, true ); +} + +void piDC::DrawGLLineArray( int n, float *vertex_array, float *color_array, bool b_hiqual ) +{ +#ifdef ocpnUSE_GL + if( ConfigurePen() ) { + + #ifdef __WXQT__ + SetGLAttrs( false ); // Some QT platforms (Android) have trouble with GL_BLEND / GL_LINE_SMOOTH + #else + SetGLAttrs( b_hiqual ); + #endif + //bool b_draw_thick = false; + + glDisable( GL_LINE_STIPPLE ); + SetGLStipple(); + + // Enable anti-aliased lines, at best quality + if( b_hiqual ) { + if( m_pen.GetWidth() > 1 ) { + //GLint parms[2]; + //glGetIntegerv( GL_SMOOTH_LINE_WIDTH_RANGE, &parms[0] ); + //if(glGetError()) + //glGetIntegerv( GL_ALIASED_LINE_WIDTH_RANGE, &parms[0] ); + + glLineWidth( wxMax(GLMinSymbolLineWidth, m_pen.GetWidth()) ); + } else + glLineWidth( wxMax(GLMinSymbolLineWidth, 1) ); + } else { + if( m_pen.GetWidth() > 1 ) { + //GLint parms[2]; + //glGetIntegerv( GL_ALIASED_LINE_WIDTH_RANGE, &parms[0] ); + glLineWidth( wxMax(GLMinSymbolLineWidth, m_pen.GetWidth()) ); + } else + glLineWidth( wxMax(GLMinSymbolLineWidth, 1) ); + } + +#ifndef USE_ANDROID_GLES2 + + glBegin( GL_LINE_STRIP ); + for( int i = 0; i < n; i++ ) + glVertex2f( vertex_array[2*i], vertex_array[2*i+1] ); + glEnd(); + +#else + glUseProgram(pi_colorv_tri_shader_program); + + GLint pos = glGetAttribLocation(pi_colorv_tri_shader_program, "position"); + glVertexAttribPointer(pos, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), vertex_array); + glEnableVertexAttribArray(pos); + + GLint colloc = glGetAttribLocation(pi_colorv_tri_shader_program, "colorv"); + glVertexAttribPointer(colloc, 4, GL_FLOAT, GL_FALSE, 4*sizeof(float), color_array); + glEnableVertexAttribArray(colloc); + + glDrawArrays(GL_LINES, 0, n); +#endif + if( b_hiqual ) { + glDisable( GL_LINE_STIPPLE ); + glDisable( GL_POLYGON_SMOOTH ); + } + } +#endif +} + + +void piDC::DrawRectangle( wxCoord x, wxCoord y, wxCoord w, wxCoord h ) +{ + if( dc ) + dc->DrawRectangle( x, y, w, h ); +#ifdef ocpnUSE_GL + else { +#ifndef USE_ANDROID_GLES2 + if( ConfigureBrush() ) { + glBegin( GL_QUADS ); + glVertex2i( x, y ); + glVertex2i( x + w, y ); + glVertex2i( x + w, y + h ); + glVertex2i( x, y + h ); + glEnd(); + } + + if( ConfigurePen() ) { + glBegin( GL_LINE_LOOP ); + glVertex2i( x, y ); + glVertex2i( x + w, y ); + glVertex2i( x + w, y + h ); + glVertex2i( x, y + h ); + glEnd(); + } +#endif + } +#endif +} + +/* draw the arc along corners */ +static void drawrrhelper( wxCoord x0, wxCoord y0, wxCoord r, int quadrant, int steps ) +{ +#ifdef ocpnUSE_GL +#ifndef USE_ANDROID_GLES2 + float step = 1.0/steps, rs = 2.0*r*step, rss = rs*step, x, y, dx, dy, ddx, ddy; + switch(quadrant) { + case 0: x = r, y = 0, dx = 0, dy = -rs, ddx = -rss, ddy = rss; break; + case 1: x = 0, y = -r, dx = -rs, dy = 0, ddx = rss, ddy = rss; break; + case 2: x = -r, y = 0, dx = 0, dy = rs, ddx = rss, ddy = -rss; break; + case 3: x = 0, y = r, dx = rs, dy = 0, ddx = -rss, ddy = -rss; break; + default: return; // avoid unitialized compiler warnings + } + + for(int i=0; iDrawRoundedRectangle( x, y, w, h, r ); +#ifdef ocpnUSE_GL + else { + r++; + int steps = ceil(sqrt((float)r)); + + wxCoord x1 = x + r, x2 = x + w - r; + wxCoord y1 = y + r, y2 = y + h - r; + +#ifdef USE_ANDROID_GLES2 + + // Grow the work buffer as necessary + size_t bufReq = steps * 8 * 2 * sizeof(float); // large, to be sure + + if( workBufSize < bufReq ){ + workBuf = (float *)realloc(workBuf, bufReq); + workBufSize = bufReq; + } + workBufIndex = 0; + + drawrrhelperGLES2( x2, y1, r, 0, steps ); + drawrrhelperGLES2( x1, y1, r, 1, steps ); + drawrrhelperGLES2( x1, y2, r, 2, steps ); + drawrrhelperGLES2( x2, y2, r, 3, steps ); + + glUseProgram( pi_color_tri_shader_program ); + + // Get pointers to the attributes in the program. + GLint mPosAttrib = glGetAttribLocation( pi_color_tri_shader_program, "position" ); + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + glVertexAttribPointer( mPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, workBuf ); + glEnableVertexAttribArray( mPosAttrib ); + + + // Border color + float bcolorv[4]; + bcolorv[0] = m_brush.GetColour().Red() / 255.0f; + bcolorv[1] = m_brush.GetColour().Green() / 255.0f; + bcolorv[2] = m_brush.GetColour().Blue() / 255.0f; + bcolorv[3] = m_brush.GetColour().Alpha() / 255.0f; + + GLint bcolloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(bcolloc, 1, bcolorv); + + + float angle = 0.; + float xoffset = 0; + float yoffset = 0; + + // Rotate + mat4x4 I, Q; + mat4x4_identity(I); + mat4x4_rotate_Z(Q, I, angle); + + // Translate + Q[3][0] = xoffset; + Q[3][1] = yoffset; + + GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)Q); + + // Perform the actual drawing. + glDrawArrays(GL_TRIANGLE_FAN, 0, workBufIndex/2); + + // Restore the per-object transform to Identity Matrix + mat4x4 IM; + mat4x4_identity(IM); + GLint matlocf = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( matlocf, 1, GL_FALSE, (const GLfloat*)IM); + + +#else + if( ConfigureBrush() ) { + glBegin( GL_TRIANGLE_FAN ); + drawrrhelper( x2, y1, r, 0, steps ); + drawrrhelper( x1, y1, r, 1, steps ); + drawrrhelper( x1, y2, r, 2, steps ); + drawrrhelper( x2, y2, r, 3, steps ); + glEnd(); + } + + if( ConfigurePen() ) { + glBegin( GL_LINE_LOOP ); + drawrrhelper( x2, y1, r, 0, steps ); + drawrrhelper( x1, y1, r, 1, steps ); + drawrrhelper( x1, y2, r, 2, steps ); + drawrrhelper( x2, y2, r, 3, steps ); + glEnd(); + } +#endif + } +#endif +} + +void piDC::DrawCircle( wxCoord x, wxCoord y, wxCoord radius ) +{ +#ifdef USE_ANDROID_GLES2 + + // Enable anti-aliased lines, at best quality + glEnable( GL_BLEND ); + + float coords[8]; + coords[0] = x - radius; coords[1] = y + radius; + coords[2] = x + radius; coords[3] = y + radius; + coords[4] = x - radius; coords[5] = y - radius; + coords[6] = x + radius; coords[7] = y - radius; + + glUseProgram( pi_circle_filled_shader_program ); + + // Get pointers to the attributes in the program. + GLint mPosAttrib = glGetAttribLocation( pi_circle_filled_shader_program, "aPos" ); + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + glVertexAttribPointer( mPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, coords ); + glEnableVertexAttribArray( mPosAttrib ); + + // Circle radius + GLint radiusloc = glGetUniformLocation(pi_circle_filled_shader_program,"circle_radius"); + glUniform1f(radiusloc, radius); + + // Circle center point + GLint centerloc = glGetUniformLocation(pi_circle_filled_shader_program,"circle_center"); + float ctrv[2]; + ctrv[0] = x; ctrv[1] = m_vpSize.y - y; + glUniform2fv(centerloc, 1, ctrv); + + // Circle color + float colorv[4]; + colorv[0] = m_brush.GetColour().Red() / 255.0f; + colorv[1] = m_brush.GetColour().Green() / 255.0f; + colorv[2] = m_brush.GetColour().Blue() / 255.0f; + colorv[3] = (m_brush == wxNullBrush || m_brush.GetStyle() == wxBRUSHSTYLE_TRANSPARENT) ? 0.0 : 1.0; + + GLint colloc = glGetUniformLocation(pi_circle_filled_shader_program,"circle_color"); + glUniform4fv(colloc, 1, colorv); + + // Border color + float bcolorv[4]; + bcolorv[0] = m_pen.GetColour().Red() / 255.0f; + bcolorv[1] = m_pen.GetColour().Green() / 255.0f; + bcolorv[2] = m_pen.GetColour().Blue() / 255.0f; + bcolorv[3] = m_pen.GetColour().Alpha() / 255.0f; + + GLint bcolloc = glGetUniformLocation(pi_circle_filled_shader_program,"border_color"); + glUniform4fv(bcolloc, 1, bcolorv); + + // Border Width + GLint borderWidthloc = glGetUniformLocation(pi_circle_filled_shader_program,"border_width"); + glUniform1f(borderWidthloc, m_pen.GetWidth()); + + +// GLint matloc = glGetUniformLocation(pi_circle_filled_shader_program,"MVMatrix"); +// glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)(cc1->GetpVP()->vp_transform) ); + + // Perform the actual drawing. + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + glDisable( GL_BLEND ); + +#else + DrawEllipse( x - radius, y - radius, 2 * radius, 2 * radius ); +#endif +} + +void piDC::StrokeCircle( wxCoord x, wxCoord y, wxCoord radius ) +{ +#if wxUSE_GRAPHICS_CONTEXT + if( pgc ) { + wxGraphicsPath gpath = pgc->CreatePath(); + gpath.AddCircle( x, y, radius ); + + pgc->SetPen( GetPen() ); + pgc->SetBrush( GetBrush() ); + pgc->DrawPath( gpath ); + + // keep dc dirty box up-to-date + dc->CalcBoundingBox( x + radius + 2, y + radius + 2 ); + dc->CalcBoundingBox( x - radius - 2, y - radius - 2 ); + } else +#endif + DrawCircle( x, y, radius ); +} + +void piDC::DrawEllipse( wxCoord x, wxCoord y, wxCoord width, wxCoord height ) +{ + if( dc ) + dc->DrawEllipse( x, y, width, height ); +#ifdef ocpnUSE_GL + else { + float r1 = width / 2, r2 = height / 2; + float cx = x + r1, cy = y + r2; + + // Enable anti-aliased lines, at best quality + glEnable( GL_BLEND ); + + /* formula for variable step count to produce smooth ellipse */ + float steps = floorf(wxMax(sqrtf(sqrtf((float)(width*width + height*height))), 1) * M_PI); + +#ifndef USE_ANDROID_GLES2 + if( ConfigureBrush() ) { + glBegin( GL_TRIANGLE_FAN ); + glVertex2f( cx, cy ); + for( float a = 0; a <= 2 * M_PI + M_PI/steps; a += 2 * M_PI / steps ) + glVertex2f( cx + r1 * sinf( a ), cy + r2 * cosf( a ) ); + glEnd(); + } + + if( ConfigurePen() ) { + glBegin( GL_LINE_LOOP ); + for( float a = 0; a < 2 * M_PI - M_PI/steps; a += 2 * M_PI / steps ) + glVertex2f( cx + r1 * sinf( a ), cy + r2 * cosf( a ) ); + glEnd(); + } +#else +#endif + glDisable( GL_BLEND ); + } +#endif +} + +void piDC::DrawPolygon( int n, wxPoint points[], wxCoord xoffset, wxCoord yoffset, float scale, float angle ) +{ + if( dc ) + dc->DrawPolygon( n, points, xoffset, yoffset ); +#ifdef ocpnUSE_GL + else { + +#ifdef __WXQT__ + SetGLAttrs( false ); // Some QT platforms (Android) have trouble with GL_BLEND / GL_LINE_SMOOTH +#else + SetGLAttrs( true ); +#endif + +#ifdef USE_ANDROID_GLES2 + // Grow the work buffer as necessary + if( workBufSize < (size_t)n*2 ){ + workBuf = (float *)realloc(workBuf, (n*4) * sizeof(float)); + workBufSize = n*4; + } + + for( int i = 0; i < n; i++ ){ + workBuf[i*2] = (points[i].x * scale); // + xoffset; + workBuf[i*2 + 1] = (points[i].y * scale); // + yoffset; + } + + glUseProgram( pi_color_tri_shader_program ); + + // Get pointers to the attributes in the program. + GLint mPosAttrib = glGetAttribLocation( pi_color_tri_shader_program, "position" ); + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + glVertexAttribPointer( mPosAttrib, 2, GL_FLOAT, GL_FALSE, 0, workBuf ); + glEnableVertexAttribArray( mPosAttrib ); + + + // Border color + float bcolorv[4]; + bcolorv[0] = m_pen.GetColour().Red() / 255.0f; + bcolorv[1] = m_pen.GetColour().Green() / 255.0f; + bcolorv[2] = m_pen.GetColour().Blue() / 255.0f; + bcolorv[3] = m_pen.GetColour().Alpha() / 255.0f; + + GLint bcolloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(bcolloc, 1, bcolorv); + + + // Rotate + mat4x4 I, Q; + mat4x4_identity(I); + mat4x4_rotate_Z(Q, I, angle); + + // Translate + Q[3][0] = xoffset; + Q[3][1] = yoffset; + + GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)Q); + + // Perform the actual drawing. + glDrawArrays(GL_LINE_LOOP, 0, n); + + // Fill color + bcolorv[0] = m_brush.GetColour().Red() / 255.0f; + bcolorv[1] = m_brush.GetColour().Green() / 255.0f; + bcolorv[2] = m_brush.GetColour().Blue() / 255.0f; + bcolorv[3] = m_brush.GetColour().Alpha() / 255.0f; + + glUniform4fv(bcolloc, 1, bcolorv); + + // For the simple common case of a convex rectangle... + // swizzle the array points to enable GL_TRIANGLE_STRIP + if(n == 4){ + float x1 = workBuf[4]; + float y1 = workBuf[5]; + workBuf[4] = workBuf[6]; + workBuf[5] = workBuf[7]; + workBuf[6] = x1; + workBuf[7] = y1; + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + } + else if(n == 3){ + glDrawArrays(GL_TRIANGLES, 0, 3); + } + + // Restore the per-object transform to Identity Matrix + mat4x4 IM; + mat4x4_identity(IM); + GLint matlocf = glGetUniformLocation(pi_color_tri_shader_program,"TransformMatrix"); + glUniformMatrix4fv( matlocf, 1, GL_FALSE, (const GLfloat*)IM); + +#else + + if( ConfigureBrush() ) { + glEnable( GL_POLYGON_SMOOTH ); + glBegin( GL_POLYGON ); + for( int i = 0; i < n; i++ ) + glVertex2f( (points[i].x * scale) + xoffset, (points[i].y * scale) + yoffset ); + glEnd(); + glDisable( GL_POLYGON_SMOOTH ); + } + + if( ConfigurePen() ) { + glEnable( GL_LINE_SMOOTH ); + glBegin( GL_LINE_LOOP ); + for( int i = 0; i < n; i++ ) + glVertex2f( (points[i].x * scale) + xoffset, (points[i].y * scale) + yoffset ); + glEnd(); + glDisable( GL_LINE_SMOOTH ); + } +#endif + + SetGLAttrs( false ); + + } +#endif +} + +#ifdef ocpnUSE_GL + +// GL callbacks + +typedef union { + GLdouble data[6]; + struct sGLvertex { + GLdouble x; + GLdouble y; + GLdouble z; + GLdouble r; + GLdouble g; + GLdouble b; + } info; +} GLvertex; + +#ifndef USE_ANDROID_GLES2 +static void piDCcombineCallback( GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], + GLdouble **dataOut ) +{ + GLvertex *vertex; + + vertex = new GLvertex(); + pi_gTesselatorVertices.Add(vertex ); + + vertex->info.x = coords[0]; + vertex->info.y = coords[1]; + vertex->info.z = coords[2]; + + for( int i = 3; i < 6; i++ ) { + vertex->data[i] = weight[0] * vertex_data[0][i] + weight[1] * vertex_data[1][i]; + } + + *dataOut = &(vertex->data[0]); +} + +static void piDCvertexCallback( GLvoid* arg ) +{ + GLvertex* vertex; + vertex = (GLvertex*) arg; + glVertex2f( (float)vertex->info.x, (float)vertex->info.y ); +} + +static void piDCerrorCallback( GLenum errorCode ) +{ +// const GLubyte *estring; +// estring = gluErrorString(errorCode); + //wxLogMessage( _T("OpenGL Tessellation Error: %s"), (char *)estring ); +} + +static void piDCbeginCallback( GLenum type ) +{ + glBegin( type ); +} + +static void piDCendCallback() +{ + glEnd(); +} +#endif + + +// GLSL callbacks + + +#ifdef USE_ANDROID_GLES2 + +static std::list odc_combine_work_data; +static void pi_odc_combineCallbackD(GLdouble coords[3], + GLdouble *vertex_data[4], + GLfloat weight[4], GLdouble **dataOut, void *data ) +{ +// double *vertex = new double[3]; +// odc_combine_work_data.push_back(vertex); +// memcpy(vertex, coords, 3*(sizeof *coords)); +// *dataOut = vertex; +} + +void pi_odc_vertexCallbackD_GLSL(GLvoid *vertex, void *data) +{ + piDC* pDC = (piDC*)data; + + // Grow the work buffer if necessary + if(pDC->s_odc_tess_vertex_idx > pDC->s_odc_tess_buf_len - 8) + { + int new_buf_len = pDC->s_odc_tess_buf_len + 100; + GLfloat * tmp = pDC->s_odc_tess_work_buf; + + pDC->s_odc_tess_work_buf = (GLfloat *)realloc(pDC->s_odc_tess_work_buf, new_buf_len * sizeof(GLfloat)); + if (NULL == pDC->s_odc_tess_work_buf) + { + free(tmp); + tmp = NULL; + } + else + pDC->s_odc_tess_buf_len = new_buf_len; + } + + GLdouble *pointer = (GLdouble *) vertex; + + pDC->s_odc_tess_work_buf[pDC->s_odc_tess_vertex_idx++] = (float)pointer[0]; + pDC->s_odc_tess_work_buf[pDC->s_odc_tess_vertex_idx++] = (float)pointer[1]; + + pDC->s_odc_nvertex++; +} + +void pi_odc_beginCallbackD_GLSL( GLenum mode, void *data) +{ + piDC* pDC = (piDC*)data; + pDC->s_odc_tess_vertex_idx_this = pDC->s_odc_tess_vertex_idx; + pDC->s_odc_tess_mode = mode; + pDC->s_odc_nvertex = 0; +} + +void pi_odc_endCallbackD_GLSL(void *data) +{ + //qDebug() << "End" << s_odc_nvertex << s_odc_tess_buf_len << s_odc_tess_vertex_idx << s_odc_tess_vertex_idx_this; + //End 5 100 10 0 +#if 1 + piDC* pDC = (piDC*)data; + + glUseProgram(pi_color_tri_shader_program); + + // Disable VBO's (vertex buffer objects) for attributes. + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); + + float *bufPt = &(pDC->s_odc_tess_work_buf[pDC->s_odc_tess_vertex_idx_this]); + GLint pos = glGetAttribLocation(pi_color_tri_shader_program, "position"); + glVertexAttribPointer(pos, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), bufPt); + glEnableVertexAttribArray(pos); + + ///GLint matloc = glGetUniformLocation(pi_color_tri_shader_program,"MVMatrix"); + ///glUniformMatrix4fv( matloc, 1, GL_FALSE, (const GLfloat*)s_tessVP.vp_transform); + + float colorv[4]; + wxColour c = pDC->GetBrush().GetColour(); + + colorv[0] = c.Red() / 255.0f; + colorv[1] = c.Green() / 255.0f; + colorv[2] = c.Blue() / 255.0f; + colorv[3] = c.Alpha() / 255.0f; + + GLint colloc = glGetUniformLocation(pi_color_tri_shader_program,"color"); + glUniform4fv(colloc, 1, colorv); + + glDrawArrays(pDC->s_odc_tess_mode, 0, pDC->s_odc_nvertex); +#endif +} +#endif + + +#endif //#ifdef ocpnUSE_GL + +void piDC::StrokePolygon( int n, wxPoint points[], wxCoord xoffset, wxCoord yoffset, float scale ) +{ +#if wxUSE_GRAPHICS_CONTEXT + if( pgc ) { + wxGraphicsPath gpath = pgc->CreatePath(); + gpath.MoveToPoint( points[0].x + xoffset, points[0].y + yoffset ); + for( int i = 1; i < n; i++ ) + gpath.AddLineToPoint( points[i].x + xoffset, points[i].y + yoffset ); + gpath.AddLineToPoint( points[0].x + xoffset, points[0].y + yoffset ); + + pgc->SetPen( GetPen() ); + pgc->SetBrush( GetBrush() ); + pgc->DrawPath( gpath ); + + for( int i = 0; i < n; i++ ) + dc->CalcBoundingBox( points[i].x + xoffset, points[i].y + yoffset ); + } else +#endif + DrawPolygon( n, points, xoffset, yoffset, scale ); +} + +void piDC::DrawBitmap( const wxBitmap &bitmap, wxCoord x, wxCoord y, bool usemask ) +{ + wxBitmap bmp; + if( x < 0 || y < 0 ) { + int dx = ( x < 0 ? -x : 0 ); + int dy = ( y < 0 ? -y : 0 ); + int w = bitmap.GetWidth() - dx; + int h = bitmap.GetHeight() - dy; + /* picture is out of viewport */ + if( w <= 0 || h <= 0 ) return; + wxBitmap newBitmap = bitmap.GetSubBitmap( wxRect( dx, dy, w, h ) ); + x += dx; + y += dy; + bmp = newBitmap; + } else { + bmp = bitmap; + } + if( dc ) + dc->DrawBitmap( bmp, x, y, usemask ); +#ifdef ocpnUSE_GL + else { +#ifdef ocpnUSE_GLES // Do not attempt to do anything with glDrawPixels if using opengles + return; // this should not be hit anymore ever anyway +#endif + +#ifndef USE_ANDROID_GLES2 + wxImage image = bmp.ConvertToImage(); + int w = image.GetWidth(), h = image.GetHeight(); + + if( usemask ) { + unsigned char *d = image.GetData(); + unsigned char *a = image.GetAlpha(); + + unsigned char mr, mg, mb; + if( !image.GetOrFindMaskColour( &mr, &mg, &mb ) && !a ){ + printf("trying to use mask to draw a bitmap without alpha or mask\n" ); + } + +#ifdef __WXOSX__ + if(image.HasMask()) + a=0; +#endif + + unsigned char *e = new unsigned char[4 * w * h]; + if(e && d){ + for( int y = 0; y < h; y++ ) + for( int x = 0; x < w; x++ ) { + unsigned char r, g, b; + int off = ( y * image.GetWidth() + x ); + r = d[off * 3 + 0]; + g = d[off * 3 + 1]; + b = d[off * 3 + 2]; + + e[off * 4 + 0] = r; + e[off * 4 + 1] = g; + e[off * 4 + 2] = b; + + e[off * 4 + 3] = + a ? a[off] : ( ( r == mr ) && ( g == mg ) && ( b == mb ) ? 0 : 255 ); +// e[off * 4 + 3] = ( ( r == mr ) && ( g == mg ) && ( b == mb ) ? 0 : 255 ); + } + } + + glColor4f( 1, 1, 1, 1 ); + GLDrawBlendData( x, y, w, h, GL_RGBA, e ); + delete[] ( e ); + } else { + glRasterPos2i( x, y ); + glPixelZoom( 1, -1 ); /* draw data from top to bottom */ + if(image.GetData()) + glDrawPixels( w, h, GL_RGB, GL_UNSIGNED_BYTE, image.GetData() ); + glPixelZoom( 1, 1 ); + } +#endif // GLES2 + } + +#endif +} + +static int NextPow2(int size) +{ + int n = size-1; // compute dimensions needed as next larger power of 2 + int shift = 1; + while ((n+1) & n){ + n |= n >> shift; + shift <<= 1; + } + + return n + 1; +} + +void piDC::DrawText( const wxString &text, wxCoord x, wxCoord y ) +{ + if( dc ) + dc->DrawText( text, x, y ); +#ifdef ocpnUSE_GL + else { + wxCoord w = 0; + wxCoord h = 0; + + if(m_buseTex){ + + m_texfont.Build( m_font ); // make sure the font is ready + m_texfont.GetTextExtent(text, &w, &h); + + if( w && h ) { + + if(m_textbackgroundcolour.Alpha() != 0) { + wxPen p = m_pen; + wxBrush b = m_brush; + SetPen(*wxTRANSPARENT_PEN); + SetBrush(wxBrush(m_textbackgroundcolour)); + DrawRoundedRectangle(x, y, w, h, 3); + SetPen(p); + SetBrush(b); + } + + glEnable( GL_BLEND ); + glEnable( GL_TEXTURE_2D ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + +#ifndef USE_ANDROID_GLES2 + glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); + glPushMatrix(); + glTranslatef(x, y, 0); + + glColor3ub( m_textforegroundcolour.Red(), + m_textforegroundcolour.Green(), + m_textforegroundcolour.Blue() ); + + + m_texfont.RenderString(text); + glPopMatrix(); +#else + m_texfont.SetColor(m_textforegroundcolour); + m_texfont.RenderString(text, x, y); +#endif + glDisable( GL_TEXTURE_2D ); + glDisable( GL_BLEND ); + + } + } + else{ + wxScreenDC sdc; + sdc.SetFont(m_font); + sdc.GetTextExtent(text, &w, &h, NULL, NULL, &m_font); + + /* create bitmap of appropriate size and select it */ + wxBitmap bmp( w, h ); + wxMemoryDC temp_dc; + temp_dc.SelectObject( bmp ); + + /* fill bitmap with black */ + temp_dc.SetBackground( wxBrush( wxColour( 0, 0, 0 ) ) ); + temp_dc.Clear(); + + /* draw the text white */ + temp_dc.SetFont( m_font ); + temp_dc.SetTextForeground( wxColour( 255, 255, 255 ) ); + temp_dc.DrawText( text, 0, 0 ); + temp_dc.SelectObject( wxNullBitmap ); + + /* use the data in the bitmap for alpha channel, + and set the color to text foreground */ + wxImage image = bmp.ConvertToImage(); + if( x < 0 || y < 0 ) { // Allow Drawing text which is offset to start off screen + int dx = ( x < 0 ? -x : 0 ); + int dy = ( y < 0 ? -y : 0 ); + w = bmp.GetWidth() - dx; + h = bmp.GetHeight() - dy; + /* picture is out of viewport */ + if( w <= 0 || h <= 0 ) return; + image = image.GetSubImage( wxRect( dx, dy, w, h ) ); + x += dx; + y += dy; + } + + unsigned char *data = new unsigned char[w * h * 4]; + unsigned char *im = image.GetData(); + + + if(im){ + unsigned int r = m_textforegroundcolour.Red(); + unsigned int g = m_textforegroundcolour.Green(); + unsigned int b = m_textforegroundcolour.Blue(); + for( int i = 0; i < h; i++ ){ + for(int j=0 ; j < w ; j++){ + unsigned int index = ((i*w) + j) * 4; + data[index] = r; + data[index+1] = g; + data[index+2] = b; + data[index+3] = im[((i*w) + j) * 3]; + } + } + } +#if 0 + glColor4ub( 255, 255, 255, 255 ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glRasterPos2i( x, y ); + glPixelZoom( 1, -1 ); + glDrawPixels( w, h, GL_RGBA, GL_UNSIGNED_BYTE, data ); + glPixelZoom( 1, 1 ); + glDisable( GL_BLEND ); +#else + unsigned int texobj; + + glGenTextures(1, &texobj); + glBindTexture(GL_TEXTURE_2D, texobj); + + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + + int TextureWidth = NextPow2(w); + int TextureHeight = NextPow2(h); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TextureWidth, TextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, data); + + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + +#ifndef USE_ANDROID_GLES2 + glColor3ub(0,0,0); + + float u = (float)w/TextureWidth, v = (float)h/TextureHeight; + glBegin(GL_QUADS); + glTexCoord2f(0, 0); glVertex2f(x, y); + glTexCoord2f(u, 0); glVertex2f(x+w, y); + glTexCoord2f(u, v); glVertex2f(x+w, y+h); + glTexCoord2f(0, v); glVertex2f(x, y+h); + glEnd(); +#else +#endif + glDisable(GL_BLEND); + glDisable(GL_TEXTURE_2D); + + glDeleteTextures(1, &texobj); +#endif + delete[] data; + } + } +#endif +} + +void piDC::GetTextExtent( const wxString &string, wxCoord *w, wxCoord *h, wxCoord *descent, + wxCoord *externalLeading, wxFont *font ) +{ + // Give at least reasonable results on failure. + if(w) *w = 100; + if(h) *h = 100; + + if( dc ) dc->GetTextExtent( string, w, h, descent, externalLeading, font ); + else { + wxFont f = m_font; + if( font ) f = *font; + + if(m_buseTex){ + #ifdef ocpnUSE_GL + m_texfont.Build( f ); // make sure the font is ready + m_texfont.GetTextExtent(string, w, h); + #else + wxMemoryDC temp_dc; + temp_dc.GetTextExtent( string, w, h, descent, externalLeading, &f ); + #endif + } + else{ + wxMemoryDC temp_dc; + temp_dc.GetTextExtent( string, w, h, descent, externalLeading, &f ); + } + + } + + // Sometimes GetTextExtent returns really wrong, uninitialized results. + // Dunno why.... + if( w && (*w > 2000) ) *w = 2000; + if( h && (*h > 500) ) *h = 500; +} + +void piDC::ResetBoundingBox() +{ + if( dc ) dc->ResetBoundingBox(); +} + +void piDC::CalcBoundingBox( wxCoord x, wxCoord y ) +{ + if( dc ) dc->CalcBoundingBox( x, y ); +} + +bool piDC::ConfigurePen() +{ + if( !m_pen.IsOk() ) return false; + if( m_pen == *wxTRANSPARENT_PEN ) return false; + + wxColour c = m_pen.GetColour(); + int width = m_pen.GetWidth(); +#ifdef ocpnUSE_GL +#ifndef USE_ANDROID_GLES2 + glColor4ub( c.Red(), c.Green(), c.Blue(), c.Alpha() ); + glLineWidth( wxMax(GLMinSymbolLineWidth, width) ); +#endif +#endif + return true; +} + +bool piDC::ConfigureBrush() +{ + if( m_brush == wxNullBrush || m_brush.GetStyle() == wxBRUSHSTYLE_TRANSPARENT ) + return false; +#ifdef ocpnUSE_GL +#ifndef USE_ANDROID_GLES2 + wxColour c = m_brush.GetColour(); + glColor4ub( c.Red(), c.Green(), c.Blue(), c.Alpha() ); +#endif +#endif + return true; +} + +void piDC::GLDrawBlendData( wxCoord x, wxCoord y, wxCoord w, wxCoord h, int format, + const unsigned char *data ) +{ +#ifdef ocpnUSE_GL +#ifndef USE_ANDROID_GLES2 + glEnable( GL_BLEND ); + glRasterPos2i( x, y ); + glPixelZoom( 1, -1 ); + glDrawPixels( w, h, format, GL_UNSIGNED_BYTE, data ); + glPixelZoom( 1, 1 ); + glDisable( GL_BLEND ); +#endif +#endif +} diff --git a/libs/pluginDC/src/qtstylesheet.cpp b/libs/pluginDC/src/qtstylesheet.cpp new file mode 100644 index 00000000..3c9d6c77 --- /dev/null +++ b/libs/pluginDC/src/qtstylesheet.cpp @@ -0,0 +1,177 @@ +#ifdef __OCPN__ANDROID__ +#include + +QString qtStyleSheet = "\ +QScrollBar:horizontal {\ +border: 0px solid grey;\ +background-color: rgb(240, 240, 240);\ +height: 35px;\ +margin: 0px 1px 0 1px;\ +}\ +QScrollBar::handle:horizontal {\ +background-color: rgb(200, 200, 200);\ +min-width: 20px;\ +border-radius: 10px;\ +}\ +QScrollBar::add-line:horizontal {\ +border: 0px solid grey;\ +background: #32CC99;\ +width: 0px;\ +subcontrol-position: right;\ +subcontrol-origin: margin;\ +}\ +QScrollBar::sub-line:horizontal {\ +border: 0px solid grey;\ +background: #32CC99;\ +width: 0px;\ +subcontrol-position: left;\ +subcontrol-origin: margin;\ +}\ +QScrollBar:vertical {\ +border: 0px solid grey;\ +background-color: rgb(240, 240, 240);\ +width: 35px;\ +margin: 1px 0px 1px 0px;\ +}\ +QScrollBar::handle:vertical {\ +background-color: rgb(200, 200, 200);\ +min-height: 20px;\ +border-radius: 10px;\ +}\ +QScrollBar::add-line:vertical {\ +border: 0px solid grey;\ +background: #32CC99;\ +height: 0px;\ +subcontrol-position: top;\ +subcontrol-origin: margin;\ +}\ +QScrollBar::sub-line:vertical {\ +border: 0px solid grey;\ +background: #32CC99;\ +height: 0px;\ +subcontrol-position: bottom;\ +subcontrol-origin: margin;\ +}\ +QCheckBox {\ +spacing: 18px;\ +}\ +QCheckBox::indicator {\ +width: 20px;\ +height: 20px;\ +}\ +QTreeWidget QScrollBar:vertical {\ + border: 0px solid grey;\ + background-color: rgb(240, 240, 240);\ + width: 35px;\ + margin: 1px 0px 1px 0px;\ +}\ +QTreeWidget QScrollBar::handle:vertical {\ + background-color: rgb(200, 200, 200);\ + min-height: 20px;\ + border-radius: 10px;\ +}\ +QTreeWidget QScrollBar::add-line:vertical {\ + border: 0px solid grey;\ + background: #32CC99;\ + height: 0px;\ + subcontrol-position: top;\ + subcontrol-origin: margin;\ +}\ +\ +QTreeWidget QScrollBar::sub-line:vertical {\ + border: 0px solid grey;\ + background: #32CC99;\ + height: 0px;\ + subcontrol-position: bottom;\ + subcontrol-origin: margin;\ +}\ +\ +QTreeWidget QScrollBar:horizontal {\ + border: 0px solid grey;\ + background-color: rgb(240, 240, 240);\ + height: 35px;\ + margin: 0px 1px 0 1px;\ +}\ +QTreeWidget QScrollBar::handle:horizontal {\ + background-color: rgb(200, 200, 200);\ + min-width: 20px;\ + border-radius: 10px;\ +}\ +QTreeWidget QScrollBar::add-line:horizontal {\ + border: 0px solid grey;\ + background: #32CC99;\ + width: 0px;\ + subcontrol-position: right;\ + subcontrol-origin: margin;\ +}\ +QTreeWidget QScrollBar::sub-line:horizontal {\ + border: 0px solid grey;\ + background: #32CC99;\ + width: 0px;\ + subcontrol-position: left;\ + subcontrol-origin: margin;\ +}\ +QScrollBar::handle:horizontal {\ +background-color: rgb(200, 200, 200);\ +min-width: 20px;\ +border-radius: 10px;\ +}\ +QScrollBar::add-line:horizontal {\ +border: 0px solid grey;\ +background: #32CC99;\ +width: 0px;\ +subcontrol-position: right;\ +subcontrol-origin: margin;\ +}\ +QScrollBar::sub-line:horizontal {\ +border: 0px solid grey;\ +background: #32CC99;\ +width: 0px;\ +subcontrol-position: left;\ +subcontrol-origin: margin;\ +}\ +QScrollBar:vertical {\ +border: 0px solid grey;\ +background-color: rgb(240, 240, 240);\ +width: 35px;\ +margin: 1px 0px 1px 0px;\ +}\ +QScrollBar::handle:vertical {\ +background-color: rgb(200, 200, 200);\ +min-height: 20px;\ +border-radius: 10px;\ +}\ +QScrollBar::add-line:vertical {\ +border: 0px solid grey;\ +background: #32CC99;\ +height: 0px;\ +subcontrol-position: top;\ +subcontrol-origin: margin;\ +}\ +QScrollBar::sub-line:vertical {\ +border: 0px solid grey;\ +background: #32CC99;\ +height: 0px;\ +subcontrol-position: bottom;\ +subcontrol-origin: margin;\ +}\ +QCheckBox {\ +spacing: 25px;\ +}\ +QCheckBox::indicator {\ +width: 30px;\ +height: 30px;\ +}\ +QRadioButton {\ + font-size: 16px;\ +} \ +QPushButton {\ + font-size: 16px;\ +} \ +QTreeWidget::item {\ + border: 0px solid grey;\ + height: 25px;\ + font-size: 25px;\ +}\ +"; +#endif diff --git a/po/POTFILES.in b/po/POTFILES.in index de0661c1..53a58a67 100644 --- a/po/POTFILES.in +++ b/po/POTFILES.in @@ -22,6 +22,7 @@ src/icons.cpp src/zuFile.cpp src/georef.c src/GribRecord.cpp +src/navobj_util.cpp include/weather_routing_pi.h include/WeatherRouting.h include/ConfigurationDialog.h @@ -46,3 +47,4 @@ include/icons.h include/zuFile.h include/georef.h include/GribRecord.h +include/navobj_util.h diff --git a/po/POTFILES.in.test b/po/POTFILES.in.test index de0661c1..53a58a67 100644 --- a/po/POTFILES.in.test +++ b/po/POTFILES.in.test @@ -22,6 +22,7 @@ src/icons.cpp src/zuFile.cpp src/georef.c src/GribRecord.cpp +src/navobj_util.cpp include/weather_routing_pi.h include/WeatherRouting.h include/ConfigurationDialog.h @@ -46,3 +47,4 @@ include/icons.h include/zuFile.h include/georef.h include/GribRecord.h +include/navobj_util.h From ec78299f545b4c00b94304652b53bd9740204317 Mon Sep 17 00:00:00 2001 From: Dave Date: Tue, 5 Sep 2023 21:15:36 -0400 Subject: [PATCH 04/73] Further refine common "libs" directory --- CMakeLists.txt | 26 +- .../json-schema-draft7.json.cpp | 185 + libs/json-schema-validator/json-uri.cpp | 149 + libs/json-schema-validator/json-validator.cpp | 1107 + .../nlohmann/json-schema.hpp | 157 + libs/json-schema-validator/nlohmann/json.hpp | 20842 ++++++++++++++++ libs/jsoncpp/CMakeLists.txt | 31 +- libs/jsoncpp/{ => include}/json/assertions.h | 0 libs/jsoncpp/{ => include}/json/autolink.h | 0 libs/jsoncpp/{ => include}/json/config.h | 0 libs/jsoncpp/{ => include}/json/features.h | 0 libs/jsoncpp/{ => include}/json/forwards.h | 0 libs/jsoncpp/{ => include}/json/json.h | 0 libs/jsoncpp/{ => include}/json/reader.h | 0 libs/jsoncpp/{ => include}/json/value.h | 0 libs/jsoncpp/{ => include}/json/writer.h | 0 .../{src => include}/json_batchallocator.h | 0 libs/nmea0183/CMakeLists.txt | 96 + libs/nmea0183/src/LatLong.hpp | 142 + libs/nmea0183/src/RMB.hpp | 83 + libs/nmea0183/src/RMC.HPP | 79 + .../TexFont.h => nmea0183/src/Response.hpp} | 105 +- .../pi_shaders.h => nmea0183/src/SatInfo.h} | 45 +- libs/nmea0183/src/Sentence.hpp | 98 + libs/nmea0183/src/dbt.cpp | 134 + libs/nmea0183/src/dbt.hpp | 75 + libs/nmea0183/src/dpt.cpp | 139 + libs/nmea0183/src/dpt.hpp | 74 + libs/nmea0183/src/expid.cpp | 429 + libs/nmea0183/src/gga.cpp | 175 + libs/nmea0183/src/gga.hpp | 81 + libs/nmea0183/src/gll.cpp | 194 + libs/nmea0183/src/gll.hpp | 76 + libs/nmea0183/src/gsv.cpp | 179 + libs/nmea0183/src/gsv.hpp | 79 + libs/nmea0183/src/hdg.cpp | 129 + libs/nmea0183/src/hdg.hpp | 77 + libs/nmea0183/src/hdm.cpp | 113 + libs/nmea0183/src/hdm.hpp | 73 + libs/nmea0183/src/hdt.cpp | 113 + libs/nmea0183/src/hdt.hpp | 63 + libs/nmea0183/src/hexvalue.cpp | 57 + libs/nmea0183/src/lat.cpp | 143 + libs/nmea0183/src/latlong.cpp | 91 + libs/nmea0183/src/long.cpp | 143 + libs/nmea0183/src/mda.cpp | 137 + libs/nmea0183/src/mda.hpp | 75 + libs/nmea0183/src/mta.cpp | 122 + libs/nmea0183/src/mta.hpp | 74 + libs/nmea0183/src/mtw.cpp | 123 + libs/nmea0183/src/mtw.hpp | 74 + libs/nmea0183/src/mwd.cpp | 133 + libs/nmea0183/src/mwd.hpp | 76 + libs/nmea0183/src/mwv.cpp | 138 + libs/nmea0183/src/mwv.hpp | 77 + libs/nmea0183/src/nmea0183.cpp | 380 + libs/nmea0183/src/nmea0183.h | 153 + libs/nmea0183/src/nmea0183.hpp | 274 + libs/nmea0183/src/response.cpp | 94 + libs/nmea0183/src/rmb.cpp | 195 + libs/nmea0183/src/rmc.cpp | 185 + libs/nmea0183/src/rsa.cpp | 134 + libs/nmea0183/src/rsa.hpp | 77 + libs/nmea0183/src/rte.cpp | 187 + libs/nmea0183/src/rte.hpp | 73 + libs/nmea0183/src/sentence.cpp | 705 + libs/nmea0183/src/talkerid.cpp | 58 + libs/nmea0183/src/vhw.cpp | 141 + libs/nmea0183/src/vhw.hpp | 76 + libs/nmea0183/src/vlw.cpp | 117 + libs/nmea0183/src/vlw.hpp | 74 + libs/nmea0183/src/vtg.cpp | 175 + libs/nmea0183/src/vtg.hpp | 76 + libs/nmea0183/src/vwr.cpp | 139 + libs/nmea0183/src/vwr.hpp | 77 + libs/nmea0183/src/vwt.cpp | 139 + libs/nmea0183/src/vwt.hpp | 77 + libs/nmea0183/src/wpl.cpp | 119 + libs/nmea0183/src/wpl.hpp | 74 + libs/nmea0183/src/xdr.cpp | 146 + libs/nmea0183/src/xdr.hpp | 89 + libs/nmea0183/src/xte.cpp | 154 + libs/nmea0183/src/xte.hpp | 77 + libs/nmea0183/src/zda.cpp | 140 + libs/nmea0183/src/zda.hpp | 78 + libs/plugingl/CMakeLists.txt | 119 - libs/plugingl/include/linmath.h | 574 - libs/plugingl/include/pidc.h | 176 - libs/plugingl/include/qtstylesheet.h | 3 - libs/plugingl/src/TexFont.cpp | 413 - libs/plugingl/src/pi_shaders.cpp | 664 - libs/plugingl/src/pidc.cpp | 1965 -- libs/plugingl/src/qtstylesheet.cpp | 177 - 93 files changed, 31186 insertions(+), 4199 deletions(-) create mode 100644 libs/json-schema-validator/json-schema-draft7.json.cpp create mode 100644 libs/json-schema-validator/json-uri.cpp create mode 100644 libs/json-schema-validator/json-validator.cpp create mode 100644 libs/json-schema-validator/nlohmann/json-schema.hpp create mode 100644 libs/json-schema-validator/nlohmann/json.hpp rename libs/jsoncpp/{ => include}/json/assertions.h (100%) rename libs/jsoncpp/{ => include}/json/autolink.h (100%) rename libs/jsoncpp/{ => include}/json/config.h (100%) rename libs/jsoncpp/{ => include}/json/features.h (100%) rename libs/jsoncpp/{ => include}/json/forwards.h (100%) rename libs/jsoncpp/{ => include}/json/json.h (100%) rename libs/jsoncpp/{ => include}/json/reader.h (100%) rename libs/jsoncpp/{ => include}/json/value.h (100%) rename libs/jsoncpp/{ => include}/json/writer.h (100%) rename libs/jsoncpp/{src => include}/json_batchallocator.h (100%) create mode 100644 libs/nmea0183/CMakeLists.txt create mode 100644 libs/nmea0183/src/LatLong.hpp create mode 100644 libs/nmea0183/src/RMB.hpp create mode 100644 libs/nmea0183/src/RMC.HPP rename libs/{plugingl/include/TexFont.h => nmea0183/src/Response.hpp} (51%) rename libs/{plugingl/include/pi_shaders.h => nmea0183/src/SatInfo.h} (65%) create mode 100644 libs/nmea0183/src/Sentence.hpp create mode 100644 libs/nmea0183/src/dbt.cpp create mode 100644 libs/nmea0183/src/dbt.hpp create mode 100644 libs/nmea0183/src/dpt.cpp create mode 100644 libs/nmea0183/src/dpt.hpp create mode 100644 libs/nmea0183/src/expid.cpp create mode 100644 libs/nmea0183/src/gga.cpp create mode 100644 libs/nmea0183/src/gga.hpp create mode 100644 libs/nmea0183/src/gll.cpp create mode 100644 libs/nmea0183/src/gll.hpp create mode 100644 libs/nmea0183/src/gsv.cpp create mode 100644 libs/nmea0183/src/gsv.hpp create mode 100644 libs/nmea0183/src/hdg.cpp create mode 100644 libs/nmea0183/src/hdg.hpp create mode 100644 libs/nmea0183/src/hdm.cpp create mode 100644 libs/nmea0183/src/hdm.hpp create mode 100644 libs/nmea0183/src/hdt.cpp create mode 100644 libs/nmea0183/src/hdt.hpp create mode 100644 libs/nmea0183/src/hexvalue.cpp create mode 100644 libs/nmea0183/src/lat.cpp create mode 100644 libs/nmea0183/src/latlong.cpp create mode 100644 libs/nmea0183/src/long.cpp create mode 100644 libs/nmea0183/src/mda.cpp create mode 100644 libs/nmea0183/src/mda.hpp create mode 100644 libs/nmea0183/src/mta.cpp create mode 100644 libs/nmea0183/src/mta.hpp create mode 100644 libs/nmea0183/src/mtw.cpp create mode 100644 libs/nmea0183/src/mtw.hpp create mode 100644 libs/nmea0183/src/mwd.cpp create mode 100644 libs/nmea0183/src/mwd.hpp create mode 100644 libs/nmea0183/src/mwv.cpp create mode 100644 libs/nmea0183/src/mwv.hpp create mode 100644 libs/nmea0183/src/nmea0183.cpp create mode 100644 libs/nmea0183/src/nmea0183.h create mode 100644 libs/nmea0183/src/nmea0183.hpp create mode 100644 libs/nmea0183/src/response.cpp create mode 100644 libs/nmea0183/src/rmb.cpp create mode 100644 libs/nmea0183/src/rmc.cpp create mode 100644 libs/nmea0183/src/rsa.cpp create mode 100644 libs/nmea0183/src/rsa.hpp create mode 100644 libs/nmea0183/src/rte.cpp create mode 100644 libs/nmea0183/src/rte.hpp create mode 100644 libs/nmea0183/src/sentence.cpp create mode 100644 libs/nmea0183/src/talkerid.cpp create mode 100644 libs/nmea0183/src/vhw.cpp create mode 100644 libs/nmea0183/src/vhw.hpp create mode 100644 libs/nmea0183/src/vlw.cpp create mode 100644 libs/nmea0183/src/vlw.hpp create mode 100644 libs/nmea0183/src/vtg.cpp create mode 100644 libs/nmea0183/src/vtg.hpp create mode 100644 libs/nmea0183/src/vwr.cpp create mode 100644 libs/nmea0183/src/vwr.hpp create mode 100644 libs/nmea0183/src/vwt.cpp create mode 100644 libs/nmea0183/src/vwt.hpp create mode 100644 libs/nmea0183/src/wpl.cpp create mode 100644 libs/nmea0183/src/wpl.hpp create mode 100644 libs/nmea0183/src/xdr.cpp create mode 100644 libs/nmea0183/src/xdr.hpp create mode 100644 libs/nmea0183/src/xte.cpp create mode 100644 libs/nmea0183/src/xte.hpp create mode 100644 libs/nmea0183/src/zda.cpp create mode 100644 libs/nmea0183/src/zda.hpp delete mode 100644 libs/plugingl/CMakeLists.txt delete mode 100644 libs/plugingl/include/linmath.h delete mode 100644 libs/plugingl/include/pidc.h delete mode 100644 libs/plugingl/include/qtstylesheet.h delete mode 100644 libs/plugingl/src/TexFont.cpp delete mode 100644 libs/plugingl/src/pi_shaders.cpp delete mode 100644 libs/plugingl/src/pidc.cpp delete mode 100644 libs/plugingl/src/qtstylesheet.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4cfa00aa..236e9b70 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -54,9 +54,9 @@ set(LONG_DESCRIPTION "WR features include: optimal routing subject to various co set(VERSION_MAJOR "1") set(VERSION_MINOR "15") -set(VERSION_PATCH "6") +set(VERSION_PATCH "7") set(VERSION_TWEAK "0") -set(VERSION_DATE "03/09/2023")#DD/MM/YYYY format +set(VERSION_DATE "05/09/2023")#DD/MM/YYYY format set(OCPN_MIN_VERSION "ov58") set(OCPN_API_VERSION_MAJOR "1") set(OCPN_API_VERSION_MINOR "16") @@ -195,13 +195,6 @@ SET (HDRS include/navobj_util.h ) -#set(EXTSRC -#) -#set(EXTINCLUDE -# extinclude/ODAPI.h -# extinclude/ODJSONSchemas.h -#) - set(LIBSSRC libs/wxJSON/src/jsonreader.cpp libs/wxJSON/src/jsonval.cpp libs/wxJSON/src/jsonwriter.cpp) set(LIBHDRS @@ -216,9 +209,6 @@ set(LIBHDRS add_definitions(-DPLUGIN_USE_SVG) -#set(EXTINCLUDE_DIR ${EXTINCLUDE_DIR} extinclude libs/ocpn-api/) - - # ----- If using JSON validation in plugin section below is needed ----- ## @@ -234,8 +224,6 @@ add_definitions(-DPLUGIN_USE_SVG) ##================================================================================ SET(SRC ${SRCS} ${HDRS}) -##SET(SRC ${SRCS} ${HDRS} ${SRC_LIBTESS2} ) - ##========================================= @@ -258,7 +246,7 @@ include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/ODAPI) include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/wxJSON/include) include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/pugixml) -include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/pluginDC) +#include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/pluginDC) ## ## ----- Change above to match project requirements for android build ----- ## @@ -279,7 +267,7 @@ if(NOT OCPN_FLATPAK_CONFIG) add_subdirectory(libs/pluginDC) target_link_libraries(${PACKAGE_NAME} ocpn::tinyxml) - target_link_libraries(${PACKAGE_NAME} ocpn::pluginDC) + target_link_libraries(${PACKAGE_NAME} ocpn::pluginDC) endif(NOT OCPN_FLATPAK_CONFIG) add_definitions(-DTIXML_USE_STL) @@ -328,11 +316,7 @@ endif(QT_ANDROID) include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/jsoncpp) add_subdirectory(libs/jsoncpp) -target_link_libraries(${PACKAGE_NAME} ${PACKAGE_NAME}_LIB_PLUGINJSON) - -include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/plugingl/include) -add_subdirectory(libs/plugingl) -target_link_libraries(${PACKAGE_NAME} ocpn::plugingl) +target_link_libraries(${PACKAGE_NAME} JSONCPP) include_directories(BEFORE ${PROJECT_SOURCE_DIR}/libs/libtess2/include) add_subdirectory(libs/libtess2) diff --git a/libs/json-schema-validator/json-schema-draft7.json.cpp b/libs/json-schema-validator/json-schema-draft7.json.cpp new file mode 100644 index 00000000..b680e2c2 --- /dev/null +++ b/libs/json-schema-validator/json-schema-draft7.json.cpp @@ -0,0 +1,185 @@ +/* + * JSON schema validator for JSON for modern C++ + * + * Copyright (c) 2016-2019 Patrick Boettcher . + * + * SPDX-License-Identifier: MIT + * + */ +#include + +namespace nlohmann +{ +namespace json_schema +{ + +json draft7_schema_builtin = R"( { + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "allOf": [ + { "$ref": "#/definitions/nonNegativeInteger" }, + { "default": 0 } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "number" + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "number" + }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/schemaArray" } + ], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { "$ref": "#" }, + { "$ref": "#/definitions/stringArray" } + ] + } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { "$ref": "#/definitions/simpleTypes" }, + { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true +} )"_json; +} +} // namespace nlohmann diff --git a/libs/json-schema-validator/json-uri.cpp b/libs/json-schema-validator/json-uri.cpp new file mode 100644 index 00000000..f8d6cbe3 --- /dev/null +++ b/libs/json-schema-validator/json-uri.cpp @@ -0,0 +1,149 @@ +/* + * JSON schema validator for JSON for modern C++ + * + * Copyright (c) 2016-2019 Patrick Boettcher . + * + * SPDX-License-Identifier: MIT + * + */ +#include "json-schema.hpp" + +#include + +namespace nlohmann +{ + +void json_uri::update(const std::string &uri) +{ + std::string pointer = ""; // default pointer is document-root + + // first split the URI into location and pointer + auto pointer_separator = uri.find('#'); + if (pointer_separator != std::string::npos) { // and extract the pointer-string if found + pointer = uri.substr(pointer_separator + 1); // remove # + + // unescape %-values IOW, decode JSON-URI-formatted JSON-pointer + std::size_t pos = pointer.size() - 1; + do { + pos = pointer.rfind('%', pos); + if (pos == std::string::npos) + break; + + if (pos >= pointer.size() - 2) { + pos--; + continue; + } + + std::string hex = pointer.substr(pos + 1, 2); + char ascii = (char) std::strtoul(hex.c_str(), nullptr, 16); + pointer.replace(pos, 3, 1, ascii); + + pos--; + } while (1); + } + + auto location = uri.substr(0, pointer_separator); + + if (location.size()) { // a location part has been found + pointer_ = ""_json_pointer; // if a location is given, the pointer is emptied + + // if it is an URN take it as it is + if (location.find("urn:") == 0) { + urn_ = location; + + // and clear URL members + proto_ = ""; + hostname_ = ""; + path_ = ""; + + } else { // it is an URL + + // split URL in protocol, hostname and path + std::size_t pos = 0; + auto proto = location.find("://", pos); + if (proto != std::string::npos) { // extract the protocol + + urn_ = ""; // clear URN-member if URL is parsed + + proto_ = location.substr(pos, proto - pos); + pos = 3 + proto; // 3 == "://" + + auto hostname = location.find("/", pos); + if (hostname != std::string::npos) { // and the hostname (no proto without hostname) + hostname_ = location.substr(pos, hostname - pos); + pos = hostname; + } + } + + auto path = location.substr(pos); + + // URNs cannot of have paths + if (urn_.size() && path.size()) + throw std::invalid_argument("Cannot add a path (" + path + ") to an URN URI (" + urn_ + ")"); + + if (path[0] == '/') // if it starts with a / it is root-path + path_ = path; + else if (pos == 0) { // the URL contained only a path and the current path has no / at the end, strip last element until / and append + auto last_slash = path_.rfind('/'); + path_ = path_.substr(0, last_slash) + '/' + path; + } else // otherwise it is a subfolder + path_.append(path); + } + } + + pointer_ = nlohmann::json::json_pointer(pointer); +} + +const std::string json_uri::location() const +{ + if (urn_.size()) + return urn_; + + std::stringstream s; + + if (proto_.size() > 0) + s << proto_ << "://"; + + s << hostname_ + << path_; + + return s.str(); +} + +std::string json_uri::to_string() const +{ + std::stringstream s; + + s << location() << " # " << pointer_.to_string(); + + return s.str(); +} + +std::ostream &operator<<(std::ostream &os, const json_uri &u) +{ + return os << u.to_string(); +} + +std::string json_uri::escape(const std::string &src) +{ + std::vector> chars = { + {"~", "~0"}, + {"/", "~1"}}; + + std::string l = src; + + for (const auto &c : chars) { + std::size_t pos = 0; + do { + pos = l.find(c.first, pos); + if (pos == std::string::npos) + break; + l.replace(pos, 1, c.second); + pos += c.second.size(); + } while (1); + } + + return l; +} + +} // namespace nlohmann diff --git a/libs/json-schema-validator/json-validator.cpp b/libs/json-schema-validator/json-validator.cpp new file mode 100644 index 00000000..8761600e --- /dev/null +++ b/libs/json-schema-validator/json-validator.cpp @@ -0,0 +1,1107 @@ +/* + * JSON schema validator for JSON for modern C++ + * + * Copyright (c) 2016-2019 Patrick Boettcher . + * + * SPDX-License-Identifier: MIT + * + */ +#include + +#include +#include +#ifdef __MSVC__ +#include +#endif + +#ifdef __OCPN__ANDROID__ +#include +#endif + +using nlohmann::json; +using nlohmann::json_uri; +using nlohmann::json_schema::root_schema; +using namespace nlohmann::json_schema; + +#ifdef JSON_SCHEMA_BOOST_REGEX +# include +# define REGEX_NAMESPACE boost +#elif defined(JSON_SCHEMA_NO_REGEX) +# define NO_STD_REGEX +#else +# include +# define REGEX_NAMESPACE std +#endif + +namespace +{ + +class schema +{ +protected: + root_schema *root_; + +public: + schema(root_schema *root) + : root_(root) {} + + virtual void validate(const json &instance, basic_error_handler &e) const = 0; + + static std::shared_ptr make(json &schema, + root_schema *root, + const std::vector &key, + std::vector uris); +}; + +class logical_not : public schema +{ + std::shared_ptr subschema_; + + void validate(const json &instance, basic_error_handler &e) const final + { + basic_error_handler err; + subschema_->validate(instance, err); + + if (!err) + e.error("", instance, "instance is valid, whereas it should NOT be as required by schema"); + } + +public: + logical_not(json &sch, + root_schema *root, + const std::vector &uris) + : schema(root) + { + subschema_ = schema::make(sch, root, {"not"}, uris); + } +}; + +enum logical_combination_types { + allOf, + anyOf, + oneOf +}; + +template +class logical_combination : public schema +{ + std::vector> subschemata_; + + void validate(const json &instance, basic_error_handler &e) const final + { + size_t count = 0; + + for (auto &s : subschemata_) { + basic_error_handler err; + s->validate(instance, err); + + if (err) { + //sub_schema_err << " one schema failed because: " << e.what() << "\n"; + if (combine_logic == allOf) { + e.error("", instance, "at least one schema has failed, but ALLOF them are required to validate."); + return; + } + } else + count++; + + if (combine_logic == oneOf && count > 1) { + e.error("", instance, "more than one schema has succeeded, but only ONEOF them is required to validate."); + return; + } + if (combine_logic == anyOf && count == 1) + return; + } + + if ((combine_logic == anyOf || combine_logic == oneOf) && count == 0) + e.error("", instance, "no validation has succeeded but ANYOF/ONEOF them is required to validate."); + } + +public: + logical_combination(json &sch, + root_schema *root, + const std::vector &uris) + : schema(root) + { + size_t c = 0; + std::string key; + switch (combine_logic) { + case allOf: + key = "allOf"; + break; + case oneOf: + key = "oneOf"; + break; + case anyOf: + key = "anyOf"; + break; + } + + for (auto &subschema : sch) + subschemata_.push_back(schema::make(subschema, root, {key, std::to_string(c++)}, uris)); + } +}; + +class type_schema : public schema +{ + std::vector> type_; + std::pair enum_, const_; + std::vector> logic_; + + static std::shared_ptr make(json &schema, + json::value_t type, + root_schema *, + const std::vector &, + std::set &); + + std::shared_ptr if_, then_, else_; + + void validate(const json &instance, basic_error_handler &e) const override final + { + // depending on the type of instance run the type specific validator - if present + auto type = type_[(uint8_t) instance.type()]; + + if (type) + type->validate(instance, e); + else + e.error("", instance, "unexpected instance type"); + + if (enum_.first) { + bool seen_in_enum = false; + for (auto &e : enum_.second) + if (instance == e) { + seen_in_enum = true; + break; + } + + if (!seen_in_enum) + e.error("", instance, "instance not found in required enum"); + } + + if (const_.first && + const_.second != instance) + e.error("", instance, "instance not const"); + + for (auto l : logic_) + l->validate(instance, e); + + if (if_) { + basic_error_handler err; + + if_->validate(instance, err); + if (!err) { + if (then_) + then_->validate(instance, e); + } else { + if (else_) + else_->validate(instance, e); + } + } + } + +public: + type_schema(json &sch, + root_schema *root, + const std::vector &uris) + : schema(root), type_((uint8_t) json::value_t::discarded + 1) + { + // association between JSON-schema-type and NLohmann-types + static const std::vector> schema_types = { + {"null", json::value_t::null}, + {"object", json::value_t::object}, + {"array", json::value_t::array}, + {"string", json::value_t::string}, + {"boolean", json::value_t::boolean}, + {"integer", json::value_t::number_integer}, + {"integer", json::value_t::number_unsigned}, + {"number", json::value_t::number_float}, + }; + + std::set known_keywords; + + auto attr = sch.find("type"); + if (attr == sch.end()) // no type field means all sub-types possible + for (auto &t : schema_types) + type_[(uint8_t) t.second] = type_schema::make(sch, t.second, root, uris, known_keywords); + else { + switch (attr.value().type()) { // "type": "type" + + case json::value_t::string: { + auto schema_type = attr.value().get(); + for (auto &t : schema_types) + if (t.first == schema_type) + type_[(uint8_t) t.second] = type_schema::make(sch, t.second, root, uris, known_keywords); + } break; + + case json::value_t::array: // "type": ["type1", "type2"] + for (auto &schema_type : attr.value()) + for (auto &t : schema_types) + if (t.first == schema_type) + type_[(uint8_t) t.second] = type_schema::make(sch, t.second, root, uris, known_keywords); + break; + + default: + break; + } + + sch.erase(attr); + } + + for (auto &key : known_keywords) + sch.erase(key); + + // with nlohmann::json floats can be seen as unsigned or integer - reuse the number-validator for + // integer values as well, if they have not been specified + if (type_[(uint8_t) json::value_t::number_float] && !type_[(uint8_t) json::value_t::number_integer]) + type_[(uint8_t) json::value_t::number_integer] = + type_[(uint8_t) json::value_t::number_unsigned] = + type_[(uint8_t) json::value_t::number_float]; + + attr = sch.find("enum"); + if (attr != sch.end()) { + enum_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("const"); + if (attr != sch.end()) { + const_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("not"); + if (attr != sch.end()) { + logic_.push_back(std::make_shared(attr.value(), root, uris)); + sch.erase(attr); + } + + attr = sch.find("allOf"); + if (attr != sch.end()) { + logic_.push_back(std::make_shared>(attr.value(), root, uris)); + sch.erase(attr); + } + + attr = sch.find("anyOf"); + if (attr != sch.end()) { + logic_.push_back(std::make_shared>(attr.value(), root, uris)); + sch.erase(attr); + } + + attr = sch.find("oneOf"); + if (attr != sch.end()) { + logic_.push_back(std::make_shared>(attr.value(), root, uris)); + sch.erase(attr); + } + + attr = sch.find("if"); + if (attr != sch.end()) { + auto attr_then = sch.find("then"); + auto attr_else = sch.find("else"); + + if (attr_then != sch.end() || attr_else != sch.end()) { + if_ = schema::make(attr.value(), root, {"if"}, uris); + + if (attr_then != sch.end()) { + then_ = schema::make(attr_then.value(), root, {"then"}, uris); + sch.erase(attr_then); + } + + if (attr_else != sch.end()) { + else_ = schema::make(attr_else.value(), root, {"else"}, uris); + sch.erase(attr_else); + } + } + sch.erase(attr); + } + } +}; + +class string : public schema +{ + std::pair maxLength_{false, 0}; + std::pair minLength_{false, 0}; + +#ifndef NO_STD_REGEX + std::pair pattern_{false, REGEX_NAMESPACE::regex()}; + std::string patternString_; +#endif + + std::pair format_; + std::function format_check_ = nullptr; + + std::size_t utf8_length(const std::string &s) const + { + size_t len = 0; + for (const unsigned char &c : s) + if ((c & 0xc0) != 0x80) + len++; + return len; + } + + void validate(const json &instance, basic_error_handler &e) const override + { + if (minLength_.first) { + if (utf8_length(instance) < minLength_.second) { + std::ostringstream s; + s << "'" << instance << "' is too short as per minLength (" << minLength_.second << ")"; + e.error("", instance, s.str()); + } + } + + if (maxLength_.first) { + if (utf8_length(instance) > maxLength_.second) { + std::ostringstream s; + s << "'" << instance << "' is too long as per maxLength (" << maxLength_.second << ")"; + e.error("", instance, s.str()); + } + } + +#ifndef NO_STD_REGEX + if (pattern_.first && + !REGEX_NAMESPACE::regex_search(instance.get(), pattern_.second)) + e.error("", instance, instance.get() + " does not match regex pattern: " + patternString_); +#endif + + if (format_.first) { + if (format_check_ == nullptr) + e.error("", instance, std::string("A format checker was not provided but a format-attribute for this string is present. ") + " cannot be validated for " + format_.second); + else + format_check_(format_.second, instance); + } + } + +public: + string(json &sch, root_schema *root) + : schema(root) + { + auto attr = sch.find("maxLength"); + if (attr != sch.end()) { + maxLength_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("minLength"); + if (attr != sch.end()) { + minLength_ = {true, attr.value()}; + sch.erase(attr); + } + +#ifndef NO_STD_REGEX + attr = sch.find("pattern"); + if (attr != sch.end()) { + patternString_ = attr.value().get(); + pattern_ = {true, REGEX_NAMESPACE::regex(attr.value().get(), + REGEX_NAMESPACE::regex::ECMAScript)}; + sch.erase(attr); + } +#endif + + attr = sch.find("format"); + if (attr != sch.end()) { + format_ = {true, attr.value()}; + sch.erase(attr); + } + } +}; + +template +class numeric : public schema +{ + std::pair maximum_{false, 0}; + std::pair minimum_{false, 0}; + + bool exclusiveMaximum_ = false; + bool exclusiveMinimum_ = false; + + std::pair multipleOf_{false, 0}; + + // multipleOf - if the rest of the division is 0 -> OK + bool violates_multiple_of(json::number_float_t x) const + { + json::number_integer_t n = static_cast(x / multipleOf_.second); + double res = (x - n * multipleOf_.second); + return fabs(res) > std::numeric_limits::epsilon(); + } + + void validate(const json &instance, basic_error_handler &e) const override + { + T value = instance; // conversion of json to value_type + + if (multipleOf_.first && value != 0) // zero is multiple of everything + if (violates_multiple_of(value)) + e.error("", instance, "is not a multiple of " + std::to_string(multipleOf_.second)); + + if (maximum_.first) + if ((exclusiveMaximum_ && value >= maximum_.second) || + value > maximum_.second) + e.error("", instance, "exceeds maximum of " + std::to_string(maximum_.second)); + + if (minimum_.first) + if ((exclusiveMinimum_ && value <= minimum_.second) || + value < minimum_.second) + e.error("", instance, "is below minimum of " + std::to_string(minimum_.second)); + } + +public: + numeric(const json &sch, root_schema *root, std::set &kw) + : schema(root) + { + auto attr = sch.find("maximum"); + if (attr != sch.end()) { + maximum_ = {true, attr.value()}; + kw.insert("maximum"); + } + + attr = sch.find("minimum"); + if (attr != sch.end()) { + minimum_ = {true, attr.value()}; + kw.insert("minimum"); + } + + attr = sch.find("exclusiveMaximum"); + if (attr != sch.end()) { + exclusiveMaximum_ = true; + maximum_ = {true, attr.value()}; + kw.insert("exclusiveMaximum"); + } + + attr = sch.find("exclusiveMinimum"); + if (attr != sch.end()) { + minimum_ = {true, attr.value()}; + exclusiveMinimum_ = true; + kw.insert("exclusiveMinimum"); + } + + attr = sch.find("multipleOf"); + if (attr != sch.end()) { + multipleOf_ = {true, attr.value()}; + kw.insert("multipleOf"); + } + } +}; + +class null : public schema +{ + void validate(const json &instance, basic_error_handler &e) const override + { + if (!instance.is_null()) + e.error("", instance, "expected to be null"); + } + +public: + null(json &, root_schema *root) + : schema(root) {} +}; + +class boolean_type : public schema +{ + void validate(const json &, basic_error_handler &) const override {} + +public: + boolean_type(json &, root_schema *root) + : schema(root) {} +}; + +class boolean : public schema +{ + bool true_; + void validate(const json &instance, basic_error_handler &e) const override + { + if (!true_) { // false schema + // empty array + //switch (instance.type()) { + //case json::value_t::array: + // if (instance.size() != 0) // valid false-schema + // e.error("", instance, "false-schema required empty array"); + // return; + //} + + e.error("", instance, "instance invalid as par false-schema"); + } + } + +public: + boolean(json &sch, root_schema *root) + : schema(root), true_(sch) {} +}; + +class required : public schema +{ + const std::vector required_; + + void validate(const json &instance, basic_error_handler &e) const override final + { + for (auto &r : required_) + if (instance.find(r) == instance.end()) + e.error("", instance, "required property '" + r + "' not found in object as a dependency"); + } + +public: + required(const std::vector &r, root_schema *root) + : schema(root), required_(r) {} +}; + +class object : public schema +{ + std::pair maxProperties_{false, 0}; + std::pair minProperties_{false, 0}; + std::vector required_; + + std::map> properties_; +#ifndef NO_STD_REGEX + std::vector>> patternProperties_; +#endif + std::shared_ptr additionalProperties_; + + std::map> dependencies_; + + std::shared_ptr propertyNames_; + + void validate(const json &instance, basic_error_handler &e) const override + { + if (maxProperties_.first && instance.size() > maxProperties_.second) + e.error("", instance, "too many properties."); + + if (minProperties_.first && instance.size() < minProperties_.second) + e.error("", instance, "too few properties."); + + for (auto &r : required_) + if (instance.find(r) == instance.end()) + e.error("", instance, "required property '" + r + "' not found in object '"); + + // for each property in instance + for (auto &p : instance.items()) { + if (propertyNames_) + propertyNames_->validate(p.key(), e); + + bool a_prop_or_pattern_matched = false; + auto schema_p = properties_.find(p.key()); + // check if it is in "properties" + if (schema_p != properties_.end()) { + a_prop_or_pattern_matched = true; + schema_p->second->validate(p.value(), e); + } + + // check all matching patternProperties + for (auto &schema_pp : patternProperties_) + if (REGEX_NAMESPACE::regex_search(p.key(), schema_pp.first)) { + a_prop_or_pattern_matched = true; + schema_pp.second->validate(p.value(), e); + } + // check additionalProperties as a last resort + if (!a_prop_or_pattern_matched && additionalProperties_) + additionalProperties_->validate(p.value(), e); + } + + for (auto &dep : dependencies_) { + auto prop = instance.find(dep.first); + if (prop != instance.end()) // if dependency-property is present in instance + dep.second->validate(instance, e); // validate + } + } + +public: + object(json &sch, + root_schema *root, + const std::vector &uris) + : schema(root) + { + auto attr = sch.find("maxProperties"); + if (attr != sch.end()) { + maxProperties_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("minProperties"); + if (attr != sch.end()) { + minProperties_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("required"); + if (attr != sch.end()) { + required_ = attr.value().get>(); + sch.erase(attr); + } + + attr = sch.find("properties"); + if (attr != sch.end()) { + for (auto prop : attr.value().items()) + properties_.insert( + std::make_pair( + prop.key(), + schema::make(prop.value(), root, {"properties", prop.key()}, uris))); + sch.erase(attr); + } + +#ifndef NO_STD_REGEX + attr = sch.find("patternProperties"); + if (attr != sch.end()) { + for (auto prop : attr.value().items()) + patternProperties_.push_back( + std::make_pair( + REGEX_NAMESPACE::regex(prop.key(), REGEX_NAMESPACE::regex::ECMAScript), + schema::make(prop.value(), root, {prop.key()}, uris))); + sch.erase(attr); + } +#endif + + attr = sch.find("additionalProperties"); + if (attr != sch.end()) { + additionalProperties_ = schema::make(attr.value(), root, {"additionalProperties"}, uris); + sch.erase(attr); + } + + attr = sch.find("dependencies"); + if (attr != sch.end()) { + for (auto &dep : attr.value().items()) + switch (dep.value().type()) { + case json::value_t::array: + dependencies_.emplace(dep.key(), + std::make_shared( + dep.value().get>(), root)); + break; + + default: + dependencies_.emplace(dep.key(), + schema::make(dep.value(), root, {"dependencies", dep.key()}, uris)); + break; + } + sch.erase(attr); + } + + attr = sch.find("propertyNames"); + if (attr != sch.end()) { + propertyNames_ = schema::make(attr.value(), root, {"propertyNames"}, uris); + sch.erase(attr); + } + } +}; + +class array : public schema +{ + std::pair maxItems_{false, 0}; + std::pair minItems_{false, 0}; + bool uniqueItems_ = false; + + std::shared_ptr items_schema_; + + std::vector> items_; + std::shared_ptr additionalItems_; + + std::shared_ptr contains_; + + void validate(const json &instance, basic_error_handler &e) const override + { + if (maxItems_.first && instance.size() > maxItems_.second) + e.error("", instance, "has too many items."); + + if (minItems_.first && instance.size() < minItems_.second) + e.error("", instance, "has too few items."); + + if (uniqueItems_) { + for (auto it = instance.cbegin(); it != instance.cend(); ++it) { + auto v = std::find(it + 1, instance.end(), *it); + if (v != instance.end()) + e.error("", instance, "items have to be unique for this array."); + } + } + + if (items_schema_) + for (auto &i : instance) + items_schema_->validate(i, e); + else { + auto item = items_.cbegin(); + for (auto &i : instance) { + std::shared_ptr item_validator; + if (item == items_.cend()) + item_validator = additionalItems_; + else { + item_validator = *item; + item++; + } + + if (!item_validator) + break; + + item_validator->validate(i, e); + } + } + + if (contains_) { + bool contained = false; + for (auto &item : instance) { + basic_error_handler local_e; + contains_->validate(item, local_e); + if (!local_e) { + contained = true; + break; + } + } + if (!contained) + e.error("", instance, "array does not contain required element as per 'contains'"); + } + } + +public: + array(json &sch, root_schema *root, const std::vector &uris) + : schema(root) + { + auto attr = sch.find("maxItems"); + if (attr != sch.end()) { + maxItems_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("minItems"); + if (attr != sch.end()) { + minItems_ = {true, attr.value()}; + sch.erase(attr); + } + + attr = sch.find("uniqueItems"); + if (attr != sch.end()) { + uniqueItems_ = attr.value(); + sch.erase(attr); + } + + attr = sch.find("items"); + if (attr != sch.end()) { + + if (attr.value().type() == json::value_t::array) { + size_t c = 0; + for (auto &subsch : attr.value()) + items_.push_back(schema::make(subsch, root, {"items", std::to_string(c++)}, uris)); + + auto attr_add = sch.find("additionalItems"); + if (attr_add != sch.end()) { + additionalItems_ = schema::make(attr_add.value(), root, {"additionalItems"}, uris); + sch.erase(attr_add); + } + + } else if (attr.value().type() == json::value_t::object || + attr.value().type() == json::value_t::boolean) + items_schema_ = schema::make(attr.value(), root, {"items"}, uris); + + sch.erase(attr); + } + + attr = sch.find("contains"); + if (attr != sch.end()) { + contains_ = schema::make(attr.value(), root, {"contains"}, uris); + sch.erase(attr); + } + } +}; + +class schema_ref : public schema +{ + const std::string id_; + std::shared_ptr target_; + + void validate(const json &instance, basic_error_handler &e) const final + { + if (target_) + target_->validate(instance, e); + else + e.error("", instance, "unresolved schema-reference " + id_); + } + +public: + schema_ref(const std::string &id, root_schema *root) + : schema(root), id_(id) {} + + const std::string &id() const { return id_; } + void set_target(std::shared_ptr target) { target_ = target; } +}; + +std::shared_ptr type_schema::make(json &schema, + json::value_t type, + root_schema *root, + const std::vector &uris, + std::set &kw) +{ + switch (type) { + case json::value_t::null: + return std::make_shared(schema, root); + case json::value_t::number_unsigned: + return std::make_shared>(schema, root, kw); + case json::value_t::number_integer: + return std::make_shared>(schema, root, kw); + case json::value_t::number_float: + return std::make_shared>(schema, root, kw); + case json::value_t::string: + return std::make_shared(schema, root); + case json::value_t::boolean: + return std::make_shared(schema, root); + case json::value_t::object: + return std::make_shared(schema, root, uris); + case json::value_t::array: + return std::make_shared(schema, root, uris); + + case json::value_t::discarded: // not a real type - silence please + break; + } + return nullptr; +} +} // namespace + +namespace nlohmann +{ +namespace json_schema +{ + +class root_schema : public schema +{ + std::function loader_; + std::function format_; + + std::shared_ptr root_; + + struct schema_file { + std::map> schemas; + std::map> unresolved; // contains all unresolved references from any other file seen during parsing + json unknown_keywords; + }; + + // location as key + std::map files_; + + schema_file &get_or_create_file(const std::string &loc) + { + auto file = files_.lower_bound(loc); + if (file != files_.end() && !(files_.key_comp()(loc, file->first))) + return file->second; + else + return files_.insert(file, {loc, {}})->second; + } + +public: + root_schema(std::function loader, + std::function format) + : schema(this), loader_(loader), format_(format) {} + + void insert(const json_uri &uri, const std::shared_ptr &s) + { + // std::cout << "adding schema '" << uri << "' '" << uri.location() << "'\n"; + + auto &file = get_or_create_file(uri.location()); + auto schema = file.schemas.lower_bound(uri.pointer()); + if (schema != file.schemas.end() && !(file.schemas.key_comp()(uri.pointer(), schema->first))) { + throw std::invalid_argument("schema with " + uri.to_string() + " already inserted\n"); + return; + } + + file.schemas.insert({uri.pointer(), s}); + + // was someone referencing this newly inserted schema? + auto unresolved = file.unresolved.find(uri.pointer()); + // std::cout << "resolving schemas looking for '" << uri.pointer() << "' in " << uri.location() << "\n"; + if (unresolved != file.unresolved.end()) { + // std::cout << " --> resolved!!\n"; + unresolved->second->set_target(s); + file.unresolved.erase(unresolved); + } + } + + void insert_unknown_keyword(const json_uri &uri, const std::string &key, json &value) + { + auto &file = get_or_create_file(uri.location()); + auto new_uri = uri.append(key); + auto pointer = new_uri.pointer(); + + // std::cout << "inserting unknown " << new_uri << " '" << pointer << "'\n"; + + // is there a reference looking for this unknown-keyword, which is thus no longer a unknown keyword but a schema + auto unresolved = file.unresolved.find(pointer); + if (unresolved != file.unresolved.end()) + schema::make(value, this, {}, {{new_uri}}); + else // no, nothing ref'd it + file.unknown_keywords[pointer] = value; + } + + std::shared_ptr get_or_create_ref(const json_uri &uri) + { + auto &file = get_or_create_file(uri.location()); + + // existing schema + auto schema = file.schemas.find(uri.pointer()); + if (schema != file.schemas.end()) + return schema->second; + + // referencing an unknown keyword, turn it into schema + try { + auto &subschema = file.unknown_keywords.at(uri.pointer()); + auto s = schema::make(subschema, this, {}, {{uri}}); + file.unknown_keywords.erase(uri.pointer()); + return s; + } catch (...) { + } + + // get or create a schema_ref + // std::cout << "using or creating a reference to " << uri << "\n"; + auto r = file.unresolved.lower_bound(uri.pointer()); + if (r != file.unresolved.end() && !(file.unresolved.key_comp()(uri.pointer(), r->first))) { + // std::cout << " --> using existing ref\n"; + return r->second; + } else { + // std::cout << " --> creating a new ref\n"; + return file.unresolved.insert(r, + {uri.pointer(), std::make_shared(uri.to_string(), this)}) + ->second; + } + } + + void set_root_schema(json schema) + { + root_ = schema::make(schema, this, {}, {{"#"}}); + + // load all files which have not yet been loaded + do { + bool new_schema_loaded = false; + + // files_ is modified during parsing, iterators are invalidated + std::vector locations; + for (auto &file : files_) + locations.push_back(file.first); + + for (auto &loc : locations) { + if (files_[loc].schemas.size() == 0) { // nothing has been loaded for this file + if (loader_) { + json sch; + + loader_(loc, sch); + + schema::make(sch, this, {}, {{loc}}); + new_schema_loaded = true; + } else { + throw std::invalid_argument("external schema reference '" + loc + "' needs loading, but no loader callback given\n"); + } + } + } + + if (!new_schema_loaded) // if no new schema loaded, no need to try again + break; + } while (1); + } + + void validate(const json &instance, basic_error_handler &e) const final + { + if (root_) + root_->validate(instance, e); + else + e.error("", "", "no root schema has yet been set for validating an instance."); + } +}; + +} // namespace json_schema +} // namespace nlohmann + +namespace +{ + +std::shared_ptr schema::make(json &schema, + root_schema *root, + const std::vector &keys, + std::vector uris) +{ + // append to all URIs the keys for this sub-schema + for (auto &key : keys) + for (auto &uri : uris) + uri = uri.append(json_uri::escape(key)); + + std::shared_ptr<::schema> sch; + + // boolean schema + if (schema.type() == json::value_t::boolean) + sch = std::make_shared(schema, root); + else if (schema.type() == json::value_t::object) { + + auto attr = schema.find("$id"); // if $id is present, this schema can be referenced by this ID + // as an additional URI + if (attr != schema.end()) { + if (std::find(uris.begin(), + uris.end(), + attr.value().get()) == uris.end()) + uris.push_back(uris.back().derive(attr.value())); // so add it to the list if it is not there already + schema.erase(attr); + } + + attr = schema.find("definitions"); + if (attr != schema.end()) { + for (auto &def : attr.value().items()) + schema::make(def.value(), root, {"definitions", def.key()}, uris); + schema.erase(attr); + } + + attr = schema.find("$ref"); + if (attr != schema.end()) { // this schema is a reference + // the last one on the uri-stack is the last id seen before coming here, + // so this is the origial URI for this reference, the $ref-value has thus be resolved from it + auto id = uris.back().derive(attr.value()); + sch = root->get_or_create_ref(id); + schema.erase(attr); + } else { + sch = std::make_shared(schema, root, uris); + } + + schema.erase("$schema"); + schema.erase("default"); + schema.erase("title"); + schema.erase("description"); + } else { + return nullptr; // TODO error/throw? when schema is invalid + } + + for (auto &uri : uris) { // for all URI reference this schema + root->insert(uri, sch); + + if (schema.type() == json::value_t::object) + for (auto &u : schema.items()) + root->insert_unknown_keyword(uri, u.key(), u.value()); + } + return sch; +} + +class throwing_error_handler : public basic_error_handler +{ + void error(const std::string &path, const json &instance, const std::string &message) + { + throw std::invalid_argument(std::string("At ") + path + " of " + instance.dump() + " - " + message + "\n"); + } +}; + +} // namespace + +namespace nlohmann +{ +namespace json_schema +{ + +json_validator::json_validator(std::function loader, + std::function format) + : root_(std::unique_ptr(new root_schema(loader, format))) +{ +} + +json_validator::~json_validator() +{ +} + +void json_validator::set_root_schema(const json &schema) +{ + root_->set_root_schema(schema); +} + +void json_validator::validate(const json &instance) +{ + throwing_error_handler err; + validate(instance, err); +} + +void json_validator::validate(const json &instance, basic_error_handler &err) +{ + root_->validate(instance, err); +} + +} // namespace json_schema +} // namespace nlohmann diff --git a/libs/json-schema-validator/nlohmann/json-schema.hpp b/libs/json-schema-validator/nlohmann/json-schema.hpp new file mode 100644 index 00000000..46dc6006 --- /dev/null +++ b/libs/json-schema-validator/nlohmann/json-schema.hpp @@ -0,0 +1,157 @@ +/* + * JSON schema validator for JSON for modern C++ + * + * Copyright (c) 2016-2019 Patrick Boettcher . + * + * SPDX-License-Identifier: MIT + * + */ +#ifndef NLOHMANN_JSON_SCHEMA_HPP__ +#define NLOHMANN_JSON_SCHEMA_HPP__ + +#ifdef _WIN32 +# if defined(JSON_SCHEMA_VALIDATOR_EXPORTS) +# define JSON_SCHEMA_VALIDATOR_API __declspec(dllexport) +# elif defined(JSON_SCHEMA_VALIDATOR_IMPORTS) +# define JSON_SCHEMA_VALIDATOR_API __declspec(dllimport) +# else +# define JSON_SCHEMA_VALIDATOR_API +# endif +#else +# define JSON_SCHEMA_VALIDATOR_API +#endif + +#include + +#ifdef NLOHMANN_JSON_VERSION_MAJOR +# if NLOHMANN_JSON_VERSION_MAJOR < 3 || NLOHMANN_JSON_VERSION_MINOR < 5 || NLOHMANN_JSON_VERSION_PATCH < 0 +# error "Please use this library with NLohmann's JSON version 3.5.0 or higher" +# endif +#else +# error "expected existing NLOHMANN_JSON_VERSION_MAJOR preproc variable, please update to NLohmann's JSON 3.5.0" +#endif + +// make yourself a home - welcome to nlohmann's namespace +namespace nlohmann +{ + +// A class representing a JSON-URI for schemas derived from +// section 8 of JSON Schema: A Media Type for Describing JSON Documents +// draft-wright-json-schema-00 +// +// New URIs can be derived from it using the derive()-method. +// This is useful for resolving refs or subschema-IDs in json-schemas. +// +// This is done implement the requirements described in section 8.2. +// +class JSON_SCHEMA_VALIDATOR_API json_uri +{ + std::string urn_; + + std::string proto_; + std::string hostname_; + std::string path_; + nlohmann::json::json_pointer pointer_; + +protected: + // decodes a JSON uri and replaces all or part of the currently stored values + void update(const std::string &uri); + + std::tuple tie() const + { + return std::tie(urn_, proto_, hostname_, path_, pointer_); + } + +public: + json_uri(const std::string &uri) + { + update(uri); + } + + const std::string protocol() const { return proto_; } + const std::string hostname() const { return hostname_; } + const std::string path() const { return path_; } + + const nlohmann::json::json_pointer pointer() const { return pointer_; } + + const std::string url() const { return location(); } + const std::string location() const; + + static std::string escape(const std::string &); + + // create a new json_uri based in this one and the given uri + // resolves relative changes (pathes or pointers) and resets part if proto or hostname changes + json_uri derive(const std::string &uri) const + { + json_uri u = *this; + u.update(uri); + return u; + } + + // append a pointer-field to the pointer-part of this uri + json_uri append(const std::string &field) const + { + json_uri u = *this; + u.pointer_ = nlohmann::json::json_pointer(u.pointer_.to_string() + '/' + escape(field)); + return u; + } + + std::string to_string() const; + + friend bool operator<(const json_uri &l, const json_uri &r) + { + return l.tie() < r.tie(); + } + + friend bool operator==(const json_uri &l, const json_uri &r) + { + return l.tie() == r.tie(); + } + + friend std::ostream &operator<<(std::ostream &os, const json_uri &u); +}; + +namespace json_schema +{ + +extern json draft7_schema_builtin; + +class basic_error_handler +{ + bool error_{false}; + +public: + virtual void error(const std::string & /*path*/, const json & /* instance */, const std::string & /*message*/) + { + error_ = true; + } + + void reset() { error_ = false; } + operator bool() const { return error_; } +}; + +class root_schema; + +class JSON_SCHEMA_VALIDATOR_API json_validator +{ + std::unique_ptr root_; + +public: + json_validator(std::function loader = nullptr, + std::function format = nullptr); + ~json_validator(); + + // insert and set thea root-schema + void set_root_schema(const json &); + + // validate a json-document based on the root-schema + void validate(const json &); + + // validate a json-document based on the root-schema with a custom error-handler + void validate(const json &, basic_error_handler &); +}; + +} // namespace json_schema +} // namespace nlohmann + +#endif /* NLOHMANN_JSON_SCHEMA_HPP__ */ diff --git a/libs/json-schema-validator/nlohmann/json.hpp b/libs/json-schema-validator/nlohmann/json.hpp new file mode 100644 index 00000000..5003a4fa --- /dev/null +++ b/libs/json-schema-validator/nlohmann/json.hpp @@ -0,0 +1,20842 @@ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 3.6.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2019 Niels Lohmann . + +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 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 6 +#define NLOHMANN_JSON_VERSION_PATCH 1 + +#include // all_of, find, for_each +#include // assert +#include // and, not, or +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#include // istream, ostream +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include + + +#include + +// #include + + +#include // transform +#include // array +#include // and, not +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include + + +#include // exception +#include // runtime_error +#include // to_string + +// #include + + +#include // size_t + +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/*! +@brief general exception of the @ref basic_json class + +This class is an extension of `std::exception` objects with a member @a id for +exception ids. It is used as the base class for all exceptions thrown by the +@ref basic_json class. This class can hence be used as "wildcard" to catch +exceptions. + +Subclasses: +- @ref parse_error for exceptions indicating a parse error +- @ref invalid_iterator for exceptions indicating errors with iterators +- @ref type_error for exceptions indicating executing a member function with + a wrong type +- @ref out_of_range for exceptions indicating access out of the defined range +- @ref other_error for exceptions indicating other library errors + +@internal +@note To have nothrow-copy-constructible exceptions, we internally use + `std::runtime_error` which can cope with arbitrary-length error messages. + Intermediate strings are built with static functions and then passed to + the actual constructor. +@endinternal + +@liveexample{The following code shows how arbitrary library exceptions can be +caught.,exception} + +@since version 3.0.0 +*/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; + + protected: + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} + + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/*! +@brief exception indicating a parse error + +This exception is thrown by the library when a parse error occurs. Parse errors +can occur during the deserialization of JSON text, CBOR, MessagePack, as well +as when using JSON Patch. + +Member @a byte holds the byte index of the last read character in the input +file. + +Exceptions have ids 1xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. +json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. +json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. +json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. +json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. +json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. +json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. +json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. +json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. +json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. +json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. +json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). + +@note For an input with n bytes, 1 is the index of the first character and n+1 + is the index of the terminating null byte or the end of file. This also + holds true when reading a byte vector (CBOR or MessagePack). + +@liveexample{The following code shows how a `parse_error` exception can be +caught.,parse_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + static parse_error create(int id_, const position_t& pos, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + what_arg; + return parse_error(id_, pos.chars_read_total, w.c_str()); + } + + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + what_arg; + return parse_error(id_, byte_, w.c_str()); + } + + /*! + @brief byte index of the parse error + + The byte index of the last read character in the input file. + + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; + + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; + +/*! +@brief exception indicating errors with iterators + +This exception is thrown if iterators passed to a library function do not match +the expected semantics. + +Exceptions have ids 2xx. + +name / id | example message | description +----------------------------------- | --------------- | ------------------------- +json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. +json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. +json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. +json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. +json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. +json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. +json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. +json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. +json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. +json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). + +@liveexample{The following code shows how an `invalid_iterator` exception can be +caught.,invalid_iterator} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class invalid_iterator : public exception +{ + public: + static invalid_iterator create(int id_, const std::string& what_arg) + { + std::string w = exception::name("invalid_iterator", id_) + what_arg; + return invalid_iterator(id_, w.c_str()); + } + + private: + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating executing a member function with a wrong type + +This exception is thrown in case of a type error; that is, a library function is +executed on a JSON value whose type does not match the expected semantics. + +Exceptions have ids 3xx. + +name / id | example message | description +----------------------------- | --------------- | ------------------------- +json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. +json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. +json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. +json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. +json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. +json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. +json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. +json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. +json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. +json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. +json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. +json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. +json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. +json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. +json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. +json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | +json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | + +@liveexample{The following code shows how a `type_error` exception can be +caught.,type_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class type_error : public exception +{ + public: + static type_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("type_error", id_) + what_arg; + return type_error(id_, w.c_str()); + } + + private: + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating access out of the defined range + +This exception is thrown in case a library function is called on an input +parameter that exceeds the expected range, for instance in case of array +indices or nonexisting object keys. + +Exceptions have ids 4xx. + +name / id | example message | description +------------------------------- | --------------- | ------------------------- +json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. +json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. +json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. +json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. +json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. +json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. +json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | +json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | +json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | + +@liveexample{The following code shows how an `out_of_range` exception can be +caught.,out_of_range} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class out_of_range : public exception +{ + public: + static out_of_range create(int id_, const std::string& what_arg) + { + std::string w = exception::name("out_of_range", id_) + what_arg; + return out_of_range(id_, w.c_str()); + } + + private: + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating other library errors + +This exception is thrown in case of errors that cannot be classified with the +other exception types. + +Exceptions have ids 5xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range + +@liveexample{The following code shows how an `other_error` exception can be +caught.,other_error} + +@since version 3.0.0 +*/ +class other_error : public exception +{ + public: + static other_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("other_error", id_) + what_arg; + return other_error(id_, w.c_str()); + } + + private: + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // pair + +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif + +// allow for portable deprecation warnings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) + #define JSON_DEPRECATED __declspec(deprecated) +#else + #define JSON_DEPRECATED +#endif + +// allow for portable nodiscard warnings +#if defined(__has_cpp_attribute) + #if __has_cpp_attribute(nodiscard) + #define JSON_NODISCARD [[nodiscard]] + #elif __has_cpp_attribute(gnu::warn_unused_result) + #define JSON_NODISCARD [[gnu::warn_unused_result]] + #else + #define JSON_NODISCARD + #endif +#else + #define JSON_NODISCARD +#endif + +// allow to disable exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// manual branch prediction +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_LIKELY(x) __builtin_expect(x, 1) + #define JSON_UNLIKELY(x) __builtin_expect(x, 0) +#else + #define JSON_LIKELY(x) x + #define JSON_UNLIKELY(x) x +#endif + +// C++ language standard detection +#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 +#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// #include + + +#include // not +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type + +namespace nlohmann +{ +namespace detail +{ +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +template +using uncvref_t = typename std::remove_cv::type>::type; + +// implementation of C++14 index_sequence and affiliates +// source: https://stackoverflow.com/a/32223343 +template +struct index_sequence +{ + using type = index_sequence; + using value_type = std::size_t; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +template +struct merge_and_renumber; + +template +struct merge_and_renumber, index_sequence> + : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; + +template +struct make_index_sequence + : merge_and_renumber < typename make_index_sequence < N / 2 >::type, + typename make_index_sequence < N - N / 2 >::type > {}; + +template<> struct make_index_sequence<0> : index_sequence<> {}; +template<> struct make_index_sequence<1> : index_sequence<0> {}; + +template +using index_sequence_for = make_index_sequence; + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // not +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include + + +#include // random_access_iterator_tag + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include + +// #include + + +// http://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann +{ +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template