diff --git a/.github/workflows/AppFwkUnitTest.yml b/.github/workflows/AppFwkUnitTest.yml index 358d2a0740..34419982e0 100644 --- a/.github/workflows/AppFwkUnitTest.yml +++ b/.github/workflows/AppFwkUnitTest.yml @@ -8,9 +8,15 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest] + qtver: [5.12.12, 6.5.3] + include: + - qtver: 6.5.3 + build_flags: -DCEE_USE_QT6=ON -DCEE_USE_QT5=OFF + - qtver: 5.12.12 + build_flags: -DCEE_USE_QT6=OFF -DCEE_USE_QT5=ON steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Set apt mirror # see https://github.com/actions/runner-images/issues/7048 @@ -22,7 +28,7 @@ jobs: sudo sed -i 's/http:\/\/azure.archive.ubuntu.com\/ubuntu\//mirror+file:\/etc\/apt\/mirrors.txt/' /etc/apt/sources.list - name: Install Linux dependencies - if: ${{contains( matrix.os, 'ubuntu') }} + if: contains(matrix.os, 'ubuntu') run: | sudo apt-get update --option="APT::Acquire::Retries=3" sudo apt-get install --option="APT::Acquire::Retries=3" libxkbcommon-x11-0 libgl1-mesa-dev mesa-common-dev libglfw3-dev libglu1-mesa-dev @@ -30,10 +36,10 @@ jobs: - name: Install Qt uses: jurplel/install-qt-action@v3 with: - version: 5.12.12 - modules: qtscript + version: ${{ matrix.qtver }} dir: "${{ github.workspace }}/Qt/" cache: true + cache-key-prefix: ${{ matrix.qtver }}-${{ matrix.os }} - name: Get CMake and Ninja uses: lukka/get-cmake@latest @@ -41,42 +47,41 @@ jobs: - name: Use MSVC (Windows) uses: ilammy/msvc-dev-cmd@v1 - - name: Configure - shell: cmake -P {0} + - name: Configure and build run: | - execute_process( - COMMAND cmake - -S Fwk - -B cmakebuild - -G Ninja - RESULT_VARIABLE result - ) - if (NOT result EQUAL 0) - message(FATAL_ERROR "Bad exit status") - endif() - - - name: Build - shell: cmake -P {0} + cmake -S Fwk/AppFwk ${{matrix.build_flags}} -B cmakebuild -G Ninja + cmake --build cmakebuild + + - name: Install run: | - set(ENV{NINJA_STATUS} "[%f/%t %o/sec] ") - execute_process( - COMMAND cmake --build cmakebuild - RESULT_VARIABLE result - ) - if (NOT result EQUAL 0) - message(FATAL_ERROR "Bad exit status") - endif() + cd cmakebuild + cmake --install . --prefix ${{github.workspace}}/cmakebuild/install - - name: Run Unit Tests + - name: Run Unit Tests Qt5 + if: matrix.qtver == '5.12.12' shell: bash run: | - cmakebuild/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests/cafPdmCore_UnitTests - cmakebuild/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests/cafPdmXml_UnitTests - cmakebuild/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/cafProjectDataModel_UnitTests - cmakebuild/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/cafPdmScripting_UnitTests + cmakebuild/cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests/cafPdmCore_UnitTests + cmakebuild/cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests/cafPdmXml_UnitTests + cmakebuild/cafProjectDataModel/cafProjectDataModel_UnitTests/cafProjectDataModel_UnitTests + cmakebuild/cafPdmScripting/cafPdmScripting_UnitTests/cafPdmScripting_UnitTests - - name: Run Unit Tests Windows (does not work on Linux) - if: contains( matrix.os, 'windows') + - name: Run Unit Tests Windows Qt5 (does not work on Linux) + if: (contains( matrix.os, 'windows') && (matrix.qtver == '5.12.12')) + shell: bash + run: cmakebuild/cafUserInterface/cafUserInterface_UnitTests/cafUserInterface_UnitTests + + - name: Run Unit Tests Qt6 + if: matrix.qtver == '6.5.3' shell: bash run: | - cmakebuild/AppFwk/cafUserInterface/cafUserInterface_UnitTests/cafUserInterface_UnitTests + cmakebuild/install/bin/cafPdmCore_UnitTests + cmakebuild/install/bin/cafPdmXml_UnitTests + cmakebuild/install/bin/cafProjectDataModel_UnitTests + cmakebuild/install/bin/cafPdmScripting_UnitTests + + - name: Run Unit Tests Windows Qt6 (does not work on Linux) + if: (contains( matrix.os, 'windows') && (matrix.qtver == '6.5.3')) + shell: bash + run: cmakebuild/install/bin/cafUserInterface_UnitTests + \ No newline at end of file diff --git a/.github/workflows/ResInsightWithCache.yml b/.github/workflows/ResInsightWithCache.yml index 4d2be6dd14..7c83bd0a88 100644 --- a/.github/workflows/ResInsightWithCache.yml +++ b/.github/workflows/ResInsightWithCache.yml @@ -33,11 +33,12 @@ jobs: vcpkg-triplet: x64-windows, build-python-module: true, execute-unit-tests: true, + execute-pytests: true, unity-build: true, publish-to-pypi: false, } - { - name: "Ubuntu Latest gcc", + name: "Ubuntu 20.04 gcc", os: ubuntu-20.04, cc: "gcc", cxx: "g++", @@ -45,29 +46,31 @@ jobs: vcpkg-triplet: x64-linux, build-python-module: true, execute-unit-tests: true, + execute-pytests: true, unity-build: false, publish-to-pypi: true, } - { - name: "Ubuntu Latest clang", - os: ubuntu-20.04, - cc: "clang", - cxx: "clang++", + name: "Ubuntu 22.04 clang-16", + os: ubuntu-22.04, + cc: "clang-16", + cxx: "clang++-16", vcpkg-response-file: vcpkg_x64-linux.txt, vcpkg-triplet: x64-linux, build-python-module: true, execute-unit-tests: true, + execute-pytests: false, unity-build: false, publish-to-pypi: false, } steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: true - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.8" - name: Display Python version @@ -84,7 +87,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r GrpcInterface/Python/requirements.txt + pip install -r GrpcInterface/Python/dev-requirements.txt - name: Use CMake uses: lukka/get-cmake@latest @@ -116,7 +119,7 @@ jobs: endif() - name: Get current time - uses: josStorer/get-current-time@v2.0.2 + uses: josStorer/get-current-time@v2 id: current-time with: format: YYYY-MM-DD @@ -126,7 +129,7 @@ jobs: - name: Cache Buildcache id: cache-buildcache - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ${{ env.BUILDCACHE_DIR }} key: ${{ matrix.config.os }}-${{ matrix.config.cc }}-cache-v03-${{ steps.current-time.outputs.formattedTime }} @@ -139,7 +142,7 @@ jobs: - name: Set apt mirror # see https://github.com/actions/runner-images/issues/7048 - if: ${{contains( matrix.config.os, 'ubuntu') }} + if: contains( matrix.config.os, 'ubuntu') run: | # make sure there is a `\t` between URL and `priority:*` attributes printf 'http://azure.archive.ubuntu.com/ubuntu priority:1\n' | sudo tee /etc/apt/mirrors.txt @@ -147,11 +150,24 @@ jobs: sudo sed -i 's/http:\/\/azure.archive.ubuntu.com\/ubuntu\//mirror+file:\/etc\/apt\/mirrors.txt/' /etc/apt/sources.list - name: Install Linux dependencies - if: ${{contains( matrix.config.os, 'ubuntu') }} + if: contains( matrix.config.os, 'ubuntu') run: | sudo apt-get update --option="APT::Acquire::Retries=3" sudo apt-get install --option="APT::Acquire::Retries=3" libxkbcommon-x11-0 libgl1-mesa-dev mesa-common-dev libglfw3-dev libglu1-mesa-dev libhdf5-dev + + - name: Install gcc-10 + if: contains( matrix.config.cc, 'gcc') + run: | sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 --slave /usr/bin/g++ g++ /usr/bin/g++-10 --slave /usr/bin/gcov gcov /usr/bin/gcov-10 + + - name: Install clang-16 + if: contains( matrix.config.cc, 'clang') + run: | + sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 100 --slave /usr/bin/g++ g++ /usr/bin/g++-11 --slave /usr/bin/gcov gcov /usr/bin/gcov-11 + sudo apt-get upgrade + wget https://apt.llvm.org/llvm.sh + sudo chmod +x llvm.sh + sudo ./llvm.sh 16 all - name: Install Qt uses: jurplel/install-qt-action@v3 @@ -170,14 +186,14 @@ jobs: appendedCacheKey: ${{ matrix.config.os }}-${{ matrix.config.cxx }}-cache-key-v2 - name: Cache dynamic version of OpenSSL (Linux) - if: ${{contains( matrix.config.os, 'ubuntu_disabled') }} - uses: actions/cache@v3 + if: contains( matrix.config.os, 'ubuntu_disabled') + uses: actions/cache@v4 with: path: ${{ github.workspace }}/ThirdParty/vcpkg/installed/x64-linux-dynamic key: ${{ matrix.config.os }}-vcpkg-x64-linux-dynamic_v05 - name: Install dynamic version of OpenSSL (Linux) - if: ${{contains( matrix.config.os, 'ubuntu') }} + if: contains( matrix.config.os, 'ubuntu') run: | $VCPKG_ROOT/vcpkg install --overlay-triplets=${{ github.workspace }}/ThirdParty/vcpkg-custom-triplets --triplet x64-linux-dynamic openssl @@ -194,6 +210,7 @@ jobs: -D CMAKE_BUILD_TYPE=$ENV{BUILD_TYPE} -D CMAKE_INSTALL_PREFIX=cmakebuild/install -D RESINSIGHT_BUNDLE_OPENSSL=true + -D RESINSIGHT_QT5_BUNDLE_LIBRARIES=true -D RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS=true -D RESINSIGHT_TREAT_WARNINGS_AS_ERRORS=true -D RESINSIGHT_ENABLE_PRECOMPILED_HEADERS=false @@ -224,11 +241,12 @@ jobs: - name: Stats for buildcache run: ${{ github.workspace }}/buildcache/bin/buildcache -s + - name: Run Unit Tests if: matrix.config.execute-unit-tests shell: bash run: | - cmakebuild/ApplicationExeCode/ResInsight --unittest + cmakebuild/ApplicationLibCode/UnitTests/ResInsight-tests - name: (Python) Check types using mypy if: matrix.config.build-python-module @@ -239,7 +257,7 @@ jobs: ${{ steps.python-path.outputs.PYTHON_EXECUTABLE }} -m mypy *.py generated/generated_classes.py - name: Run pytest - if: matrix.config.build-python-module + if: matrix.config.execute-pytests env: RESINSIGHT_EXECUTABLE: ${{ runner.workspace }}/ResInsight/cmakebuild/ApplicationExeCode/ResInsight run: | @@ -250,14 +268,13 @@ jobs: - name: Upload python distribution folder if: matrix.config.publish-to-pypi - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: python-distribution path: GrpcInterface/Python/dist - - name: Upload Windows install artifact - if: ${{contains( matrix.config.os, 'windows') }} - uses: actions/upload-artifact@v3 + - name: Upload artifacts + uses: actions/upload-artifact@v4 with: name: ResInsight-${{ matrix.config.name }} path: ${{ runner.workspace }}/ResInsight/cmakebuild/install diff --git a/.github/workflows/clang-format.yml b/.github/workflows/clang-format.yml index b498585139..25010ffe32 100644 --- a/.github/workflows/clang-format.yml +++ b/.github/workflows/clang-format.yml @@ -20,7 +20,7 @@ jobs: sudo apt-get update sudo apt-get install --option="APT::Acquire::Retries=3" clang-format-15 clang-format-15 --version - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Check format - ApplicationLibCode run: | cd ApplicationLibCode @@ -36,7 +36,7 @@ jobs: cd Fwk/AppFwk find -name '*.h' -o -name '*.cpp' -o -name '*.inl' | grep -v gtest | xargs clang-format-15 -i git diff - - uses: peter-evans/create-pull-request@v5 + - uses: peter-evans/create-pull-request@v6 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: "Fixes by clang-format" diff --git a/.github/workflows/clang-tidy.yml b/.github/workflows/clang-tidy.yml index ff7d8fea04..c9b0a35b59 100644 --- a/.github/workflows/clang-tidy.yml +++ b/.github/workflows/clang-tidy.yml @@ -31,7 +31,7 @@ jobs: } steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: submodules: true @@ -69,11 +69,14 @@ jobs: run: | cd build run-clang-tidy-15 -config-file ../ApplicationLibCode/.clang-tidy -fix files ApplicationLibCode + run-clang-tidy-15 -config-file ../GrpcInterface/.clang-tidy -fix files GrpcInterface - name: Run clang-format after clang-tidy run: | cd ApplicationLibCode find -name '*.h' -o -name '*.cpp' -o -name '*.inl' | xargs clang-format-15 -i - - uses: peter-evans/create-pull-request@v5 + cd ../GrpcInterface + find -name '*.h' -o -name '*.cpp' -o -name '*.inl' | xargs clang-format-15 -i + - uses: peter-evans/create-pull-request@v6 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: "Fixes by clang-tidy" @@ -82,3 +85,4 @@ jobs: branch-suffix: random add-paths: | ApplicationLibCode/* + GrpcInterface/* diff --git a/.github/workflows/cmake-format.yml b/.github/workflows/cmake-format.yml index 0538602ce3..c6db7afa8e 100644 --- a/.github/workflows/cmake-format.yml +++ b/.github/workflows/cmake-format.yml @@ -9,7 +9,7 @@ jobs: - name: Install cmakelang for cmake-format run: | python3 -m pip install --user cmakelang - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Check format - ApplicationLibCode run: | ~/.local/bin/cmake-format -c ${{ github.workspace }}/cmake/cmake-format.py -i CMakeLists.txt @@ -28,7 +28,7 @@ jobs: cd .. git diff - - uses: peter-evans/create-pull-request@v5 + - uses: peter-evans/create-pull-request@v6 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: "Fixes by cmake-format" diff --git a/.github/workflows/delete_artifacts.py b/.github/workflows/delete_artifacts.py index 6d19130d68..169c6ae4b3 100644 --- a/.github/workflows/delete_artifacts.py +++ b/.github/workflows/delete_artifacts.py @@ -6,7 +6,7 @@ org_name = "OPM" repo_name = "ResInsight" -keep_artifacts = 20 +keep_artifacts = 100 def get_all_artifacts(repo_name: str, headers: dict) -> []: amount_items_per_page = 50 diff --git a/.github/workflows/delete_artifacts.yml b/.github/workflows/delete_artifacts.yml index f187b2207a..af0eeea882 100644 --- a/.github/workflows/delete_artifacts.yml +++ b/.github/workflows/delete_artifacts.yml @@ -12,9 +12,9 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: setup python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: 3.8 - name: Remove old artifacts diff --git a/.github/workflows/python-linting.yml b/.github/workflows/python-linting.yml index 64f721f271..6e312f79ca 100644 --- a/.github/workflows/python-linting.yml +++ b/.github/workflows/python-linting.yml @@ -6,8 +6,8 @@ jobs: lint: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 with: python-version: '3.10' - name: (Python) Use black to do linting @@ -15,7 +15,7 @@ jobs: pip install black cd GrpcInterface black . - - uses: peter-evans/create-pull-request@v5 + - uses: peter-evans/create-pull-request@v6 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: "Python code linting changes detected by black" diff --git a/.github/workflows/spell-check.yml b/.github/workflows/spell-check.yml index 1972c5da5a..7c4799a0db 100644 --- a/.github/workflows/spell-check.yml +++ b/.github/workflows/spell-check.yml @@ -7,11 +7,11 @@ jobs: build: runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: sobolevn/misspell-fixer-action@master with: options: "-rsvnuR ApplicationLibCode/" - - uses: peter-evans/create-pull-request@v5 + - uses: peter-evans/create-pull-request@v6 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: "Fixes by misspell-fixer" diff --git a/.gitmodules b/.gitmodules index da885ca10b..03c750c207 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,9 +7,6 @@ [submodule "ThirdParty/fast_float"] path = ThirdParty/fast_float url = https://github.com/fastfloat/fast_float -[submodule "ThirdParty/qtadvanceddocking"] - path = ThirdParty/qtadvanceddocking - url = https://github.com/CeetronSolutions/qtadvanceddocking.git [submodule "ThirdParty/custom-opm-common/opm-common"] path = ThirdParty/custom-opm-common/opm-common url = https://github.com/CeetronSolutions/opm-common @@ -25,3 +22,9 @@ [submodule "ThirdParty/tomlplusplus"] path = ThirdParty/tomlplusplus url = https://github.com/marzer/tomlplusplus.git +[submodule "ThirdParty/qtadvanceddocking"] + path = ThirdParty/qtadvanceddocking + url = https://github.com/CeetronSolutions/qtadvanceddocking.git +[submodule "ThirdParty/spdlog"] + path = ThirdParty/spdlog + url = https://github.com/gabime/spdlog.git diff --git a/ApplicationExeCode/CMakeLists.txt b/ApplicationExeCode/CMakeLists.txt index be6d00179e..e749eca703 100644 --- a/ApplicationExeCode/CMakeLists.txt +++ b/ApplicationExeCode/CMakeLists.txt @@ -271,14 +271,14 @@ set(LINK_LIBRARIES ${VIZ_FWK_LIBRARIES} ApplicationLibCode Commands + RigGeoMechDataModel + RifGeoMechFileInterface ) if(RESINSIGHT_ENABLE_GRPC) list(APPEND LINK_LIBRARIES GrpcInterface) endif() -list(APPEND LINK_LIBRARIES RigGeoMechDataModel) - if(RESINSIGHT_USE_ODB_API) add_definitions(-DUSE_ODB_API) list(APPEND LINK_LIBRARIES RifOdbReader) @@ -317,68 +317,6 @@ endif() # ############################################################################## # Copy Dlls on MSVC # ############################################################################## -if(MSVC) - - if(NOT ${RESINSIGHT_ODB_API_DIR} EQUAL "") - set(RESINSIGHT_USE_ODB_API 1) - endif() - - # Odb Dlls - if(RESINSIGHT_USE_ODB_API) - # Find all the dlls - file(GLOB RI_ALL_ODB_DLLS ${RESINSIGHT_ODB_API_DIR}/lib/*.dll) - - # Strip off the path - foreach(aDLL ${RI_ALL_ODB_DLLS}) - get_filename_component(filenameWithExt ${aDLL} NAME) - list(APPEND RI_ODB_DLLS ${filenameWithExt}) - endforeach(aDLL) - - foreach(aDLL ${RI_ODB_DLLS}) - list(APPEND RI_FILENAMES ${RESINSIGHT_ODB_API_DIR}/lib/${aDLL}) - endforeach() - endif() - - # OpenVDS Dlls - set(OPENVDS_DLL_NAMES openvds segyutils) - foreach(OPENVDS_DLL_NAME ${OPENVDS_DLL_NAMES}) - list(APPEND RI_FILENAMES - ${RESINSIGHT_OPENVDS_API_DIR}/bin/msvc_141/${OPENVDS_DLL_NAME}.dll - ) - endforeach(OPENVDS_DLL_NAME) - list(APPEND RI_FILENAMES - ${RESINSIGHT_OPENVDS_API_DIR}/bin/msvc_141/SEGYImport.exe - ) - - # HDF5 Dlls - if(RESINSIGHT_FOUND_HDF5) - set(HDF5_DLL_NAMES hdf5 hdf5_cpp szip zlib) - foreach(HDF5_DLL_NAME ${HDF5_DLL_NAMES}) - list(APPEND RI_FILENAMES ${RESINSIGHT_HDF5_DIR}/bin/${HDF5_DLL_NAME}.dll) - endforeach(HDF5_DLL_NAME) - endif() - -else() - # Linux - - # OpenVDS lib files - list(APPEND RI_FILENAMES ${RESINSIGHT_OPENVDS_API_DIR}/bin/SEGYImport) - - set(OPENVDS_LIB_NAMES - libopenvds.so - libopenvds.so.3 - libopenvds.so.3.2.7 - libopenvds-e1541338.so.3.2.7 - libsegyutils.so - libsegyutils.so.3 - libsegyutils.so.3.2.7 - ) - foreach(OPENVDS_LIB_NAME ${OPENVDS_LIB_NAMES}) - list(APPEND RI_FILENAMES - ${RESINSIGHT_OPENVDS_API_DIR}/lib64/${OPENVDS_LIB_NAME} - ) - endforeach(OPENVDS_LIB_NAME) -endif(MSVC) # create an empty library target that will be used to copy files to the build # folder @@ -398,11 +336,7 @@ foreach(riFileName ${RI_FILENAMES}) $ ) endforeach() -add_custom_target( - PreBuildFileCopy - COMMENT "PreBuildFileCopy step: copy runtime files into build folder" - ${copyCommands} -) +add_custom_target(PreBuildFileCopy ${copyCommands}) set_property(TARGET PreBuildFileCopy PROPERTY FOLDER "FileCopyTargets") # Make ResInsight depend on the prebuild target. @@ -446,8 +380,15 @@ endif(RESINSIGHT_ENABLE_GRPC) # bundle libraries together with private installation if(RESINSIGHT_PRIVATE_INSTALL) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") - # tell binary to first attempt to load libraries from its own directory - set(RESINSIGHT_INSTALL_RPATH "\$ORIGIN") + + set(RESINSIGHT_INSTALL_RPATH + "" + CACHE STRING "RPATH to be injected into binary" + ) + mark_as_advanced(FORCE RESINSIGHT_INSTALL_RPATH) + + # Add ORIGIN to represent the directory where the binary is located + set(RESINSIGHT_INSTALL_RPATH ${RESINSIGHT_INSTALL_RPATH} "\$ORIGIN") if(${RESINSIGHT_USE_ODB_API}) # This is a "hack" to make ResInsight runtime find the ODB so files used @@ -543,6 +484,8 @@ if(RESINSIGHT_PRIVATE_INSTALL) OPTIONAL ) + install(FILES qt.conf DESTINATION ${RESINSIGHT_INSTALL_FOLDER}/) + endif(RESINSIGHT_QT5_BUNDLE_LIBRARIES) endif() diff --git a/ApplicationExeCode/Resources/ResInsight.qrc b/ApplicationExeCode/Resources/ResInsight.qrc index 32ff262ffc..7c2e9a61bd 100644 --- a/ApplicationExeCode/Resources/ResInsight.qrc +++ b/ApplicationExeCode/Resources/ResInsight.qrc @@ -277,14 +277,16 @@ SeismicDelta16x16.png SeismicView16x16.png SeismicView24x24.png - SeismicViews24x24.png - SeismicData24x24.png - SeismicSection16x16.png - Fullscreen.png + SeismicViews24x24.png + SeismicData24x24.png + SeismicSection16x16.png + Fullscreen.png plot-template-standard.svg plot-template-ensemble.svg decline-curve.svg regression-curve.svg + padlock.svg + warning.svg fs_CellFace.glsl diff --git a/ApplicationExeCode/Resources/padlock.svg b/ApplicationExeCode/Resources/padlock.svg new file mode 100644 index 0000000000..5009f6cebf --- /dev/null +++ b/ApplicationExeCode/Resources/padlock.svg @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/ApplicationExeCode/Resources/warning.svg b/ApplicationExeCode/Resources/warning.svg new file mode 100644 index 0000000000..7944bbfa8e --- /dev/null +++ b/ApplicationExeCode/Resources/warning.svg @@ -0,0 +1,2 @@ + +ionicons-v5-r \ No newline at end of file diff --git a/ApplicationExeCode/RiaGrpcConsoleApplication.cpp b/ApplicationExeCode/RiaGrpcConsoleApplication.cpp index b0e17ee9ab..dae4ef68d2 100644 --- a/ApplicationExeCode/RiaGrpcConsoleApplication.cpp +++ b/ApplicationExeCode/RiaGrpcConsoleApplication.cpp @@ -46,7 +46,7 @@ RiaGrpcConsoleApplication::RiaGrpcConsoleApplication( int& argc, char** argv ) { m_idleTimer = new QTimer( this ); connect( m_idleTimer, SIGNAL( timeout() ), this, SLOT( doIdleProcessing() ) ); - m_idleTimer->start( 0 ); + m_idleTimer->start( 5 ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationExeCode/RiaMain.cpp b/ApplicationExeCode/RiaMain.cpp index 03b74e9cab..b8d35b48c2 100644 --- a/ApplicationExeCode/RiaMain.cpp +++ b/ApplicationExeCode/RiaMain.cpp @@ -17,8 +17,8 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RiaArgumentParser.h" -#include "RiaLogging.h" #include "RiaMainTools.h" +#include "RiaPreferences.h" #ifdef ENABLE_GRPC #include "RiaGrpcConsoleApplication.h" @@ -40,11 +40,15 @@ #include #endif +#include + +void manageSegFailure( int signalCode ); + RiaApplication* createApplication( int& argc, char* argv[] ) { for ( int i = 1; i < argc; ++i ) { - if ( !qstrcmp( argv[i], "--console" ) || !qstrcmp( argv[i], "--unittest" ) || !qstrcmp( argv[i], "--version" ) ) + if ( !qstrcmp( argv[i], "--console" ) || !qstrcmp( argv[i], "--unittest" ) ) { #ifdef ENABLE_GRPC return new RiaGrpcConsoleApplication( argc, argv ); @@ -72,8 +76,12 @@ int main( int argc, char* argv[] ) return 1; } #endif - // Global initialization - RiaLogging::loggerInstance()->setLevel( int( RILogLevel::RI_LL_DEBUG ) ); + + // The Qt::AA_ShareOpenGLContexts setting is needed when we have multiple viz widgets in flight + // and we have a setup where these widgets belong to different top-level windows, or end up + // belonging to different top-level windows through re-parenting. + // See test application QtTestBenchOpenGLWidget + QApplication::setAttribute( Qt::AA_ShareOpenGLContexts ); // Create feature manager before the application object is created RiaMainTools::initializeSingletons(); @@ -112,6 +120,17 @@ int main( int argc, char* argv[] ) QLocale::setDefault( QLocale( QLocale::English, QLocale::UnitedStates ) ); setlocale( LC_NUMERIC, "C" ); + // Set up signal handlers + if ( RiaPreferences::current()->loggerTrapSignalAndFlush() ) + { + signal( SIGINT, manageSegFailure ); + signal( SIGILL, manageSegFailure ); + signal( SIGFPE, manageSegFailure ); + signal( SIGSEGV, manageSegFailure ); + signal( SIGTERM, manageSegFailure ); + signal( SIGABRT, manageSegFailure ); + } + // Handle the command line arguments. // Todo: Move to a one-shot timer, delaying the execution until we are inside the event loop. // The complete handling of the resulting ApplicationStatus must be moved along. diff --git a/ApplicationExeCode/RiaMainTools.cpp b/ApplicationExeCode/RiaMainTools.cpp index 4a2fdcded3..8f5700acbb 100644 --- a/ApplicationExeCode/RiaMainTools.cpp +++ b/ApplicationExeCode/RiaMainTools.cpp @@ -17,6 +17,8 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RiaMainTools.h" +#include "RiaFileLogger.h" +#include "RiaLogging.h" #include "RiaRegressionTestRunner.h" #include "RiaSocketCommand.h" @@ -25,6 +27,32 @@ #include "cafPdmDefaultObjectFactory.h" #include "cafPdmUiFieldEditorHandle.h" +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void manageSegFailure( int signalCode ) +{ + // Executing function here is not safe, but works as expected on Windows. Behavior on Linux is undefined, but will + // work in some cases. + // https://github.com/gabime/spdlog/issues/1607 + + auto loggers = RiaLogging::loggerInstances(); + + QString str = QString( "Segmentation fault. Signal code: %1" ).arg( signalCode ); + + for ( auto logger : loggers ) + { + if ( auto fileLogger = dynamic_cast( logger ) ) + { + fileLogger->error( str.toStdString().data() ); + + fileLogger->flush(); + } + } + + exit( 1 ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationExeCode/qt.conf b/ApplicationExeCode/qt.conf new file mode 100644 index 0000000000..f747e09377 --- /dev/null +++ b/ApplicationExeCode/qt.conf @@ -0,0 +1,2 @@ +[Paths] +Plugins = plugins \ No newline at end of file diff --git a/ApplicationLibCode/Adm/LicenseInformation.txt b/ApplicationLibCode/Adm/LicenseInformation.txt index 828794e6f4..f89389d990 100644 --- a/ApplicationLibCode/Adm/LicenseInformation.txt +++ b/ApplicationLibCode/Adm/LicenseInformation.txt @@ -683,3 +683,35 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI 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. + +=============================================================================== + Notice for spdlog +=============================================================================== + +https://github.com/gabime/spdlog/blob/v1.x/LICENSE + +The MIT License (MIT) + +Copyright (c) 2016 Gabi Melman. + +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. + +-- NOTE: Third party dependency used by this software -- +This software depends on the fmt lib (MIT License), +and users must comply to its license: https://raw.githubusercontent.com/fmtlib/fmt/master/LICENSE diff --git a/ApplicationLibCode/Adm/RiaVersionInfo.h.cmake b/ApplicationLibCode/Adm/RiaVersionInfo.h.cmake index 5cdacb8332..8e2910f76a 100644 --- a/ApplicationLibCode/Adm/RiaVersionInfo.h.cmake +++ b/ApplicationLibCode/Adm/RiaVersionInfo.h.cmake @@ -34,3 +34,5 @@ #define RESINSIGHT_OCTAVE_VERSION "@OCTAVE_VERSION_STRING@" #define RESINSIGHT_PYTHON_VERSION "@Python3_VERSION@" + +#define RESINSIGHT_GIT_HASH "@RESINSIGHT_GIT_HASH@" \ No newline at end of file diff --git a/ApplicationLibCode/Adm/projectfilekeywords/2024.03/ri-fieldKeywords.txt b/ApplicationLibCode/Adm/projectfilekeywords/2024.03/ri-fieldKeywords.txt new file mode 100644 index 0000000000..155de9a1ba --- /dev/null +++ b/ApplicationLibCode/Adm/projectfilekeywords/2024.03/ri-fieldKeywords.txt @@ -0,0 +1,5650 @@ +// ResInsight version string : 2024.03.0-RC_05 +// Report generated : Fri Mar 22 08:17:14 2024 +// +// + +AnalysisPlot - class RimAnalysisPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + AnalysisPlotData + TimeStepFilter + TimeSteps + ReferenceCase + IsUsingAutoName + PlotDescription + BarOrientation + MajorGroupType + MediumGroupType + MinorGroupType + ValueSortOperation + groupForColors + UseTopBarsFilter + MaxBarCount + UseBarText + UseCaseInBarText + UseEnsembleInBarText + UseSummaryItemInBarText + UseTimeStepInBarText + UseQuantityInBarText + BarTextFontSize + ValueAxisProperties + PlotDataFilterCollection + +AnalysisPlotCollection - class RimAnalysisPlotCollection + AnalysisPlots + +AnalysisPlotDataEntry - class RimAnalysisPlotDataEntry + SummaryCase + Ensemble + SummaryAddress + IsEnsembleCurve + +Annotations - class RimAnnotationInViewCollection + IsActive + TextAnnotations + AnnotationPlaneDepth + SnapAnnotations + TextAnnotationsInView + ReachCircleAnnotationsInView + UserDefinedPolylinesAnnotationsInView + PolylinesFromFileAnnotationsInView + AnnotationFontSize + +AsciiDataCurve - class RimAsciiDataCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + PlotAxis + TimeSteps + Values + Title + +CalcScript - class RimCalcScript + AbsolutePath + +CellEdgeResultSlot - class RimCellEdgeColors + EnableCellEdgeColors + propertyType + CellEdgeVariable + UseXVariable + UseYVariable + UseZVariable + LegendDefinition + SelectedProperties + ShowTextValuesIfItemIsUnchecked + SingleVarEdgeResult + +CellFilterCollection - class RimCellFilterCollection + Active + CombineFilterMode + CellFilters + RangeFilters + +CellIndexFilter - class RimCellIndexFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + ElementSetId + +CellPropertyFilter - class RimEclipsePropertyFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + SelectedValues + ResultDefinition + LowerBound + UpperBound + CategorySelection + IsDuplicatedFromLinkedView + +CellPropertyFilters - class RimEclipsePropertyFilterCollection + Active + PropertyFilters + +CellRangeFilter - class RimCellRangeFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + StartIndexI + CellCountI + StartIndexJ + CellCountJ + StartIndexK + CellCountK + +CellRangeFilterCollection - class RimCellFilterCollection + Active + CombineFilterMode + CellFilters + RangeFilters + +ChangeDataSourceFeatureUi - class RimWellLogCurveCommonDataSource + CurveCase + SummaryCase + TrajectoryType + CurveWellPath + SimulationWellName + BranchDetection + Allow3DSelectionLink + Branch + CurveTimeStep + WBSSmoothing + WBSSmoothingThreshold + MaximumCurvePointInterval + RftTimeStep + RftWellName + SegmentBranchIndex + SegmentBranchType + +CmdAddItemExecData - class caf::CmdAddItemExecData + PathToField + indexAfter + createdItemIndex + +CmdDeleteItemExecData - class caf::CmdDeleteItemExecData + PathToField + indexToObject + deletedObjectAsXml + +CmdSelectionChangeExecData - class caf::CmdSelectionChangeExecData + selectionLevel + previousSelection + newSelection + +ColorLegend - class RimColorLegend + ColorLegendName + ColorLegendItems + +ColorLegendCollection - class RimColorLegendCollection + CustomColorLegends + +ColorLegendItem - class RimColorLegendItem + Color + CategoryValue + CategoryName + +CompletionTemplateCollection - class RimCompletionTemplateCollection + FractureTemplates + StimPlanModelTemplates + ValveTemplates + FractureGroupStatisticsCollection + +CorrelationMatrixPlot - class RimCorrelationMatrixPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + AnalysisPlotData + TimeStepFilter + TimeStep + AutoTitle + PlotTitle + LabelFontSize + AxisTitleFontSize + AxisValueFontSize + UseCaseFilter + CurveSetForFiltering + EditCaseFilter + CorrelationAbsValues + CorrelationSorting + CorrelationAbsSorting + ExcludeParamsWithoutVariation + ShowOnlyTopNCorrelations + TopNFilterCount + LegendConfig + SelectedParameters + +CorrelationPlot - class RimCorrelationPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + AnalysisPlotData + TimeStepFilter + TimeStep + AutoTitle + PlotTitle + LabelFontSize + AxisTitleFontSize + AxisValueFontSize + UseCaseFilter + CurveSetForFiltering + EditCaseFilter + CorrelationAbsValues + CorrelationAbsSorting + ExcludeParamsWithoutVariation + ShowOnlyTopNCorrelations + TopNFilterCount + SelectedParameters + BarColor + +CorrelationPlotCollection - class RimCorrelationPlotCollection + CorrelationPlots + CorrelationReports + +CorrelationReportPlot - class RimCorrelationReportPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotWindowTitle + MatrixPlot + CorrelationPlot + CrossPlot + SubTitleFontSize + LabelFontSize + AxisTitleFontSize + AxisValueFontSize + +CrossSection - class RimExtrudedCurveIntersection + Active + ShowInactiveCells + UseSeparateIntersectionDataSource + SeparateIntersectionDataSource + UserDescription + Type + Direction + WellPath + SimulationWell + ProjectPolygon + Points + PointsUi + AzimuthAngle + DipAngle + CustomExtrusionPoints + TwoAzimuthPoints + Branch + ExtentLength + lengthUp + lengthDown + SurfaceIntersections + UpperThreshold + LowerThreshold + DepthFilter + CollectionUpperThreshold + CollectionLowerThreshold + ThresholdOverridden + CollectionDepthFilterType + EnableKFilter + KRangeFilter + KFilterCollectionOverride + KRangeCollectionFilter + +CrossSectionCollection - class RimIntersectionCollection + CrossSections + IntersectionBoxes + Active + UpperDepthThreshold + LowerDepthThreshold + DepthFilterOverride + CollectionDepthFilterType + OverrideKFilter + KRangeFilter + ApplyCellFilters + +CsvSummaryCase - class RimCsvSummaryCase + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + FileType + StartDate + +CurveIntersection - class RimExtrudedCurveIntersection + Active + ShowInactiveCells + UseSeparateIntersectionDataSource + SeparateIntersectionDataSource + UserDescription + Type + Direction + WellPath + SimulationWell + ProjectPolygon + Points + PointsUi + AzimuthAngle + DipAngle + CustomExtrusionPoints + TwoAzimuthPoints + Branch + ExtentLength + lengthUp + lengthDown + SurfaceIntersections + UpperThreshold + LowerThreshold + DepthFilter + CollectionUpperThreshold + CollectionLowerThreshold + ThresholdOverridden + CollectionDepthFilterType + EnableKFilter + KRangeFilter + KFilterCollectionOverride + KRangeCollectionFilter + +DataContainerFloat - class RimcDataContainerDouble + values + +DataContainerString - class RimcDataContainerString + values + +DataContainerTime - class RimcDataContainerTime + values + +DeclineCurve - class RimSummaryDeclineCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + SummaryCase + SummaryAddress + Resampling + HorizontalAxisType + SummaryCaseX + SummaryAddressX + IsEnsembleCurve + PlotAxis + Axis + XAxis + SummaryCurveNameConfig + isTopZWithinCategory + DeclineCurveType + PredictionYears + HyperbolicDeclineConstant + MinTimeSliderPosition + MaxTimeSliderPosition + ShowTimeSelectionInPlot + +DepthTrackPlot - class RimDepthTrackPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + TemplateText + PlotNamingMethod + DepthType + DepthUnit + MinimumDepth + MaximumDepth + ShowDepthGridLines + AutoScaleDepthEnabled + DepthAxisVisibility + ShowDepthMarkerLine + AutoZoomMinDepthFactor + AutoZoomMaxDepthFactor + DepthAnnotations + SubTitleFontSize + AxisTitleFontSize + AxisValueFontSize + NameConfig + FilterEnsembleCurveSet + DepthEqualization + Tracks + DepthOrientation + +DoubleParameter - class RimDoubleParameter + Name + Label + Description + Advanced + Valid + Value + +Eclipse2dViewCollection - class RimEclipseContourMapViewCollection + EclipseViews + +EclipseCase - class RimEclipseResultCase + Name + (A)CaseUserDescription + NameSetting + Id + (A)CaseId + FilePath + (A)CaseFileName + (A)GridFileName + DefaultFormationNames + TimeStepFilter + IntersectionViewCollection + ReservoirViews + MatrixModelResults + FractureModelResults + FlipXAxis + FlipYAxis + ContourMaps + InputPropertyCollection + gridModelReader + UnitSystem + FlowDiagSolutions + SourSimFileName + MswMergeThreshold + +EclipseGeometrySelectionItem - class RimEclipseGeometrySelectionItem + EclipseCase + GridIndex + CellIndex + LocalIntersectionPoint + +EclipseResultAddress - class RimEclipseResultAddress + ResultName + ResultType + EclipseCase + +ElasticProperties - class RimElasticProperties + FilePath + ShowScaledProperties + PropertyScalingCollection + +ElasticPropertyScaling - class RimElasticPropertyScaling + Name + IsChecked + Formation + Facies + Property + Scale + +ElasticPropertyScalingCollection - class RimElasticPropertyScalingCollection + ElasticPropertyScalings + +EnsembleFractureStatistics - class RimEnsembleFractureStatistics + Name + FilePaths + ExcludeZeroWidthFractures + MeshAlignmentType + MeshType + NumberOfSamplesX + NumberOfSamplesY + AdaptiveMeanType + AdaptiveNumLayersType + AdaptiveNumLayers + SelectedStatisticsType + ComputeStatistics + +EnsembleFractureStatisticsPlot - class RimEnsembleFractureStatisticsPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + NumHistogramBins + HistogramBarColor + HistogramGapWidth + HistogramFrequencyType + Precision + TickNumberFormat + GraphType + AxisValueFontSize + AxisTitleFontSize + EnsembleFractureStatistics + Property + +EnsembleFractureStatisticsPlotCollection - class RimEnsembleFractureStatisticsPlotCollection + EnsembleFractureStatisticsPlots + +EnsembleStatisticsSurface - class RimEnsembleStatisticsSurface + SurfaceUserDecription + SurfaceColor + DepthOffset + StatisticsType + +EnsembleSurface - class RimEnsembleSurface + SurfaceUserDecription + SubCollections + SurfacesField + FilterEnsembleCurveSet + +EnsembleWellLogStatisticsCurve - class RimEnsembleWellLogStatisticsCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + TrajectoryType + CurveWellPath + ReferenceWellPath + SimulationWellName + BranchDetection + Branch + CurveCase + CurveEclipseResult + CurveGeomechResult + CurveTimeStep + GeomPartId + AddCaseNameToCurveName + AddPropertyToCurveName + AddWellNameToCurveName + AddTimestepToCurveName + AddDateToCurveName + EnsembleWellLogCurveSet + StatisticsType + +EnsembleWellLogs - class RimEnsembleWellLogs + Name + WellLogFiles + +EnsembleWellLogsCollection - class RimEnsembleWellLogsCollection + EnsembleWellLogsCollection + +FaciesInitialPressureConfig - class RimFaciesInitialPressureConfig + IsChecked + FaciesName + FaciesValue + Fraction + +FaciesProperties - class RimFaciesProperties + FilePath + FaciesDefinition + ColorLegend + +Fault - class RimFaultInView + FaultName + ShowFault + Color + +FaultReactivationModel - class RimFaultReactivationModel + Name + IsChecked + UserDescription + GeoMechCase + BaseDirectory + ModelThickness + ModelExtentFromAnchor + ModelMinZ + ModelBelowSize + StartCellIndex + StartCellFace + FaultExtendUpwards + FaultExtendDownwards + FaultZoneCells + ShowModelPlane + Fault + ModelPart1Color + ModelPart2Color + MaxReservoirCellHeight + MinReservoirCellHeight + CellHeightGrowFactor + MinReservoirCellWidth + CellWidthGrowFactor + UseLocalCoordinates + TimeStepFilter + TimeSteps + UseGridPorePressure + UseGridVoidRatio + UseGridTemperature + UseGridDensity + UseGridElasticProperties + WaterDensity + FrictionAngle + SeabedTemperature + LateralStressCoefficient + StressSource + Targets + MaterialParameters + +FaultReactivationModelCollection - class RimFaultReactivationModelCollection + Name + IsChecked + UserDescription + FaultReactivationModels + +Faults - class RimFaultInViewCollection + Active + ShowFaultFaces + ShowOppositeFaultFaces + ApplyCellFilters + OnlyShowWithDefNeighbor + FaultFaceCulling + ShowFaultLabel + FaultLabelColor + ShowNNCs + HideNncsWhenNoResultIsAvailable + Faults + ShowFaultsOutsideFilters + +FileSummaryCase - class RimFileSummaryCase + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + IncludeRestartFiles + AdditionalSummaryFilePath + RftCase + +FileSurface - class RimFileSurface + SurfaceUserDecription + SurfaceColor + DepthOffset + SurfaceFilePath + +FishbonesCollection - class RimFishbonesCollection + Name + IsChecked + FishbonesSubs + StartMD + MainBoreDiameter + MainBoreSkinFactor + +FishbonesMultipleSubs - class RimFishbones + Active + Name + Color + LateralCountPerSub + LateralLength + LateralExitAngle + LateralBuildAngle + LateralTubingDiameter + LateralOpenHoleRoghnessFactor + LateralTubingRoghnessFactor + LateralInstallSuccessFraction + IcdCount + IcdOrificeDiameter + IcdFlowCoefficient + SubsLocationMode + RangeStart + RangeEnd + RangeSubSpacing + RangeSubCount + LocationOfSubs + ValveLocations + SubsOrientationMode + InstallationRotationAngles + FixedInstallationRotationAngle + PipeProperties + +FishbonesPipeProperties - class RimFishbonesPipeProperties + LateralHoleDiameter + SkinFactor + +FlowCharacteristicsPlot - class RimFlowCharacteristicsPlot + WindowController + ShowWindow + WindowGeometry + FlowCase + FlowDiagSolution + TimeSelectionType + SelectedTimeSteps + SelectedTimeStepsUi + CellPVThreshold + ShowLegend + CellFilter + CellFilterView + TracerFilter + SelectedTracerNames + MinCommunication + MaxTof + +FlowDiagSolution - class RimFlowDiagSolution + UserDescription + +FlowPlotCollection - class RimFlowPlotCollection + FlowCharacteristicsPlot + DefaultWellConnectivityTable + DefaultWellAllocationOverTimePlot + DefaultWellAllocationPlot + WellDistributionPlotCollection + StoredWellAllocationPlots + StoredFlowCharacteristicsPlots + +FormationNames - class RimFormationNames + FormationNamesFileName + +FormationNamesCollectionObject - class RimFormationNamesCollection + FormationNamesList + +FractureContainment - class RimFractureContainment + IsUsingFractureContainment + TopKLayer + BaseKLayer + TruncateAtFaults + FaultThrowValue + +FractureDefinitionCollection - class RimFractureTemplateCollection + DefaultUnitForTemplates + FractureDefinitions + NextValidFractureTemplateId + +FractureGroupStatisticsCollection - class RimEnsembleFractureStatisticsCollection + FractureGroupStatistics + +FractureTemplateCollection - class RimFractureTemplateCollection + DefaultUnitForTemplates + FractureDefinitions + NextValidFractureTemplateId + +GeoMech2dViewCollection - class RimGeoMechContourMapViewCollection + GeoMechViews + +GeoMechGeometrySelectionItem - class RimGeoMechGeometrySelectionItem + GeoMechCase + m_gridIndex + m_cellIndex + m_elementFace + m_hasIntersectionTriangle + m_intersectionTriangle_0 + m_intersectionTriangle_1 + m_intersectionTriangle_2 + m_localIntersectionPoint + +GeoMechPart - class RimGeoMechPart + Name + IsChecked + PartId + +GeoMechPartCollection - class RimGeoMechPartCollection + Parts + +GeoMechPropertyFilter - class RimGeoMechPropertyFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + SelectedValues + ResultDefinition + LowerBound + UpperBound + +GeoMechPropertyFilters - class RimGeoMechPropertyFilterCollection + Active + PropertyFilters + +GeoMechResultDefinition - class RimGeoMechResultDefinition + IsChecked + ResultPositionType + ResultFieldName + ResultComponentName + TimeLapseBaseTimeStep + ReferenceTimeStep + CompactionRefLayer + NormalizeByHSP + NormalizationAirGap + +GeoMechResultSlot - class RimGeoMechCellColors + IsChecked + ResultPositionType + ResultFieldName + ResultComponentName + TimeLapseBaseTimeStep + ReferenceTimeStep + CompactionRefLayer + NormalizeByHSP + NormalizationAirGap + LegendDefinition + +GeoMechView - class RimGeoMechView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + CrossSections + IntersectionResultDefColl + ReservoirSurfaceResultDefColl + GridCollection + OverlayInfoConfig + WellMeasurements + SurfaceInViewCollection + SeismicSectionCollection + PolygonInViewCollection + RangeFilters + GridCellResult + TensorResults + FaultReactivationResult + PropertyFilters + Parts + ShowDisplacement + DisplacementScaling + +GridCaseSurface - class RimGridCaseSurface + SurfaceUserDecription + SurfaceColor + DepthOffset + SourceCase + SliceIndex + Watertight + IncludeInactiveCells + +GridCollection - class RimGridCollection + IsActive + MainGrid + PersistentLgrs + +GridCrossPlotCurve - class RimGridCrossPlotCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + +GridCrossPlotCurveSet - class RimGridCrossPlotDataSet + Name + IsChecked + Case + TimeStep + VisibleCellView + Grouping + XAxisProperty + YAxisProperty + GroupingProperty + NameConfig + CrossPlotCurves + CrossPlotRegressionCurves + UseCustomColor + CustomColor + PlotCellFilterCollection + +GridCrossPlotRegressionCurve - class RimGridCrossPlotRegressionCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + RegressionType + MinExtrapolationRangeX + MaxExtrapolationRangeX + PolynomialDegree + MinRangeX + MaxRangeX + MinRangeY + MaxRangeY + ShowDataSelectionInPlot + +GridInfo - class RimGridInfo + IsActive + GridName + GridIndex + +GridInfoCollection - class RimGridInfoCollection + IsActive + GridInfos + +GridStatisticsPlot - class RimGridStatisticsPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + NumHistogramBins + HistogramBarColor + HistogramGapWidth + HistogramFrequencyType + Precision + TickNumberFormat + GraphType + AxisValueFontSize + AxisTitleFontSize + Case + TimeStep + VisibleCellView + Property + +GridStatisticsPlotCollection - class RimGridStatisticsPlotCollection + GridStatisticsPlots + +GridSummaryCase - class RimGridSummaryCase_obsolete + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + Associated3DCase + CachedCasename + Associated3DCaseGridFileName + IncludeRestartFiles + +GridTimeHistoryCurve - class RimGridTimeHistoryCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + GeometrySelectionText + EclipseResultDefinition + GeoMechResultDefinition + GeometrySelectionItem + PlotAxis + +IntegerParameter - class RimIntegerParameter + Name + Label + Description + Advanced + Valid + Value + +Intersection2dView - class Rim2dIntersectionView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + Intersection + ShowDefiningPoints + ShowAxisLines + +Intersection2dViewCollection - class Rim2dIntersectionViewCollection + IntersectionViews + +IntersectionBox - class RimBoxIntersection + Active + ShowInactiveCells + UseSeparateIntersectionDataSource + SeparateIntersectionDataSource + UserDescription + singlePlaneState + MinXCoord + MaxXCoord + MinYCoord + MaxYCoord + MinDepth + MaxDepth + xySliderStepSize + DepthSliderStepSize + +IntersectionCollection - class RimIntersectionCollection + CrossSections + IntersectionBoxes + Active + UpperDepthThreshold + LowerDepthThreshold + DepthFilterOverride + CollectionDepthFilterType + OverrideKFilter + KRangeFilter + ApplyCellFilters + +IntersectionResultDefinition - class RimIntersectionResultDefinition + IsActive + Case + TimeStep + IntersectionResultDefinitionDescription + EclipseResultDef + GeoMechResultDef + LegendConfig + TernaryLegendConfig + +Legend - class RimRegularLegendConfig + ShowLegend + NumberOfLevels + Precision + TickNumberFormat + ColorRangeMode + ColorLegend + MappingMode + RangeType + UserDefinedMax + UserDefinedMin + CategoryColorMode + ResultVariableUsage + CenterLegendAroundZero + +ListParameter - class RimListParameter + Name + Label + Description + Advanced + Valid + Value + +MainPlotCollection - class RimMainPlotCollection + Show + WellLogPlotCollection + RftPlotCollection + PltPlotCollection + SummaryMultiPlotCollection + AnalysisPlotCollection + CorrelationPlotCollection + SummaryCrossPlotCollection + SummaryTableCollection + FlowPlotCollection + Rim3dCrossPlotCollection + RimSaturationPressurePlotCollection + RimMultiPlotCollection + StimPlanModelPlotCollection + VfpPlotCollection + GridStatisticsPlotCollection + EnsembleFractureStatisticsPlotCollection + SummaryPlotCollection + +MdiWindowController - class RimMdiWindowController + MainWindowID + xPos + yPos + Width + Height + IsMaximized + +MockModelSettings - class RimMockModelSettings + CellCountX + CellCountY + CellCountZ + TotalCellCount + ResultCount + TimeStepCount + +ModeledWellPath - class RimModeledWellPath + Name + (A)WellPathName + AirGap + DatumElevation + UnitSystem + SimWellName + SimBranchIndex + ShowWellPathLabel + MeasuredDepthLabelInterval + ShowWellPath + WellPathRadiusScale + WellPathColor + Completions + CompletionSettings + WellLogFiles + CollectionOf3dWellLogCurves + WellPathFormationKeyInFile + WellPathFormationFilePath + WellPathAttributes + WellPathTieIn + WellIASettings + WellPathGeometryDef + +MultiPlot - class RimMultiPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + ProjectFileVersionString + ShowTitleInPlot + PlotDescription + Plots + NumberOfColumns + RowsPerPage + ShowPlotTitles + MajorTickmarkCount + SubTitleFontSize + PagePreviewMode + +MultiSnapshotDefinition - class RimAdvancedSnapshotExportDefinition + IsActive + View + EclipseResultType + SelectedEclipseResults + TimeStepStart + TimeStepEnd + SnapShotDirection + RangeFilterStart + RangeFilterEnd + AdditionalCases + +MultiSummaryPlot - class RimSummaryMultiPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + ProjectFileVersionString + ShowTitleInPlot + PlotDescription + Plots + NumberOfColumns + RowsPerPage + ShowPlotTitles + MajorTickmarkCount + SubTitleFontSize + PagePreviewMode + AutoPlotTitle + AutoSubPlotTitle + LinkSubPlotAxes + LinkTimeAxis + AutoAdjustAppearance + Allow3DSelectionLink + AxisRangeAggregation + PlotFilterYAxisThreshold + DefaultStepDimension + +NonNetLayers - class RimNonNetLayers + IsChecked + Cutoff + Facies + FaciesDefinition + +ObservedDataCollection - class RimObservedDataCollection + ObservedDataArray + ObservedFmuRftDataArray + PressureDepthDataArray + +ObservedFmuRftData - class RimObservedFmuRftData + Name + Directory + +ObservedPressureDepthData - class RimPressureDepthData + Name + File + +ParameterGroup - class RimParameterGroup + Parameters + Name + Label + Comment + Expanded + ParameterLists + +ParameterList - class RimParameterList + ParameterNames + Name + Label + +ParameterResultCrossPlot - class RimParameterResultCrossPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + AnalysisPlotData + TimeStepFilter + TimeStep + AutoTitle + PlotTitle + LabelFontSize + AxisTitleFontSize + AxisValueFontSize + UseCaseFilter + CurveSetForFiltering + EditCaseFilter + EnsembleParameter + +PdmDocument - class caf::PdmDocument + DocumentFileName + +PdmObjectCollection - class caf::PdmObjectCollection + PdmObjects + +PdmObjectGroup - class caf::PdmObjectGroup + +Perforation - class RimPerforationInterval + Name + IsChecked + StartMeasuredDepth + EndMeasuredDepth + Diameter + SkinFactor + StartOfHistory + UseCustomStartDate + StartDate + UseCustomEndDate + EndDate + Valves + +PerforationCollection - class RimPerforationCollection + Name + IsChecked + Perforations + NonDarcyParameters + +PlotDataFilterCollection - class RimPlotDataFilterCollection + IsActive + PlotDataFiltersField + +PlotDataFilterItem - class RimPlotDataFilterItem + IsActive + FilterTarget + FilterAddressField + QuantityText + FilterOperation + MinTopN + Max + Min + EnsembleParameterValueCategories + ConsideredTimestepsType + ExplicitlySelectedTimeSteps + +PlotTemplateCollection - class RimPlotTemplateFolderItem + FolderName + FileNames + SubFolders + +PlotTemplateFileItem - class RimPlotTemplateFileItem + AbsolutePath + +PolyLineFilter - class RimPolygonFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + PolygonFilterType + PolyIncludeType + PolygonDataSource + GeometricalShape + InternalPolygon + Polygon + EnableFiltering + EnableKFilter + KRangeFilter + Targets + +PolygonFilter - class RimPolygonFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + PolygonFilterType + PolyIncludeType + PolygonDataSource + GeometricalShape + InternalPolygon + Polygon + EnableFiltering + EnableKFilter + KRangeFilter + Targets + +PolylineTarget - class RimPolylineTarget + TargetPointXyd + +PolylinesFromFileAnnotation - class RimPolylinesFromFileAnnotation + IsActive + ClosePolyline + ShowLines + ShowSpheres + Appearance + PolyLineFilePath + PolyLineDescription + +PressureTable - class RimPressureTable + Items + PressureDate + +PressureTableItem - class RimPressureTableItem + Depth + InitialPressure + Pressure + +PropertyFilter - class RimPropertyFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + SelectedValues + +RegressionAnalysisCurve - class RimSummaryRegressionAnalysisCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + SummaryCase + SummaryAddress + Resampling + HorizontalAxisType + SummaryCaseX + SummaryAddressX + IsEnsembleCurve + PlotAxis + Axis + XAxis + SummaryCurveNameConfig + isTopZWithinCategory + DataSourceForRegression + SourceCurveSet + EnsembleStatisticsType + RegressionType + ForecastForward + ForecastBackward + ForecastUnit + PolynomialDegree + TimeRangeSelection + MinTimeSliderPosition + MaxTimeSliderPosition + ShowTimeSelectionInPlot + XRangeSelection + ValueRangeX + YRangeSelection + ValueRangeY + +ResInsightAnalysisModels - class RimEclipseCaseCollection + Reservoirs + CaseGroups + +ResInsightGeoMechCase - class RimGeoMechCase + Name + (A)CaseUserDescription + NameSetting + Id + (A)CaseId + FilePath + (A)CaseFileName + (A)GridFileName + DefaultFormationNames + TimeStepFilter + IntersectionViewCollection + GeoMechViews + CaseCohesion + FrctionAngleDeg + ElementPropertyFileNames + BiotCoefficientType + BiotFixedCoefficient + BiotResultAddress + InitialPermeabilityType + InitialPermeabilityFixed + InitialPermeabilityAddress + PermeabilityExponent + WaterDensityShearSlipIndicator + ContourMaps + MudWeightWindowParameters + +ResInsightGeoMechModels - class RimGeoMechModels + Cases + +ResInsightOilField - class RimOilField + AnalysisModels + GeoMechModels + WellPathCollection + CompletionTemplateCollection + SummaryCaseCollection + FormationNamesCollection + ObservedDataCollection + AnnotationCollection + EnsembleWellLogsCollection + PolygonCollection + FractureDefinitionCollection + SurfaceCollection + SeismicCollection + SeismicViewCollection + +ResInsightProject - class RimProject + DocumentFileName + ProjectFileVersionString + ReferencedExternalFiles + OilFields + ColorLegendCollection + WellPathImport + MainPlotCollection + LinkedViews + CalculationCollection + GridCalculationCollection + CommandObjects + MultiSnapshotDefinitions + TreeViewStates + TreeViewCurrentModelIndexPaths + PlotWindowTreeViewStates + PlotWindowTreeViewCurrentModelIndexPaths + show3DWindow + showPlotWindow + showPlotWindowOnTopOf3DWindow + tiled3DWindow + tiledPlotWindow + DialogData + Reservoirs + CaseGroups + TileMode3DWindow + TileModePlotWindow + +ResampleData - class RimcSummaryResampleData + TimeSteps + Values + +ReservoirCellResultStorage - class RimReservoirCellResultsStorage + ResultCacheFileName + ResultCacheEntries + +ReservoirView - class RimEclipseView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + CrossSections + IntersectionResultDefColl + ReservoirSurfaceResultDefColl + GridCollection + OverlayInfoConfig + WellMeasurements + SurfaceInViewCollection + SeismicSectionCollection + PolygonInViewCollection + RangeFilters + CustomEclipseCase + GridCellResult + GridCellEdgeResult + ElementVectorResult + FaultResultSettings + StimPlanColors + VirtualPerforationResult + WellCollection + FaultCollection + FaultReactivationModelCollection + AnnotationCollection + StreamlineCollection + PropertyFilters + ShowInactiveCells + ShowInvalidCells + AdditionalResultsForResultInfo + +ResultDefinition - class RimEclipseResultDefinition + IsChecked + ResultType + PorosityModelType + ResultVariable + FlowDiagSolution + TimeLapseBaseTimeStep + DifferenceCase + DivideByCellFaceArea + SelectedInjectorTracers + SelectedProducerTracers + SelectedSouringTracers + FlowTracerSelectionMode + PhaseSelection + ShowOnlyVisibleCategoriesInLegend + MSyncSelectedInjProd + MSyncSelectedProdInj + +ResultSlot - class RimEclipseCellColors + IsChecked + ResultType + PorosityModelType + ResultVariable + FlowDiagSolution + TimeLapseBaseTimeStep + DifferenceCase + DivideByCellFaceArea + SelectedInjectorTracers + SelectedProducerTracers + SelectedSouringTracers + FlowTracerSelectionMode + PhaseSelection + ShowOnlyVisibleCategoriesInLegend + MSyncSelectedInjProd + MSyncSelectedProdInj + LegendDefinition + ResultVarLegendDefinitionList + TernaryLegendDefinition + LegendDefinitionPtrField + +ResultStorageEntryInfo - class RimReservoirCellResultsStorageEntryInfo + ResultType + ResultName + TimeSteps + DaysSinceSimulationStart + FilePositionDataStart + +RftAddress - class RimDataSourceForRftPlt + SourceType + EclipseCase + SummaryCase + Ensemble + WellLogFile + ObservedFmuRftData + PressureDepthData + +RiaMemoryCleanup - class RiaMemoryCleanup + DataCase + ResultsToDelete + +RiaPreferences - class RiaPreferences + navigationPolicy + enableGrpcServer + defaultGrpcPort + scriptDirectory + scriptEditorExecutable + MaxScriptFoldersDepth + octaveExecutable + octaveShowHeaderInfoWhenExecutingScripts + pythonExecutable + pythonDebugInfo + loggerFilename + loggerFlushInterval + loggerTrapSignalAndFlush + ssihubAddress + defaultMeshModeType + defaultGridLineColors + defaultFaultGridLineColors + defaultWellLableColor + defaultViewerBackgroundColor + defaultScaleFactorZ + defaultSceneFontSizePt + defaultAnnotationFontSizePt + defaultWellLabelFontSizePt + defaultPlotFontSizePt + showLegendBackground + enableFaultsByDefault + showInfoBox + showGridBox + lastUsedProjectFileName + autocomputeDepth + loadAndShowSoil + holoLensDisableCertificateVerification + csvTextExportFieldSeparator + gridModelReader + readerSettings + dateFormat + timeFormat + useUndoRedo + plotTemplateFolders + MaxPlotTemplateFoldersDepth + defaultPlotTemplate + pageSize + pageOrientation + pageLeftMargin + pageTopMargin + pageRightMargin + pageBottomMargin + openExportedPdfInViewer + writeEchoInGrdeclFiles + useQtChartsPlotByDefault + gridCalculationExpressionFolder + summaryCalculationExpressionFolder + SurfaceImportResamplingDistance + MultiLateralWellPattern + guiTheme + summaryPreferences + geoMechPreferences + systemPreferences + +RiaPreferencesGeoMech - class RiaPreferencesGeoMech + geomechWIADefaultXML + geomechWIACommand + geomechFRMDefaultXML + geomechFRMCommand + keepTemporaryFile + waitForInputFileEdit + +RiaPreferencesSummary - class RiaPreferencesSummary + summaryRestartFilesShowImportDialog + summaryImportMode + gridImportMode + summaryEnsembleImportMode + defaultSummaryHistoryCurveStyle + defaultSummaryCurvesTextFilter + defaultSummaryPlot + CrossPlotAddressCombinations + defaultSummaryTemplates + createEnhancedSummaryDataFile_v01 + useEnhancedSummaryDataFile + createH5SummaryDataFile_v01 + createH5SummaryFileThreadCount + summaryReaderType_v01 + showSummaryTimeAsLongString + useMultipleThreadsWhenLoadingSummaryCases + DefaultNumberOfColumns + DefaultRowsPerPage + curveColorByPhase + appendHistoryVectorForDragDrop + historyCurveContrastColor + +RiaPreferencesSystem - class RiaPreferencesSystem + useShaders + showHud + appendClassNameToUiText + appendFieldKeywordToToolTipText + showViewIdInTree + showTestToolbar + includeFractureDebugInfoFile + holoLensExportFolder + showProjectChangedDialog + showProgressBar + showPdfExportDialog + gtestFilter + exportScalingFactor + eclipseReaderMode + +RiaRegressionTest - class RiaRegressionTest + workingFolder + folderContainingDiffTool + folderContainingGitTool + regressionTestFolder + showInteractiveDiffImages + useOpenMPForGeometryCreation + openReportInBrowser + testFilter + appendTestsAfterTestFilter + invalidateExternalFilePaths + forcePlotEngine + exportSnapshots3dViews + exportSnapshotsPlots + +RicCaseAndFileExportSettingsUi - class RicCaseAndFileExportSettingsUi + Folder + CaseToApply + +RicCellRangeUi - class RicCellRangeUi + Case + GridIndex + StartIndexI + StartIndexJ + StartIndexK + CellCountI + CellCountJ + CellCountK + +RicCreateDepthAdjustedLasFilesUi - class RicCreateDepthAdjustedLasFilesUi + ExportFolder + SelectedCase + SourceWell + WellLogFile + SelectedResultProperties + DestinationWells + +RicCreateEnsembleSurfaceUi - class RicCreateEnsembleSurfaceUi + Layers + AutoCreateEnsembleSurfaces + MinLayer + MaxLayer + +RicCreateEnsembleWellLogUi - class RicCreateEnsembleWellLogUi + AutoCreateEnsembleWellLogs + TimeStep + WellPathSource + WellPath + WellFilePath + SelectedProperties + +RicCreateMultipleWellPathLateralsUi - class RicCreateMultipleWellPathLateralsUi + SourceLaterals + TopLevelWellPath + Locations + +RicCreateRftPlotsFeatureUi - class RicCreateRftPlotsFeatureUi + SelectedWellNames + +RicDeleteItemExecData - class RicDeleteItemExecData + PathToField + Description + indexToObject + deletedObjectAsXml + +RicExportCarfinUi - class RicExportCarfinUi + CellRange + ExportFileName + CaseToApply + CellCountI + CellCountJ + CellCountK + MaxWellCount + +RicExportCompletionDataSettingsUi - class RicExportCompletionDataSettingsUi + Folder + CaseToApply + FileSplit + compdatExport + TimeStepIndex + IncludeMSW + UseLateralNTG + IncludePerforations + IncludeFishbones + IncludeFractures + TransScalingType + TransScalingTimeStep + TransScalingWBHPSource + TransScalingWBHP + ExcludeMainBoreForFishbones + ReportCompletionTypesSeparately + ExportDataSourceAsComment + ExportWelspec + CompletionWelspecAfterMainBore + UseCustomFileName + CustomFileName + +RicExportContourMapToTextUi - class RicExportContourMapToTextUi + ExportFileName + ExportLocalCoordinates + UndefinedValueLabel + ExcludeUndefinedValues + +RicExportEclipseInputGridUi - class RicExportEclipseSectorModelUi + ExportGrid + ExportGridFilename + ExportInLocalCoords + InvisibleCellActnum + GridBoxSelection + MinI + MinJ + MinK + MaxI + MaxJ + MaxK + ExportFaults + ExportFaultsFilename + RefinementCountI + RefinementCountJ + RefinementCountK + ExportParams + ExportParamsFilename + ExportMainKeywords + WriteEchoInGrdeclFiles + ExportFolder + +RicExportLgrUi - class RicExportLgrUi + ExportFolder + CaseToApply + TimeStepIndex + IncludePerforations + IncludeFractures + IncludeFishbones + CellCountI + CellCountJ + CellCountK + SplitType + +RicExportToLasFileObj - class RicExportToLasFileObj + tvdrkbOffset + +RicExportToLasFileResampleUi - class RicExportToLasFileResampleUi + ExportFolder + FilePrefix + CapitalizeFileName + CurveUnitConversion + ActivateResample + ResampleInterval + ExportTvdrkb + tvdrkbOffsets + +RicExportWellPathsUi - class RicExportWellPathsUi + ExportFolder + MdStepSize + +RicGridCalculator - class RicGridCalculatorUi + CurrentCalculation + +RicHoloLensCreateSessionUi - class RicHoloLensCreateSessionUi + SessionName + SessionPinCode + ServerSettings + +RicHoloLensExportToFolderUi - class RicHoloLensExportToFolderUi + ViewForExport + ExportFolder + +RicHoloLensServerSettings - class RicHoloLensServerSettings + ServerAddress + +RicLinkVisibleViewsFeatureUi - class RicLinkVisibleViewsFeatureUi + MasterView + +RicPasteAsciiDataToSummaryPlotFeatureUi - class RicPasteAsciiDataToSummaryPlotFeatureUi + PlotTitle + CurvePrefix + DecimalSeparator + DateFormat + TimeFormat + UseCustomDateFormat + CustomDateTimeFormat + LineStyle + Symbol + SymbolSkipDinstance + CellSeparator + TimeColumnName + +RicSaturationPressureUi - class RicSaturationPressureUi + CaseToApply + TimeStep + +RicSaveEclipseInputVisibleCellsUi - class RicSaveEclipseInputVisibleCellsUi + ExportFilename + ExportKeyword + VisibleActiveCellsValue + HiddenActiveCellsValue + InactiveCellsValue + WriteEchoInGrdeclFiles + +RicSaveMultiPlotTemplateFeatureSettings - class RicSaveMultiPlotTemplateFeatureSettings + FilePath + Name + PersistObjectNameWells + PersistObjectNameGroups + PersistObjectNameRegions + +RicSelectCaseOrEnsembleUi - class RicSelectCaseOrEnsembleUi + SelectedSummaryCase + SelectedEnsemble + +RicSelectPlotTemplateUi - class RicSelectPlotTemplateUi + SelectedPlotTemplates + +RicSelectSummaryPlotUI - class RicSelectSummaryPlotUI + SelectedSummaryPlot + CreateNewPlot + NewViewName + +RicSelectViewUI - class RicSelectViewUI + MasterView + CreateNewView + NewViewName + +RicSummaryAddressSelection - class RiuSummaryVectorSelectionUi + SummaryCases + CurrentSummaryCategory + SelectedSummaryCategories + FieldVectors + FieldCalculationIds + Aquifers + AquiferVectors + AquifierCalculationIds + NetworkNames + NetworkVectors + NetworkCalculationIds + MiscVectors + MiscCalculationIds + Regions + RegionsVectors + RegionCalculationIds + Region2RegionRegions + Region2RegionVectors + Region2RegionCalculationIds + WellGroupWellGroupNames + WellGroupVectors + WellGroupCalculationIds + WellWellName + WellVectors + WellCalculationIds + WellCompletionWellName + WellCompletionIjk + WellCompletionVectors + WellCompletionCalculationIds + WellCompletionLgrLgrName + WellCompletionLgrWellName + WellCompletionLgrIjk + WellCompletionLgrVectors + WellCompletionLgrCalculationIds + WellLgrLgrName + WellLgrWellName + WellLgrVectors + WellLgrCalculationIds + WellSegmentWellName + WellSegmentNumber + WellSegmentVectors + WellSegmentCalculationIds + BlockIjk + BlockVectors + BlockCalculationIds + BlockLgrLgrName + BlockLgrIjk + BlockLgrVectors + BlockLgrCalculationIds + ImportedVectors + ImportedCalculationIds + +RicSummaryCurveCalculator - class RicSummaryCurveCalculatorUi + CurrentCalculation + +RicSummaryCurveCreator - class RicSummaryPlotEditorUi + TargetPlot + UseAutoAppearanceAssignment + AppearanceApplyButton + CaseAppearanceType + VariableAppearanceType + WellAppearanceType + GroupAppearanceType + RegionAppearanceType + ApplySelection + Close + OK + SummaryCurveNameConfig + +RicWellPathsUnitSystemSettingsUi - class RicWellPathsUnitSystemSettingsUi + UnitSystem + +RifReaderSettings - class RifReaderSettings + importFaults + importSimulationNNCs + includeInactiveCellsInFaultGeometry + importAdvancedMswData + useResultIndexFile + skipWellData + includeFileAbsolutePathPrefix + importSummaryData + +Rim3dWellLogCurveCollection - class Rim3dWellLogCurveCollection + Show3dWellLogCurves + PlaneWidthScaling + Show3dWellLogGrid + Show3dWellLogBackground + ArrayOf3dWellLogCurves + +Rim3dWellLogExtractionCurve - class Rim3dWellLogExtractionCurve + Show3dWellLogCurve + MinCurveValue + MaxCurveValue + DrawPlane + CurveColor + CurveCase + CurveTimeStep + GeomPartId + CurveEclipseResult + CurveGeomechResult + NameConfig + +Rim3dWellLogFileCurve - class Rim3dWellLogFileCurve + Show3dWellLogCurve + MinCurveValue + MaxCurveValue + DrawPlane + CurveColor + CurveWellLogChannel + WellLogFile + NameConfig + +Rim3dWellLogRftCurve - class Rim3dWellLogRftCurve + Show3dWellLogCurve + MinCurveValue + MaxCurveValue + DrawPlane + CurveColor + eclipseResultCase + timeStep + wellLogChannelName + NameConfig + +RimAnnotationCollection - class RimAnnotationCollection + IsActive + TextAnnotations + ReachCircleAnnotations + UserDefinedPolylineAnnotations + PolylineFromFileAnnotations + +RimAnnotationCollectionBase - class RimAnnotationCollectionBase + IsActive + TextAnnotations + +RimAnnotationGroupCollection - class RimAnnotationGroupCollection + IsActive + Annotations + +RimAnnotationLineAppearance - class RimAnnotationLineAppearance + LineFieldsHidden + Color + Thickness + +RimAnnotationTextAppearance - class RimAnnotationTextAppearance + FontSize + FontColor + BackgroundColor + AnchorLineColor + +RimBinaryExportSettings - class RimBinaryExportSettings + Filename + EclipseKeyword + UndefinedValue + WriteEchoInGrdeclFiles + +RimCaseCollection - class RimCaseCollection + Reservoirs + +RimCellFilterCollection - class RimCellFilterCollection + Active + CombineFilterMode + CellFilters + RangeFilters + +RimCommandExecuteScript - class RimCommandExecuteScript + Name + ScriptText + IsEnabled + +RimCommandIssueFieldChanged - class RimCommandIssueFieldChanged + CommandName + ObjectName + FieldName + FieldValueToApply + +RimCommandObject - class RimCommandObject + +RimCommandRouter - class RimCommandRouter + +RimContourMapView - class RimEclipseContourMapView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + CrossSections + IntersectionResultDefColl + ReservoirSurfaceResultDefColl + GridCollection + OverlayInfoConfig + WellMeasurements + SurfaceInViewCollection + SeismicSectionCollection + PolygonInViewCollection + RangeFilters + CustomEclipseCase + GridCellResult + GridCellEdgeResult + ElementVectorResult + FaultResultSettings + StimPlanColors + VirtualPerforationResult + WellCollection + FaultCollection + FaultReactivationModelCollection + AnnotationCollection + StreamlineCollection + PropertyFilters + ShowInactiveCells + ShowInvalidCells + AdditionalResultsForResultInfo + ContourMapProjection + ShowAxisLines + ShowScaleLegend + +RimCsvUserData - class RimCsvUserData + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + UseCustomIdentifier + SummaryType + IdentifierName + ParseOptions + +RimCustomObjectiveFunction - class RimCustomObjectiveFunction + FunctionTitle + CustomFunctionTitle + Weights + ObjectiveFunctions + +RimCustomObjectiveFunctionCollection - class RimCustomObjectiveFunctionCollection + ObjectiveFunctions + +RimCustomObjectiveFunctionWeight - class RimCustomObjectiveFunctionWeight + WeightTitle + ObjectiveSummaryAddress + WeightValue + ObjectiveFunction + +RimDerivedEnsembleCase - class RimDerivedSummaryCase + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + SummaryCase1 + Operator + SummaryCase2 + UseFixedTimeStep + FixedTimeStepIndex + InUse + +RimDerivedEnsembleCaseCollection - class RimDerivedEnsembleCaseCollection + SummaryCases + SummaryCollectionName + CreateAutoName + NameCount + IsEnsemble + Id + (A)EnsembleId + Ensemble1 + Ensemble2 + Operator + CaseCount + MatchOnParameters + UseFixedTimeStep + FixedTimeStepIndex + +RimDialogData - class RimDialogData + ExportCarfin + ExportCompletionData + MultipleFractionsData + HoloLenseExportToFolderData + ExportwellPathsData + ExportLgr + ExportSectorModel + MockModelSettings + CreateEnsembleSurfaceUi + CreateEnsembleWellLogUi + +RimEclipseContourMapProjection - class RimEclipseContourMapProjection + Name + IsChecked + SampleSpacing + ResultAggregation + ContourLines + ContourLabels + SmoothContourLines + WeightByParameter + WeightingResult + +RimEclipseResultAddressCollection - class RimEclipseResultAddressCollection + Name + Addresses + ResultType + +RimElementVectorResult - class RimElementVectorResult + LegendDefinition + ShowOil + ShowGas + ShowWater + ShowResult + VectorView + VectorSurfaceCrossingLocation + ShowVectorI + ShowVectorJ + ShowVectorK + ShowNncData + Threshold + VectorColor + UniformVectorColor + SizeScale + +RimEllipseFractureTemplate - class RimEllipseFractureTemplate + Id + UserDescription + UnitSystem + Orientation + UserDefinedPerforationLength + AzimuthAngle + SkinFactor + PerforationLength + PerforationEfficiency + WellDiameter + ConductivityType + WellPathDepthAtFracture + FractureContainmentField + NonDarcyFlowType + UserDefinedDFactor + FractureWidthType + FractureWidth + BetaFactorType + InertialCoefficient + PermeabilityType + RelativePermeability + EffectivePermeability + RelativeGasDensity + GasViscosity + HeightScaleFactor + WidthScaleFactor + DFactorScaleFactor + ConductivityFactor + HalfLength + Height + Width + Permeability + +RimEmCase - class RimEmCase + Name + (A)CaseUserDescription + NameSetting + Id + (A)CaseId + FilePath + (A)CaseFileName + (A)GridFileName + DefaultFormationNames + TimeStepFilter + IntersectionViewCollection + ReservoirViews + MatrixModelResults + FractureModelResults + FlipXAxis + FlipYAxis + ContourMaps + InputPropertyCollection + +RimEnsembleCurveFilter - class RimEnsembleCurveFilter + FilterTitle + Active + FilterMode + EnsembleParameter + ObjectiveSummaryAddress + ObjectiveFunction + CustomObjectiveFunction + MinValue + MaxValue + Categories + RealizationFilter + +RimEnsembleCurveFilterCollection - class RimEnsembleCurveFilterCollection + Active + CurveFilters + +RimEnsembleCurveSet - class RimEnsembleCurveSet + EnsembleCurveSet + IsActive + SummaryGroup + SummaryAddress + Resampling + HorizontalAxisType + XAddressSelector + ColorMode + Color + MainEnsembleColor + ColorTransparency + EnsembleParameter + EnsembleParameterSorting + UseCustomAppearance + LineStyle + PointSymbol + SymbolSize + StatisticsUseCustomAppearance + StatisticsLineStyle + StatisticsPointSymbol + StatisticsSymbolSize + ObjectiveSummaryAddress + CustomObjectiveFunction + ShowObjectiveFunctionFormula + MinDateRange + MinTimeSliderPosition + MaxDateRange + MaxTimeSliderPosition + TimeStepFilter + TimeSteps + PlotAxis + Axis + LegendConfig + CurveFilters + CustomObjectiveFunctions + ObjectiveFunction + Statistics + UserDefinedName + AutoName + SummaryAddressNameTools + +RimEnsembleCurveSetCollection - class RimEnsembleCurveSetCollection + EnsembleCurveSets + IsActive + +RimEnsembleStatistics - class RimEnsembleStatistics + Active + ShowStatisticsCurveLegends + HideEnsembleCurves + ShowEnsembleCurves + BasedOnFilteredCases + ShowP10Curve + ShowP50Curve + ShowP90Curve + ShowMeanCurve + ShowCurveLabels + IncludeIncompleteCurves + CrossPlotCurvesBinCount + CrossPlotCurvesStatisticsRealizationCountThresholdPerBin + Color + +RimEnsembleWellLogCurveSet - class RimEnsembleWellLogCurveSet + EnsembleCurveSet + IsActive + EnsembleWellLogs + WellLogChannelName + FilterEnsembleCurveSet + DepthEqualization + ColorMode + Color + Statistics + UserDefinedName + AutoName + PlotCurveAppearance + +RimEquilibriumAxisAnnotation - class RimEquilibriumAxisAnnotation + Active + Name + Value + RangeStart + RangeEnd + PenStyle + AnnotationType + Associated3DCase + m_equilNum + +RimExportInputSettings - class RimExportInputSettings + Filename + Keyword + WriteEchoInGrdeclFiles + +RimFaultResultSlot - class RimEclipseFaultColors + ShowCustomFaultResult + CustomResultSlot + +RimFractureExportSettings - class RimFractureExportSettings + Filename + CaseToApply + +RimGeoMechContourMapProjection - class RimGeoMechContourMapProjection + Name + IsChecked + SampleSpacing + ResultAggregation + ContourLines + ContourLabels + SmoothContourLines + LimitToPorRegion + VerticalLimit + PaddingAroundPorRegion + +RimGeoMechContourMapView - class RimGeoMechContourMapView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + CrossSections + IntersectionResultDefColl + ReservoirSurfaceResultDefColl + GridCollection + OverlayInfoConfig + WellMeasurements + SurfaceInViewCollection + SeismicSectionCollection + PolygonInViewCollection + RangeFilters + GridCellResult + TensorResults + FaultReactivationResult + PropertyFilters + Parts + ShowDisplacement + DisplacementScaling + ContourMapProjection + ShowAxisLines + ShowScaleLegend + +RimGeoMechFaultReactivationResult - class RimGeoMechFaultReactivationResult + DistanceFromFault + FaultNormal + FaultTopPosition + FaultBottomPosition + FaceAWellPath + FaceBWellPath + FaceAWellPathPartIndex + FaceBWellPathPartIndex + +RimGridCalculation - class RimGridCalculation + Description + Expression + Unit + Variables + Id + VisibleCellView + DefaultValueType + DefaultValue + DestinationCase + AllDestinationCase + AdditionalCasesType + AdditionalCaseGroup + NonVisibleResultAddress + SelectedTimeSteps + +RimGridCalculationCollection - class RimGridCalculationCollection + Calculations + +RimGridCalculationVariable - class RimGridCalculationVariable + VariableName + ResultType + ResultVariable + EclipseGridCase + TimeStep + +RimGridCrossPlot - class RimGridCrossPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + ShowInfoBox + NameConfig + xAxisProperties + yAxisProperties + CrossPlotCurve + +RimGridCrossPlotCollection - class RimGridCrossPlotCollection + GridCrossPlots + +RimGridCrossPlotCurveSetNameConfig - class RimGridCrossPlotDataSetNameConfig + CustomCurveName + AddCaseName + AddAxisVariables + AddTimeStep + AddGrouping + +RimGridCrossPlotNameConfig - class RimGridCrossPlotNameConfig + CustomCurveName + AddDataSetNames + +RimIdenticalGridCaseGroup - class RimIdenticalGridCaseGroup + UserDescription + GroupId + StatisticsCaseCollection + CaseCollection + +RimInputProperty - class RimEclipseInputProperty + ResultName + EclipseKeyword + FileName + +RimInputPropertyCollection - class RimEclipseInputPropertyCollection + InputProperties + +RimInputReservoir - class RimEclipseInputCase + Name + (A)CaseUserDescription + NameSetting + Id + (A)CaseId + FilePath + (A)CaseFileName + (A)GridFileName + DefaultFormationNames + TimeStepFilter + IntersectionViewCollection + ReservoirViews + MatrixModelResults + FractureModelResults + FlipXAxis + FlipYAxis + ContourMaps + InputPropertyCollection + AdditionalFileNamesProxy + +RimIntersectionResultsDefinitionCollection - class RimIntersectionResultsDefinitionCollection + isActive + IntersectionResultDefinitions + +RimMeasurement - class RimMeasurement + +RimMswCompletionParameters - class RimMswCompletionParameters + RefMDType + RefMD + CustomValuesForLateral + LinerDiameter + RoughnessFactor + PressureDrop + LengthAndDepth + EnforceMaxSegmentLength + MaxSegmentLength + +RimMudWeightWindowParameters - class RimMudWeightWindowParameters + WellDeviationSourceType + WellDeviationFixed + WellDeviationAddress + WellAzimuthSourceType + WellAzimuthFixed + WellAzimuthAddress + UCSSourceType + UCSFixed + UCSAddress + PoissonsRatioSourceType + PoissonsRatioFixed + PoissonsRatioAddress + K0_FGSourceType + K0_FGFixed + K0_FGAddress + obg0SourceType + obg0Fixed + obg0Address + AirGap + SHMultiplier + UpperLimitType + LowerLimitType + FractureGradientCalculationType + PorePressureNonReservoirSource + UserPPNonReservoir + PPNonReservoirAddress + ReferenceLayer + +RimMultiPlotCollection - class RimMultiPlotCollection + MultiPlots + +RimMultipleEclipseResults - class RimMultipleEclipseResults + IsChecked + showCenterCoordinates + showCornerCoordinates + SelectedProperties + +RimMultipleLocations - class RimMultipleLocations + LocationMode + RangeStart + RangeEnd + Spacing + RangeValveCount + Locations + +RimMultipleValveLocations - class RimMultipleValveLocations + LocationMode + RangeStart + RangeEnd + ValveSpacing + RangeValveCount + LocationOfValves + +RimNonDarcyPerforationParameters - class RimNonDarcyPerforationParameters + NonDarcyFlowType + UserDefinedDFactor + GridPermeabilityScalingFactor + WellRadius + RelativeGasDensity + GasViscosity + InertialCoefficientBeta0 + PermeabilityScalingFactor + PorosityScalingFactor + +RimObjectiveFunction - class RimObjectiveFunction + FunctionType + NormalizeByNumberOfObservations + NormalizeByNumberOfVectors + ErrorEstimatePercentage + UseSquaredError + +RimObservedEclipseUserData - class RimObservedEclipseUserData + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + UseCustomIdentifier + SummaryType + IdentifierName + +RimOilFieldEntry - class RimOilFieldEntry + OilFieldName + EdmId + Selected + wellsFilePath + Wells + +RimOilRegionEntry - class RimOilRegionEntry + OilRegionEntry + Fields + Selected + +RimPlotAxisAnnotation - class RimPlotAxisAnnotation + Active + Name + Value + RangeStart + RangeEnd + PenStyle + +RimPlotCellFilterCollection - class RimPlotCellFilterCollection + Name + IsChecked + FilterMode + CellFilters + +RimPlotCellPropertyFilter - class RimPlotCellPropertyFilter + Name + IsChecked + FilterMode + ResultDefinition + LowerBound + UpperBound + +RimPlotRectAnnotation - class RimPlotRectAnnotation + Name + IsChecked + MinX + MaxX + MinY + MaxY + Color + Transparency + Text + +RimPolygon - class RimPolygon + Name + IsReadOnly + PointsInDomainCoords + Appearance + +RimPolygonAppearance - class RimPolygonAppearance + IsClosed + ShowLines + ShowSpheres + LineThickness + SphereRadiusFactor + LineColor + SphereColor + PolygonPlaneDepth + LockPolygon + +RimPolygonCollection - class RimPolygonCollection + Polygons + PolygonFiles + +RimPolygonFileFile - class RimPolygonFile + Name + StimPlanFileName + Polygons + +RimPolygonInView - class RimPolygonInView + Name + IsChecked + Polygon + HandleScalingFactor + +RimPolygonInViewCollection - class RimPolygonInViewCollection + Name + IsChecked + Polygons + Collections + +RimPolylineAppearance - class RimPolylineAppearance + LineFieldsHidden + Color + Thickness + SphereFieldsHidden + SphereColor + SphereRadiusFactor + +RimPolylinesAnnotationInView - class RimPolylinesAnnotationInView + IsActive + SourceAnnotation + +RimPolylinesFromFileAnnotationInView - class RimPolylinesFromFileAnnotationInView + IsActive + SourceAnnotation + +RimProcess - class RimProcess + Command + Description + ID + +RimReachCircleAnnotation - class RimReachCircleAnnotation + IsActive + CenterPointXyd + Radius + Name + Appearance + +RimReachCircleAnnotationInView - class RimReachCircleAnnotationInView + IsActive + SourceAnnotation + +RimResultSelectionUi - class RimResultSelectionUi + Case + Result + +RimRftCase - class RimRftCase + RftFilePath + DataDeckFilePath + +RimRftTopologyCurve - class RimRftTopologyCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + SummaryCase + TimeStep + WellName + SegmentBranchIndex + SegmentBranchType + CurveType + SymbolLocation + +RimRoffCase - class RimRoffCase + Name + (A)CaseUserDescription + NameSetting + Id + (A)CaseId + FilePath + (A)CaseFileName + (A)GridFileName + DefaultFormationNames + TimeStepFilter + IntersectionViewCollection + ReservoirViews + MatrixModelResults + FractureModelResults + FlipXAxis + FlipYAxis + ContourMaps + InputPropertyCollection + +RimSEGYConvertOptions - class RimSEGYConvertOptions + InputFilename + OutputFilename + SampleStartOverride + SampleUnit + HeaderFilename + +RimSaturationPressurePlot - class RimSaturationPressurePlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + ShowInfoBox + NameConfig + xAxisProperties + yAxisProperties + CrossPlotCurve + +RimSaturationPressurePlotCollection - class RimSaturationPressurePlotCollection + SaturationPressurePlots + +RimSeismicView - class RimSeismicView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + SeismicData + SurfaceInViewCollection + SeismicSectionCollection + AnnotationCollection + OverlayInfoConfig + +RimStatisticalCalculation - class RimEclipseStatisticsCase + Name + (A)CaseUserDescription + NameSetting + Id + (A)CaseId + FilePath + (A)CaseFileName + (A)GridFileName + DefaultFormationNames + TimeStepFilter + IntersectionViewCollection + ReservoirViews + MatrixModelResults + FractureModelResults + FlipXAxis + FlipYAxis + ContourMaps + InputPropertyCollection + DataSourceForStatistics + GridCalculation + GridCalculationFilterView + SelectedTimeSteps + ResultType + PorosityModel + DynamicPropertiesToCalculate + StaticPropertiesToCalculate + GeneratedPropertiesToCalculate + InputPropertiesToCalculate + FractureDynamicPropertiesToCalculate + FractureStaticPropertiesToCalculate + FractureGeneratedPropertiesToCalculate + FractureInputPropertiesToCalculate + CalculatePercentiles + PercentileCalculationType + LowPercentile + MidPercentile + HighPercentile + WellDataSourceCase + UseZeroAsInactiveCellValue + +RimStatisticalCollection - class RimEclipseStatisticsCaseCollection + Reservoirs + +RimStimPlanColors - class RimStimPlanColors + IsChecked + ResultName + DefaultColor + LegendConfigurations + ShowStimPlanMesh + StimPlanCellVizMode + +RimStimPlanFractureTemplate - class RimStimPlanFractureTemplate + Id + UserDescription + UnitSystem + Orientation + UserDefinedPerforationLength + AzimuthAngle + SkinFactor + PerforationLength + PerforationEfficiency + WellDiameter + ConductivityType + WellPathDepthAtFracture + FractureContainmentField + NonDarcyFlowType + UserDefinedDFactor + FractureWidthType + FractureWidth + BetaFactorType + InertialCoefficient + PermeabilityType + RelativePermeability + EffectivePermeability + RelativeGasDensity + GasViscosity + HeightScaleFactor + WidthScaleFactor + DFactorScaleFactor + ConductivityFactor + StimPlanFileName + UserDefinedWellPathDepthAtFracture + BorderPolygonResultName + ActiveTimeStepIndex + ConductivityResultName + ShowStimPlanMesh + +RimStimPlanLegendConfig - class RimStimPlanLegendConfig + Name + Legend + +RimSummaryAddressCollection - class RimSummaryAddressCollection + Name + ContentsType + SummaryAddresses + AddressSubfolders + CaseId + EnsembleId + +RimSummaryAddressSelector - class RimSummaryAddressSelector + SummaryCase + SummaryCaseCollection + SummaryAddress + PlotAxisProperties + Resampling + +RimSummaryCalculation - class RimSummaryCalculation + Description + Expression + Unit + Variables + Id + DistributeToOtherItems + DistributeToAllCases + +RimSummaryCalculationCollection - class RimSummaryCalculationCollection + Calculations + +RimSummaryCalculationVariable - class RimSummaryCalculationVariable + VariableName + SummaryCase + SummaryAddress + +RimSummaryCurveCollection - class RimSummaryCurveCollection + CollectionCurves + IsActive + +RimSummaryCurveCollectionModifier - class RimSummaryPlotSourceStepping + StepDimension + CurveCase + IncludeEnsembleCasesForCaseStepping + WellName + GroupName + NetworkName + Region + VectorName + CellBlock + Segment + Completion + Aquifer + Ensemble + Placeholder + AutoUpdateAppearance + +RimSummaryMultiPlotCollection - class RimSummaryMultiPlotCollection + MultiSummaryPlots + +RimSummaryPlotManager - class RimSummaryPlotManager + SummaryPlot + FilterText + AddressCandidates + SelectedDataSources + IncludeDiffCurves + IndividualPlotPerObject + IndividualPlotPerVector + IndividualPlotPerDataSource + CreateMultiPlot + +RimSummaryTable - class RimSummaryTable + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + TableName + AutomaticTableName + SummaryCase + Vector + Categories + ResamplingSelection + ThresholdValue + ExcludedTableRows + ShowValueLabels + MaxTimeLabelCount + AxisTitleFontSize + AxisLabelFontSize + ValueLabelFontSize + LegendConfig + MappingType + RangeType + +RimSummaryTableCollection - class RimSummaryTableCollection + SummaryTables + +RimSurfaceIntersectionBand - class RimSurfaceIntersectionBand + IsChecked + LineAppearance + BandColor + BandOpacity + BandPolygonOffsetUnit + Surfaces + NameProxy + +RimSurfaceIntersectionCollection - class RimSurfaceIntersectionCollection + IsChecked + IntersectionBands + IntersectionCurves + +RimSurfaceIntersectionCurve - class RimSurfaceIntersectionCurve + IsChecked + LineAppearance + Surface1 + NameProxy + +RimTensorResults - class RimTensorResults + LegendDefinition + ResultVariable + ShowTensors + Principal1 + Principal2 + Principal3 + Threshold + VectorColor + ScaleMethod + SizeScale + RangeType + +RimTernaryLegendConfig - class RimTernaryLegendConfig + ShowTernaryLegend + Precision + RangeType + ternaryRangeSummary + UserDefinedMaxSoil + UserDefinedMinSoil + UserDefinedMaxSgas + UserDefinedMinSgas + UserDefinedMaxSwat + UserDefinedMinSwat + +RimTextAnnotation - class RimTextAnnotation + AnchorPointXyd + LabelPointXyd + Text + IsActive + TextAppearance + +RimTextAnnotationInView - class RimTextAnnotationInView + IsActive + SourceAnnotation + +RimThermalFractureTemplate - class RimThermalFractureTemplate + Id + UserDescription + UnitSystem + Orientation + UserDefinedPerforationLength + AzimuthAngle + SkinFactor + PerforationLength + PerforationEfficiency + WellDiameter + ConductivityType + WellPathDepthAtFracture + FractureContainmentField + NonDarcyFlowType + UserDefinedDFactor + FractureWidthType + FractureWidth + BetaFactorType + InertialCoefficient + PermeabilityType + RelativePermeability + EffectivePermeability + RelativeGasDensity + GasViscosity + HeightScaleFactor + WidthScaleFactor + DFactorScaleFactor + ConductivityFactor + StimPlanFileName + UserDefinedWellPathDepthAtFracture + BorderPolygonResultName + ActiveTimeStepIndex + ConductivityResultName + FilterCakePressureDrop + +RimTimeAxisAnnotation - class RimTimeAxisAnnotation + Active + Name + Value + RangeStart + RangeEnd + PenStyle + Color + +RimTimeStepFilter - class RimTimeStepFilter + FilterType + FirstTimeStep + LastTimeStep + Interval + DateFormat + TimeStepIndicesToImport + OnlyLastFrame + +RimUserDefinedIndexFilter - class RimUserDefinedIndexFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + IndividualCellIndexes + +RimUserDefinedPolylinesAnnotationInView - class RimUserDefinedPolylinesAnnotationInView + IsActive + SourceAnnotation + +RimVfpPlotCollection - class RimVfpPlotCollection + VfpPlots + +RimViewLinkerCollection - class RimViewLinkerCollection + Active + ViewLinkers + +RimViewNameConfig - class RimViewNameConfig + CustomCurveName + AddCaseName + AddAggregationType + AddProperty + AddSampleSpacing + +RimVirtualPerforationResults - class RimVirtualPerforationResults + ShowConnectionFactors + ShowClosedConnections + GeometryScaleFactor + LegendDefinition + +RimWellAllocationOverTimePlot - class RimWellAllocationOverTimePlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + PlotDescription + CurveCase + WellName + FromTimeStep + ToTimeStep + TimeStepRangeFilterMode + TimeStepCount + ExcludeTimeSteps + FlowDiagSolution + FlowValueType + GroupSmallContributions + SmallContributionsThreshold + AxisTitleFontSize + AxisValueFontSize + +RimWellConnectivityTable - class RimWellConnectivityTable + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + CurveCase + VisibleCellView + ViewFilterType + FlowDiagSolution + TimeStepSelectopn + SelectProducersAndInjectorsForTimeSteps + ThresholdValue + TimeSampleValueType + TimeStep + TimeRangeValueType + FromTimeStep + ToTimeStep + TimeStepRangeFilterMode + TimeStepCount + ExcludeTimeSteps + SelectedProducerTracers + SelectedInjectorTracers + SyncSelectedProdInj + SyncSelectedInjProd + ShowValueLabels + AxisTitleFontSize + AxisLabelFontSize + ValueLabelFontSize + LegendConfig + MappingType + RangeType + +RimWellIASettings - class RimWellIASettings + Name + IsChecked + GeomechCase + BaseDir + StartMeasuredDepth + EndMeasuredDepth + BufferXY + ModelingParameters + TimeStepParameters + showBox + startDate + boxValid + +RimWellIASettingsCollection - class RimWellIASettingsCollection + WellIASettings + +RimWellLogExtractionCurve - class RimWellLogExtractionCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + TrajectoryType + CurveWellPath + ReferenceWellPath + SimulationWellName + BranchDetection + Branch + CurveCase + CurveEclipseResult + CurveGeomechResult + CurveTimeStep + GeomPartId + AddCaseNameToCurveName + AddPropertyToCurveName + AddWellNameToCurveName + AddTimestepToCurveName + AddDateToCurveName + +RimWellLogExtractionCurveNameConfig - class RimWellLogExtractionCurveNameConfig + CustomCurveName + AddCaseName + AddProperty + AddWellName + AddTimeStep + AddDate + +RimWellLogFileCurveNameConfig - class RimWellLogLasFileCurveNameConfig + CustomCurveName + +RimWellLogLasFileCurveNameConfig - class RimWellLogLasFileCurveNameConfig + CustomCurveName + +RimWellLogPlotNameConfig - class RimWellLogPlotNameConfig + CustomCurveName + +RimWellLogRftCurveNameConfig - class RimWellLogRftCurveNameConfig + CustomCurveName + +RimWellLogWbsCurve - class RimWellLogWbsCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + TrajectoryType + CurveWellPath + ReferenceWellPath + SimulationWellName + BranchDetection + Branch + CurveCase + CurveEclipseResult + CurveGeomechResult + CurveTimeStep + GeomPartId + AddCaseNameToCurveName + AddPropertyToCurveName + AddWellNameToCurveName + AddTimestepToCurveName + AddDateToCurveName + SmoothCurve + SmoothingThreshold + MaximumCurvePointInterval + +RimWellPathEntry - class RimWellPathEntry + Name + Selected + WellPathType + surveyType + requestUrl + wellPathFilePath + +RimWellPathImport - class RimWellPathImport + WellTypeSurvey + WellTypePlans + UtmMode + UtmNorth + UtmSouth + UtmEast + UtmWest + Regions + +RimWellPathTieIn - class RimWellPathTieIn + ParentWellPath + ChildWellPath + TieInMeasuredDepth + AddValveAtConnection + Valve + +RiuCreateMultipleFractionsUi - class RiuCreateMultipleFractionsUi + SourceCase + MinDistanceFromWellTd + MaxFracturesPerWell + Options + FractureCreationSummary + +RiuMultipleFractionsOptions - class RicCreateMultipleFracturesOptionItemUi + TopKLayer + BaseKLayer + Template + MinSpacing + +ScriptLocation - class RimScriptCollection + ScriptDirectory + CalcScripts + SubDirectories + +SeismicCollection - class RimSeismicDataCollection + SeismicData + DifferenceData + +SeismicData - class RimSeismicData + LegendDefinition + userClipValue + userMuteThreshold + SeismicUserDecription + SeismicFilePath + +SeismicDataCollection - class RimSeismicDataCollection + SeismicData + DifferenceData + +SeismicDifferenceData - class RimSeismicDifferenceData + LegendDefinition + userClipValue + userMuteThreshold + SeismicUserDecription + SeismicData1 + SeismicData2 + +SeismicSection - class RimSeismicSection + Name + IsChecked + UserDescription + Type + SeismicData + WellPath + Targets + InlineIndex + CrosslineIndex + DepthIndex + LineThickness + LineColor + ShowSeismicOutline + ShowSectionLine + TransparentSection + DepthFilter + UpperThreshold + LowerThreshold + +SeismicSectionCollection - class RimSeismicSectionCollection + Name + IsChecked + UserDescription + SeismicSections + SurfaceIntersectionLinesScaleFactor + SurfacesWithVisibleSurfaceLines + +SeismicView - class RimSeismicView + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + NameConfig + CameraPosition + CameraPointOfInterest + PerspectiveProjection + GridZScale + BackgroundColor + (A)ViewBackgroundColor + MaximumFrameRate + CurrentTimeStep + MeshMode + SurfaceMode + ShowGridBox + DisableLighting + ShowZScale + ComparisonView + FontSize + AnnotationStrategy + AnnotationCountHint + UseCustomAnnotationStrategy + SeismicData + SurfaceInViewCollection + SeismicSectionCollection + AnnotationCollection + OverlayInfoConfig + +SeismicViewCollection - class RimSeismicViewCollection + Views + +SimWellFracture - class RimSimWellFracture + Name + IsChecked + FractureDef + EditTemplate + CreateEllipseTemplate + CreateStimPlanTemplate + AutoUpdateWellPathDepthAtFractureFromTemplate + WellPathDepthAtFracture + Azimuth + PerforationLength + PerforationEfficiency + WellDiameter + Dip + Tilt + FractureUnit + TimeIndexToPlot + MeasuredDepth + Branch + +SimWellFractureCollection - class RimSimWellFractureCollection + Fractures + +StimPlanFractureTemplate - class RimStimPlanFractureTemplate + Id + UserDescription + UnitSystem + Orientation + UserDefinedPerforationLength + AzimuthAngle + SkinFactor + PerforationLength + PerforationEfficiency + WellDiameter + ConductivityType + WellPathDepthAtFracture + FractureContainmentField + NonDarcyFlowType + UserDefinedDFactor + FractureWidthType + FractureWidth + BetaFactorType + InertialCoefficient + PermeabilityType + RelativePermeability + EffectivePermeability + RelativeGasDensity + GasViscosity + HeightScaleFactor + WidthScaleFactor + DFactorScaleFactor + ConductivityFactor + StimPlanFileName + UserDefinedWellPathDepthAtFracture + BorderPolygonResultName + ActiveTimeStepIndex + ConductivityResultName + ShowStimPlanMesh + +StimPlanModel - class RimStimPlanModel + Name + IsChecked + StimPlanModelTemplate + EditModelTemplate + EclipseCase + TimeStep + InitialPressureEclipseCase + StaticEclipseCase + MeasuredDepth + ExtractionOffsetTop + ExtractionOffsetBottom + ExtractionDepthTop + ExtractionDepthBottom + ExtractionType + ThicknessDirectionWellPath + BoundingBoxHorizontal + BoundingBoxVertical + UseDetailedFluidLoss + RelativePermeabilityFactor + PoroElasticConstant + ThermalExpansionCoefficient + PerforationLength + FractureOrientation + AzimuthAngle + FormationDip + AutoComputeBarrier + Barrier + DistanceToBarrier + BarrierDip + WellPenetrationLayer + ShowOnlyBarrierFault + ShowAllFaults + BarrierFaultName + BarrierTextAnnotation + PerforationInterval + +StimPlanModelCollection - class RimStimPlanModelCollection + Name + IsChecked + StimPlanModels + +StimPlanModelCurve - class RimStimPlanModelCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + TrajectoryType + CurveWellPath + ReferenceWellPath + SimulationWellName + BranchDetection + Branch + CurveCase + CurveEclipseResult + CurveGeomechResult + CurveTimeStep + GeomPartId + AddCaseNameToCurveName + AddPropertyToCurveName + AddWellNameToCurveName + AddTimestepToCurveName + AddDateToCurveName + StimPlanModel + CurveProperty + +StimPlanModelPlot - class RimStimPlanModelPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + TemplateText + PlotNamingMethod + DepthType + DepthUnit + MinimumDepth + MaximumDepth + ShowDepthGridLines + AutoScaleDepthEnabled + DepthAxisVisibility + ShowDepthMarkerLine + AutoZoomMinDepthFactor + AutoZoomMaxDepthFactor + DepthAnnotations + SubTitleFontSize + AxisTitleFontSize + AxisValueFontSize + NameConfig + FilterEnsembleCurveSet + DepthEqualization + Tracks + DepthOrientation + StimPlanModel + EditModel + EclipseCase + TimeStep + +StimPlanModelPlotCollection - class RimStimPlanModelPlotCollection + StimPlanModelPlots + +StimPlanModelTemplate - class RimStimPlanModelTemplate + Name + Id + DynamicEclipseCase + TimeStep + InitialPressureEclipseCase + UseForInitialPressure + UseForPressure + EditPressureTable + StaticEclipseCase + UseEqlNumForPressureInterpolation + DefaultPorosity + DefaultPermeability + DefaultFacies + VerticalStress + VerticalStressGradient + StressDepth + ReferenceTemperature + ReferenceTemperatureGradient + ReferenceTemperatureDepth + OverburdenHeight + OverburdenFormation + OverburdenFacies + OverburdenPorosity + OverburdenPermeability + OverburdenFluidDensity + UnderburdenHeight + UnderburdenFormation + UnderburdenFacies + UnderburdenPorosity + UnderburdenPermeability + UnderburdenFluidDensity + FaciesInitialPressureConfigs + PressureTable + ElasticProperties + FaciesProperties + NonNetLayers + +StimPlanModelTemplateCollection - class RimStimPlanModelTemplateCollection + StimPlanModelTemplates + NextValidId + +StreamlineInViewCollection - class RimStreamlineInViewCollection + LegendDefinition + Name + FlowThreshold + LengthThreshold + Resolution + MaxDays + UseProducers + UseInjectors + Phase + isActive + VisualizationMode + ColorMode + AnimationSpeed + AnimationIndex + ScaleFactor + TracerLength + +StringParameter - class RimStringParameter + Name + Label + Description + Advanced + Valid + Value + +SummaryAddress - class RimSummaryAddress + SummaryVarType + SummaryQuantityName + SummaryRegion + SummaryRegion2 + SummaryWellGroup + SummaryNetworkGroup + SummaryWell + SummaryWellSegment + SummaryLgr + SummaryCellI + SummaryCellJ + SummaryCellK + SummaryAquifer + IsErrorResult + CalculationId + CaseId + EnsembleId + +SummaryCaseCollection - class RimSummaryCaseMainCollection + SummaryCases + SummaryCaseCollections + +SummaryCaseSubCollection - class RimSummaryCaseCollection + SummaryCases + SummaryCollectionName + CreateAutoName + NameCount + IsEnsemble + Id + (A)EnsembleId + +SummaryCrossPlot - class RimSummaryCrossPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + IsUsingAutoName + PlotDescription + normalizeCurveYValues + useQtChartsPlot + SummaryCurveCollection + EnsembleCurveSetCollection + GridTimeHistoryCurves + AsciiDataCurves + AxisProperties + LeftYAxisProperties + RightYAxisProperties + BottomAxisProperties + TimeAxisProperties + +SummaryCrossPlotCollection - class RimSummaryCrossPlotCollection + SummaryCrossPlots + +SummaryCurve - class RimSummaryCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + SummaryCase + SummaryAddress + Resampling + HorizontalAxisType + SummaryCaseX + SummaryAddressX + IsEnsembleCurve + PlotAxis + Axis + XAxis + SummaryCurveNameConfig + isTopZWithinCategory + +SummaryCurveAutoName - class RimSummaryCurveAutoName + LongVectorName + VectorName + Unit + RegionNumber + WellGroupName + WellName + WellSegmentNumber + LgrName + Completion + Aquifer + CaseName + +SummaryObservedDataFile - class RimSummaryObservedDataFile + ShortName + NameSetting + ShowSubNodesInTree + AutoShortyName + SummaryHeaderFilename + Id + (A)CaseId + UseCustomIdentifier + SummaryType + IdentifierName + +SummaryPageDownloadEntity - class SummaryPageDownloadEntity + Name + RequestUrl + ResponseFilename + +SummaryPlot - class RimSummaryPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + IsUsingAutoName + PlotDescription + normalizeCurveYValues + useQtChartsPlot + SummaryCurveCollection + EnsembleCurveSetCollection + GridTimeHistoryCurves + AsciiDataCurves + AxisProperties + LeftYAxisProperties + RightYAxisProperties + BottomAxisProperties + TimeAxisProperties + +SummaryPlotCollection - class RimSummaryPlotCollection + SummaryPlots + +SummaryTimeAxisProperties - class RimSummaryTimeAxisProperties + Active + ShowTitle + Title + AutoZoom + TimeMode + TimeUnit + VisibleDateRangeMax + VisibleDateRangeMin + VisibleTimeRangeMax + VisibleTimeRangeMin + VisibleTimeModeRangeMax + VisibleTimeModeRangeMin + TitlePosition + FontSize + ValuesFontSize + AutoDate + DateComponents + TimeComponents + DateFormat + TimeFormat + TickmarkType + TickmarkInterval + TickmarkIntervalStep + MajorTickmarkCount + Annotations + +SummaryYAxisProperties - class RimPlotAxisProperties + Active + Name + AxisTitle + AutoTitle + DisplayLongName + DisplayShortName + DisplayUnitText + CustomTitle + VisibleRangeMax + VisibleRangeMin + NumberFormat + Decimals + ScaleFactor + AutoZoom + LogarithmicScale + AxisInverted + ShowNumbers + PlotAxis + PlotAxisIndex + TitlePosition + TitleDeltaFontSize + ValueDeltaFontSize + Annotations + MajorTickmarkCount + +Surface - class RimFileSurface + SurfaceUserDecription + SurfaceColor + DepthOffset + SurfaceFilePath + +SurfaceCollection - class RimSurfaceCollection + SurfaceUserDecription + SubCollections + SurfacesField + +SurfaceInView - class RimSurfaceInView + Active + ShowInactiveCells + UseSeparateIntersectionDataSource + SeparateIntersectionDataSource + Name + SurfaceRef + ResultDefinition + +SurfaceInViewCollection - class RimSurfaceInViewCollection + Name + IsChecked + SurfacesInViewFieldCollections + SurfacesInViewField + SurfaceCollectionRef + +SurfaceResultDefinition - class RimSurfaceResultDefinition + Name + IsChecked + PropertyName + LegendConfig + SurfaceInView + +ThermalFractureTemplate - class RimThermalFractureTemplate + Id + UserDescription + UnitSystem + Orientation + UserDefinedPerforationLength + AzimuthAngle + SkinFactor + PerforationLength + PerforationEfficiency + WellDiameter + ConductivityType + WellPathDepthAtFracture + FractureContainmentField + NonDarcyFlowType + UserDefinedDFactor + FractureWidthType + FractureWidth + BetaFactorType + InertialCoefficient + PermeabilityType + RelativePermeability + EffectivePermeability + RelativeGasDensity + GasViscosity + HeightScaleFactor + WidthScaleFactor + DFactorScaleFactor + ConductivityFactor + StimPlanFileName + UserDefinedWellPathDepthAtFracture + BorderPolygonResultName + ActiveTimeStepIndex + ConductivityResultName + FilterCakePressureDrop + +TofAccumulatedPhaseFractionsPlot - class RimTofAccumulatedPhaseFractionsPlot + WindowController + ShowWindow + WindowGeometry + PlotDescription + ShowPlotTitle + MaxTof + +TotalWellAllocationPlot - class RimTotalWellAllocationPlot + WindowController + ShowWindow + WindowGeometry + PlotDescription + ShowPlotTitle + +TriangleGeometry - class RimcTriangleGeometry + XCoords + YCoords + ZCoords + Connections + MeshXCoords + MeshYCoords + MeshZCoords + FaultMeshXCoords + FaultMeshYCoords + FaultMeshZCoords + DisplayModelOffset + +UserDefinedFilter - class RimUserDefinedFilter + UserDescription + Active + Case + FilterType + GridIndex + PropagateToSubGrids + IndividualCellIndices + +UserDefinedPolylinesAnnotation - class RimUserDefinedPolylinesAnnotation + IsActive + ClosePolyline + ShowLines + ShowSpheres + Appearance + Name + Targets + +ValveTemplate - class RimValveTemplate + Name + UnitSystem + CompletionType + UserLabel + OrificeDiameter + FlowCoefficient + AICDParameters + +ValveTemplateCollection - class RimValveTemplateCollection + ValveDefinitions + ValveUnits + +VfpPlot - class RimVfpPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + PlotTitle + FilePath + TableType + TableNumber + ReferenceDepth + FlowingPhase + FlowingWaterFraction + FlowingGasFraction + InterpolatedVariable + PrimaryVariable + FamilyVariable + LiquidFlowRateIdx + THPIdx + ArtificialLiftQuantityIdx + WaterCutIdx + GasLiquidRatioIdx + +View3dOverlayInfoConfig - class Rim3dOverlayInfoConfig + Active + ShowAnimProgress + ShowInfoText + ShowResultInfo + ShowHistogram + ShowVolumeWeightedMean + ShowVersionInfo + StatisticsTimeRange + StatisticsCellRange + +ViewController - class RimViewController + Active + Name + ManagedView + SyncCamera + ShowCursor + SyncTimeStep + SyncCellResult + SyncLegendDefinitions + SyncRangeFilters + SyncPropertyFilters + DuplicatePropertyFilters + +ViewLinker - class RimViewLinker + Name + MainView + ManagedViews + +WbsParameters - class RimWbsParameters + PorePressureReservoirSource + PorePressureNonReservoirSource + UserPPNonReservoir + PoissionRatioSource + UcsSource + OBG0Source + DFSource + K0SHSource + FGShaleSource + K0FGSource + WaterDensitySource + UserPoissonRatio + UserUcs + UserDF + UserK0FG + UserK0SH + FGMultiplier + WaterDensity + GeoMechCase + WellPath + TimeStep + FrameIndex + +Well - class RimSimWellInView + Name + (A)WellName + ShowWell + ShowWellLabel + ShowWellHead + ShowWellPipe + ShowWellSpheres + ShowWellDisks + WellHeadScaleFactor + WellPipeRadiusScale + WellPipeColor + WellDiskColor + ShowWellCells + ShowWellCellFence + FractureCollection + +WellAllocationPlot - class RimWellAllocationPlot + WindowController + ShowWindow + WindowGeometry + PlotDescription + ShowPlotTitle + BranchDetection + CurveCase + PlotTimeStep + WellName + FlowDiagSolution + FlowType + GroupSmallContributions + SmallContributionsThreshold + AccumulatedWellFlowPlot + TotalWellFlowPlot + WellAllocLegend + TofAccumulatedPhaseFractionsPlot + +WellAllocationPlotLegend - class RimWellAllocationPlotLegend + ShowPlotLegend + +WellBoreStabilityPlot - class RimWellBoreStabilityPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + TemplateText + PlotNamingMethod + DepthType + DepthUnit + MinimumDepth + MaximumDepth + ShowDepthGridLines + AutoScaleDepthEnabled + DepthAxisVisibility + ShowDepthMarkerLine + AutoZoomMinDepthFactor + AutoZoomMaxDepthFactor + DepthAnnotations + SubTitleFontSize + AxisTitleFontSize + AxisValueFontSize + NameConfig + FilterEnsembleCurveSet + DepthEqualization + Tracks + DepthOrientation + WbsParameters + +WellDistributionPlot - class RimWellDistributionPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + Case + TimeStepIndex + WellName + Phase + GroupSmallContributions + SmallContributionsRelativeThreshold + MaximumTOF + +WellDistributionPlotCollection - class RimWellDistributionPlotCollection + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + Case + TimeStepIndex + WellName + GroupSmallContributions + SmallContributionsRelativeThreshold + MaximumTOF + Plots + ShowOil + ShowGas + ShowWater + PlotDescription + +WellFlowRateCurve - class RimWellFlowRateCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + +WellLogCalculatedCurve - class RimWellLogCalculatedCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + Operator + DepthSource + FirstWellLogCurve + SecondWellLogCurve + +WellLogCsvFile - class RimWellLogCsvFile + FileName + Date + WellLogFileChannels + WellName + Name + +WellLogExtractionCurve - class RimWellLogExtractionCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + TrajectoryType + CurveWellPath + ReferenceWellPath + SimulationWellName + BranchDetection + Branch + CurveCase + CurveEclipseResult + CurveGeomechResult + CurveTimeStep + GeomPartId + AddCaseNameToCurveName + AddPropertyToCurveName + AddWellNameToCurveName + AddTimestepToCurveName + AddDateToCurveName + +WellLogFile - class RimWellLogLasFile + FileName + Date + WellLogFileChannels + WellName + Name + WellFlowCondition + +WellLogFileChannel - class RimWellLogFileChannel + Name + +WellLogFileCurve - class RimWellLogLasFileCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + CurveWellPath + CurveWellLogChannel + WellLogFile + +WellLogLasFile - class RimWellLogLasFile + FileName + Date + WellLogFileChannels + WellName + Name + WellFlowCondition + +WellLogLasFileCurve - class RimWellLogLasFileCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + CurveWellPath + CurveWellLogChannel + WellLogFile + +WellLogPlot - class RimWellLogPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + TemplateText + PlotNamingMethod + DepthType + DepthUnit + MinimumDepth + MaximumDepth + ShowDepthGridLines + AutoScaleDepthEnabled + DepthAxisVisibility + ShowDepthMarkerLine + AutoZoomMinDepthFactor + AutoZoomMaxDepthFactor + DepthAnnotations + SubTitleFontSize + AxisTitleFontSize + AxisValueFontSize + NameConfig + FilterEnsembleCurveSet + DepthEqualization + Tracks + DepthOrientation + +WellLogPlotCollection - class RimWellLogPlotCollection + WellLogPlots + +WellLogPlotTrack - class RimWellLogTrack + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + RowSpan + ColSpan + TrackDescription + Curves + VisibleXRangeMin + VisibleXRangeMax + AutoScaleX + LogarithmicScaleX + InvertPropertyValueAxis + IsPropertyAxisEnabled + ShowXGridLines + ExplicitTickIntervals + MinAndMaxTicksOnly + MajorTickIntervals + MinorTickIntervals + AxisFontSize + AnnotationType + RegionDisplay + ColorShadingLegend + ColorShadingTransparency + ShowFormationLabels + RegionLabelFontSize + FormationSource + FormationTrajectoryType + FormationWellPath + FormationWellPathForSourceWellPath + FormationSimulationWellName + FormationBranchIndex + FormationBranchDetection + FormationCase + FormationLevel + ShowFormationFluids + ShowWellPathAttributes + WellPathAttributesInLegend + ShowWellPathCompletions + WellPathCompletionsInLegend + ShowWellPathAttrBothSides + ShowWellPathAttrLabels + AttributesWellPathSource + AttributesCollection + AutoCheckStateBasedOnCurveData + OverburdenHeight + UnderburdenHeight + ResultDefinition + EnsembleWellLogCurveSet + +WellLogRftCurve - class RimWellLogRftCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + CurveEclipseResultCase + CurveSummaryCase + CurveEnsemble + ObservedFmuRftData + PressureDepthData + TimeStep + WellName + BranchIndex + BranchDetection + WellLogChannelName + RftDataType + SegmentResultName + SegmentBranchIndex + SegmentBranchType + ScaleFactor + CurveColorByPhase + +WellMeasurement - class RimWellMeasurement + WellName + Depth + Date + Value + Kind + Quality + Remark + FilePath + +WellMeasurementCurve - class RimWellMeasurementCurve + Show + AutoCheckStateBasedOnCurveData + CurveName + TemplateText + CurveNamingMethod + LegendDescription + AutoName + ShowLegend + ShowErrorBars + Color + FillColor + Thickness + CurveInterpolation + LineStyle + FillStyle + PointSymbol + SymbolEdgeColor + SymbolSkipPxDist + SymbolLabel + SymbolSize + SymbolLabelPosition + PlotCurveAppearance + AdditionalDataSources + RectAnnotation + StackCurve + StackPhaseColors + CurveWellPath + CurveMeasurementKind + +WellMeasurementFilePath - class RimWellMeasurementFilePath + UserDecription + FilePath + +WellMeasurementInView - class RimWellMeasurementInView + Name + IsChecked + MeasurementKind + LegendDefinition + WellsSerialized + AvailableWellsSerialized + LowerBound + UpperBound + QualityFilter + RadiusScaleFactor + +WellMeasurements - class RimWellMeasurementCollection + Measurements + ImportedFiles + +WellMeasurementsInView - class RimWellMeasurementInViewCollection + Name + IsChecked + MeasurementKinds + linkWellVisibility + +WellPath - class RimFileWellPath + AirGap + DatumElevation + UnitSystem + SimWellName + SimBranchIndex + ShowWellPathLabel + MeasuredDepthLabelInterval + ShowWellPath + WellPathRadiusScale + WellPathColor + Completions + CompletionSettings + WellLogFiles + CollectionOf3dWellLogCurves + WellPathFormationKeyInFile + WellPathFormationFilePath + WellPathAttributes + WellPathTieIn + WellIASettings + WellPathFilepath + WellPathFilePathInCache + WellPathNumberInFile + UseAutoGeneratedPointAtSeaLevel + +WellPathAicdParameters - class RimWellPathAicdParameters + DeviceOpen + StrengthAICD + DensityCalibrationFluid + ViscosityCalibrationFluid + VolumeFlowRateExponent + ViscosityFunctionExponent + CriticalWaterLiquidFractionEmul + ViscosityTransitionRegionEmul + MaxRatioOfEmulsionVisc + MaxFlowRate + ExponentOilDensity + ExponentWaterDensity + ExponentGasDensity + ExponentOilViscosity + ExponentWaterViscosity + ExponentGasViscosity + +WellPathAttribute - class RimWellPathAttribute + CompletionType + DepthStart + DepthEnd + DiameterInInches + +WellPathAttributes - class RimWellPathAttributeCollection + Name + IsChecked + Attributes + +WellPathBase - class RimWellPath + AirGap + DatumElevation + UnitSystem + SimWellName + SimBranchIndex + ShowWellPathLabel + MeasuredDepthLabelInterval + ShowWellPath + WellPathRadiusScale + WellPathColor + Completions + CompletionSettings + WellLogFiles + CollectionOf3dWellLogCurves + WellPathFormationKeyInFile + WellPathFormationFilePath + WellPathAttributes + WellPathTieIn + WellIASettings + +WellPathCompletionSettings - class RimWellPathCompletionSettings + WellNameForExport + WellGroupNameForExport + ReferenceDepthForExport + WellTypeForExport + DrainageRadiusForPI + GasInflowEq + AutoWellShutIn + AllowWellCrossFlow + WellBoreFluidPVTTable + HydrostaticDensity + FluidInPlaceRegion + MswParameters + MswLinerDiameter + MswRoughness + +WellPathCompletions - class RimWellPathCompletions + Perforations + Fishbones + Fractures + StimPlanModels + WellNameForExport + WellGroupNameForExport + ReferenceDepthForExport + WellTypeForExport + DrainageRadiusForPI + GasInflowEq + AutoWellShutIn + AllowWellCrossFlow + WellBoreFluidPVTTable + HydrostaticDensity + FluidInPlaceRegion + +WellPathFracture - class RimWellPathFracture + Name + IsChecked + FractureDef + EditTemplate + CreateEllipseTemplate + CreateStimPlanTemplate + AutoUpdateWellPathDepthAtFractureFromTemplate + WellPathDepthAtFracture + Azimuth + PerforationLength + PerforationEfficiency + WellDiameter + Dip + Tilt + FractureUnit + TimeIndexToPlot + MeasuredDepth + +WellPathFractureCollection - class RimWellPathFractureCollection + Name + IsChecked + Fractures + +WellPathGeometry - class RimWellPathGeometryDef + ReferencePosUtmXyd + AirGap + MdAtFirstTarget + WellPathTargets + ShowAbsolutePosForWellTargets + UseTopLevelWellReferencePoint + UseAutoGeneratedTargetAtSeaLevel + LinkReferencePointUpdates + AttachedToParentWell + FixedWellPathPoints + FixedMeasuredDepths + ShowSpheres + SphereColor + SphereRadiusFactor + WellTargetHandleScalingFactor + +WellPathGeometryDef - class RimWellPathGeometryDef + ReferencePosUtmXyd + AirGap + MdAtFirstTarget + WellPathTargets + ShowAbsolutePosForWellTargets + UseTopLevelWellReferencePoint + UseAutoGeneratedTargetAtSeaLevel + LinkReferencePointUpdates + AttachedToParentWell + FixedWellPathPoints + FixedMeasuredDepths + ShowSpheres + SphereColor + SphereRadiusFactor + WellTargetHandleScalingFactor + +WellPathGroup - class RimWellPathGroup + AirGap + DatumElevation + UnitSystem + SimWellName + SimBranchIndex + ShowWellPathLabel + MeasuredDepthLabelInterval + ShowWellPath + WellPathRadiusScale + WellPathColor + Completions + CompletionSettings + WellLogFiles + CollectionOf3dWellLogCurves + WellPathFormationKeyInFile + WellPathFormationFilePath + WellPathAttributes + WellPathTieIn + WellIASettings + ChildWellPaths + GroupName + AddValveAtConnection + Valve + +WellPathTarget - class RimWellPathTarget + IsEnabled + TargetPoint + TargetPointForDisplay + TargetMeasuredDepth + Dogleg1 + Dogleg2 + UseFixedAzimuth + Azimuth + UseFixedInclination + Inclination + EstimatedDogleg1 + EstimatedDogleg2 + EstimatedAzimuth + EstimatedInclination + TargetType + HasTangentConstraint + +WellPathValve - class RimWellPathValve + Name + IsChecked + ValveTemplate + StartMeasuredDepth + ValveLocations + EditTemplate + CreateTemplate + +WellPaths - class RimWellPathCollection + Active + ShowWellPathLabel + WellPathLabelColor + GlobalWellPathVisibility + WellPathRadiusScale + WellPathClip + WellPathClipZDistance + WellPaths + WellMeasurements + +WellPltPlot - class RimWellPltPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + TemplateText + PlotNamingMethod + DepthType + DepthUnit + MinimumDepth + MaximumDepth + ShowDepthGridLines + AutoScaleDepthEnabled + DepthAxisVisibility + ShowDepthMarkerLine + AutoZoomMinDepthFactor + AutoZoomMaxDepthFactor + DepthAnnotations + SubTitleFontSize + AxisTitleFontSize + AxisValueFontSize + NameConfig + FilterEnsembleCurveSet + DepthEqualization + Tracks + DepthOrientation + WellLog + WellName + Sources + TimeSteps + UseStandardConditionCurves + UseReservoirConditionCurves + Phases + +WellPltPlotCollection - class RimPltPlotCollection + PltPlots + +WellRftEnsembleCurveSet - class RimWellRftEnsembleCurveSet + Ensemble + ColorMode + EnsembleParameter + LegendConfig + EclipseResultCase + +WellRftPlot - class RimWellRftPlot + WindowController + ShowWindow + WindowGeometry + Id + (A)ViewId + ShowPlotTitle + ShowTrackLegends + TrackLegendsHorizontal + LegendItemsClickable + TitleFontSize + LegendDeltaFontSize + LegendPosition + PlotDescription + TemplateText + PlotNamingMethod + DepthType + DepthUnit + MinimumDepth + MaximumDepth + ShowDepthGridLines + AutoScaleDepthEnabled + DepthAxisVisibility + ShowDepthMarkerLine + AutoZoomMinDepthFactor + AutoZoomMaxDepthFactor + DepthAnnotations + SubTitleFontSize + AxisTitleFontSize + AxisValueFontSize + NameConfig + FilterEnsembleCurveSet + DepthEqualization + Tracks + DepthOrientation + ShowStatisticsCurves + ShowEnsembleCurves + ShowErrorObserved + WellLog + WellName + BranchIndex + BranchDetection + EnsembleCurveSets + EclipseResultCase + +WellRftPlotCollection - class RimRftPlotCollection + RftPlots + +Wells - class RimSimWellInViewCollection + Active + ShowWellsIntersectingVisibleCells + WellHeadScale + WellHeadPositionScaleFactor + WellPipeRadiusScale + CellCenterSphereScale + WellLabelColor + ShowConnectionStatusColors + WellColorForApply + WellPipeColors + WellPipeVertexCount + WellPipeCoordType + DefaultWellFenceDirection + WellCellTransparency + IsAutoDetectingBranches + WellHeadPosition + Wells + ShowWellValvesTristate + WellDiskSummaryCase + WellDiskQuantity + WellDiskPropertyType + WellDiskPropertyConfigType + WellDiskShowQuantityLabels + WellDiskShowLabelsBackground + WellDiskScaleFactor + WellDiskColor + ShowWellCommunicationLines + +cafNamedTreeNode - class cafNamedTreeNode + ChildNodes + Name + IsChecked + +cafObjectReferenceTreeNode - class cafObjectReferenceTreeNode + ChildNodes + ReferencedObject + +cafTreeNode - class cafTreeNode + ChildNodes + +cloneView - class RicfCloneView + viewId + +closeProject - class RicfCloseProject + +computeCaseGroupStatistics - class RicfComputeCaseGroupStatistics + caseGroupId + caseIds + +createGridCaseGroup - class RicfCreateGridCaseGroup + casePaths + +createGridCaseGroupResult - class RicfCreateGridCaseGroupResult + groupId + groupName + +createLgrForCompletions - class RicfCreateLgrForCompletions + caseId + timeStep + wellPathNames + refinementI + refinementJ + refinementK + splitType + +createMultiPlot - class RicNewMultiPlotFeature + plots + +createMultipleFractures - class RicfCreateMultipleFractures + caseId + wellPathNames + minDistFromWellTd + maxFracturesPerWell + templateId + topLayer + baseLayer + spacing + action + +createSaturationPressurePlots - class RicfCreateSaturationPressurePlots + caseIds + +createStatisticsCase - class RicfCreateStatisticsCase + caseGroupId + +createStatisticsCaseResult - class RicfCreateStatisticsCaseResult + caseId + +createView - class RicfCreateView + caseId + +createViewResult - class RicfCreateViewResult + viewId + +createWbsPlotResult - class RicfCreateWbsPlotResult + viewId + +createWellBoreStabilityPlot - class RicfCreateWellBoreStabilityPlotFeature + caseId + wellPath + timeStep + wbsParameters + +exportContourMapToText - class RicExportContourMapToTextFeature + exportFileName + exportLocalCoordinates + undefinedValueLabel + excludeUndefinedValues + viewId + +exportFlowCharacteristics - class RicfExportFlowCharacteristics + caseId + timeSteps + injectors + producers + fileName + minimumCommunication + aquiferCellThreshold + +exportLgrForCompletions - class RicfExportLgrForCompletions + caseId + timeStep + wellPathNames + refinementI + refinementJ + refinementK + splitType + +exportMsw - class RicfExportMsw + caseId + wellPath + includePerforations + includeFishbones + includeFractures + fileSplit + +exportMultiCaseSnapshots - class RicfExportMultiCaseSnapshots + gridListFile + +exportProperty - class RicfExportProperty + caseId + timeStep + property + eclipseKeyword + undefinedValue + exportFile + +exportPropertyInViews - class RicfExportPropertyInViews + caseId + viewIds + viewNames + undefinedValue + +exportSimWellFractureCompletions - class RicfExportSimWellFractureCompletions + caseId + viewId + viewName + timeStep + simulationWellNames + fileSplit + compdatExport + +exportSnapshots - class RicfExportSnapshots + type + prefix + caseId + viewId + exportFolder + plotOutputFormat + +exportVisibleCells - class RicfExportVisibleCells + caseId + viewId + viewName + exportKeyword + visibleActiveCellsValue + hiddenActiveCellsValue + inactiveCellsValue + +exportWellLogPlotData - class RicfExportWellLogPlotData + exportFormat + viewId + exportFolder + filePrefix + exportTvdRkb + capitalizeFileNames + resampleInterval + convertCurveUnits + +exportWellLogPlotDataResult - class RicfExportWellLogPlotDataResult + exportedFiles + +exportWellPathCompletions - class RicfExportWellPathCompletions + caseId + timeStep + wellPathNames + fileSplit + compdatExport + combinationMode + includeMsw + useNtgHorizontally + includePerforations + includeFishbones + includeFractures + excludeMainBoreForFishbones + performTransScaling + transScalingTimeStep + transScalingWBHPFromSummary + transScalingWBHP + exportComments + exportWelspec + customFileName + +exportWellPaths - class RicfExportWellPaths + wellPathNames + mdStepSize + +importFormationNames - class RicfImportFormationNames + formationFiles + applyToCaseId + +importWellLogFiles - class RicfImportWellLogFiles + wellLogFolder + wellLogFiles + +importWellLogFilesResult - class RicfImportWellLogFilesResult + wellPathNames + +importWellPaths - class RicImportWellPaths + wellPathFolder + wellPathFiles + +importWellPathsResult - class RicImportWellPathsResult + wellPathNames + +loadCase - class RicfLoadCase + path + gridOnly + +loadCaseResult - class RicfLoadCaseResult + id + +openProject - class RicfOpenProject + path + +replaceCase - class RicfSingleCaseReplace + caseId + newGridFile + +replaceMultipleCases - class RicfMultiCaseReplace + +replaceSourceCases - class RicfReplaceSourceCases + caseGroupId + gridListFile + +runOctaveScript - class RicfRunOctaveScript + path + caseIds + +saveProject - class RicSaveProjectFeature + filePath + +saveProjectAs - class RicSaveProjectAsFeature + filePath + +scaleFractureTemplate - class RicfScaleFractureTemplate + id + halfLength + height + dFactor + conductivity + width + +setExportFolder - class RicfSetExportFolder + type + path + createFolder + +setFractureContainment - class RicfSetFractureContainment + id + topLayer + baseLayer + +setMainWindowSize - class RicfSetMainWindowSize + height + width + +setPlotWindowSize - class RicfSetPlotWindowSize + height + width + +setStartDir - class RicfSetStartDir + path + +setTimeStep - class RicfSetTimeStep + caseId + viewId + timeStep + +stackCurves - class RicStackSelectedCurvesFeature + curves + +unstackCurves - class RicUnstackSelectedCurvesFeature + curves + diff --git a/ApplicationLibCode/Adm/projectfilekeywords/2024.03/ri-objectKeywords.txt b/ApplicationLibCode/Adm/projectfilekeywords/2024.03/ri-objectKeywords.txt new file mode 100644 index 0000000000..2d9fbfffb3 --- /dev/null +++ b/ApplicationLibCode/Adm/projectfilekeywords/2024.03/ri-objectKeywords.txt @@ -0,0 +1,477 @@ +// ResInsight version string : 2024.03.0-RC_05 +// Report generated : Fri Mar 22 08:17:14 2024 +// +// + +AnalysisPlot +AnalysisPlotCollection +AnalysisPlotDataEntry +Annotations +AsciiDataCurve +CalcScript +CellEdgeResultSlot +CellFilterCollection +CellIndexFilter +CellPropertyFilter +CellPropertyFilters +CellRangeFilter +CellRangeFilterCollection +ChangeDataSourceFeatureUi +CmdAddItemExecData +CmdDeleteItemExecData +CmdSelectionChangeExecData +ColorLegend +ColorLegendCollection +ColorLegendItem +CompletionTemplateCollection +CorrelationMatrixPlot +CorrelationPlot +CorrelationPlotCollection +CorrelationReportPlot +CrossSection +CrossSectionCollection +CsvSummaryCase +CurveIntersection +DataContainerFloat +DataContainerString +DataContainerTime +DeclineCurve +DepthTrackPlot +DoubleParameter +Eclipse2dViewCollection +EclipseCase +EclipseGeometrySelectionItem +EclipseResultAddress +ElasticProperties +ElasticPropertyScaling +ElasticPropertyScalingCollection +EnsembleFractureStatistics +EnsembleFractureStatisticsPlot +EnsembleFractureStatisticsPlotCollection +EnsembleStatisticsSurface +EnsembleSurface +EnsembleWellLogStatisticsCurve +EnsembleWellLogs +EnsembleWellLogsCollection +FaciesInitialPressureConfig +FaciesProperties +Fault +FaultReactivationModel +FaultReactivationModelCollection +Faults +FileSummaryCase +FileSurface +FishbonesCollection +FishbonesMultipleSubs +FishbonesPipeProperties +FlowCharacteristicsPlot +FlowDiagSolution +FlowPlotCollection +FormationNames +FormationNamesCollectionObject +FractureContainment +FractureDefinitionCollection +FractureGroupStatisticsCollection +FractureTemplateCollection +GeoMech2dViewCollection +GeoMechGeometrySelectionItem +GeoMechPart +GeoMechPartCollection +GeoMechPropertyFilter +GeoMechPropertyFilters +GeoMechResultDefinition +GeoMechResultSlot +GeoMechView +GridCaseSurface +GridCollection +GridCrossPlotCurve +GridCrossPlotCurveSet +GridCrossPlotRegressionCurve +GridInfo +GridInfoCollection +GridStatisticsPlot +GridStatisticsPlotCollection +GridSummaryCase +GridTimeHistoryCurve +IntegerParameter +Intersection2dView +Intersection2dViewCollection +IntersectionBox +IntersectionCollection +IntersectionResultDefinition +Legend +ListParameter +MainPlotCollection +MdiWindowController +MockModelSettings +ModeledWellPath +MultiPlot +MultiSnapshotDefinition +MultiSummaryPlot +NonNetLayers +ObservedDataCollection +ObservedFmuRftData +ObservedPressureDepthData +ParameterGroup +ParameterList +ParameterResultCrossPlot +PdmDocument +PdmObjectCollection +PdmObjectGroup +Perforation +PerforationCollection +PlotDataFilterCollection +PlotDataFilterItem +PlotTemplateCollection +PlotTemplateFileItem +PolyLineFilter +PolygonFilter +PolylineTarget +PolylinesFromFileAnnotation +PressureTable +PressureTableItem +PropertyFilter +RegressionAnalysisCurve +ResInsightAnalysisModels +ResInsightGeoMechCase +ResInsightGeoMechModels +ResInsightOilField +ResInsightProject +ResampleData +ReservoirCellResultStorage +ReservoirView +ResultDefinition +ResultSlot +ResultStorageEntryInfo +RftAddress +RiaMemoryCleanup +RiaPreferences +RiaPreferencesGeoMech +RiaPreferencesSummary +RiaPreferencesSystem +RiaRegressionTest +RicCaseAndFileExportSettingsUi +RicCellRangeUi +RicCreateDepthAdjustedLasFilesUi +RicCreateEnsembleSurfaceUi +RicCreateEnsembleWellLogUi +RicCreateMultipleWellPathLateralsUi +RicCreateRftPlotsFeatureUi +RicDeleteItemExecData +RicExportCarfinUi +RicExportCompletionDataSettingsUi +RicExportContourMapToTextUi +RicExportEclipseInputGridUi +RicExportLgrUi +RicExportToLasFileObj +RicExportToLasFileResampleUi +RicExportWellPathsUi +RicGridCalculator +RicHoloLensCreateSessionUi +RicHoloLensExportToFolderUi +RicHoloLensServerSettings +RicLinkVisibleViewsFeatureUi +RicPasteAsciiDataToSummaryPlotFeatureUi +RicSaturationPressureUi +RicSaveEclipseInputVisibleCellsUi +RicSaveMultiPlotTemplateFeatureSettings +RicSelectCaseOrEnsembleUi +RicSelectPlotTemplateUi +RicSelectSummaryPlotUI +RicSelectViewUI +RicSummaryAddressSelection +RicSummaryCurveCalculator +RicSummaryCurveCreator +RicWellPathsUnitSystemSettingsUi +RifReaderSettings +Rim3dWellLogCurveCollection +Rim3dWellLogExtractionCurve +Rim3dWellLogFileCurve +Rim3dWellLogRftCurve +RimAnnotationCollection +RimAnnotationCollectionBase +RimAnnotationGroupCollection +RimAnnotationLineAppearance +RimAnnotationTextAppearance +RimBinaryExportSettings +RimCaseCollection +RimCellFilterCollection +RimCommandExecuteScript +RimCommandIssueFieldChanged +RimCommandObject +RimCommandRouter +RimContourMapView +RimCsvUserData +RimCustomObjectiveFunction +RimCustomObjectiveFunctionCollection +RimCustomObjectiveFunctionWeight +RimDerivedEnsembleCase +RimDerivedEnsembleCaseCollection +RimDialogData +RimEclipseContourMapProjection +RimEclipseResultAddressCollection +RimElementVectorResult +RimEllipseFractureTemplate +RimEmCase +RimEnsembleCurveFilter +RimEnsembleCurveFilterCollection +RimEnsembleCurveSet +RimEnsembleCurveSetCollection +RimEnsembleStatistics +RimEnsembleWellLogCurveSet +RimEquilibriumAxisAnnotation +RimExportInputSettings +RimFaultResultSlot +RimFractureExportSettings +RimGeoMechContourMapProjection +RimGeoMechContourMapView +RimGeoMechFaultReactivationResult +RimGridCalculation +RimGridCalculationCollection +RimGridCalculationVariable +RimGridCrossPlot +RimGridCrossPlotCollection +RimGridCrossPlotCurveSetNameConfig +RimGridCrossPlotNameConfig +RimIdenticalGridCaseGroup +RimInputProperty +RimInputPropertyCollection +RimInputReservoir +RimIntersectionResultsDefinitionCollection +RimMeasurement +RimMswCompletionParameters +RimMudWeightWindowParameters +RimMultiPlotCollection +RimMultipleEclipseResults +RimMultipleLocations +RimMultipleValveLocations +RimNonDarcyPerforationParameters +RimObjectiveFunction +RimObservedEclipseUserData +RimOilFieldEntry +RimOilRegionEntry +RimPlotAxisAnnotation +RimPlotCellFilterCollection +RimPlotCellPropertyFilter +RimPlotRectAnnotation +RimPolygon +RimPolygonAppearance +RimPolygonCollection +RimPolygonFileFile +RimPolygonInView +RimPolygonInViewCollection +RimPolylineAppearance +RimPolylinesAnnotationInView +RimPolylinesFromFileAnnotationInView +RimProcess +RimReachCircleAnnotation +RimReachCircleAnnotationInView +RimResultSelectionUi +RimRftCase +RimRftTopologyCurve +RimRoffCase +RimSEGYConvertOptions +RimSaturationPressurePlot +RimSaturationPressurePlotCollection +RimSeismicView +RimStatisticalCalculation +RimStatisticalCollection +RimStimPlanColors +RimStimPlanFractureTemplate +RimStimPlanLegendConfig +RimSummaryAddressCollection +RimSummaryAddressSelector +RimSummaryCalculation +RimSummaryCalculationCollection +RimSummaryCalculationVariable +RimSummaryCurveCollection +RimSummaryCurveCollectionModifier +RimSummaryMultiPlotCollection +RimSummaryPlotManager +RimSummaryTable +RimSummaryTableCollection +RimSurfaceIntersectionBand +RimSurfaceIntersectionCollection +RimSurfaceIntersectionCurve +RimTensorResults +RimTernaryLegendConfig +RimTextAnnotation +RimTextAnnotationInView +RimThermalFractureTemplate +RimTimeAxisAnnotation +RimTimeStepFilter +RimUserDefinedIndexFilter +RimUserDefinedPolylinesAnnotationInView +RimVfpPlotCollection +RimViewLinkerCollection +RimViewNameConfig +RimVirtualPerforationResults +RimWellAllocationOverTimePlot +RimWellConnectivityTable +RimWellIASettings +RimWellIASettingsCollection +RimWellLogExtractionCurve +RimWellLogExtractionCurveNameConfig +RimWellLogFileCurveNameConfig +RimWellLogLasFileCurveNameConfig +RimWellLogPlotNameConfig +RimWellLogRftCurveNameConfig +RimWellLogWbsCurve +RimWellPathEntry +RimWellPathImport +RimWellPathTieIn +RiuCreateMultipleFractionsUi +RiuMultipleFractionsOptions +ScriptLocation +SeismicCollection +SeismicData +SeismicDataCollection +SeismicDifferenceData +SeismicSection +SeismicSectionCollection +SeismicView +SeismicViewCollection +SimWellFracture +SimWellFractureCollection +StimPlanFractureTemplate +StimPlanModel +StimPlanModelCollection +StimPlanModelCurve +StimPlanModelPlot +StimPlanModelPlotCollection +StimPlanModelTemplate +StimPlanModelTemplateCollection +StreamlineInViewCollection +StringParameter +SummaryAddress +SummaryCaseCollection +SummaryCaseSubCollection +SummaryCrossPlot +SummaryCrossPlotCollection +SummaryCurve +SummaryCurveAutoName +SummaryObservedDataFile +SummaryPageDownloadEntity +SummaryPlot +SummaryPlotCollection +SummaryTimeAxisProperties +SummaryYAxisProperties +Surface +SurfaceCollection +SurfaceInView +SurfaceInViewCollection +SurfaceResultDefinition +ThermalFractureTemplate +TofAccumulatedPhaseFractionsPlot +TotalWellAllocationPlot +TriangleGeometry +UserDefinedFilter +UserDefinedPolylinesAnnotation +ValveTemplate +ValveTemplateCollection +VfpPlot +View3dOverlayInfoConfig +ViewController +ViewLinker +WbsParameters +Well +WellAllocationPlot +WellAllocationPlotLegend +WellBoreStabilityPlot +WellDistributionPlot +WellDistributionPlotCollection +WellFlowRateCurve +WellLogCalculatedCurve +WellLogCsvFile +WellLogExtractionCurve +WellLogFile +WellLogFileChannel +WellLogFileCurve +WellLogLasFile +WellLogLasFileCurve +WellLogPlot +WellLogPlotCollection +WellLogPlotTrack +WellLogRftCurve +WellMeasurement +WellMeasurementCurve +WellMeasurementFilePath +WellMeasurementInView +WellMeasurements +WellMeasurementsInView +WellPath +WellPathAicdParameters +WellPathAttribute +WellPathAttributes +WellPathBase +WellPathCompletionSettings +WellPathCompletions +WellPathFracture +WellPathFractureCollection +WellPathGeometry +WellPathGeometryDef +WellPathGroup +WellPathTarget +WellPathValve +WellPaths +WellPltPlot +WellPltPlotCollection +WellRftEnsembleCurveSet +WellRftPlot +WellRftPlotCollection +Wells +cafNamedTreeNode +cafObjectReferenceTreeNode +cafTreeNode +cloneView +closeProject +computeCaseGroupStatistics +createGridCaseGroup +createGridCaseGroupResult +createLgrForCompletions +createMultiPlot +createMultipleFractures +createSaturationPressurePlots +createStatisticsCase +createStatisticsCaseResult +createView +createViewResult +createWbsPlotResult +createWellBoreStabilityPlot +exportContourMapToText +exportFlowCharacteristics +exportLgrForCompletions +exportMsw +exportMultiCaseSnapshots +exportProperty +exportPropertyInViews +exportSimWellFractureCompletions +exportSnapshots +exportVisibleCells +exportWellLogPlotData +exportWellLogPlotDataResult +exportWellPathCompletions +exportWellPaths +importFormationNames +importWellLogFiles +importWellLogFilesResult +importWellPaths +importWellPathsResult +loadCase +loadCaseResult +openProject +replaceCase +replaceMultipleCases +replaceSourceCases +runOctaveScript +saveProject +saveProjectAs +scaleFractureTemplate +setExportFolder +setFractureContainment +setMainWindowSize +setPlotWindowSize +setStartDir +setTimeStep +stackCurves +unstackCurves diff --git a/ApplicationLibCode/Application/RiaApplication.cpp b/ApplicationLibCode/Application/RiaApplication.cpp index 8211705f7d..7bef9598e1 100644 --- a/ApplicationLibCode/Application/RiaApplication.cpp +++ b/ApplicationLibCode/Application/RiaApplication.cpp @@ -40,6 +40,8 @@ #include "RicfCommandObject.h" #include "PlotTemplates/RimPlotTemplateFolderItem.h" +#include "Polygons/RimPolygonCollection.h" + #include "Rim2dIntersectionViewCollection.h" #include "RimAnnotationCollection.h" #include "RimAnnotationInViewCollection.h" @@ -125,10 +127,6 @@ #include // for usleep #endif // WIN32 -#ifdef USE_UNIT_TESTS -#include "gtest/gtest.h" -#endif // USE_UNIT_TESTS - // Required to ignore warning of usused variable when defining caf::PdmMarkdownGenerator #if defined( __clang__ ) #pragma clang diagnostic ignored "-Wunused-variable" @@ -548,6 +546,8 @@ bool RiaApplication::loadProject( const QString& projectFileName, ProjectLoadAct { seismicData->ensureFileReaderIsInitialized(); } + + oilField->polygonCollection()->loadData(); } { @@ -662,7 +662,10 @@ bool RiaApplication::loadProject( const QString& projectFileName, ProjectLoadAct } } - setActiveReservoirView( riv ); + if ( riv->showWindow() ) + { + setActiveReservoirView( riv ); + } RimGridView* rigv = dynamic_cast( riv ); if ( rigv ) rigv->cellFilterCollection()->updateIconState(); @@ -1395,56 +1398,6 @@ void RiaApplication::waitUntilCommandObjectsHasBeenProcessed() m_commandQueueLock.unlock(); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int RiaApplication::launchUnitTests() -{ -#ifdef USE_UNIT_TESTS - - caf::ProgressInfoBlocker progressBlocker; - cvf::Assert::setReportMode( cvf::Assert::CONSOLE ); - - int argc = QCoreApplication::arguments().size(); - QStringList arguments = QCoreApplication::arguments(); - std::vector argumentsStd; - for ( QString qstring : arguments ) - { - argumentsStd.push_back( qstring.toStdString() ); - } - std::vector argVector; - for ( std::string& string : argumentsStd ) - { - argVector.push_back( &string.front() ); - } - char** argv = argVector.data(); - - testing::InitGoogleTest( &argc, argv ); - - // - // Use the gtest filter to execute a subset of tests - QString filterText = RiaPreferencesSystem::current()->gtestFilter(); - if ( !filterText.isEmpty() ) - { - ::testing::GTEST_FLAG( filter ) = filterText.toStdString(); - - // Example on filter syntax - //::testing::GTEST_FLAG( filter ) = "*RifCaseRealizationParametersReaderTest*"; - } - - // Use this macro in main() to run all tests. It returns 0 if all - // tests are successful, or 1 otherwise. - // - // RUN_ALL_TESTS() should be invoked after the command line has been - // parsed by InitGoogleTest(). - - return RUN_ALL_TESTS(); - -#else - return -1; -#endif -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -1562,14 +1515,6 @@ void RiaApplication::initialize() caf::SelectionManager::instance()->setPdmRootObject( project() ); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int RiaApplication::launchUnitTestsWithConsole() -{ - return launchUnitTests(); -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Application/RiaApplication.h b/ApplicationLibCode/Application/RiaApplication.h index 590070cd05..5496295dbf 100644 --- a/ApplicationLibCode/Application/RiaApplication.h +++ b/ApplicationLibCode/Application/RiaApplication.h @@ -21,12 +21,11 @@ #include "RiaDefines.h" -#include "cafPdmField.h" -#include "cafPdmObject.h" - -#include "cvfFont.h" +#include "cafPdmPointer.h" #include "cvfObject.h" +#include +#include #include #include #include @@ -35,7 +34,6 @@ #include -#include #include class QAction; @@ -79,7 +77,8 @@ class UiProcess; namespace cvf { class ProgramOptions; -} +class Font; +} // namespace cvf //================================================================================================== /// Base class for all ResInsight applications. I.e. console and GUI @@ -198,7 +197,6 @@ class RiaApplication // Public implementation specific overrides virtual void initialize(); virtual ApplicationStatus handleArguments( gsl::not_null progOpt ) = 0; - virtual int launchUnitTestsWithConsole(); virtual void addToRecentFiles( const QString& fileName ) {} virtual void showFormattedTextInMessageBoxOrConsole( const QString& errMsg ) = 0; diff --git a/ApplicationLibCode/Application/RiaConsoleApplication.cpp b/ApplicationLibCode/Application/RiaConsoleApplication.cpp index b40ee52e0f..97a4b8b88b 100644 --- a/ApplicationLibCode/Application/RiaConsoleApplication.cpp +++ b/ApplicationLibCode/Application/RiaConsoleApplication.cpp @@ -103,8 +103,9 @@ void RiaConsoleApplication::initialize() RiaApplication::initialize(); - RiaLogging::setLoggerInstance( std::make_unique() ); - RiaLogging::loggerInstance()->setLevel( int( RiaLogging::logLevelBasedOnPreferences() ) ); + auto logger = std::make_unique(); + logger->setLevel( int( RiaLogging::logLevelBasedOnPreferences() ) ); + RiaLogging::appendLoggerInstance( std::move( logger ) ); m_socketServer = new RiaSocketServer( this ); } @@ -130,6 +131,7 @@ RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments( gsl::n if ( progOpt->option( "version" ) ) { QString text = QString( STRPRODUCTVER ) + "\n"; + text += "SHA " + QString( RESINSIGHT_GIT_HASH ) + "\n"; showFormattedTextInMessageBoxOrConsole( text ); @@ -153,22 +155,6 @@ RiaApplication::ApplicationStatus RiaConsoleApplication::handleArguments( gsl::n return RiaApplication::ApplicationStatus::EXIT_COMPLETED; } - // Unit testing - // -------------------------------------------------------- - if ( cvf::Option o = progOpt->option( "unittest" ) ) - { - int testReturnValue = launchUnitTestsWithConsole(); - if ( testReturnValue == 0 ) - { - return RiaApplication::ApplicationStatus::EXIT_COMPLETED; - } - else - { - RiaLogging::error( "Error running unit tests" ); - return RiaApplication::ApplicationStatus::EXIT_WITH_ERROR; - } - } - if ( cvf::Option o = progOpt->option( "startdir" ) ) { CVF_ASSERT( o.valueCount() == 1 ); diff --git a/ApplicationLibCode/Application/RiaDefines.cpp b/ApplicationLibCode/Application/RiaDefines.cpp index da3dcdda27..14dad18650 100644 --- a/ApplicationLibCode/Application/RiaDefines.cpp +++ b/ApplicationLibCode/Application/RiaDefines.cpp @@ -269,6 +269,12 @@ RiaDefines::EclipseUnitSystem RiaDefines::fromDepthUnit( DepthUnitType depthUnit //-------------------------------------------------------------------------------------------------- RiaDefines::ImportFileType RiaDefines::obtainFileTypeFromFileName( const QString& fileName ) { + if ( fileName.endsWith( "h5grid", Qt::CaseInsensitive ) ) + { + // EM data must be detected first, since "h5grid" also matches "grid" and is interpreted as Eclipse file + return ImportFileType::EM_H5GRID; + } + if ( fileName.endsWith( "EGRID", Qt::CaseInsensitive ) ) { return ImportFileType::ECLIPSE_EGRID_FILE; diff --git a/ApplicationLibCode/Application/RiaDefines.h b/ApplicationLibCode/Application/RiaDefines.h index 3591116eff..33dc5d6eef 100644 --- a/ApplicationLibCode/Application/RiaDefines.h +++ b/ApplicationLibCode/Application/RiaDefines.h @@ -132,10 +132,11 @@ enum class ImportFileType ECLIPSE_SUMMARY_FILE = 0x08, GEOMECH_ODB_FILE = 0x10, RESINSIGHT_PROJECT_FILE = 0x20, - ROFF_FILE = 0x30, GEOMECH_INP_FILE = 0x40, + EM_H5GRID = 0x80, + ROFF_FILE = 0x100, ECLIPSE_RESULT_GRID = ECLIPSE_GRID_FILE | ECLIPSE_EGRID_FILE, - ANY_ECLIPSE_FILE = ECLIPSE_RESULT_GRID | ECLIPSE_INPUT_FILE | ECLIPSE_SUMMARY_FILE | ROFF_FILE, + ANY_ECLIPSE_FILE = ECLIPSE_RESULT_GRID | ECLIPSE_INPUT_FILE | ECLIPSE_SUMMARY_FILE | ROFF_FILE | EM_H5GRID, ANY_GEOMECH_FILE = GEOMECH_ODB_FILE | GEOMECH_INP_FILE, ANY_IMPORT_FILE = 0xFF }; @@ -242,8 +243,17 @@ enum class View3dContent ALL = 0b00011111 }; +enum class ItemIn3dView +{ + NONE = 0b00000000, + SURFACE = 0b00000001, + POLYGON = 0b00000010, + ALL = 0b00000011 +}; + }; // namespace RiaDefines // Activate bit mask operators at global scope ENABLE_BITMASK_OPERATORS( RiaDefines::MultiPlotPageUpdateType ) ENABLE_BITMASK_OPERATORS( RiaDefines::View3dContent ) +ENABLE_BITMASK_OPERATORS( RiaDefines::ItemIn3dView ) diff --git a/ApplicationLibCode/Application/RiaFontCache.cpp b/ApplicationLibCode/Application/RiaFontCache.cpp index 188b9ced9a..85e4f53d31 100644 --- a/ApplicationLibCode/Application/RiaFontCache.cpp +++ b/ApplicationLibCode/Application/RiaFontCache.cpp @@ -20,9 +20,11 @@ #include "RiaGuiApplication.h" +#include "cafAssert.h" #include "cafFixedAtlasFont.h" #include + #include //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Application/RiaGuiApplication.cpp b/ApplicationLibCode/Application/RiaGuiApplication.cpp index 295420acbf..461e99ec54 100644 --- a/ApplicationLibCode/Application/RiaGuiApplication.cpp +++ b/ApplicationLibCode/Application/RiaGuiApplication.cpp @@ -23,6 +23,7 @@ #include "RiaArgumentParser.h" #include "RiaBaseDefs.h" #include "RiaDefines.h" +#include "RiaFileLogger.h" #include "RiaFilePathTools.h" #include "RiaFontCache.h" #include "RiaImportEclipseCaseTools.h" @@ -141,10 +142,6 @@ #include // for usleep #endif // WIN32 -#ifdef USE_UNIT_TESTS -#include "gtest/gtest.h" -#endif // USE_UNIT_TESTS - //================================================================================================== /// /// \class RiaGuiApplication @@ -432,9 +429,18 @@ void RiaGuiApplication::initialize() auto logger = std::make_unique(); logger->addMessagePanel( m_mainWindow->messagePanel() ); logger->addMessagePanel( m_mainPlotWindow->messagePanel() ); - RiaLogging::setLoggerInstance( std::move( logger ) ); + logger->setLevel( int( RiaLogging::logLevelBasedOnPreferences() ) ); + + RiaLogging::appendLoggerInstance( std::move( logger ) ); - RiaLogging::loggerInstance()->setLevel( int( RiaLogging::logLevelBasedOnPreferences() ) ); + auto filename = RiaPreferences::current()->loggerFilename(); + if ( !filename.isEmpty() ) + { + auto fileLogger = std::make_unique( filename.toStdString() ); + fileLogger->setLevel( int( RiaLogging::logLevelBasedOnPreferences() ) ); + + RiaLogging::appendLoggerInstance( std::move( fileLogger ) ); + } } m_socketServer = new RiaSocketServer( this ); } @@ -457,6 +463,16 @@ RiaApplication::ApplicationStatus RiaGuiApplication::handleArguments( gsl::not_n return RiaApplication::ApplicationStatus::EXIT_COMPLETED; } + if ( progOpt->option( "version" ) ) + { + QString text = QString( STRPRODUCTVER ) + "\n"; + text += "SHA " + QString( RESINSIGHT_GIT_HASH ) + "\n"; + + showFormattedTextInMessageBoxOrConsole( text ); + + return RiaApplication::ApplicationStatus::EXIT_COMPLETED; + } + // Code generation // ----------------- if ( cvf::Option o = progOpt->option( "generate" ) ) @@ -474,22 +490,6 @@ RiaApplication::ApplicationStatus RiaGuiApplication::handleArguments( gsl::not_n return RiaApplication::ApplicationStatus::EXIT_COMPLETED; } - // Unit testing - // -------------------------------------------------------- - if ( cvf::Option o = progOpt->option( "unittest" ) ) - { - int testReturnValue = launchUnitTestsWithConsole(); - if ( testReturnValue == 0 ) - { - return RiaApplication::ApplicationStatus::EXIT_COMPLETED; - } - else - { - RiaLogging::error( "Error running unit tests" ); - return RiaApplication::ApplicationStatus::EXIT_WITH_ERROR; - } - } - if ( cvf::Option o = progOpt->option( "regressiontest" ) ) { CVF_ASSERT( o.valueCount() == 1 ); @@ -501,7 +501,7 @@ RiaApplication::ApplicationStatus RiaGuiApplication::handleArguments( gsl::not_n auto stdLogger = std::make_unique(); stdLogger->setLevel( int( RILogLevel::RI_LL_DEBUG ) ); - RiaLogging::setLoggerInstance( std::move( stdLogger ) ); + RiaLogging::appendLoggerInstance( std::move( stdLogger ) ); RiaRegressionTestRunner::instance()->executeRegressionTests( regressionTestPath, QStringList() ); return ApplicationStatus::EXIT_COMPLETED; @@ -881,31 +881,6 @@ RiaApplication::ApplicationStatus RiaGuiApplication::handleArguments( gsl::not_n return ApplicationStatus::KEEP_GOING; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int RiaGuiApplication::launchUnitTestsWithConsole() -{ - // Following code is taken from cvfAssert.cpp -#ifdef WIN32 - { - // Allocate a new console for this app - // Only one console can be associated with an app, so should fail if a console is already present. - AllocConsole(); - - FILE* consoleFilePointer; - - freopen_s( &consoleFilePointer, "CONOUT$", "w", stdout ); - freopen_s( &consoleFilePointer, "CONOUT$", "w", stderr ); - - // Make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well - std::ios::sync_with_stdio(); - } -#endif - - return launchUnitTests(); -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -964,10 +939,14 @@ void RiaGuiApplication::createMainWindow() m_mainWindow->showWindow(); // if there is an existing logger, reconnect to it - auto logger = dynamic_cast( RiaLogging::loggerInstance() ); - if ( logger ) + + for ( auto logger : RiaLogging::loggerInstances() ) { - logger->addMessagePanel( m_mainWindow->messagePanel() ); + auto messagePanelLogger = dynamic_cast( logger ); + if ( messagePanelLogger ) + { + messagePanelLogger->addMessagePanel( m_mainWindow->messagePanel() ); + } } } diff --git a/ApplicationLibCode/Application/RiaGuiApplication.h b/ApplicationLibCode/Application/RiaGuiApplication.h index c2c2805f6e..2e293d380b 100644 --- a/ApplicationLibCode/Application/RiaGuiApplication.h +++ b/ApplicationLibCode/Application/RiaGuiApplication.h @@ -21,11 +21,6 @@ #include "RiaApplication.h" #include "RiaDefines.h" -#include "cafPdmField.h" -#include "cafPdmObject.h" - -#include "cvfObject.h" - #include #include #include @@ -127,7 +122,6 @@ class RiaGuiApplication : public QApplication, public RiaApplication // Public RiaApplication overrides void initialize() override; ApplicationStatus handleArguments( gsl::not_null progOpt ) override; - int launchUnitTestsWithConsole() override; void addToRecentFiles( const QString& fileName ) override; void showFormattedTextInMessageBoxOrConsole( const QString& errMsg ) override; diff --git a/ApplicationLibCode/Application/RiaMemoryCleanup.cpp b/ApplicationLibCode/Application/RiaMemoryCleanup.cpp index d5b65bb13b..d72e85f2a0 100644 --- a/ApplicationLibCode/Application/RiaMemoryCleanup.cpp +++ b/ApplicationLibCode/Application/RiaMemoryCleanup.cpp @@ -17,6 +17,7 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RiaMemoryCleanup.h" +#include "RiaStdStringTools.h" #include "RigCaseCellResultsData.h" #include "RigEclipseResultInfo.h" @@ -34,6 +35,10 @@ #include "cafPdmUiPushButtonEditor.h" #include "cafPdmUiTreeSelectionEditor.h" +#include +#include +#include + //================================================================================================== /// /// @@ -54,7 +59,10 @@ RiaMemoryCleanup::RiaMemoryCleanup() m_resultsToDelete.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_performDelete, "ClearSelectedData", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_performDelete ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_performDelete ); + + CAF_PDM_InitFieldNoDefault( &m_showMemoryReport, "ShowMemoryReport", "" ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_showMemoryReport ); } //-------------------------------------------------------------------------------------------------- @@ -107,6 +115,38 @@ void RiaMemoryCleanup::clearSelectedResultsFromMemory() m_geomResultAddresses.clear(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +class TextDialog : public QDialog +{ +public: + TextDialog( const QString& text, QWidget* parent = nullptr ) + : QDialog( parent ) + { + auto textWidget = new QTextEdit( "", this ); + textWidget->setPlainText( text ); + auto layout = new QVBoxLayout( this ); + layout->addWidget( textWidget ); + setLayout( layout ); + } +}; + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaMemoryCleanup::showMemoryReport() +{ + auto [summary, details] = createMemoryReport(); + + QString allText = summary + "\n\n" + details; + + auto dialog = new TextDialog( allText ); + dialog->setWindowTitle( "Memory Report" ); + dialog->setMinimumSize( 800, 600 ); + dialog->show(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -204,6 +244,12 @@ void RiaMemoryCleanup::fieldChangedByUi( const caf::PdmFieldHandle* changedField m_resultsToDelete.uiCapability()->updateConnectedEditors(); m_performDelete = false; } + else if ( changedField == &m_showMemoryReport ) + { + m_showMemoryReport = false; + + showMemoryReport(); + } } //-------------------------------------------------------------------------------------------------- @@ -310,10 +356,72 @@ void RiaMemoryCleanup::defineEditorAttribute( const caf::PdmFieldHandle* field, { if ( field == &m_performDelete ) { - caf::PdmUiPushButtonEditorAttribute* attrib = dynamic_cast( attribute ); + auto attrib = dynamic_cast( attribute ); if ( attrib ) { attrib->m_buttonText = "Clear Checked Data From Memory"; } } + if ( field == &m_showMemoryReport ) + { + auto attrib = dynamic_cast( attribute ); + if ( attrib ) + { + attrib->m_buttonText = "Show Memory Report"; + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RiaMemoryCleanup::createMemoryReport() +{ + QString details; + + auto allCases = RimProject::current()->allGridCases(); + + size_t totalMemory = 0; + for ( auto gridCase : allCases ) + { + if ( auto eclipseCase = dynamic_cast( gridCase ) ) + { + RigCaseCellResultsData* caseData = eclipseCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL ); + if ( caseData ) + { + size_t totalMemoryForCase = 0; + QString caseReport; + + auto memoryUse = caseData->resultValueCount(); + for ( const auto& [name, valueCount] : memoryUse ) + { + if ( valueCount > 0 ) + { + size_t memory = valueCount * sizeof( double ); + totalMemoryForCase += memory; + + auto formattedValueCount = RiaStdStringTools::formatThousandGrouping( valueCount ); + + caseReport += QString( " %1 MB\tValue count %2, %3\n" ) + .arg( memory / 1024.0 / 1024.0, 0, 'f', 2 ) + .arg( QString::fromStdString( formattedValueCount ) ) + .arg( QString::fromStdString( name ) ); + } + } + + totalMemory += totalMemoryForCase; + + if ( totalMemoryForCase > 0 ) + { + details += + QString( "%1 - %2 MB\n" ).arg( eclipseCase->caseUserDescription() ).arg( totalMemoryForCase / 1024.0 / 1024.0, 0, 'f', 2 ); + + details += caseReport; + } + } + } + } + + QString summary = QString( "Total memory used: %1 MB\n\n" ).arg( totalMemory / 1024.0 / 1024.0, 0, 'f', 2 ); + return std::make_pair( summary, details ); } diff --git a/ApplicationLibCode/Application/RiaMemoryCleanup.h b/ApplicationLibCode/Application/RiaMemoryCleanup.h index 15ee6d1538..cc154fb982 100644 --- a/ApplicationLibCode/Application/RiaMemoryCleanup.h +++ b/ApplicationLibCode/Application/RiaMemoryCleanup.h @@ -39,6 +39,8 @@ class RiaMemoryCleanup : public caf::PdmObject void setPropertiesFromView( Rim3dView* view ); void clearSelectedResultsFromMemory(); + static void showMemoryReport(); + protected: void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; @@ -52,10 +54,13 @@ class RiaMemoryCleanup : public caf::PdmObject void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + static std::pair createMemoryReport(); + private: caf::PdmPtrField m_case; caf::PdmField> m_resultsToDelete; std::vector m_geomResultAddresses; std::vector m_eclipseResultAddresses; caf::PdmField m_performDelete; + caf::PdmField m_showMemoryReport; }; diff --git a/ApplicationLibCode/Application/RiaPlotDefines.cpp b/ApplicationLibCode/Application/RiaPlotDefines.cpp index a3c23c0812..5405da79f5 100644 --- a/ApplicationLibCode/Application/RiaPlotDefines.cpp +++ b/ApplicationLibCode/Application/RiaPlotDefines.cpp @@ -169,6 +169,14 @@ QString RiaDefines::namingVariableWaterDepth() return "$WATER_DEPTH"; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaDefines::selectionTextNone() +{ + return "None"; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Application/RiaPlotDefines.h b/ApplicationLibCode/Application/RiaPlotDefines.h index 9cae9e693c..0ecaeeb8bc 100644 --- a/ApplicationLibCode/Application/RiaPlotDefines.h +++ b/ApplicationLibCode/Application/RiaPlotDefines.h @@ -93,6 +93,8 @@ QString namingVariableTimestep(); QString namingVariableAirGap(); QString namingVariableWaterDepth(); +QString selectionTextNone(); + double minimumDefaultValuePlot(); double minimumDefaultLogValuePlot(); double maximumDefaultValuePlot(); diff --git a/ApplicationLibCode/Application/RiaPreferences.cpp b/ApplicationLibCode/Application/RiaPreferences.cpp index 3439233871..d0ea2ebdee 100644 --- a/ApplicationLibCode/Application/RiaPreferences.cpp +++ b/ApplicationLibCode/Application/RiaPreferences.cpp @@ -34,12 +34,14 @@ #include "cafPdmFieldCvfColor.h" #include "cafPdmSettings.h" +#include "cafPdmUiCheckBoxAndTextEditor.h" #include "cafPdmUiCheckBoxEditor.h" #include "cafPdmUiComboBoxEditor.h" #include "cafPdmUiFieldHandle.h" #include "cafPdmUiFilePathEditor.h" #include "cafPdmUiLineEditor.h" +#include #include #include #include @@ -125,6 +127,19 @@ RiaPreferences::RiaPreferences() m_pythonExecutable.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); CAF_PDM_InitField( &showPythonDebugInfo, "pythonDebugInfo", false, "Show Python Debug Info" ); + auto defaultFilename = QStandardPaths::writableLocation( QStandardPaths::DocumentsLocation ); + if ( defaultFilename.isEmpty() ) + { + defaultFilename = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); + } + defaultFilename += "/ResInsight.log"; + + CAF_PDM_InitField( &m_loggerFilename, "loggerFilename", std::make_pair( false, defaultFilename ), "Logging To File" ); + m_loggerFilename.uiCapability()->setUiEditorTypeName( caf::PdmUiCheckBoxAndTextEditor::uiEditorTypeName() ); + + CAF_PDM_InitField( &m_loggerFlushInterval, "loggerFlushInterval", 500, "Logging Flush Interval [ms]" ); + CAF_PDM_InitField( &m_loggerTrapSignalAndFlush, "loggerTrapSignalAndFlush", false, "Trap SIGNAL and Flush File Logs" ); + CAF_PDM_InitField( &ssihubAddress, "ssihubAddress", QString( "http://" ), "SSIHUB Address" ); ssihubAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); @@ -461,6 +476,13 @@ void RiaPreferences::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& caf::PdmUiGroup* otherGroup = uiOrdering.addNewGroup( "Other" ); otherGroup->add( &m_gridCalculationExpressionFolder ); otherGroup->add( &m_summaryCalculationExpressionFolder ); + + caf::PdmUiGroup* loggingGroup = uiOrdering.addNewGroup( "Logging" ); + loggingGroup->add( &m_loggerFilename ); + loggingGroup->add( &m_loggerFlushInterval ); + loggingGroup->add( &m_loggerTrapSignalAndFlush ); + m_loggerTrapSignalAndFlush.uiCapability()->setUiReadOnly( !m_loggerFilename().first ); + m_loggerFlushInterval.uiCapability()->setUiReadOnly( !m_loggerFilename().first ); } else if ( RiaApplication::enableDevelopmentFeatures() && uiConfigName == RiaPreferences::tabNameSystem() ) { @@ -932,6 +954,35 @@ QString RiaPreferences::octaveExecutable() const return m_octaveExecutable().trimmed(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaPreferences::loggerFilename() const +{ + if ( m_loggerFilename().first ) + { + return m_loggerFilename().second; + } + + return {}; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RiaPreferences::loggerFlushInterval() const +{ + return m_loggerFlushInterval(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RiaPreferences::loggerTrapSignalAndFlush() const +{ + return m_loggerTrapSignalAndFlush(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Application/RiaPreferences.h b/ApplicationLibCode/Application/RiaPreferences.h index bcceb40a82..96628784f7 100644 --- a/ApplicationLibCode/Application/RiaPreferences.h +++ b/ApplicationLibCode/Application/RiaPreferences.h @@ -117,6 +117,10 @@ class RiaPreferences : public caf::PdmObject QString pythonExecutable() const; QString octaveExecutable() const; + QString loggerFilename() const; + int loggerFlushInterval() const; + bool loggerTrapSignalAndFlush() const; + RiaPreferencesGeoMech* geoMechPreferences() const; RiaPreferencesSummary* summaryPreferences() const; RiaPreferencesSystem* systemPreferences() const; @@ -203,6 +207,11 @@ class RiaPreferences : public caf::PdmObject caf::PdmField m_octaveExecutable; caf::PdmField m_pythonExecutable; + // Logging + caf::PdmField> m_loggerFilename; + caf::PdmField m_loggerFlushInterval; + caf::PdmField m_loggerTrapSignalAndFlush; + // Surface Import caf::PdmField m_surfaceImportResamplingDistance; diff --git a/ApplicationLibCode/Application/RiaPreferencesSummary.cpp b/ApplicationLibCode/Application/RiaPreferencesSummary.cpp index 9983ba5364..ae0b493ff3 100644 --- a/ApplicationLibCode/Application/RiaPreferencesSummary.cpp +++ b/ApplicationLibCode/Application/RiaPreferencesSummary.cpp @@ -121,8 +121,7 @@ RiaPreferencesSummary::RiaPreferencesSummary() "" ); CAF_PDM_InitField( &m_selectDefaultTemplates, "selectDefaultTemplate", false, "", "", "Select Default Templates" ); - m_selectDefaultTemplates.xmlCapability()->disableIO(); - m_selectDefaultTemplates.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_selectDefaultTemplates ); CAF_PDM_InitFieldNoDefault( &m_selectedDefaultTemplates, "defaultSummaryTemplates", "Select Summary Plot Templates" ); m_selectedDefaultTemplates.uiCapability()->setUiReadOnly( true ); diff --git a/ApplicationLibCode/Application/RiaResultNames.cpp b/ApplicationLibCode/Application/RiaResultNames.cpp index 9bb98050d4..cac4338ada 100644 --- a/ApplicationLibCode/Application/RiaResultNames.cpp +++ b/ApplicationLibCode/Application/RiaResultNames.cpp @@ -443,6 +443,38 @@ QString RiaResultNames::wbsPPResult() return "PP"; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsPPMinResult() +{ + return "PP_MIN"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsPPMaxResult() +{ + return "PP_MAX"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsPPExpResult() +{ + return "PP_EXP"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsPPInitialResult() +{ + return "PP_INIT"; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -459,6 +491,45 @@ QString RiaResultNames::wbsSHMkResult() return "SH_MK"; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsSHMkExpResult() +{ + return "SH_MK_EXP"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsSHMkMinResult() +{ + return "SH_MK_MIN"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsSHMkMaxResult() +{ + return "SH_MK_MAX"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsFGMkExpResult() +{ + return "FG_MK_EXP"; +} +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaResultNames::wbsFGMkMinResult() +{ + return "FG_MK_MIN"; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -519,5 +590,14 @@ std::vector RiaResultNames::wbsDerivedResultNames() wbsSFGResult(), wbsSHResult(), wbsSHMkResult(), + wbsSHMkExpResult(), + wbsSHMkMinResult(), + wbsSHMkMaxResult(), + wbsFGMkExpResult(), + wbsFGMkMinResult(), + wbsPPMinResult(), + wbsPPMaxResult(), + wbsPPExpResult(), + wbsPPInitialResult(), }; } diff --git a/ApplicationLibCode/Application/RiaResultNames.h b/ApplicationLibCode/Application/RiaResultNames.h index e6b600eca9..184aa85ff6 100644 --- a/ApplicationLibCode/Application/RiaResultNames.h +++ b/ApplicationLibCode/Application/RiaResultNames.h @@ -92,6 +92,15 @@ QString wbsSHMkResult(); QString wbsOBGResult(); QString wbsFGResult(); QString wbsSFGResult(); +QString wbsFGMkExpResult(); +QString wbsFGMkMinResult(); +QString wbsSHMkExpResult(); +QString wbsSHMkMinResult(); +QString wbsSHMkMaxResult(); +QString wbsPPMinResult(); +QString wbsPPMaxResult(); +QString wbsPPExpResult(); +QString wbsPPInitialResult(); // Fault results QString formationBinaryAllanResultName(); diff --git a/ApplicationLibCode/Application/RiaSummaryDefines.cpp b/ApplicationLibCode/Application/RiaSummaryDefines.cpp index ca10038193..26fff23313 100644 --- a/ApplicationLibCode/Application/RiaSummaryDefines.cpp +++ b/ApplicationLibCode/Application/RiaSummaryDefines.cpp @@ -157,3 +157,11 @@ QString RiaDefines::summaryCalculated() { return "Calculated"; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RiaDefines::summaryRealizationNumber() +{ + return "RI:REALIZATION_NUM"; +} diff --git a/ApplicationLibCode/Application/RiaSummaryDefines.h b/ApplicationLibCode/Application/RiaSummaryDefines.h index 3429c423a3..cdc26b3854 100644 --- a/ApplicationLibCode/Application/RiaSummaryDefines.h +++ b/ApplicationLibCode/Application/RiaSummaryDefines.h @@ -52,4 +52,6 @@ QString summaryLgrWell(); QString summaryLgrBlock(); QString summaryCalculated(); +QString summaryRealizationNumber(); + }; // namespace RiaDefines diff --git a/ApplicationLibCode/Application/Tools/CMakeLists_files.cmake b/ApplicationLibCode/Application/Tools/CMakeLists_files.cmake index 711f1a1a41..ad437b02db 100644 --- a/ApplicationLibCode/Application/Tools/CMakeLists_files.cmake +++ b/ApplicationLibCode/Application/Tools/CMakeLists_files.cmake @@ -53,6 +53,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RiaOpenMPTools.h ${CMAKE_CURRENT_LIST_DIR}/RiaNumericalTools.h ${CMAKE_CURRENT_LIST_DIR}/RiaRegressionTextTools.h + ${CMAKE_CURRENT_LIST_DIR}/RiaFileLogger.h ) set(SOURCE_GROUP_SOURCE_FILES @@ -103,6 +104,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RiaOpenMPTools.cpp ${CMAKE_CURRENT_LIST_DIR}/RiaNumericalTools.cpp ${CMAKE_CURRENT_LIST_DIR}/RiaRegressionTextTools.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaFileLogger.cpp ) list(APPEND CODE_SOURCE_FILES ${SOURCE_GROUP_SOURCE_FILES}) diff --git a/ApplicationLibCode/Application/Tools/RiaArgumentParser.cpp b/ApplicationLibCode/Application/Tools/RiaArgumentParser.cpp index 9aac68cc24..ed231aea5b 100644 --- a/ApplicationLibCode/Application/Tools/RiaArgumentParser.cpp +++ b/ApplicationLibCode/Application/Tools/RiaArgumentParser.cpp @@ -130,9 +130,6 @@ bool RiaArgumentParser::parseArguments( cvf::ProgramOptions* progOpt ) progOpt->registerOption( "updateregressiontestbase", "", "System command", cvf::ProgramOptions::SINGLE_VALUE ); progOpt->registerOption( "regressiontest", "", "System command", cvf::ProgramOptions::SINGLE_VALUE ); -#ifdef USE_UNIT_TESTS - progOpt->registerOption( "unittest", "", "System command" ); -#endif progOpt->registerOption( "generate", "[]", "Generate code or documentation", cvf::ProgramOptions::SINGLE_VALUE ); progOpt->registerOption( "ignoreArgs", "", "System command. Ignore all arguments. Mostly for testing purposes" ); progOpt->registerOption( "version", "", "Display the application version string" ); diff --git a/ApplicationLibCode/Application/Tools/RiaEclipseUnitTools.cpp b/ApplicationLibCode/Application/Tools/RiaEclipseUnitTools.cpp index 1e005e5b4f..45f13f274c 100644 --- a/ApplicationLibCode/Application/Tools/RiaEclipseUnitTools.cpp +++ b/ApplicationLibCode/Application/Tools/RiaEclipseUnitTools.cpp @@ -48,7 +48,7 @@ double RiaEclipseUnitTools::darcysConstant( RiaDefines::EclipseUnitSystem unitSy //-------------------------------------------------------------------------------------------------- /// Convert Gas to oil equivalents -/// If field unit, the Gas is in Mega ft^3 while the others are in [stb] (barrel) +/// If field unit, the Gas is in Mft^3(=1000ft^3) while the others are in [stb] (barrel) //-------------------------------------------------------------------------------------------------- double RiaEclipseUnitTools::convertSurfaceGasFlowRateToOilEquivalents( RiaDefines::EclipseUnitSystem caseUnitSystem, double eclGasFlowRate ) { @@ -56,18 +56,24 @@ double RiaEclipseUnitTools::convertSurfaceGasFlowRateToOilEquivalents( RiaDefine /// we convert gas to stb as well. Based on /// 1 [stb] = 0.15898729492800007 [m^3] /// 1 [ft] = 0.3048 [m] - /// megaFt3ToStbFactor = 1.0 / (1.0e-6 * 0.15898729492800007 * ( 1.0 / 0.3048 )^3 ) - /// double megaFt3ToStbFactor = 178107.60668; + /// + /// NB Mft^3 = 1000 ft^3 - can wrongly be interpreted as M for Mega in metric units - double fieldGasToOilEquivalent = 1.0e6 / 5800; // Mega ft^3 to BOE - double metricGasToOilEquivalent = 1.0 / 1.0e3; // Sm^3 Gas to Sm^3 oe + if ( caseUnitSystem == RiaDefines::EclipseUnitSystem::UNITS_FIELD ) + { + const double fieldGasToOilEquivalent = 1000.0 / 5614.63; - double oilEquivalentGasRate = HUGE_VAL; + return fieldGasToOilEquivalent * eclGasFlowRate; + } - if ( caseUnitSystem == RiaDefines::EclipseUnitSystem::UNITS_FIELD ) oilEquivalentGasRate = fieldGasToOilEquivalent * eclGasFlowRate; - if ( caseUnitSystem == RiaDefines::EclipseUnitSystem::UNITS_METRIC ) oilEquivalentGasRate = metricGasToOilEquivalent * eclGasFlowRate; + if ( caseUnitSystem == RiaDefines::EclipseUnitSystem::UNITS_METRIC ) + { + double metricGasToOilEquivalent = 1.0 / 1000.0; // Sm^3 Gas to Sm^3 oe + + return metricGasToOilEquivalent * eclGasFlowRate; + } - return oilEquivalentGasRate; + return HUGE_VAL; } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Application/Tools/RiaFileLogger.cpp b/ApplicationLibCode/Application/Tools/RiaFileLogger.cpp new file mode 100644 index 0000000000..3200527fd0 --- /dev/null +++ b/ApplicationLibCode/Application/Tools/RiaFileLogger.cpp @@ -0,0 +1,168 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RiaFileLogger.h" +#include "RiaPreferences.h" + +#include "spdlog/logger.h" +#include "spdlog/sinks/basic_file_sink.h" +#include "spdlog/spdlog.h" + +class RiaFileLogger::Impl +{ +public: + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + Impl( const std::string& fileName ) + { + try + { + m_spdlogger = spdlog::basic_logger_mt( "basic_logger", fileName ); + + auto flushInterval = RiaPreferences::current()->loggerFlushInterval(); + spdlog::flush_every( std::chrono::milliseconds( flushInterval ) ); + } + catch ( ... ) + { + } + } + + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + void log( const std::string& message ) + { + if ( m_spdlogger ) m_spdlogger->info( message ); + } + + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + void info( const std::string& message ) + { + if ( m_spdlogger ) m_spdlogger->info( message ); + } + + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + void debug( const std::string& message ) + { + if ( m_spdlogger ) m_spdlogger->debug( message ); + } + + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + void error( const std::string& message ) + { + if ( m_spdlogger ) m_spdlogger->error( message ); + } + + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + void warning( const std::string& message ) + { + if ( m_spdlogger ) m_spdlogger->warn( message ); + } + + //-------------------------------------------------------------------------------------------------- + /// + //-------------------------------------------------------------------------------------------------- + void flush() + { + if ( m_spdlogger ) m_spdlogger->flush(); + } + +private: + std::shared_ptr m_spdlogger; +}; + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RiaFileLogger::RiaFileLogger( const std::string& filename ) + : m_impl( new Impl( filename ) ) + , m_logLevel( int( RILogLevel::RI_LL_DEBUG ) ) + +{ +} + +//-------------------------------------------------------------------------------------------------- +/// The destructor must be located in the cpp file after the definition of RiaFileLogger::Impl to make sure the Impl class is defined when +/// the destructor of std::unique_ptr is called +//-------------------------------------------------------------------------------------------------- +RiaFileLogger::~RiaFileLogger() = default; + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RiaFileLogger::level() const +{ + return m_logLevel; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaFileLogger::setLevel( int logLevel ) +{ + m_logLevel = logLevel; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaFileLogger::error( const char* message ) +{ + m_impl->error( message ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaFileLogger::warning( const char* message ) +{ + m_impl->warning( message ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaFileLogger::info( const char* message ) +{ + m_impl->info( message ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaFileLogger::debug( const char* message ) +{ + m_impl->debug( message ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaFileLogger::flush() +{ + if ( m_impl ) m_impl->flush(); +} diff --git a/ApplicationLibCode/Application/Tools/RiaFileLogger.h b/ApplicationLibCode/Application/Tools/RiaFileLogger.h new file mode 100644 index 0000000000..2506eb2282 --- /dev/null +++ b/ApplicationLibCode/Application/Tools/RiaFileLogger.h @@ -0,0 +1,47 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RiaLogging.h" + +//================================================================================================== +// +//================================================================================================== +class RiaFileLogger : public RiaLogger +{ +public: + explicit RiaFileLogger( const std::string& filename ); + ~RiaFileLogger() override; + + int level() const override; + void setLevel( int logLevel ) override; + + void error( const char* message ) override; + void warning( const char* message ) override; + void info( const char* message ) override; + void debug( const char* message ) override; + + void flush(); + +private: + int m_logLevel; + + class Impl; + std::unique_ptr m_impl; +}; diff --git a/ApplicationLibCode/Application/Tools/RiaFilePathTools.cpp b/ApplicationLibCode/Application/Tools/RiaFilePathTools.cpp index 377eca7157..9cb625acd1 100644 --- a/ApplicationLibCode/Application/Tools/RiaFilePathTools.cpp +++ b/ApplicationLibCode/Application/Tools/RiaFilePathTools.cpp @@ -204,9 +204,12 @@ QStringList RiaFilePathTools::splitPathIntoComponents( const QString& inputPath, { auto path = QDir::cleanPath( inputPath ); - QStringList components; + auto indexOfLastSeparator = path.lastIndexOf( separator() ); + auto indexOfDrive = path.indexOf( ':' ); - QDir dir( path ); + QString pathWithoutDrive = path.mid( indexOfDrive + 1, indexOfLastSeparator - ( indexOfDrive + 1 ) ); + + QStringList components = RiaTextStringTools::splitSkipEmptyParts( pathWithoutDrive, separator() ); QFileInfo fileInfo( path ); @@ -214,18 +217,14 @@ QStringList RiaFilePathTools::splitPathIntoComponents( const QString& inputPath, { QString extension = fileInfo.completeSuffix(); path = path.replace( QString( ".%1" ).arg( extension ), "" ); - components.push_front( extension ); - components.push_front( fileInfo.baseName() ); + components.push_back( extension ); + components.push_back( fileInfo.baseName() ); } else { components.push_back( fileInfo.fileName() ); } - while ( dir.cdUp() ) - { - components.push_front( dir.dirName() ); - } return components; } @@ -330,16 +329,10 @@ std::map RiaFilePathTools::keyPathComponentsForEachFilePat { std::map allComponents; - std::multiset allPathComponents; for ( auto fileName : filePaths ) { QStringList pathComponentsForFile = splitPathIntoComponents( fileName, true ); allComponents[fileName] = pathComponentsForFile; - - for ( auto pathComponent : pathComponentsForFile ) - { - allPathComponents.insert( pathComponent ); - } } auto topNode = std::unique_ptr( new PathNode( "", nullptr ) ); @@ -376,3 +369,22 @@ bool RiaFilePathTools::isFirstOlderThanSecond( const std::string& firstFileName, return ( timeFirstFile < timeSecondFile ); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::string RiaFilePathTools::makeSuitableAsFileName( const std::string candidateName ) +{ + if ( candidateName.empty() ) return "noname"; + + QString tmp = QString::fromStdString( candidateName ); + + tmp.replace( ' ', '_' ); + tmp.replace( '/', '_' ); + tmp.replace( '\\', '_' ); + tmp.replace( ':', '_' ); + tmp.replace( '&', '_' ); + tmp.replace( '|', '_' ); + + return tmp.toStdString(); +} diff --git a/ApplicationLibCode/Application/Tools/RiaFilePathTools.h b/ApplicationLibCode/Application/Tools/RiaFilePathTools.h index fa857254c2..755aefd4ac 100644 --- a/ApplicationLibCode/Application/Tools/RiaFilePathTools.h +++ b/ApplicationLibCode/Application/Tools/RiaFilePathTools.h @@ -44,6 +44,7 @@ class RiaFilePathTools static QString removeDuplicatePathSeparators( const QString& path ); static QString rootSearchPathFromSearchFilter( const QString& searchFilter ); static QString commonRootOfFileNames( const QStringList& filePaths ); + static std::string makeSuitableAsFileName( const std::string candidateName ); static QStringList splitPathIntoComponents( const QString& path, bool splitExtensionIntoSeparateEntry = false ); diff --git a/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.cpp b/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.cpp index 292ec19036..1bd15d442f 100644 --- a/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.cpp +++ b/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.cpp @@ -40,6 +40,7 @@ #include "RimEclipseInputCase.h" #include "RimEclipseResultCase.h" #include "RimEclipseView.h" +#include "RimEmCase.h" #include "RimFileSummaryCase.h" #include "RimIdenticalGridCaseGroup.h" #include "RimMainPlotCollection.h" @@ -357,6 +358,8 @@ int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( const QStr return -1; } + RimMainPlotCollection::current()->ensureDefaultFlowPlotsAreCreated(); + if ( createView ) { RimEclipseView* riv = rimResultReservoir->createAndAddReservoirView(); @@ -588,3 +591,56 @@ RimRoffCase* RiaImportEclipseCaseTools::openRoffCaseFromFileName( const QString& return roffCase; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RiaImportEclipseCaseTools::openEmFilesFromFileNames( const QStringList& fileNames, bool createDefaultView, std::vector& createdCaseIds ) +{ + if ( fileNames.empty() ) return false; + + RimProject* project = RimProject::current(); + if ( !project ) return false; + + RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels() : nullptr; + if ( !analysisModels ) return false; + + for ( auto fileName : fileNames ) + { + auto* emCase = new RimEmCase(); + project->assignCaseIdToCase( emCase ); + emCase->setGridFileName( fileName ); + + bool gridImportSuccess = emCase->openEclipseGridFile(); + if ( !gridImportSuccess ) + { + const auto errMsg = "Failed to import grid from file: " + fileName.toStdString(); + RiaLogging::error( errMsg.c_str() ); + delete emCase; + continue; + } + + analysisModels->cases.push_back( emCase ); + analysisModels->updateConnectedEditors(); + + RimEclipseView* eclipseView = nullptr; + if ( createDefaultView ) + { + eclipseView = emCase->createAndAddReservoirView(); + + eclipseView->cellResult()->setResultType( RiaDefines::ResultCatType::INPUT_PROPERTY ); + eclipseView->loadDataAndUpdate(); + + emCase->updateAllRequiredEditors(); + if ( RiaGuiApplication::isRunning() ) + { + if ( RiuMainWindow::instance() ) RiuMainWindow::instance()->selectAsCurrentItem( eclipseView->cellResult() ); + + // Make sure the call to setExpanded is done after the call to selectAsCurrentItem + Riu3DMainWindowTools::setExpanded( eclipseView ); + } + } + } + + return true; +} diff --git a/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.h b/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.h index 2a34be3f0b..35e91708c2 100644 --- a/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.h +++ b/ApplicationLibCode/Application/Tools/RiaImportEclipseCaseTools.h @@ -59,6 +59,8 @@ class RiaImportEclipseCaseTools static std::vector openRoffCasesFromFileNames( const QStringList& fileNames, bool createDefaultView ); static RimRoffCase* openRoffCaseFromFileName( const QString& fileName, bool createDefaultView ); + static bool openEmFilesFromFileNames( const QStringList& fileNames, bool createDefaultView, std::vector& createdCaseIds ); + private: static int openEclipseCaseShowTimeStepFilterImpl( const QString& fileName, bool showTimeStepFilter, diff --git a/ApplicationLibCode/Application/Tools/RiaLogging.cpp b/ApplicationLibCode/Application/Tools/RiaLogging.cpp index 0dc96721f1..014dcfc281 100644 --- a/ApplicationLibCode/Application/Tools/RiaLogging.cpp +++ b/ApplicationLibCode/Application/Tools/RiaLogging.cpp @@ -169,22 +169,28 @@ void RiaDefaultConsoleLogger::writeToConsole( const std::string& str ) // //================================================================================================== -std::unique_ptr RiaLogging::sm_logger = std::make_unique(); +std::vector> RiaLogging::sm_logger; //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RiaLogger* RiaLogging::loggerInstance() +std::vector RiaLogging::loggerInstances() { - return sm_logger.get(); + std::vector loggerInstances; + for ( auto& logger : sm_logger ) + { + loggerInstances.push_back( logger.get() ); + } + + return loggerInstances; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RiaLogging::setLoggerInstance( std::unique_ptr loggerInstance ) +void RiaLogging::appendLoggerInstance( std::unique_ptr loggerInstance ) { - sm_logger = std::move( loggerInstance ); + sm_logger.push_back( std::move( loggerInstance ) ); } //-------------------------------------------------------------------------------------------------- @@ -202,10 +208,13 @@ RILogLevel RiaLogging::logLevelBasedOnPreferences() //-------------------------------------------------------------------------------------------------- void RiaLogging::error( const QString& message ) { - if ( sm_logger && sm_logger->level() >= int( RILogLevel::RI_LL_ERROR ) ) + for ( const auto& logger : sm_logger ) { + if ( logger && logger->level() >= int( RILogLevel::RI_LL_ERROR ) ) + { #pragma omp critical( critical_section_logging ) - sm_logger->error( message.toLatin1().constData() ); + logger->error( message.toLatin1().constData() ); + } } } @@ -214,10 +223,13 @@ void RiaLogging::error( const QString& message ) //-------------------------------------------------------------------------------------------------- void RiaLogging::warning( const QString& message ) { - if ( sm_logger && sm_logger->level() >= int( RILogLevel::RI_LL_WARNING ) ) + for ( const auto& logger : sm_logger ) { + if ( logger && logger->level() >= int( RILogLevel::RI_LL_WARNING ) ) + { #pragma omp critical( critical_section_logging ) - sm_logger->warning( message.toLatin1().constData() ); + logger->warning( message.toLatin1().constData() ); + } } } @@ -226,10 +238,13 @@ void RiaLogging::warning( const QString& message ) //-------------------------------------------------------------------------------------------------- void RiaLogging::info( const QString& message ) { - if ( sm_logger && sm_logger->level() >= int( RILogLevel::RI_LL_INFO ) ) + for ( const auto& logger : sm_logger ) { + if ( logger && logger->level() >= int( RILogLevel::RI_LL_INFO ) ) + { #pragma omp critical( critical_section_logging ) - sm_logger->info( message.toLatin1().constData() ); + logger->info( message.toLatin1().constData() ); + } } } @@ -238,10 +253,13 @@ void RiaLogging::info( const QString& message ) //-------------------------------------------------------------------------------------------------- void RiaLogging::debug( const QString& message ) { - if ( sm_logger && sm_logger->level() >= int( RILogLevel::RI_LL_DEBUG ) ) + for ( const auto& logger : sm_logger ) { + if ( logger && logger->level() >= int( RILogLevel::RI_LL_DEBUG ) ) + { #pragma omp critical( critical_section_logging ) - sm_logger->debug( message.toLatin1().constData() ); + logger->debug( message.toLatin1().constData() ); + } } } diff --git a/ApplicationLibCode/Application/Tools/RiaLogging.h b/ApplicationLibCode/Application/Tools/RiaLogging.h index 1aa7f31341..c0e8e5bf1b 100644 --- a/ApplicationLibCode/Application/Tools/RiaLogging.h +++ b/ApplicationLibCode/Application/Tools/RiaLogging.h @@ -60,8 +60,8 @@ class RiaLogger class RiaLogging { public: - static RiaLogger* loggerInstance(); - static void setLoggerInstance( std::unique_ptr loggerInstance ); + static std::vector loggerInstances(); + static void appendLoggerInstance( std::unique_ptr loggerInstance ); static RILogLevel logLevelBasedOnPreferences(); @@ -73,7 +73,7 @@ class RiaLogging static void errorInMessageBox( QWidget* parent, const QString& title, const QString& text ); private: - static std::unique_ptr sm_logger; + static std::vector> sm_logger; }; //================================================================================================== diff --git a/ApplicationLibCode/Application/Tools/RiaStdStringTools.cpp b/ApplicationLibCode/Application/Tools/RiaStdStringTools.cpp index 1f1bafb62f..dd0178f1cd 100644 --- a/ApplicationLibCode/Application/Tools/RiaStdStringTools.cpp +++ b/ApplicationLibCode/Application/Tools/RiaStdStringTools.cpp @@ -17,12 +17,15 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RiaStdStringTools.h" +#include "RiaLogging.h" #include "fast_float/include/fast_float/fast_float.h" -#include +#include + #include #include +#include const std::string WHITESPACE = " \n\r\t\f\v"; @@ -138,6 +141,26 @@ bool RiaStdStringTools::startsWithAlphabetic( const std::string& s ) return isalpha( s[0] ) != 0; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::string RiaStdStringTools::formatThousandGrouping( long value ) +{ + class my_punct : public std::numpunct + { + protected: + char do_decimal_point() const override { return '.'; } + char do_thousands_sep() const override { return ' '; } + std::string do_grouping() const override { return std::string( "\3" ); } + }; + + std::ostringstream os; + os.imbue( std::locale( os.getloc(), new my_punct ) ); + fixed( os ); + os << value; + return os.str(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -281,3 +304,118 @@ std::string RiaStdStringTools::removeHtmlTags( const std::string& s ) return result; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::set RiaStdStringTools::valuesFromRangeSelection( const std::string& s ) +{ + try + { + std::set result; + std::istringstream stringStream( s ); + std::string token; + + while ( std::getline( stringStream, token, ',' ) ) + { + token = RiaStdStringTools::trimString( token ); + + std::istringstream tokenStream( token ); + int startIndex, endIndex; + char dash; + + if ( tokenStream >> startIndex ) + { + if ( tokenStream >> dash && dash == '-' && tokenStream >> endIndex ) + { + if ( startIndex > endIndex ) + { + // If start is greater than end, swap them + std::swap( startIndex, endIndex ); + } + + for ( int i = startIndex; i <= endIndex; ++i ) + { + result.insert( i ); + } + } + else + { + result.insert( startIndex ); + } + } + } + + return result; + } + catch ( const std::exception& e ) + { + QString str = QString( "Failed to convert text string \" %1 \" to list of integers : " ).arg( QString::fromStdString( s ) ) + + QString::fromStdString( e.what() ); + RiaLogging::error( str ); + } + catch ( ... ) + { + QString str = + QString( "Failed to convert text string \" %1 \" to list of integers : Caught unknown exception" ).arg( QString::fromStdString( s ) ); + RiaLogging::error( str ); + } + + return {}; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::set RiaStdStringTools::valuesFromRangeSelection( const std::string& s, int minVal, int maxVal ) +{ + try + { + std::set result; + std::stringstream stringStream( s ); + std::string token; + + while ( std::getline( stringStream, token, ',' ) ) + { + token = RiaStdStringTools::trimString( token ); + + // Check for range + size_t dashPos = token.find( '-' ); + if ( dashPos != std::string::npos ) + { + int startIndex = ( dashPos == 0 ) ? minVal : std::stoi( token.substr( 0, dashPos ) ); + int endIndex = ( dashPos == token.size() - 1 ) ? maxVal : std::stoi( token.substr( dashPos + 1 ) ); + if ( startIndex > endIndex ) + { + // If start is greater than end, swap them + std::swap( startIndex, endIndex ); + } + for ( int i = startIndex; i <= endIndex; ++i ) + { + result.insert( i ); + } + } + else + { + // Check for individual numbers + result.insert( std::stoi( token ) ); + } + } + + return result; + } + catch ( const std::exception& e ) + { + QString str = QString( "Failed to convert text string \" %1 \" to list of integers : " ).arg( QString::fromStdString( s ) ) + + QString::fromStdString( e.what() ); + RiaLogging::error( str ); + } + catch ( ... ) + { + QString str = + QString( "Failed to convert text string \" %1 \" to list of integers : Caught unknown exception" ).arg( QString::fromStdString( s ) ); + RiaLogging::error( str ); + } + + return {}; +} diff --git a/ApplicationLibCode/Application/Tools/RiaStdStringTools.h b/ApplicationLibCode/Application/Tools/RiaStdStringTools.h index 81afb1d528..1cf32eb457 100644 --- a/ApplicationLibCode/Application/Tools/RiaStdStringTools.h +++ b/ApplicationLibCode/Application/Tools/RiaStdStringTools.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -43,6 +44,8 @@ class RiaStdStringTools static bool containsAlphabetic( const std::string& s ); static bool startsWithAlphabetic( const std::string& s ); + static std::string formatThousandGrouping( long value ); + // Conversion using fastest known approach static bool toDouble( const std::string_view& s, double& value ); static bool toInt( const std::string_view& s, int& value ); @@ -58,6 +61,13 @@ class RiaStdStringTools static std::string removeHtmlTags( const std::string& s ); + // Convert the string "1,2,5-8,10" to {1, 2, 5, 6, 7, 8, 10} + static std::set valuesFromRangeSelection( const std::string& s ); + + // Convert the range string with support for open ended expressions. minimum and maximum value will be used to limit the ranges. + // The input "-3,5-8,10-", min:1, max:12 will produce {1, 2, 3, 5, 6, 7, 8, 10, 11, 12} + static std::set valuesFromRangeSelection( const std::string& s, int minimumValue, int maximumValue ); + private: template static void splitByDelimiter( const std::string& str, Container& cont, char delimiter = ' ' ); diff --git a/ApplicationLibCode/Application/Tools/RiaSummaryTools.cpp b/ApplicationLibCode/Application/Tools/RiaSummaryTools.cpp index 90a83766fb..5af3086149 100644 --- a/ApplicationLibCode/Application/Tools/RiaSummaryTools.cpp +++ b/ApplicationLibCode/Application/Tools/RiaSummaryTools.cpp @@ -215,7 +215,7 @@ void RiaSummaryTools::getSummaryCasesAndAddressesForCalculation( int for ( RimUserDefinedCalculationVariable* v : calculation->allVariables() ) { - RimSummaryCalculationVariable* scv = dynamic_cast( v ); + auto* scv = dynamic_cast( v ); if ( scv ) { cases.push_back( scv->summaryCase() ); @@ -328,3 +328,68 @@ void RiaSummaryTools::copyCurveAxisData( RimSummaryCurve& curve, const RimSummar curve.setLeftOrRightAxisY( otherCurve.axisY() ); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaSummaryTools::updateRequiredCalculatedCurves( RimSummaryCase* sourceSummaryCase ) +{ + RimSummaryCalculationCollection* calcColl = RimProject::current()->calculationCollection(); + + for ( RimUserDefinedCalculation* summaryCalculation : calcColl->calculations() ) + { + bool needsUpdate = RiaSummaryTools::isCalculationRequired( summaryCalculation, sourceSummaryCase ); + if ( needsUpdate ) + { + summaryCalculation->parseExpression(); + summaryCalculation->calculate(); + summaryCalculation->updateDependentObjects(); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RiaSummaryTools::isCalculationRequired( const RimUserDefinedCalculation* summaryCalculation, const RimSummaryCase* summaryCase ) +{ + std::vector variables = summaryCalculation->allVariables(); + for ( RimUserDefinedCalculationVariable* variable : variables ) + { + if ( auto* summaryVariable = dynamic_cast( variable ) ) + { + return summaryVariable->summaryCase() == summaryCase; + } + } + + return false; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiaSummaryTools::reloadSummaryCase( RimSummaryCase* summaryCase ) +{ + if ( !summaryCase ) return; + + summaryCase->updateAutoShortName(); + summaryCase->createSummaryReaderInterface(); + summaryCase->createRftReaderInterface(); + summaryCase->refreshMetaData(); + + RiaSummaryTools::updateRequiredCalculatedCurves( summaryCase ); + + RimSummaryMultiPlotCollection* summaryPlotColl = RiaSummaryTools::summaryMultiPlotCollection(); + for ( RimSummaryMultiPlot* multiPlot : summaryPlotColl->multiPlots() ) + { + for ( RimSummaryPlot* summaryPlot : multiPlot->summaryPlots() ) + { + summaryPlot->loadDataAndUpdate(); + + // Consider to make the zoom optional + summaryPlot->zoomAll(); + } + + multiPlot->updatePlotTitles(); + } +} diff --git a/ApplicationLibCode/Application/Tools/RiaSummaryTools.h b/ApplicationLibCode/Application/Tools/RiaSummaryTools.h index 0ae7a43ef9..e293625716 100644 --- a/ApplicationLibCode/Application/Tools/RiaSummaryTools.h +++ b/ApplicationLibCode/Application/Tools/RiaSummaryTools.h @@ -25,6 +25,7 @@ #include +class RifEclipseSummaryAddress; class RimSummaryPlot; class RimSummaryMultiPlot; class RimSummaryMultiPlotCollection; @@ -35,8 +36,7 @@ class RimSummaryTable; class RimSummaryTableCollection; class RimObservedDataCollection; class RimSummaryCurve; - -class RifEclipseSummaryAddress; +class RimUserDefinedCalculation; class QStringList; @@ -85,4 +85,10 @@ class RiaSummaryTools static void copyCurveDataSources( RimSummaryCurve& curve, const RimSummaryCurve& otherCurve ); static void copyCurveAxisData( RimSummaryCurve& curve, const RimSummaryCurve& otherCurve ); + + static void reloadSummaryCase( RimSummaryCase* summaryCase ); + +private: + static void updateRequiredCalculatedCurves( RimSummaryCase* sourceSummaryCase ); + static bool isCalculationRequired( const RimUserDefinedCalculation* summaryCalculation, const RimSummaryCase* summaryCase ); }; diff --git a/ApplicationLibCode/Application/Tools/WellPathTools/RiaSCurveCalculator.cpp b/ApplicationLibCode/Application/Tools/WellPathTools/RiaSCurveCalculator.cpp index 19084db449..f0015fcdfd 100644 --- a/ApplicationLibCode/Application/Tools/WellPathTools/RiaSCurveCalculator.cpp +++ b/ApplicationLibCode/Application/Tools/WellPathTools/RiaSCurveCalculator.cpp @@ -272,8 +272,7 @@ void RiaSCurveCalculator::initializeByFinding_q1q2( cvf::Vec3d p1, double azi1, SolveStatus solveResultStatus = NOT_SOLVED; - int backstepLevel = 0; - int iteration = 1; + int iteration = 1; for ( iteration = 1; iteration < maxIterations; ++iteration ) { if ( fabs( q1Step ) > maxStepSize || fabs( q2Step ) > maxStepSize ) @@ -349,18 +348,12 @@ void RiaSCurveCalculator::initializeByFinding_q1q2( cvf::Vec3d p1, double azi1, // if (isZeroCrossingR2) q2Step = 0.9 * q2Step * fabs( R2_error ) / ( fabs( R2_error_new ) + fabs( R2_error ) ); - ++backstepLevel; - #ifdef DEBUG_OUTPUT_ON std::cout << " Backstep needed. " << std::endl; #endif continue; } - else - { - backstepLevel = 0; - } } #ifdef DEBUG_OUTPUT_ON diff --git a/ApplicationLibCode/CMakeLists.txt b/ApplicationLibCode/CMakeLists.txt index 57192e6738..e88e49300d 100644 --- a/ApplicationLibCode/CMakeLists.txt +++ b/ApplicationLibCode/CMakeLists.txt @@ -90,23 +90,6 @@ find_package(Eigen3 REQUIRED) # Defining all the source (and header) files # ############################################################################## -# Use all h files in the subdirectories to make them available in the project -file(GLOB_RECURSE HEADER_FILES *.h) - -set(SOCKET_INTERFACE_FILES - SocketInterface/RiaSocketServer.cpp - SocketInterface/RiaProjectInfoCommands.cpp - SocketInterface/RiaCaseInfoCommands.cpp - SocketInterface/RiaGeometryCommands.cpp - SocketInterface/RiaNNCCommands.cpp - SocketInterface/RiaPropertyDataCommands.cpp - SocketInterface/RiaWellDataCommands.cpp - SocketInterface/RiaSocketTools.cpp - SocketInterface/RiaSocketDataTransfer.cpp -) - -list(APPEND CPP_SOURCES ${SOCKET_INTERFACE_FILES} ${UNIT_TEST_FILES}) - list( APPEND REFERENCED_CMAKE_FILES @@ -140,6 +123,7 @@ list( ProjectDataModel/Intersections/CMakeLists_files.cmake ProjectDataModel/CellFilters/CMakeLists_files.cmake ProjectDataModel/ProcessControl/CMakeLists_files.cmake + ProjectDataModel/Polygons/CMakeLists_files.cmake ProjectDataModel/WellLog/CMakeLists_files.cmake ProjectDataModel/WellMeasurement/CMakeLists_files.cmake ProjectDataModel/WellPath/CMakeLists_files.cmake @@ -159,23 +143,9 @@ list( UserInterface/AnalysisPlots/CMakeLists_files.cmake CommandFileInterface/CMakeLists_files.cmake CommandFileInterface/Core/CMakeLists_files.cmake + SocketInterface/CMakeLists_files.cmake ) -option(RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS - "Include ApplicationCode Unit Tests" OFF -) -mark_as_advanced(FORCE RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS) -if(RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS) - add_definitions(-DUSE_UNIT_TESTS) - - list(APPEND REFERENCED_CMAKE_FILES UnitTests/CMakeLists_files.cmake) - - list(APPEND CPP_SOURCES - ${ResInsight_SOURCE_DIR}/ThirdParty/gtest/gtest-all.cc - ) - -endif() - # Include source file lists from *.cmake files foreach(referencedfile ${REFERENCED_CMAKE_FILES}) include(${referencedfile}) @@ -235,14 +205,11 @@ if(RESINSIGHT_FOUND_HDF5) list(APPEND CPP_SOURCES ${HDF5_FILES}) add_definitions(-DUSE_HDF5) + add_definitions(-DH5_BUILT_AS_DYNAMIC_LIB) if(MSVC) - add_definitions(-DH5_BUILT_AS_DYNAMIC_LIB) list(APPEND RI_PRIVATE_INCLUDES ${RESINSIGHT_HDF5_DIR}/include) - else() - add_definitions(-DH5_BUILT_AS_DYNAMIC_LIB) - add_definitions(${HDF5_DEFINITIONS}) list(APPEND RI_PRIVATE_INCLUDES ${HDF5_INCLUDE_DIRS}) endif() # MSVC @@ -267,21 +234,9 @@ qt5_wrap_ui(FORM_FILES_CPP ${QT_UI_FILES}) # Create source groups - see also included CMakeLists_files.cmake # ############################################################################## source_group("ModelVisualization" FILES ${MODEL_VISUALIZATION_FILES}) -source_group("SocketInterface" FILES ${SOCKET_INTERFACE_FILES}) -source_group("UnitTests" FILES ${UNIT_TEST_FILES}) -list( - APPEND - ALL_SOURCE_FILES - ${CPP_SOURCES} - ${MOC_SOURCE_FILES} - ${FORM_FILES_CPP} - ${HEADER_FILES} - ${REFERENCED_CMAKE_FILES} - ../ResInsightVersion.cmake - .clang-format - .clang-tidy - Adm/RiaVersionInfo.h.cmake +list(APPEND ALL_SOURCE_FILES ${CPP_SOURCES} ${MOC_SOURCE_FILES} + ${FORM_FILES_CPP} ) add_library(${PROJECT_NAME} OBJECT ${ALL_SOURCE_FILES}) @@ -291,11 +246,6 @@ mark_as_advanced(FORCE RESINSIGHT_ENABLE_PRECOMPILED_HEADERS) if(RESINSIGHT_ENABLE_PRECOMPILED_HEADERS) message("Precompiled Headers is enabled on : ${PROJECT_NAME}") target_precompile_headers(ApplicationLibCode PRIVATE pch.h) - - set_source_files_properties( - ${ResInsight_SOURCE_DIR}/ThirdParty/gtest/gtest-all.cc - PROPERTIES SKIP_PRECOMPILE_HEADERS ON - ) endif() if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") @@ -382,16 +332,14 @@ if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") endif() target_link_libraries( - ${PROJECT_NAME} ${LINK_LIBRARIES} ${EXTERNAL_LINK_LIBRARIES} + ${PROJECT_NAME} PUBLIC ${LINK_LIBRARIES} ${EXTERNAL_LINK_LIBRARIES} ) target_include_directories( ${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Commands ${CMAKE_CURRENT_SOURCE_DIR}/Commands/EclipseCommands - ${CMAKE_CURRENT_SOURCE_DIR}/ResultStatisticsCache ${CMAKE_CURRENT_SOURCE_DIR}/ProjectDataModelCommands/CommandRouter - ${CMAKE_CURRENT_SOURCE_DIR}/UserInterface/AnalysisPlots ${RI_PRIVATE_INCLUDES} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/Adm @@ -437,10 +385,13 @@ target_include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/ReservoirDataModel/Completions ${CMAKE_CURRENT_SOURCE_DIR}/ReservoirDataModel/ResultAccessors ${CMAKE_CURRENT_SOURCE_DIR}/ReservoirDataModel/ResultCalculators + ${CMAKE_CURRENT_SOURCE_DIR}/ResultStatisticsCache ${CMAKE_CURRENT_SOURCE_DIR}/SocketInterface ${CMAKE_CURRENT_SOURCE_DIR}/UserInterface + ${CMAKE_CURRENT_SOURCE_DIR}/UserInterface/AnalysisPlots ${CMAKE_CURRENT_SOURCE_DIR}/GeoMech/GeoMechDataModel ${CMAKE_CURRENT_SOURCE_DIR}/GeoMech/GeoMechVisualization + ${CMAKE_CURRENT_SOURCE_DIR}/GeoMech/GeoMechFileInterface ${CMAKE_CURRENT_SOURCE_DIR}/GeoMech/OdbReader ${CMAKE_CURRENT_SOURCE_DIR}/Measurement ${ResInsight_SOURCE_DIR}/ThirdParty @@ -471,3 +422,16 @@ if(RESINSIGHT_ENABLE_UNITY_BUILD) ) endforeach(fileToExclude) endif() + +# ############################################################################## +# Unit tests +# ############################################################################## + +option(RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS + "Include ApplicationLibCode Unit Tests" OFF +) +mark_as_advanced(FORCE RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS) +if(RESINSIGHT_INCLUDE_APPLICATION_UNIT_TESTS) + enable_testing() + add_subdirectory(UnitTests) +endif() diff --git a/ApplicationLibCode/Commands/ApplicationCommands/CMakeLists_files.cmake b/ApplicationLibCode/Commands/ApplicationCommands/CMakeLists_files.cmake index 9a641063bc..6d33bbcc4b 100644 --- a/ApplicationLibCode/Commands/ApplicationCommands/CMakeLists_files.cmake +++ b/ApplicationLibCode/Commands/ApplicationCommands/CMakeLists_files.cmake @@ -1,5 +1,4 @@ set(SOURCE_GROUP_HEADER_FILES - ${CMAKE_CURRENT_LIST_DIR}/RicLaunchUnitTestsFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicShowPlotWindowFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicShowMainWindowFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicTileWindowsFeature.h @@ -20,10 +19,10 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RicShowClassNamesFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicShowPlotDataCtxFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicOpenInTextEditorFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicShowMemoryReportFeature.h ) set(SOURCE_GROUP_SOURCE_FILES - ${CMAKE_CURRENT_LIST_DIR}/RicLaunchUnitTestsFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicShowPlotWindowFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicShowMainWindowFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicTileWindowsFeature.cpp @@ -44,6 +43,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RicShowClassNamesFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicShowPlotDataCtxFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicOpenInTextEditorFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicShowMemoryReportFeature.cpp ) list(APPEND COMMAND_CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) diff --git a/ApplicationLibCode/Commands/ApplicationCommands/RicLaunchUnitTestsFeature.cpp b/ApplicationLibCode/Commands/ApplicationCommands/RicShowMemoryReportFeature.cpp similarity index 68% rename from ApplicationLibCode/Commands/ApplicationCommands/RicLaunchUnitTestsFeature.cpp rename to ApplicationLibCode/Commands/ApplicationCommands/RicShowMemoryReportFeature.cpp index 7f3aded561..6581677cb5 100644 --- a/ApplicationLibCode/Commands/ApplicationCommands/RicLaunchUnitTestsFeature.cpp +++ b/ApplicationLibCode/Commands/ApplicationCommands/RicShowMemoryReportFeature.cpp @@ -1,7 +1,6 @@ ///////////////////////////////////////////////////////////////////////////////// // -// Copyright (C) 2015- Statoil ASA -// Copyright (C) 2015- Ceetron Solutions AS +// Copyright (C) 2024 Equinor ASA // // ResInsight is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by @@ -17,28 +16,26 @@ // ///////////////////////////////////////////////////////////////////////////////// -#include "RicLaunchUnitTestsFeature.h" +#include "RicShowMemoryReportFeature.h" -#include "RiaApplication.h" +#include "RiaMemoryCleanup.h" #include -CAF_CMD_SOURCE_INIT( RicLaunchUnitTestsFeature, "RicLaunchUnitTestsFeature" ); +CAF_CMD_SOURCE_INIT( RicShowMemoryReportFeature, "RicShowMemoryReportFeature" ); //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RicLaunchUnitTestsFeature::onActionTriggered( bool isChecked ) +void RicShowMemoryReportFeature::onActionTriggered( bool isChecked ) { - disableModelChangeContribution(); - - RiaApplication::instance()->launchUnitTestsWithConsole(); + RiaMemoryCleanup::showMemoryReport(); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RicLaunchUnitTestsFeature::setupActionLook( QAction* actionToSetup ) +void RicShowMemoryReportFeature::setupActionLook( QAction* actionToSetup ) { - actionToSetup->setText( "Launch Unit Tests" ); + actionToSetup->setText( "Memory Report" ); } diff --git a/ApplicationLibCode/Commands/ApplicationCommands/RicShowMemoryReportFeature.h b/ApplicationLibCode/Commands/ApplicationCommands/RicShowMemoryReportFeature.h new file mode 100644 index 0000000000..e61b201cb5 --- /dev/null +++ b/ApplicationLibCode/Commands/ApplicationCommands/RicShowMemoryReportFeature.h @@ -0,0 +1,33 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicShowMemoryReportFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +private: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/CMakeLists.txt b/ApplicationLibCode/Commands/CMakeLists.txt index 931eb11e82..740ee78f12 100644 --- a/ApplicationLibCode/Commands/CMakeLists.txt +++ b/ApplicationLibCode/Commands/CMakeLists.txt @@ -41,6 +41,7 @@ set(COMMAND_REFERENCED_CMAKE_FILES PlotTemplateCommands/CMakeLists_files.cmake FractureCommands/CMakeLists_files.cmake PlotBuilderCommands/CMakeLists_files.cmake + PolygonCommands/CMakeLists_files.cmake ) # Include source file lists from *.cmake files diff --git a/ApplicationLibCode/Commands/CMakeLists_files.cmake b/ApplicationLibCode/Commands/CMakeLists_files.cmake index d2fcebaf9a..be2b342e52 100644 --- a/ApplicationLibCode/Commands/CMakeLists_files.cmake +++ b/ApplicationLibCode/Commands/CMakeLists_files.cmake @@ -93,6 +93,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RicImportGridCalculationExpressionsFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicExportSummaryCalculationExpressionsFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicImportSummaryCalculationExpressionsFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicImportWellLogCsvFileFeature.h ) set(SOURCE_GROUP_SOURCE_FILES @@ -189,6 +190,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RicImportGridCalculationExpressionsFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicExportSummaryCalculationExpressionsFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicImportSummaryCalculationExpressionsFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicImportWellLogCsvFileFeature.cpp ) if(RESINSIGHT_USE_QT_CHARTS) diff --git a/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilter3dviewFeature.cpp b/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilter3dviewFeature.cpp index 52db3a8110..def2a95673 100644 --- a/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilter3dviewFeature.cpp +++ b/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilter3dviewFeature.cpp @@ -18,6 +18,8 @@ #include "RicNewPolygonFilter3dviewFeature.h" +#include "Polygons/RimPolygonInView.h" + #include "RiaApplication.h" #include "RimCase.h" #include "RimCellFilterCollection.h" @@ -46,7 +48,7 @@ void RicNewPolygonFilter3dviewFeature::onActionTriggered( bool isChecked ) // and the case to use RimCase* sourceCase = viewOrComparisonView->ownerCase(); - RimPolygonFilter* lastCreatedOrUpdated = filtColl->addNewPolygonFilter( sourceCase ); + RimPolygonFilter* lastCreatedOrUpdated = filtColl->addNewPolygonFilter( sourceCase, nullptr ); if ( lastCreatedOrUpdated ) { Riu3DMainWindowTools::selectAsCurrentItem( lastCreatedOrUpdated ); diff --git a/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilterFeature.cpp b/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilterFeature.cpp index 4e8ba926b2..dab91b8510 100644 --- a/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilterFeature.cpp +++ b/ApplicationLibCode/Commands/CellFilterCommands/RicNewPolygonFilterFeature.cpp @@ -18,9 +18,16 @@ #include "RicNewPolygonFilterFeature.h" +#include "RiaApplication.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonInView.h" + #include "RimCase.h" #include "RimCellFilterCollection.h" +#include "RimGridView.h" #include "RimPolygonFilter.h" + #include "Riu3DMainWindowTools.h" #include "cafSelectionManagerTools.h" @@ -35,16 +42,31 @@ CAF_CMD_SOURCE_INIT( RicNewPolygonFilterFeature, "RicNewPolygonFilterFeature" ); //-------------------------------------------------------------------------------------------------- void RicNewPolygonFilterFeature::onActionTriggered( bool isChecked ) { - // Find the selected Cell Filter Collection - std::vector colls = caf::selectedObjectsByTypeStrict(); - if ( colls.empty() ) return; - RimCellFilterCollection* filtColl = colls[0]; + auto cellFilterCollection = caf::SelectionManager::instance()->selectedItemOfType(); + + if ( !cellFilterCollection ) + { + RimGridView* activeView = RiaApplication::instance()->activeMainOrComparisonGridView(); + if ( activeView ) + { + cellFilterCollection = activeView->cellFilterCollection(); + } + } + + if ( !cellFilterCollection ) return; + + auto polygon = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !polygon ) + { + if ( auto polygonInView = caf::SelectionManager::instance()->selectedItemOfType() ) + { + polygon = polygonInView->polygon(); + } + } - // and the case to use - RimCase* sourceCase = filtColl->firstAncestorOrThisOfTypeAsserted(); + auto sourceCase = cellFilterCollection->firstAncestorOrThisOfTypeAsserted(); - RimPolygonFilter* lastCreatedOrUpdated = filtColl->addNewPolygonFilter( sourceCase ); - if ( lastCreatedOrUpdated ) + if ( auto lastCreatedOrUpdated = cellFilterCollection->addNewPolygonFilter( sourceCase, polygon ) ) { Riu3DMainWindowTools::selectAsCurrentItem( lastCreatedOrUpdated ); } @@ -56,5 +78,5 @@ void RicNewPolygonFilterFeature::onActionTriggered( bool isChecked ) void RicNewPolygonFilterFeature::setupActionLook( QAction* actionToSetup ) { actionToSetup->setIcon( QIcon( ":/CellFilter_Polygon.png" ) ); - actionToSetup->setText( "New Polygon Filter" ); + actionToSetup->setText( "Create Polygon Filter" ); } diff --git a/ApplicationLibCode/Commands/CompletionExportCommands/RicExportFractureCompletionsImpl.cpp b/ApplicationLibCode/Commands/CompletionExportCommands/RicExportFractureCompletionsImpl.cpp index 5dea97597e..b707801c30 100644 --- a/ApplicationLibCode/Commands/CompletionExportCommands/RicExportFractureCompletionsImpl.cpp +++ b/ApplicationLibCode/Commands/CompletionExportCommands/RicExportFractureCompletionsImpl.cpp @@ -34,12 +34,12 @@ #include "RimFractureTemplate.h" #include "RimObservedEclipseUserData.h" #include "RimProject.h" +#include "RimReloadCaseTools.h" #include "RimSimWellFracture.h" #include "RimSimWellFractureCollection.h" #include "RimSimWellInView.h" #include "RimStimPlanFractureTemplate.h" #include "RimSummaryCase.h" -#include "RimSummaryCaseMainCollection.h" #include "RimWellPath.h" #include "RimWellPathCompletions.h" #include "RimWellPathFracture.h" @@ -449,31 +449,27 @@ void RicExportFractureCompletionsImpl::getWellPressuresAndInitialProductionTimeS currentDate = caseTimeSteps.back(); } - RifEclipseSummaryAddress wbhpPressureAddress = RifEclipseSummaryAddress::wellAddress( "WBHP", wellPathName.toStdString() ); - RimSummaryCaseMainCollection* mainCollection = RiaSummaryTools::summaryCaseMainCollection(); - if ( mainCollection ) - { - RimSummaryCase* summaryCase = mainCollection->findSummaryCaseFromEclipseResultCase( resultCase ); + RifEclipseSummaryAddress wbhpPressureAddress = RifEclipseSummaryAddress::wellAddress( "WBHP", wellPathName.toStdString() ); - if ( summaryCase && summaryCase->summaryReader() ) + auto summaryCase = RimReloadCaseTools::findSummaryCaseFromEclipseResultCase( resultCase ); + if ( summaryCase && summaryCase->summaryReader() ) + { + auto [isOk, values] = summaryCase->summaryReader()->values( wbhpPressureAddress ); + if ( isOk ) { - auto [isOk, values] = summaryCase->summaryReader()->values( wbhpPressureAddress ); - if ( isOk ) + std::vector summaryTimeSteps = summaryCase->summaryReader()->timeSteps( wbhpPressureAddress ); + CVF_ASSERT( values.size() == summaryTimeSteps.size() ); + for ( size_t i = 0; i < summaryTimeSteps.size(); ++i ) { - std::vector summaryTimeSteps = summaryCase->summaryReader()->timeSteps( wbhpPressureAddress ); - CVF_ASSERT( values.size() == summaryTimeSteps.size() ); - for ( size_t i = 0; i < summaryTimeSteps.size(); ++i ) + QDateTime summaryDate = RiaQDateTimeTools::fromTime_t( summaryTimeSteps[i] ); + if ( initialProductionDate.isNull() && values[i] > 0.0 ) + { + initialProductionDate = summaryDate; + *initialWellPressure = values[i]; + } + if ( summaryDate <= currentDate ) { - QDateTime summaryDate = RiaQDateTimeTools::fromTime_t( summaryTimeSteps[i] ); - if ( initialProductionDate.isNull() && values[i] > 0.0 ) - { - initialProductionDate = summaryDate; - *initialWellPressure = values[i]; - } - if ( summaryDate <= currentDate ) - { - *currentWellPressure = values[i]; - } + *currentWellPressure = values[i]; } } } diff --git a/ApplicationLibCode/Commands/CompletionExportCommands/RicWellPathExportCompletionDataFeatureImpl.cpp b/ApplicationLibCode/Commands/CompletionExportCommands/RicWellPathExportCompletionDataFeatureImpl.cpp index 99f450e497..21293dbbc6 100644 --- a/ApplicationLibCode/Commands/CompletionExportCommands/RicWellPathExportCompletionDataFeatureImpl.cpp +++ b/ApplicationLibCode/Commands/CompletionExportCommands/RicWellPathExportCompletionDataFeatureImpl.cpp @@ -91,9 +91,19 @@ void RicWellPathExportCompletionDataFeatureImpl::exportCompletions( const std::v const std::vector& simWells, const RicExportCompletionDataSettingsUi& exportSettings ) { - if ( exportSettings.caseToApply() == nullptr || exportSettings.caseToApply()->eclipseCaseData() == nullptr ) + if ( exportSettings.caseToApply() == nullptr ) { - RiaLogging::error( "Export Completions Data: Cannot export completions data without specified eclipse case" ); + RiaLogging::error( "Export Completions Data: Cannot export completions data a valid Eclipse case" ); + return; + } + + // Ensure that the case is open. This will enable export without any open views. + // https://github.com/OPM/ResInsight/issues/11134 + exportSettings.caseToApply()->ensureReservoirCaseIsOpen(); + + if ( exportSettings.caseToApply()->eclipseCaseData() == nullptr ) + { + RiaLogging::error( "Export Completions Data: No data available for Eclipse Case" ); return; } diff --git a/ApplicationLibCode/Commands/CrossSectionCommands/CMakeLists_files.cmake b/ApplicationLibCode/Commands/CrossSectionCommands/CMakeLists_files.cmake index d1a18ed21d..bb0d00bef9 100644 --- a/ApplicationLibCode/Commands/CrossSectionCommands/CMakeLists_files.cmake +++ b/ApplicationLibCode/Commands/CrossSectionCommands/CMakeLists_files.cmake @@ -6,6 +6,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RicNewPolylineIntersectionFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicNewAzimuthDipIntersectionFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicCopyIntersectionsToAllViewsInCaseFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicNewPolygonIntersectionFeature.h ) set(SOURCE_GROUP_SOURCE_FILES @@ -16,6 +17,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RicNewPolylineIntersectionFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicNewAzimuthDipIntersectionFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicCopyIntersectionsToAllViewsInCaseFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicNewPolygonIntersectionFeature.cpp ) list(APPEND COMMAND_CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) diff --git a/ApplicationLibCode/Commands/CrossSectionCommands/RicNewPolygonIntersectionFeature.cpp b/ApplicationLibCode/Commands/CrossSectionCommands/RicNewPolygonIntersectionFeature.cpp new file mode 100644 index 0000000000..3ee2f4e7a3 --- /dev/null +++ b/ApplicationLibCode/Commands/CrossSectionCommands/RicNewPolygonIntersectionFeature.cpp @@ -0,0 +1,68 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicNewPolygonIntersectionFeature.h" + +#include "RiaApplication.h" + +#include "RimExtrudedCurveIntersection.h" +#include "RimGridView.h" +#include "RimIntersectionCollection.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonInView.h" + +#include "cafSelectionManager.h" + +#include + +CAF_CMD_SOURCE_INIT( RicNewPolygonIntersectionFeature, "RicNewPolygonIntersectionFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicNewPolygonIntersectionFeature::onActionTriggered( bool isChecked ) +{ + RimGridView* activeView = RiaApplication::instance()->activeMainOrComparisonGridView(); + if ( !activeView ) return; + + auto collection = activeView->intersectionCollection(); + if ( !collection ) return; + + auto polygon = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !polygon ) + { + if ( auto polygonInView = caf::SelectionManager::instance()->selectedItemOfType() ) + { + polygon = polygonInView->polygon(); + } + } + + auto intersection = new RimExtrudedCurveIntersection(); + intersection->configureForProjectPolyLine( polygon ); + collection->appendIntersectionAndUpdate( intersection ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicNewPolygonIntersectionFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setIcon( QIcon( ":/CrossSection16x16.png" ) ); + actionToSetup->setText( "Create Polygon Intersection" ); +} diff --git a/ApplicationLibCode/Commands/ApplicationCommands/RicLaunchUnitTestsFeature.h b/ApplicationLibCode/Commands/CrossSectionCommands/RicNewPolygonIntersectionFeature.h similarity index 88% rename from ApplicationLibCode/Commands/ApplicationCommands/RicLaunchUnitTestsFeature.h rename to ApplicationLibCode/Commands/CrossSectionCommands/RicNewPolygonIntersectionFeature.h index d6d27b45d7..f06741ab06 100644 --- a/ApplicationLibCode/Commands/ApplicationCommands/RicLaunchUnitTestsFeature.h +++ b/ApplicationLibCode/Commands/CrossSectionCommands/RicNewPolygonIntersectionFeature.h @@ -1,7 +1,6 @@ ///////////////////////////////////////////////////////////////////////////////// // -// Copyright (C) 2015- Statoil ASA -// Copyright (C) 2015- Ceetron Solutions AS +// Copyright (C) 2024 Equinor ASA // // ResInsight is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by @@ -24,7 +23,7 @@ //================================================================================================== /// //================================================================================================== -class RicLaunchUnitTestsFeature : public caf::CmdFeature +class RicNewPolygonIntersectionFeature : public caf::CmdFeature { CAF_CMD_HEADER_INIT; diff --git a/ApplicationLibCode/Commands/ExportCommands/RicAdvancedSnapshotExportFeature.cpp b/ApplicationLibCode/Commands/ExportCommands/RicAdvancedSnapshotExportFeature.cpp index ebd090ed0d..0a4085f80f 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicAdvancedSnapshotExportFeature.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicAdvancedSnapshotExportFeature.cpp @@ -47,6 +47,7 @@ #include "cafUtils.h" #include +#include #include #include diff --git a/ApplicationLibCode/Commands/ExportCommands/RicCellRangeUi.cpp b/ApplicationLibCode/Commands/ExportCommands/RicCellRangeUi.cpp index 4b66a26310..d540878e3a 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicCellRangeUi.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicCellRangeUi.cpp @@ -218,8 +218,7 @@ void RicCellRangeUi::setDefaultValues() if ( grid == mainGrid && actCellInfo ) { - cvf::Vec3st min, max; - actCellInfo->IJKBoundingBox( min, max ); + auto [min, max] = actCellInfo->ijkBoundingBox(); // Adjust to Eclipse indexing min.x() = min.x() + 1; @@ -273,8 +272,7 @@ void RicCellRangeUi::updateLegendText() if ( grid == mainGrid && actCellInfo ) { - cvf::Vec3st min, max; - actCellInfo->IJKBoundingBox( min, max ); + auto [min, max] = actCellInfo->ijkBoundingBox(); // Adjust to Eclipse indexing min.x() = min.x() + 1; diff --git a/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesImpl.cpp b/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesImpl.cpp index 036731fa87..5850acc945 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesImpl.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesImpl.cpp @@ -33,6 +33,7 @@ #include "RimEclipseCase.h" #include "RimGeoMechCase.h" #include "RimMainPlotCollection.h" +#include "RimWellLogFile.h" #include "RimWellLogLasFile.h" #include "RimWellLogPlotCollection.h" #include "RimWellPath.h" @@ -214,14 +215,16 @@ void RicCreateDepthAdjustedLasFilesImpl::createDestinationWellLasFile( const QSt // Add tvd msl values if existing if ( !tvdMslValues.empty() ) { - const auto unitText = sourceWellLogData->wellLogChannelUnitString( RiaDefines::propertyNameTvdMslDepth(), deptUnit ).toStdString(); + const auto unitText = + sourceWellLogData->convertedWellLogChannelUnitString( RiaDefines::propertyNameTvdMslDepth(), deptUnit ).toStdString(); lasFile.AddLog( RiaDefines::propertyNameTvdMslDepth().toStdString(), unitText, "True vertical depth " + depthUnitComment, tvdMslValues ); } // Add tvd rkb values if existing if ( !tvdRkbValues.empty() ) { - const auto unitText = sourceWellLogData->wellLogChannelUnitString( RiaDefines::propertyNameTvdRkbDepth(), deptUnit ).toStdString(); + const auto unitText = + sourceWellLogData->convertedWellLogChannelUnitString( RiaDefines::propertyNameTvdRkbDepth(), deptUnit ).toStdString(); lasFile.AddLog( RiaDefines::propertyNameTvdRkbDepth().toStdString(), unitText, "True vertical depth (Rotary Kelly Bushing)", tvdRkbValues ); } diff --git a/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesUi.cpp b/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesUi.cpp index f35d1cb23a..ad275a9233 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesUi.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicCreateDepthAdjustedLasFilesUi.cpp @@ -31,7 +31,6 @@ #include "cafPdmUiCheckBoxEditor.h" #include "cafPdmUiFilePathEditor.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeSelectionEditor.h" CAF_PDM_SOURCE_INIT( RicCreateDepthAdjustedLasFilesUi, "RicCreateDepthAdjustedLasFilesUi" ); @@ -140,7 +139,7 @@ void RicCreateDepthAdjustedLasFilesUi::fieldChangedByUi( const caf::PdmFieldHand wellLogFile = nullptr; if ( sourceWell != nullptr && !sourceWell->wellLogFiles().empty() ) { - wellLogFile = sourceWell->wellLogFiles()[0]; + wellLogFile = dynamic_cast( sourceWell->wellLogFiles()[0] ); } } if ( changedField == &wellLogFile ) @@ -188,7 +187,7 @@ void RicCreateDepthAdjustedLasFilesUi::setDefaultValues() if ( !wellPath->wellLogFiles().empty() ) { sourceWell = wellPath; - wellLogFile = wellPath->wellLogFiles()[0]; + wellLogFile = dynamic_cast( sourceWell->wellLogFiles()[0] ); break; } } diff --git a/ApplicationLibCode/Commands/ExportCommands/RicExportEclipseSectorModelUi.cpp b/ApplicationLibCode/Commands/ExportCommands/RicExportEclipseSectorModelUi.cpp index 3a16a078e5..88a5c427d1 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicExportEclipseSectorModelUi.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicExportEclipseSectorModelUi.cpp @@ -33,7 +33,6 @@ #include "cafPdmUiFilePathEditor.h" #include "cafPdmUiGroup.h" #include "cafPdmUiLineEditor.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeSelectionEditor.h" #include @@ -516,8 +515,7 @@ void RicExportEclipseSectorModelUi::applyBoundaryDefaults() { if ( exportGridBox == ACTIVE_CELLS_BOX ) { - cvf::Vec3st minActive, maxActive; - m_caseData->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL )->IJKBoundingBox( minActive, maxActive ); + auto [minActive, maxActive] = m_caseData->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL )->ijkBoundingBox(); setMin( cvf::Vec3i( minActive ) ); setMax( cvf::Vec3i( maxActive ) ); } diff --git a/ApplicationLibCode/Commands/ExportCommands/RicExportInpFileFeature.cpp b/ApplicationLibCode/Commands/ExportCommands/RicExportInpFileFeature.cpp index e880051cf5..c6939db9b0 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicExportInpFileFeature.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicExportInpFileFeature.cpp @@ -48,19 +48,13 @@ void RicExportInpFileFeature::onActionTriggered( bool isChecked ) auto faultReactivationModel = caf::SelectionManager::instance()->selectedItemOfType(); if ( faultReactivationModel ) { - const QString frmTitle( "Fault Reactivation Modeling" ); - if ( !faultReactivationModel->extractAndExportModelData() ) - { - QMessageBox::critical( nullptr, frmTitle, "Unable to get necessary data from the input case." ); - return; - } - - QString exportFile = faultReactivationModel->baseDir() + "/faultreactivation.inp"; - auto [isOk, errorMessage] = RifFaultReactivationModelExporter::exportToFile( exportFile.toStdString(), *faultReactivationModel ); + auto [isOk, errorMessage] = RifFaultReactivationModelExporter::exportToFile( *faultReactivationModel ); if ( !isOk ) { - QString outErrorText = - QString( "Failed to export INP model to file %1.\n\n%2" ).arg( exportFile ).arg( QString::fromStdString( errorMessage ) ); + const QString frmTitle( "Fault Reactivation Modeling" ); + QString outErrorText = QString( "Failed to export INP model to file %1.\n\n%2" ) + .arg( QString::fromStdString( faultReactivationModel->inputFilename() ) ) + .arg( QString::fromStdString( errorMessage ) ); QMessageBox::critical( nullptr, frmTitle, outErrorText ); } } diff --git a/ApplicationLibCode/Commands/ExportCommands/RicExportToLasFileResampleUi.cpp b/ApplicationLibCode/Commands/ExportCommands/RicExportToLasFileResampleUi.cpp index 152d23c9e4..c2dfb84fa1 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicExportToLasFileResampleUi.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicExportToLasFileResampleUi.cpp @@ -20,7 +20,6 @@ #include "cafPdmUiCheckBoxEditor.h" #include "cafPdmUiFilePathEditor.h" -#include "cafPdmUiOrdering.h" #include diff --git a/ApplicationLibCode/Commands/ExportCommands/RicExportWellPathsUi.cpp b/ApplicationLibCode/Commands/ExportCommands/RicExportWellPathsUi.cpp index c44aac515c..87a2decc15 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicExportWellPathsUi.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicExportWellPathsUi.cpp @@ -25,7 +25,6 @@ #include "RimProject.h" #include "cafPdmUiFilePathEditor.h" -#include "cafPdmUiOrdering.h" CAF_PDM_SOURCE_INIT( RicExportWellPathsUi, "RicExportWellPathsUi" ); diff --git a/ApplicationLibCode/Commands/ExportCommands/RicSaveEclipseInputVisibleCellsUi.cpp b/ApplicationLibCode/Commands/ExportCommands/RicSaveEclipseInputVisibleCellsUi.cpp index 0745a3b89f..8ed93cd536 100644 --- a/ApplicationLibCode/Commands/ExportCommands/RicSaveEclipseInputVisibleCellsUi.cpp +++ b/ApplicationLibCode/Commands/ExportCommands/RicSaveEclipseInputVisibleCellsUi.cpp @@ -22,7 +22,6 @@ #include "RiaPreferences.h" #include "cafPdmUiFilePathEditor.h" -#include "cafPdmUiOrdering.h" #include diff --git a/ApplicationLibCode/Commands/FractureCommands/RicCreateMultipleFracturesFeature.cpp b/ApplicationLibCode/Commands/FractureCommands/RicCreateMultipleFracturesFeature.cpp index a2c12c1c32..45786e161f 100644 --- a/ApplicationLibCode/Commands/FractureCommands/RicCreateMultipleFracturesFeature.cpp +++ b/ApplicationLibCode/Commands/FractureCommands/RicCreateMultipleFracturesFeature.cpp @@ -68,14 +68,12 @@ void RicCreateMultipleFracturesFeature::replaceFractures() //-------------------------------------------------------------------------------------------------- std::pair RicCreateMultipleFracturesFeature::ijkRangeForGrid( RimEclipseCase* gridCase ) const { - cvf::Vec3st minIJK; - cvf::Vec3st maxIJK; if ( gridCase && gridCase->eclipseCaseData() ) { - gridCase->eclipseCaseData()->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL )->IJKBoundingBox( minIJK, maxIJK ); - return std::make_pair( minIJK, maxIJK ); + return gridCase->eclipseCaseData()->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL )->ijkBoundingBox(); } - return std::make_pair( cvf::Vec3st(), cvf::Vec3st() ); + + return {}; } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Commands/GeoMechCommands/RicGeoMechCopyCaseFeature.cpp b/ApplicationLibCode/Commands/GeoMechCommands/RicGeoMechCopyCaseFeature.cpp index 880b3337d4..efc09f2fa6 100644 --- a/ApplicationLibCode/Commands/GeoMechCommands/RicGeoMechCopyCaseFeature.cpp +++ b/ApplicationLibCode/Commands/GeoMechCommands/RicGeoMechCopyCaseFeature.cpp @@ -50,10 +50,15 @@ void RicGeoMechCopyCaseFeature::onActionTriggered( bool isChecked ) RiaApplication* app = RiaApplication::instance(); QString defaultDir = app->lastUsedDialogDirectory( "GEOMECH_MODEL" ); + QString filterStr; +#if USE_ODB_API + filterStr += "Abaqus results (*.odb);;"; +#endif + filterStr += "Abaqus input file (*.inp)"; + for ( RimGeoMechCase* gmc : cases ) { - QString fileName = - RiuFileDialogTools::getOpenFileName( nullptr, "Import Geo-Mechanical Model", defaultDir, "Abaqus results (*.odb)" ); + QString fileName = RiuFileDialogTools::getOpenFileName( nullptr, "Import Geo-Mechanical Model", defaultDir, filterStr ); if ( fileName.isEmpty() ) break; defaultDir = QFileInfo( fileName ).absolutePath(); diff --git a/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseFeature.cpp b/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseFeature.cpp index f02d949fa2..abf1fcc5f1 100644 --- a/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseFeature.cpp +++ b/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseFeature.cpp @@ -34,11 +34,14 @@ void RicImportGeoMechCaseFeature::onActionTriggered( bool isChecked ) { RiaApplication* app = RiaApplication::instance(); + QString filterStr; +#if USE_ODB_API + filterStr += "Abaqus results (*.odb);;"; +#endif + filterStr += "Abaqus input file (*.inp)"; + QString defaultDir = app->lastUsedDialogDirectory( "GEOMECH_MODEL" ); - QStringList fileNames = RiuFileDialogTools::getOpenFileNames( nullptr, - "Import Geo-Mechanical Model", - defaultDir, - "Abaqus results (*.odb);;Abaqus input file (*.inp)" ); + QStringList fileNames = RiuFileDialogTools::getOpenFileNames( nullptr, "Import Geo-Mechanical Model", defaultDir, filterStr ); if ( !fileNames.empty() ) defaultDir = QFileInfo( fileNames.last() ).absolutePath(); app->setLastUsedDialogDirectory( "GEOMECH_MODEL", defaultDir ); diff --git a/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseTimeStepFilterFeature.cpp b/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseTimeStepFilterFeature.cpp index a5c5a1ff8d..b02bbd5cf0 100644 --- a/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseTimeStepFilterFeature.cpp +++ b/ApplicationLibCode/Commands/GeoMechCommands/RicImportGeoMechCaseTimeStepFilterFeature.cpp @@ -36,9 +36,14 @@ void RicImportGeoMechCaseTimeStepFilterFeature::onActionTriggered( bool isChecke { RiaApplication* app = RiaApplication::instance(); + QString filterStr; +#if USE_ODB_API + filterStr += "Abaqus results (*.odb);;"; +#endif + filterStr += "Abaqus input file (*.inp)"; + QString defaultDir = app->lastUsedDialogDirectory( "GEOMECH_MODEL" ); - QStringList fileNames = - RiuFileDialogTools::getOpenFileNames( nullptr, "Import Geo-Mechanical Model", defaultDir, "Abaqus results (*.odb)" ); + QStringList fileNames = RiuFileDialogTools::getOpenFileNames( nullptr, "Import Geo-Mechanical Model", defaultDir, filterStr ); if ( !fileNames.empty() ) defaultDir = QFileInfo( fileNames.last() ).absolutePath(); for ( QString fileName : fileNames ) { diff --git a/ApplicationLibCode/Commands/GeoMechCommands/RicRunFaultReactModelingFeature.cpp b/ApplicationLibCode/Commands/GeoMechCommands/RicRunFaultReactModelingFeature.cpp index 73335da878..f989e847fd 100644 --- a/ApplicationLibCode/Commands/GeoMechCommands/RicRunFaultReactModelingFeature.cpp +++ b/ApplicationLibCode/Commands/GeoMechCommands/RicRunFaultReactModelingFeature.cpp @@ -62,27 +62,13 @@ void RicRunFaultReactModelingFeature::onActionTriggered( bool isChecked ) runProgress.setProgressDescription( "Writing input files." ); - auto [modelOk, errorMsg] = model->validateBeforeRun(); - - if ( !modelOk ) - { - QMessageBox::critical( nullptr, frmTitle, QString::fromStdString( errorMsg ) ); - return; - } - - if ( !model->extractAndExportModelData() ) - { - QMessageBox::critical( nullptr, frmTitle, "Unable to get necessary data from the input case." ); - return; - } - - QString exportFile = model->inputFilename(); - auto [result, errText] = RifFaultReactivationModelExporter::exportToFile( exportFile.toStdString(), *model ); + auto [result, errText] = RifFaultReactivationModelExporter::exportToFile( *model ); if ( !result ) { - QString outErrorText = - QString( "Failed to export INP model to file %1.\n\n%2" ).arg( exportFile ).arg( QString::fromStdString( errText ) ); + QString outErrorText = QString( "Failed to export INP model to file %1.\n\n%2" ) + .arg( QString::fromStdString( model->inputFilename() ) ) + .arg( QString::fromStdString( errText ) ); QMessageBox::critical( nullptr, frmTitle, outErrorText ); return; } @@ -121,7 +107,7 @@ void RicRunFaultReactModelingFeature::onActionTriggered( bool isChecked ) for ( auto gCase : RimProject::current()->geoMechCases() ) { - if ( model->outputOdbFilename() == gCase->gridFileName() ) + if ( QString::fromStdString( model->outputOdbFilename() ) == gCase->gridFileName() ) { gCase->reloadDataAndUpdate(); auto& views = gCase->geoMechViews(); @@ -138,11 +124,11 @@ void RicRunFaultReactModelingFeature::onActionTriggered( bool isChecked ) } RiaApplication* app = RiaApplication::instance(); - if ( !app->openOdbCaseFromFile( model->outputOdbFilename() ) ) + if ( !app->openOdbCaseFromFile( QString::fromStdString( model->outputOdbFilename() ) ) ) { QMessageBox::critical( nullptr, frmTitle, - "Failed to load modeling results from file \"" + model->outputOdbFilename() + + "Failed to load modeling results from file \"" + QString::fromStdString( model->outputOdbFilename() ) + "\". Check log window for additional information." ); } } diff --git a/ApplicationLibCode/Commands/GeoMechCommands/RicShowFaultReactModelFeature.cpp b/ApplicationLibCode/Commands/GeoMechCommands/RicShowFaultReactModelFeature.cpp index c69214e435..99f3056a9a 100644 --- a/ApplicationLibCode/Commands/GeoMechCommands/RicShowFaultReactModelFeature.cpp +++ b/ApplicationLibCode/Commands/GeoMechCommands/RicShowFaultReactModelFeature.cpp @@ -54,15 +54,9 @@ void RicShowFaultReactModelFeature::onActionTriggered( bool isChecked ) if ( model == nullptr ) return; const QString frmTitle( "Fault Reactivation Modeling" ); - const QString exportFile = model->inputFilename(); - if ( !model->extractAndExportModelData() ) - { - QMessageBox::critical( nullptr, frmTitle, "Unable to get necessary data from the input case." ); - return; - } - - auto [result, errText] = RifFaultReactivationModelExporter::exportToFile( exportFile.toStdString(), *model ); + auto exportFile = QString::fromStdString( model->inputFilename() ); + auto [result, errText] = RifFaultReactivationModelExporter::exportToFile( *model ); if ( !result ) { QString outErrorText = diff --git a/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensCreateSessionUi.cpp b/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensCreateSessionUi.cpp index 80766ce294..ccbed05d73 100644 --- a/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensCreateSessionUi.cpp +++ b/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensCreateSessionUi.cpp @@ -24,7 +24,6 @@ #include "RicHoloLensServerSettings.h" #include "cafPdmSettings.h" -#include "cafPdmUiOrdering.h" #include "cvfAssert.h" diff --git a/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensExportToFolderUi.cpp b/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensExportToFolderUi.cpp index 45a63791a3..fd3406b999 100644 --- a/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensExportToFolderUi.cpp +++ b/ApplicationLibCode/Commands/HoloLensCommands/RicHoloLensExportToFolderUi.cpp @@ -25,7 +25,6 @@ #include "RimProject.h" #include "cafPdmUiFilePathEditor.h" -#include "cafPdmUiOrdering.h" CAF_PDM_SOURCE_INIT( RicHoloLensExportToFolderUi, "RicHoloLensExportToFolderUi" ); diff --git a/ApplicationLibCode/Commands/MeasurementCommands/RicMeasurementPickEventHandler.cpp b/ApplicationLibCode/Commands/MeasurementCommands/RicMeasurementPickEventHandler.cpp index 774a8686e4..e8ef60d643 100644 --- a/ApplicationLibCode/Commands/MeasurementCommands/RicMeasurementPickEventHandler.cpp +++ b/ApplicationLibCode/Commands/MeasurementCommands/RicMeasurementPickEventHandler.cpp @@ -19,8 +19,6 @@ #include "RicMeasurementPickEventHandler.h" #include "RiaApplication.h" -#include "RiuViewer.h" -#include "RiuViewerCommands.h" #include "Rim3dView.h" #include "RimExtrudedCurveIntersection.h" @@ -28,13 +26,18 @@ #include "RimMeasurement.h" #include "RimProject.h" -#include "cafDisplayCoordTransform.h" -#include "cafSelectionManager.h" +#include "RiuViewer.h" +#include "RiuViewerCommands.h" #include "RivPartPriority.h" +#include "cafDisplayCoordTransform.h" +#include "cafSelectionManager.h" + #include "cvfPart.h" +#include + #include //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Commands/OperationsUsingObjReferences/RicPasteFeatureImpl.cpp b/ApplicationLibCode/Commands/OperationsUsingObjReferences/RicPasteFeatureImpl.cpp index 71bdef8551..5185d11fbc 100644 --- a/ApplicationLibCode/Commands/OperationsUsingObjReferences/RicPasteFeatureImpl.cpp +++ b/ApplicationLibCode/Commands/OperationsUsingObjReferences/RicPasteFeatureImpl.cpp @@ -33,6 +33,7 @@ #include "cafPdmObjectHandle.h" #include +#include #include #include diff --git a/ApplicationLibCode/Commands/PolygonCommands/CMakeLists_files.cmake b/ApplicationLibCode/Commands/PolygonCommands/CMakeLists_files.cmake new file mode 100644 index 0000000000..c4afbccf2d --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/CMakeLists_files.cmake @@ -0,0 +1,29 @@ +set(SOURCE_GROUP_HEADER_FILES + ${CMAKE_CURRENT_LIST_DIR}/RicCreatePolygonFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicImportPolygonFileFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicReloadPolygonFileFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicDuplicatePolygonFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicExportPolygonCsvFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicExportPolygonPolFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicSimplifyPolygonFeature.h +) + +set(SOURCE_GROUP_SOURCE_FILES + ${CMAKE_CURRENT_LIST_DIR}/RicCreatePolygonFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicImportPolygonFileFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicReloadPolygonFileFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicDuplicatePolygonFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicExportPolygonCsvFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicExportPolygonPolFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicSimplifyPolygonFeature.cpp +) + +list(APPEND COMMAND_CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) + +list(APPEND COMMAND_CODE_SOURCE_FILES ${SOURCE_GROUP_SOURCE_FILES}) + +source_group( + "CommandFeature\\Polygons" + FILES ${SOURCE_GROUP_HEADER_FILES} ${SOURCE_GROUP_SOURCE_FILES} + ${CMAKE_CURRENT_LIST_DIR}/CMakeLists_files.cmake +) diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicCreatePolygonFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicCreatePolygonFeature.cpp new file mode 100644 index 0000000000..1b4770b9ee --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicCreatePolygonFeature.cpp @@ -0,0 +1,60 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicCreatePolygonFeature.h" + +#include "RiaApplication.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonCollection.h" +#include "Polygons/RimPolygonTools.h" +#include "Rim3dView.h" +#include "RimOilField.h" +#include "RimProject.h" + +#include "Riu3DMainWindowTools.h" + +#include + +CAF_CMD_SOURCE_INIT( RicCreatePolygonFeature, "RicCreatePolygonFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicCreatePolygonFeature::onActionTriggered( bool isChecked ) +{ + auto proj = RimProject::current(); + auto polygonCollection = proj->activeOilField()->polygonCollection(); + + auto newPolygon = polygonCollection->appendUserDefinedPolygon(); + polygonCollection->uiCapability()->updateAllRequiredEditors(); + + Riu3DMainWindowTools::setExpanded( newPolygon ); + + auto activeView = RiaApplication::instance()->activeReservoirView(); + RimPolygonTools::activate3dEditOfPolygonInView( newPolygon, activeView ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicCreatePolygonFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Create Polygon" ); + actionToSetup->setIcon( QIcon( ":/PolylinesFromFile16x16.png" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicCreatePolygonFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicCreatePolygonFeature.h new file mode 100644 index 0000000000..414d25f86c --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicCreatePolygonFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicCreatePolygonFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicDuplicatePolygonFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicDuplicatePolygonFeature.cpp new file mode 100644 index 0000000000..7c0101dd7e --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicDuplicatePolygonFeature.cpp @@ -0,0 +1,79 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicDuplicatePolygonFeature.h" + +#include "RiaApplication.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonCollection.h" +#include "Polygons/RimPolygonInView.h" +#include "Polygons/RimPolygonTools.h" +#include "Rim3dView.h" +#include "RimOilField.h" +#include "RimProject.h" + +#include "Riu3DMainWindowTools.h" + +#include "cafSelectionManager.h" +#include + +CAF_CMD_SOURCE_INIT( RicDuplicatePolygonFeature, "RicDuplicatePolygonFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicDuplicatePolygonFeature::onActionTriggered( bool isChecked ) +{ + auto sourcePolygon = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !sourcePolygon ) + { + auto sourcePolygonInView = caf::SelectionManager::instance()->selectedItemOfType(); + if ( sourcePolygonInView ) + { + sourcePolygon = sourcePolygonInView->polygon(); + } + } + + if ( !sourcePolygon ) return; + + auto proj = RimProject::current(); + auto polygonCollection = proj->activeOilField()->polygonCollection(); + + auto newPolygon = polygonCollection->createUserDefinedPolygon(); + newPolygon->setPointsInDomainCoords( sourcePolygon->pointsInDomainCoords() ); + auto sourceName = sourcePolygon->name(); + newPolygon->setName( "Copy of " + sourceName ); + polygonCollection->addUserDefinedPolygon( newPolygon ); + + polygonCollection->uiCapability()->updateAllRequiredEditors(); + + Riu3DMainWindowTools::setExpanded( newPolygon ); + + auto activeView = RiaApplication::instance()->activeReservoirView(); + RimPolygonTools::selectPolygonInView( newPolygon, activeView ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicDuplicatePolygonFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Duplicate Polygon" ); + actionToSetup->setIcon( QIcon( ":/caf/duplicate.svg" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicDuplicatePolygonFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicDuplicatePolygonFeature.h new file mode 100644 index 0000000000..a54a5975fa --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicDuplicatePolygonFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicDuplicatePolygonFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonCsvFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonCsvFeature.cpp new file mode 100644 index 0000000000..64e05b7942 --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonCsvFeature.cpp @@ -0,0 +1,82 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicExportPolygonCsvFeature.h" + +#include "RiaGuiApplication.h" +#include "RiaLogging.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonInView.h" +#include "Polygons/RimPolygonTools.h" + +#include "RiuFileDialogTools.h" + +#include "cafSelectionManager.h" + +#include +#include + +CAF_CMD_SOURCE_INIT( RicExportPolygonCsvFeature, "RicExportPolygonCsvFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicExportPolygonCsvFeature::onActionTriggered( bool isChecked ) +{ + auto sourcePolygon = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !sourcePolygon ) + { + auto sourcePolygonInView = caf::SelectionManager::instance()->selectedItemOfType(); + if ( sourcePolygonInView ) + { + sourcePolygon = sourcePolygonInView->polygon(); + } + } + + if ( !sourcePolygon ) return; + + auto app = RiaGuiApplication::instance(); + auto fallbackPath = app->lastUsedDialogDirectory( "BINARY_GRID" ); + auto polygonPath = app->lastUsedDialogDirectoryWithFallback( RimPolygonTools::polygonCacheName(), fallbackPath ); + auto polygonFileName = polygonPath + "/" + sourcePolygon->name() + ".csv"; + + auto fileName = RiuFileDialogTools::getSaveFileName( nullptr, + "Select File for Polygon Export to CSV", + polygonFileName, + "CSV Files (*.csv);;All files(*.*)" ); + + if ( !RimPolygonTools::exportPolygonCsv( sourcePolygon, fileName ) ) + { + RiaLogging::error( "Failed to export polygon to " + fileName ); + } + else + { + RiaLogging::info( "Completed polygon export to " + fileName ); + app->setLastUsedDialogDirectory( RimPolygonTools::polygonCacheName(), QFileInfo( fileName ).absolutePath() ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicExportPolygonCsvFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Export Polygon CSV" ); + actionToSetup->setIcon( QIcon( ":/Save.svg" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonCsvFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonCsvFeature.h new file mode 100644 index 0000000000..844b87248a --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonCsvFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicExportPolygonCsvFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonPolFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonPolFeature.cpp new file mode 100644 index 0000000000..cfdf1839f4 --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonPolFeature.cpp @@ -0,0 +1,82 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicExportPolygonPolFeature.h" + +#include "RiaGuiApplication.h" +#include "RiaLogging.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonInView.h" +#include "Polygons/RimPolygonTools.h" + +#include "RiuFileDialogTools.h" + +#include "cafSelectionManager.h" + +#include +#include + +CAF_CMD_SOURCE_INIT( RicExportPolygonPolFeature, "RicExportPolygonPolFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicExportPolygonPolFeature::onActionTriggered( bool isChecked ) +{ + auto sourcePolygon = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !sourcePolygon ) + { + auto sourcePolygonInView = caf::SelectionManager::instance()->selectedItemOfType(); + if ( sourcePolygonInView ) + { + sourcePolygon = sourcePolygonInView->polygon(); + } + } + + if ( !sourcePolygon ) return; + + auto app = RiaGuiApplication::instance(); + auto fallbackPath = app->lastUsedDialogDirectory( "BINARY_GRID" ); + auto polygonPath = app->lastUsedDialogDirectoryWithFallback( RimPolygonTools::polygonCacheName(), fallbackPath ); + auto polygonFileName = polygonPath + "/" + sourcePolygon->name() + ".pol"; + + auto fileName = RiuFileDialogTools::getSaveFileName( nullptr, + "Select File for Polygon Export to POL", + polygonFileName, + "POL Files (*.pol);;All files(*.*)" ); + + if ( !RimPolygonTools::exportPolygonPol( sourcePolygon, fileName ) ) + { + RiaLogging::error( "Failed to export polygon to " + fileName ); + } + else + { + RiaLogging::info( "Completed polygon export to " + fileName ); + RiaApplication::instance()->setLastUsedDialogDirectory( RimPolygonTools::polygonCacheName(), QFileInfo( fileName ).absolutePath() ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicExportPolygonPolFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Export Polygon POL" ); + actionToSetup->setIcon( QIcon( ":/Save.svg" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonPolFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonPolFeature.h new file mode 100644 index 0000000000..66f3a7babb --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicExportPolygonPolFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicExportPolygonPolFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicImportPolygonFileFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicImportPolygonFileFeature.cpp new file mode 100644 index 0000000000..f4f1ffc8ed --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicImportPolygonFileFeature.cpp @@ -0,0 +1,87 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicImportPolygonFileFeature.h" + +#include "RiaApplication.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonCollection.h" +#include "Polygons/RimPolygonFile.h" +#include "Polygons/RimPolygonTools.h" +#include "RimOilField.h" +#include "RimProject.h" + +#include "Riu3DMainWindowTools.h" +#include "RiuFileDialogTools.h" + +#include +#include + +CAF_CMD_SOURCE_INIT( RicImportPolygonFileFeature, "RicImportPolygonFileFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicImportPolygonFileFeature::onActionTriggered( bool isChecked ) +{ + RiaApplication* app = RiaApplication::instance(); + + auto fallbackPath = app->lastUsedDialogDirectory( "BINARY_GRID" ); + auto polygonPath = app->lastUsedDialogDirectoryWithFallback( RimPolygonTools::polygonCacheName(), fallbackPath ); + + QStringList fileNames = RiuFileDialogTools::getOpenFileNames( Riu3DMainWindowTools::mainWindowWidget(), + "Import Polygons", + polygonPath, + "Polylines (*.csv *.dat *.pol);;Text Files (*.txt);;Polylines " + "(*.dat);;Polylines (*.pol);;Polylines (*.csv);;All Files (*.*)" ); + + if ( fileNames.isEmpty() ) return; + + // Remember the path to next time + app->setLastUsedDialogDirectory( RimPolygonTools::polygonCacheName(), QFileInfo( fileNames.last() ).absolutePath() ); + + auto proj = RimProject::current(); + auto polygonCollection = proj->activeOilField()->polygonCollection(); + + RimPolygon* objectToSelect = nullptr; + + for ( const auto& filename : fileNames ) + { + auto newPolygonFile = new RimPolygonFile(); + newPolygonFile->setFileName( filename ); + newPolygonFile->loadData(); + polygonCollection->addPolygonFile( newPolygonFile ); + + if ( !newPolygonFile->polygons().empty() ) objectToSelect = newPolygonFile->polygons().front(); + } + + polygonCollection->uiCapability()->updateAllRequiredEditors(); + + Riu3DMainWindowTools::setExpanded( objectToSelect ); + Riu3DMainWindowTools::selectAsCurrentItem( objectToSelect ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicImportPolygonFileFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Import Polygon" ); + actionToSetup->setIcon( QIcon( ":/PolylinesFromFile16x16.png" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicImportPolygonFileFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicImportPolygonFileFeature.h new file mode 100644 index 0000000000..c1309c517a --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicImportPolygonFileFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicImportPolygonFileFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicReloadPolygonFileFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicReloadPolygonFileFeature.cpp new file mode 100644 index 0000000000..b3bb1ff89c --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicReloadPolygonFileFeature.cpp @@ -0,0 +1,51 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicReloadPolygonFileFeature.h" + +#include "Polygons/RimPolygonFile.h" + +#include "cafSelectionManager.h" + +#include + +CAF_CMD_SOURCE_INIT( RicReloadPolygonFileFeature, "RicReloadPolygonFileFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicReloadPolygonFileFeature::onActionTriggered( bool isChecked ) +{ + auto polygonFile = caf::SelectionManager::instance()->selectedItemOfType(); + if ( polygonFile ) + { + polygonFile->loadData(); + polygonFile->objectChanged.send(); + + polygonFile->updateConnectedEditors(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicReloadPolygonFileFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Reload" ); + actionToSetup->setIcon( QIcon( ":/Refresh.svg" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicReloadPolygonFileFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicReloadPolygonFileFeature.h new file mode 100644 index 0000000000..14d4a263a2 --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicReloadPolygonFileFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicReloadPolygonFileFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicSimplifyPolygonFeature.cpp b/ApplicationLibCode/Commands/PolygonCommands/RicSimplifyPolygonFeature.cpp new file mode 100644 index 0000000000..d8695176fc --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicSimplifyPolygonFeature.cpp @@ -0,0 +1,73 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicSimplifyPolygonFeature.h" + +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonInView.h" + +#include "RigCellGeometryTools.h" + +#include "cafSelectionManager.h" + +#include +#include + +CAF_CMD_SOURCE_INIT( RicSimplifyPolygonFeature, "RicSimplifyPolygonFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicSimplifyPolygonFeature::onActionTriggered( bool isChecked ) +{ + auto sourcePolygon = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !sourcePolygon ) + { + auto sourcePolygonInView = caf::SelectionManager::instance()->selectedItemOfType(); + if ( sourcePolygonInView ) + { + sourcePolygon = sourcePolygonInView->polygon(); + } + } + + if ( !sourcePolygon ) return; + + const double defaultEpsilon = 10.0; + + bool ok; + auto epsilon = + QInputDialog::getDouble( nullptr, "Simplify Polygon Threshold", "Threshold:", defaultEpsilon, 1.0, 1000.0, 1, &ok, Qt::WindowFlags(), 1 ); + + if ( ok ) + { + auto coords = sourcePolygon->pointsInDomainCoords(); + RigCellGeometryTools::simplifyPolygon( &coords, epsilon ); + + sourcePolygon->setPointsInDomainCoords( coords ); + sourcePolygon->coordinatesChanged.send(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicSimplifyPolygonFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Simplify Polygon" ); + actionToSetup->setIcon( QIcon( ":/PolylinesFromFile16x16.png" ) ); +} diff --git a/ApplicationLibCode/Commands/PolygonCommands/RicSimplifyPolygonFeature.h b/ApplicationLibCode/Commands/PolygonCommands/RicSimplifyPolygonFeature.h new file mode 100644 index 0000000000..1b74d5876c --- /dev/null +++ b/ApplicationLibCode/Commands/PolygonCommands/RicSimplifyPolygonFeature.h @@ -0,0 +1,33 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" + +//================================================================================================== +/// +//================================================================================================== +class RicSimplifyPolygonFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/Commands/RicCopyGridStatisticsToClipboardFeature.cpp b/ApplicationLibCode/Commands/RicCopyGridStatisticsToClipboardFeature.cpp index 665ff94603..c0d3f023e8 100644 --- a/ApplicationLibCode/Commands/RicCopyGridStatisticsToClipboardFeature.cpp +++ b/ApplicationLibCode/Commands/RicCopyGridStatisticsToClipboardFeature.cpp @@ -18,7 +18,7 @@ #include "RicCopyGridStatisticsToClipboardFeature.h" -#include "RiaApplication.h" +#include "RiaGuiApplication.h" #include "RicWellLogTools.h" diff --git a/ApplicationLibCode/Commands/RicCreateEnsembleSurfaceUi.cpp b/ApplicationLibCode/Commands/RicCreateEnsembleSurfaceUi.cpp index f29e549794..49b2dbec12 100644 --- a/ApplicationLibCode/Commands/RicCreateEnsembleSurfaceUi.cpp +++ b/ApplicationLibCode/Commands/RicCreateEnsembleSurfaceUi.cpp @@ -22,7 +22,6 @@ #include "cafPdmObject.h" #include "cafPdmUiCheckBoxEditor.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeSelectionEditor.h" CAF_PDM_SOURCE_INIT( RicCreateEnsembleSurfaceUi, "RicCreateEnsembleSurfaceUi" ); diff --git a/ApplicationLibCode/Commands/RicCreateEnsembleWellLogUi.cpp b/ApplicationLibCode/Commands/RicCreateEnsembleWellLogUi.cpp index f486cf5dda..4d81c07d67 100644 --- a/ApplicationLibCode/Commands/RicCreateEnsembleWellLogUi.cpp +++ b/ApplicationLibCode/Commands/RicCreateEnsembleWellLogUi.cpp @@ -34,7 +34,6 @@ #include "cafPdmObject.h" #include "cafPdmUiCheckBoxEditor.h" #include "cafPdmUiFilePathEditor.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeSelectionEditor.h" CAF_PDM_SOURCE_INIT( RicCreateEnsembleWellLogUi, "RicCreateEnsembleWellLogUi" ); diff --git a/ApplicationLibCode/Commands/RicCreateTemporaryLgrFeature.cpp b/ApplicationLibCode/Commands/RicCreateTemporaryLgrFeature.cpp index 27d9a7cfa5..f85f08aeca 100644 --- a/ApplicationLibCode/Commands/RicCreateTemporaryLgrFeature.cpp +++ b/ApplicationLibCode/Commands/RicCreateTemporaryLgrFeature.cpp @@ -322,7 +322,7 @@ void RicCreateTemporaryLgrFeature::computeCachedData( RimEclipseCase* eclipseCas if ( eclipseCaseData ) { eclipseCaseData->mainGrid()->computeCachedData(); - eclipseCaseData->computeActiveCellBoundingBoxes(); + eclipseCase->computeActiveCellsBoundingBox(); } if ( cellResultsDataMatrix ) diff --git a/ApplicationLibCode/Commands/RicDeleteTemporaryLgrsFeature.cpp b/ApplicationLibCode/Commands/RicDeleteTemporaryLgrsFeature.cpp index 0aadabafa3..92d4400886 100644 --- a/ApplicationLibCode/Commands/RicDeleteTemporaryLgrsFeature.cpp +++ b/ApplicationLibCode/Commands/RicDeleteTemporaryLgrsFeature.cpp @@ -41,7 +41,7 @@ void RicDeleteTemporaryLgrsFeature::deleteAllTemporaryLgrs( RimEclipseCase* ecli if ( eclipseCase ) { - RimReloadCaseTools::reloadAllEclipseGridData( eclipseCase ); + RimReloadCaseTools::reloadEclipseGrid( eclipseCase ); } } diff --git a/ApplicationLibCode/Commands/RicImportElementPropertyFeature.cpp b/ApplicationLibCode/Commands/RicImportElementPropertyFeature.cpp index 2449949ee2..3560318b0b 100644 --- a/ApplicationLibCode/Commands/RicImportElementPropertyFeature.cpp +++ b/ApplicationLibCode/Commands/RicImportElementPropertyFeature.cpp @@ -28,6 +28,8 @@ #include "RiuFileDialogTools.h" +#include "cafSelectionManagerTools.h" + #include #include @@ -38,14 +40,37 @@ CAF_CMD_SOURCE_INIT( RicImportElementPropertyFeature, "RicImportElementPropertyF //-------------------------------------------------------------------------------------------------- void RicImportElementPropertyFeature::onActionTriggered( bool isChecked ) { - importElementProperties(); + std::vector uiItems; + caf::SelectionManager::instance()->selectedItems( uiItems ); + + RimGeoMechCase* geomCase = nullptr; + + if ( !uiItems.empty() ) + { + geomCase = dynamic_cast( uiItems[0] ); + } + + if ( geomCase == nullptr ) + { + Rim3dView* activeView = RiaApplication::instance()->activeReservoirView(); + if ( !activeView ) return; + + RimGeoMechView* activeGmv = dynamic_cast( activeView ); + if ( !activeGmv ) return; + + geomCase = activeGmv->geoMechCase(); + } + + importElementProperties( geomCase ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RicImportElementPropertyFeature::importElementProperties() +void RicImportElementPropertyFeature::importElementProperties( RimGeoMechCase* pCase ) { + if ( pCase == nullptr ) return; + RiaApplication* app = RiaApplication::instance(); QString defaultDir = app->lastUsedDialogDirectory( "ELM_PROPS" ); @@ -65,16 +90,7 @@ void RicImportElementPropertyFeature::importElementProperties() app->setLastUsedDialogDirectory( "ELM_PROPS", defaultDir ); - Rim3dView* activeView = RiaApplication::instance()->activeReservoirView(); - if ( !activeView ) return; - - RimGeoMechView* activeGmv = dynamic_cast( activeView ); - if ( !activeGmv ) return; - - if ( activeGmv->geoMechCase() ) - { - activeGmv->geoMechCase()->addElementPropertyFiles( filePaths ); - } + pCase->addElementPropertyFiles( filePaths ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Commands/RicImportElementPropertyFeature.h b/ApplicationLibCode/Commands/RicImportElementPropertyFeature.h index 064c2a026e..acedefa6e4 100644 --- a/ApplicationLibCode/Commands/RicImportElementPropertyFeature.h +++ b/ApplicationLibCode/Commands/RicImportElementPropertyFeature.h @@ -20,6 +20,8 @@ #include "cafCmdFeature.h" +class RimGeoMechCase; + //================================================================================================== /// //================================================================================================== @@ -27,7 +29,7 @@ class RicImportElementPropertyFeature : public caf::CmdFeature { CAF_CMD_HEADER_INIT; - static void importElementProperties(); + static void importElementProperties( RimGeoMechCase* pCase ); protected: void onActionTriggered( bool isChecked ) override; diff --git a/ApplicationLibCode/Commands/RicImportGeneralDataFeature.cpp b/ApplicationLibCode/Commands/RicImportGeneralDataFeature.cpp index 403986e172..822ca97660 100644 --- a/ApplicationLibCode/Commands/RicImportGeneralDataFeature.cpp +++ b/ApplicationLibCode/Commands/RicImportGeneralDataFeature.cpp @@ -60,6 +60,7 @@ RicImportGeneralDataFeature::OpenCaseResults QStringList eclipseInputFiles; QStringList eclipseSummaryFiles; QStringList roffFiles; + QStringList emFiles; for ( const QString& fileName : fileNames ) { @@ -80,6 +81,10 @@ RicImportGeneralDataFeature::OpenCaseResults { roffFiles.push_back( fileName ); } + else if ( fileTypeAsInt & int( ImportFileType::EM_H5GRID ) ) + { + emFiles.push_back( fileName ); + } } OpenCaseResults results; @@ -120,6 +125,14 @@ RicImportGeneralDataFeature::OpenCaseResults RiaApplication::instance()->setLastUsedDialogDirectory( defaultDirectoryLabel( ImportFileType::ROFF_FILE ), defaultDir ); } + if ( !emFiles.empty() ) + { + if ( !RiaImportEclipseCaseTools::openEmFilesFromFileNames( emFiles, createDefaultView, results.createdCaseIds ) ) + { + return OpenCaseResults(); + } + } + return results; } diff --git a/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.cpp b/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.cpp index eb66a3977e..3cb9abbd5c 100644 --- a/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.cpp +++ b/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.cpp @@ -18,64 +18,26 @@ #include "RicImportGridModelFromSummaryCaseFeature.h" -#include "ApplicationCommands/RicShowMainWindowFeature.h" - -#include "RiaEclipseFileNameTools.h" #include "RiaImportEclipseCaseTools.h" -#include "RiaLogging.h" #include "RimEclipseCase.h" #include "RimFileSummaryCase.h" -#include "RimGridView.h" -#include "RimProject.h" - -#include "Riu3DMainWindowTools.h" +#include "RimReloadCaseTools.h" #include "cafSelectionManager.h" #include -#include CAF_CMD_SOURCE_INIT( RicImportGridModelFromSummaryCaseFeature, "RicImportGridModelFromSummaryCaseFeature" ); -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RicImportGridModelFromSummaryCaseFeature::openOrImportGridModelFromSummaryCase( const RimFileSummaryCase* summaryCase ) -{ - if ( !summaryCase ) return false; - - if ( findAndActivateFirstView( summaryCase ) ) return true; - - QString summaryFileName = summaryCase->summaryHeaderFilename(); - RiaEclipseFileNameTools fileHelper( summaryFileName ); - auto candidateGridFileName = fileHelper.findRelatedGridFile(); - - if ( QFileInfo::exists( candidateGridFileName ) ) - { - bool createView = true; - auto id = RiaImportEclipseCaseTools::openEclipseCaseFromFile( candidateGridFileName, createView ); - if ( id > -1 ) - { - RiaLogging::info( QString( "Imported %1" ).arg( candidateGridFileName ) ); - - return true; - } - } - - RiaLogging::info( QString( "No grid case found based on summary file %1" ).arg( summaryFileName ) ); - - return false; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RicImportGridModelFromSummaryCaseFeature::onActionTriggered( bool isChecked ) { - RimFileSummaryCase* summaryCase = caf::SelectionManager::instance()->selectedItemOfType(); + auto* summaryCase = caf::SelectionManager::instance()->selectedItemOfType(); - openOrImportGridModelFromSummaryCase( summaryCase ); + RimReloadCaseTools::openOrImportGridModelFromSummaryCase( summaryCase ); } //-------------------------------------------------------------------------------------------------- @@ -85,13 +47,13 @@ void RicImportGridModelFromSummaryCaseFeature::setupActionLook( QAction* actionT { actionToSetup->setIcon( QIcon( ":/3DWindow.svg" ) ); - RimFileSummaryCase* summaryCase = caf::SelectionManager::instance()->selectedItemOfType(); + auto* summaryCase = caf::SelectionManager::instance()->selectedItemOfType(); QString summaryCaseName; if ( summaryCase ) summaryCaseName = summaryCase->caseName(); QString txt; - auto gridCase = gridModelFromSummaryCase( summaryCase ); + auto gridCase = RimReloadCaseTools::gridModelFromSummaryCase( summaryCase ); if ( gridCase ) { txt = "Open Grid Model View"; @@ -108,44 +70,3 @@ void RicImportGridModelFromSummaryCaseFeature::setupActionLook( QAction* actionT actionToSetup->setText( txt ); } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RicImportGridModelFromSummaryCaseFeature::findAndActivateFirstView( const RimFileSummaryCase* summaryCase ) -{ - auto gridCase = gridModelFromSummaryCase( summaryCase ); - if ( gridCase ) - { - if ( !gridCase->gridViews().empty() ) - { - RicShowMainWindowFeature::showMainWindow(); - - Riu3DMainWindowTools::selectAsCurrentItem( gridCase->gridViews().front() ); - - return true; - } - } - - return false; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimEclipseCase* RicImportGridModelFromSummaryCaseFeature::gridModelFromSummaryCase( const RimSummaryCase* summaryCase ) -{ - if ( summaryCase ) - { - QString summaryFileName = summaryCase->summaryHeaderFilename(); - RiaEclipseFileNameTools fileHelper( summaryFileName ); - auto candidateGridFileName = fileHelper.findRelatedGridFile(); - - RimProject* project = RimProject::current(); - auto gridCase = project->eclipseCaseFromGridFileName( candidateGridFileName ); - - return gridCase; - } - - return nullptr; -} diff --git a/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.h b/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.h index d2c43ac6dd..5649061f32 100644 --- a/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.h +++ b/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCaseFeature.h @@ -31,13 +31,7 @@ class RicImportGridModelFromSummaryCaseFeature : public caf::CmdFeature { CAF_CMD_HEADER_INIT; -public: - static bool openOrImportGridModelFromSummaryCase( const RimFileSummaryCase* summaryCase ); - static RimEclipseCase* gridModelFromSummaryCase( const RimSummaryCase* summaryCase ); - protected: void onActionTriggered( bool isChecked ) override; void setupActionLook( QAction* actionToSetup ) override; - - static bool findAndActivateFirstView( const RimFileSummaryCase* summaryCase ); }; diff --git a/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCurveFeature.cpp b/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCurveFeature.cpp index 80842ec680..1d36cf7887 100644 --- a/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCurveFeature.cpp +++ b/ApplicationLibCode/Commands/RicImportGridModelFromSummaryCurveFeature.cpp @@ -18,10 +18,9 @@ #include "RicImportGridModelFromSummaryCurveFeature.h" -#include "RicImportGridModelFromSummaryCaseFeature.h" - #include "RimFileSummaryCase.h" #include "RimProject.h" +#include "RimReloadCaseTools.h" #include "cafSelectionManager.h" @@ -44,11 +43,9 @@ void RicImportGridModelFromSummaryCurveFeature::onActionTriggered( bool isChecke { if ( sumCase->caseId() == summaryCaseId ) { - auto fileSummaryCase = dynamic_cast( sumCase ); - - if ( fileSummaryCase ) + if ( auto fileSummaryCase = dynamic_cast( sumCase ) ) { - RicImportGridModelFromSummaryCaseFeature::openOrImportGridModelFromSummaryCase( fileSummaryCase ); + RimReloadCaseTools::openOrImportGridModelFromSummaryCase( fileSummaryCase ); return; } diff --git a/ApplicationLibCode/Commands/RicImportWellLogCsvFileFeature.cpp b/ApplicationLibCode/Commands/RicImportWellLogCsvFileFeature.cpp new file mode 100644 index 0000000000..18b963e8e0 --- /dev/null +++ b/ApplicationLibCode/Commands/RicImportWellLogCsvFileFeature.cpp @@ -0,0 +1,98 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicImportWellLogCsvFileFeature.h" + +#include "RiaGuiApplication.h" +#include "RiaLogging.h" + +#include "RimOilField.h" +#include "RimProject.h" +#include "RimWellLogCsvFile.h" +#include "RimWellPath.h" +#include "RimWellPathCollection.h" + +#include "Riu3DMainWindowTools.h" +#include "RiuFileDialogTools.h" + +#include "cafSelectionManager.h" + +#include +#include + +CAF_CMD_SOURCE_INIT( RicImportWellLogCsvFileFeature, "RicImportWellLogCsvFileFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RicImportWellLogCsvFileFeature::isCommandEnabled() const +{ + return caf::SelectionManager::instance()->selectedItemOfType() != nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicImportWellLogCsvFileFeature::onActionTriggered( bool isChecked ) +{ + QString pathCacheName = "WELL_LOGS_DIR"; + + if ( auto wellPath = caf::SelectionManager::instance()->selectedItemOfType() ) + { + RiaGuiApplication* app = RiaGuiApplication::instance(); + + QString defaultDir = app->lastUsedDialogDirectory( pathCacheName ); + QString fileName = + RiuFileDialogTools::getOpenFileName( nullptr, "Open Well Log CSV", defaultDir, "Well Log csv (*.csv);;All files(*.*)" ); + + if ( fileName.isEmpty() ) return; + + RimOilField* oilField = RimProject::current()->activeOilField(); + if ( oilField == nullptr ) return; + + if ( !oilField->wellPathCollection ) oilField->wellPathCollection = std::make_unique(); + + RimWellLogCsvFile* wellLogCsvFile = new RimWellLogCsvFile; + wellLogCsvFile->setFileName( fileName ); + oilField->wellPathCollection->addWellLog( wellLogCsvFile, wellPath ); + + QString errorMessage; + if ( !wellLogCsvFile->readFile( &errorMessage ) ) + { + wellPath->deleteWellLogFile( wellLogCsvFile ); + QString displayMessage = "Errors opening the CSV file: \n" + errorMessage; + RiaLogging::errorInMessageBox( Riu3DMainWindowTools::mainWindowWidget(), "File open error", displayMessage ); + return; + } + else + { + wellLogCsvFile->updateConnectedEditors(); + } + + app->setLastUsedDialogDirectory( pathCacheName, QFileInfo( fileName ).absolutePath() ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicImportWellLogCsvFileFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setIcon( QIcon( ":/LasFile16x16.png" ) ); + actionToSetup->setText( "Import Well Log From CSV" ); +} diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicAppendPointsToPolygonFilterFeature.h b/ApplicationLibCode/Commands/RicImportWellLogCsvFileFeature.h similarity index 91% rename from ApplicationLibCode/Commands/WellPathCommands/RicAppendPointsToPolygonFilterFeature.h rename to ApplicationLibCode/Commands/RicImportWellLogCsvFileFeature.h index 35cee0a6c5..a9f79e291c 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/RicAppendPointsToPolygonFilterFeature.h +++ b/ApplicationLibCode/Commands/RicImportWellLogCsvFileFeature.h @@ -1,6 +1,6 @@ ///////////////////////////////////////////////////////////////////////////////// // -// Copyright (C) 2021- Equinor ASA +// Copyright (C) 2023- Equinor ASA // // ResInsight is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by @@ -23,7 +23,7 @@ //================================================================================================== /// //================================================================================================== -class RicAppendPointsToPolygonFilterFeature : public caf::CmdFeature +class RicImportWellLogCsvFileFeature : public caf::CmdFeature { CAF_CMD_HEADER_INIT; diff --git a/ApplicationLibCode/Commands/RicNewContourMapViewFeature.cpp b/ApplicationLibCode/Commands/RicNewContourMapViewFeature.cpp index 8611c14ec1..5793c615c0 100644 --- a/ApplicationLibCode/Commands/RicNewContourMapViewFeature.cpp +++ b/ApplicationLibCode/Commands/RicNewContourMapViewFeature.cpp @@ -68,7 +68,7 @@ bool RicNewContourMapViewFeature::isCommandEnabled() const bool selectedCase = caf::SelectionManager::instance()->selectedItemOfType() != nullptr; RimGeoMechView* gmView = caf::SelectionManager::instance()->selectedItemOfType(); - if ( gmView ) + if ( gmView && gmView->femParts() ) { // if we have more than one geomech part, contour maps does not work with the current implementation if ( gmView->femParts()->partCount() > 1 ) return false; diff --git a/ApplicationLibCode/Commands/RicReloadCaseFeature.cpp b/ApplicationLibCode/Commands/RicReloadCaseFeature.cpp index a0fe62c8c4..c7d2bc744e 100644 --- a/ApplicationLibCode/Commands/RicReloadCaseFeature.cpp +++ b/ApplicationLibCode/Commands/RicReloadCaseFeature.cpp @@ -70,7 +70,7 @@ void RicReloadCaseFeature::onActionTriggered( bool isChecked ) timeStepFilter[0]->clearFilteredTimeSteps(); } - RimReloadCaseTools::reloadAllEclipseData( selectedCase ); + RimReloadCaseTools::reloadEclipseGridAndSummary( selectedCase ); selectedCase->updateConnectedEditors(); } } diff --git a/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.cpp b/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.cpp index 83eb9c676c..a8b33df69c 100644 --- a/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.cpp +++ b/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.cpp @@ -20,17 +20,12 @@ #include "RiaLogging.h" #include "RiaSummaryTools.h" -#include "RicReplaceSummaryCaseFeature.h" -#include "RimMainPlotCollection.h" #include "RimObservedDataCollection.h" #include "RimObservedSummaryData.h" #include "RimSummaryCase.h" #include "RimSummaryCaseCollection.h" #include "RimSummaryCaseMainCollection.h" -#include "RimSummaryMultiPlot.h" -#include "RimSummaryMultiPlotCollection.h" -#include "RimSummaryPlot.h" #include "cafPdmObject.h" #include "cafSelectionManager.h" @@ -39,18 +34,6 @@ CAF_CMD_SOURCE_INIT( RicReloadSummaryCaseFeature, "RicReloadSummaryCaseFeature" ); -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RicReloadSummaryCaseFeature::reloadSummaryCase( RimSummaryCase* summaryCase ) -{ - summaryCase->createSummaryReaderInterface(); - summaryCase->createRftReaderInterface(); - summaryCase->refreshMetaData(); - - RicReplaceSummaryCaseFeature::updateRequredCalculatedCurves( summaryCase ); -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -69,12 +52,10 @@ void RicReloadSummaryCaseFeature::onActionTriggered( bool isChecked ) std::vector caseSelection = selectedSummaryCases(); for ( RimSummaryCase* summaryCase : caseSelection ) { - reloadSummaryCase( summaryCase ); + RiaSummaryTools::reloadSummaryCase( summaryCase ); RiaLogging::info( QString( "Reloaded data for %1" ).arg( summaryCase->summaryHeaderFilename() ) ); } - - RimMainPlotCollection::current()->loadDataAndUpdateAllPlots(); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.h b/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.h index fd8b1bdec3..d756c8462e 100644 --- a/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.h +++ b/ApplicationLibCode/Commands/RicReloadSummaryCaseFeature.h @@ -28,9 +28,6 @@ class RicReloadSummaryCaseFeature : public caf::CmdFeature { CAF_CMD_HEADER_INIT; -public: - static void reloadSummaryCase( RimSummaryCase* summaryCase ); - protected: bool isCommandEnabled() const override; void onActionTriggered( bool isChecked ) override; diff --git a/ApplicationLibCode/Commands/RicReplaceCaseFeature.cpp b/ApplicationLibCode/Commands/RicReplaceCaseFeature.cpp index 2eba90951f..0384407d82 100644 --- a/ApplicationLibCode/Commands/RicReplaceCaseFeature.cpp +++ b/ApplicationLibCode/Commands/RicReplaceCaseFeature.cpp @@ -19,6 +19,7 @@ #include "RicReplaceCaseFeature.h" +#include "RiaEclipseFileNameTools.h" #include "RiaGuiApplication.h" #include "RiaSummaryTools.h" @@ -41,6 +42,7 @@ #include #include +#include CAF_CMD_SOURCE_INIT( RicReplaceCaseFeature, "RicReplaceCaseFeature" ); @@ -67,54 +69,54 @@ bool RicReplaceCaseFeature::isCommandEnabled() const //-------------------------------------------------------------------------------------------------- void RicReplaceCaseFeature::onActionTriggered( bool isChecked ) { - std::vector selectedEclipseCases; - caf::SelectionManager::instance()->objectsByType( &selectedEclipseCases ); + auto eclipseResultCase = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !eclipseResultCase ) return; + + auto summaryCase = RimReloadCaseTools::findSummaryCaseFromEclipseResultCase( eclipseResultCase ); RiaGuiApplication::clearAllSelections(); const QStringList fileNames = RicImportGeneralDataFeature::getEclipseFileNamesWithDialog( RiaDefines::ImportFileType::ECLIPSE_RESULT_GRID ); if ( fileNames.isEmpty() ) return; - const QString fileName = fileNames[0]; + const auto& fileName = fileNames.front(); + + eclipseResultCase->setGridFileName( fileName ); + eclipseResultCase->reloadEclipseGridFile(); - for ( RimEclipseResultCase* selectedCase : selectedEclipseCases ) + std::vector timeStepFilter = eclipseResultCase->descendantsIncludingThisOfType(); + if ( timeStepFilter.size() == 1 ) { - selectedCase->setGridFileName( fileName ); - selectedCase->reloadEclipseGridFile(); + timeStepFilter[0]->clearFilteredTimeSteps(); + } - std::vector timeStepFilter = selectedCase->descendantsIncludingThisOfType(); - if ( timeStepFilter.size() == 1 ) - { - timeStepFilter[0]->clearFilteredTimeSteps(); - } + RimReloadCaseTools::reloadEclipseGrid( eclipseResultCase ); + eclipseResultCase->updateConnectedEditors(); - RimReloadCaseTools::reloadAllEclipseData( selectedCase ); - selectedCase->updateConnectedEditors(); + // Use the file base name as case user description + QFileInfo fileInfoNew( fileName ); + eclipseResultCase->setCaseUserDescription( fileInfoNew.baseName() ); - // Use the file base name as case user description - QFileInfo fi( fileName ); - selectedCase->setCaseUserDescription( fi.baseName() ); + RiaEclipseFileNameTools helper( fileName ); + auto summaryFileNames = helper.findSummaryFileCandidates(); + if ( summaryCase && !summaryFileNames.empty() ) + { + QMessageBox msgBox; + msgBox.setIcon( QMessageBox::Question ); + + QString questionText; + questionText = QString( + "Found an open summary case for the same reservoir model.\n\nDo you want to replace the file name for the summary case?" ); - // Find and update attached grid summary cases. - RimSummaryCaseMainCollection* sumCaseColl = RiaSummaryTools::summaryCaseMainCollection(); - if ( sumCaseColl ) + msgBox.setText( questionText ); + msgBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No ); + + int ret = msgBox.exec(); + if ( ret == QMessageBox::Yes ) { - auto summaryCase = sumCaseColl->findSummaryCaseFromEclipseResultCase( selectedCase ); - if ( summaryCase ) - { - summaryCase->updateAutoShortName(); - summaryCase->createSummaryReaderInterface(); - summaryCase->createRftReaderInterface(); - - RimSummaryMultiPlotCollection* summaryPlotColl = RiaSummaryTools::summaryMultiPlotCollection(); - for ( RimSummaryMultiPlot* multiPlot : summaryPlotColl->multiPlots() ) - { - for ( RimSummaryPlot* summaryPlot : multiPlot->summaryPlots() ) - { - summaryPlot->loadDataAndUpdate(); - } - } - } + summaryCase->setSummaryHeaderFileName( summaryFileNames.front() ); + + RiaSummaryTools::reloadSummaryCase( summaryCase ); } } } diff --git a/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.cpp b/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.cpp index c32d9f08f4..a6203ac131 100644 --- a/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.cpp +++ b/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.cpp @@ -18,57 +18,31 @@ #include "RicReplaceSummaryCaseFeature.h" +#include "RiaEclipseFileNameTools.h" #include "RiaLogging.h" #include "RiaSummaryTools.h" #include "RicImportGeneralDataFeature.h" +#include "RimEclipseCase.h" #include "RimFileSummaryCase.h" -#include "RimProject.h" -#include "RimSummaryAddress.h" -#include "RimSummaryCalculation.h" -#include "RimSummaryCalculationCollection.h" -#include "RimSummaryCalculationVariable.h" -#include "RimSummaryCase.h" -#include "RimSummaryCaseCollection.h" -#include "RimSummaryCaseMainCollection.h" -#include "RimSummaryCurve.h" -#include "RimSummaryMultiPlot.h" -#include "RimSummaryMultiPlotCollection.h" -#include "RimSummaryPlot.h" +#include "RimReloadCaseTools.h" #include "cafPdmObject.h" #include "cafSelectionManager.h" #include +#include +#include CAF_CMD_SOURCE_INIT( RicReplaceSummaryCaseFeature, "RicReplaceSummaryCaseFeature" ); -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RicReplaceSummaryCaseFeature::updateRequredCalculatedCurves( RimSummaryCase* sourceSummaryCase ) -{ - RimSummaryCalculationCollection* calcColl = RimProject::current()->calculationCollection(); - - for ( RimUserDefinedCalculation* summaryCalculation : calcColl->calculations() ) - { - bool needsUpdate = RicReplaceSummaryCaseFeature::checkIfCalculationNeedsUpdate( summaryCalculation, sourceSummaryCase ); - if ( needsUpdate ) - { - summaryCalculation->parseExpression(); - summaryCalculation->calculate(); - summaryCalculation->updateDependentObjects(); - } - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- bool RicReplaceSummaryCaseFeature::isCommandEnabled() const { - RimSummaryCase* rimSummaryCase = caf::SelectionManager::instance()->selectedItemOfType(); + auto rimSummaryCase = caf::SelectionManager::instance()->selectedItemOfType(); return rimSummaryCase != nullptr; } @@ -77,44 +51,48 @@ bool RicReplaceSummaryCaseFeature::isCommandEnabled() const //-------------------------------------------------------------------------------------------------- void RicReplaceSummaryCaseFeature::onActionTriggered( bool isChecked ) { - RimFileSummaryCase* summaryCase = caf::SelectionManager::instance()->selectedItemOfType(); + auto* summaryCase = caf::SelectionManager::instance()->selectedItemOfType(); if ( !summaryCase ) return; const QStringList fileNames = RicImportGeneralDataFeature::getEclipseFileNamesWithDialog( RiaDefines::ImportFileType::ECLIPSE_SUMMARY_FILE ); if ( fileNames.isEmpty() ) return; + auto gridModel = RimReloadCaseTools::gridModelFromSummaryCase( summaryCase ); + QString oldSummaryHeaderFilename = summaryCase->summaryHeaderFilename(); - summaryCase->setSummaryHeaderFileName( fileNames[0] ); - summaryCase->updateAutoShortName(); - summaryCase->createSummaryReaderInterface(); - summaryCase->createRftReaderInterface(); - summaryCase->refreshMetaData(); - RiaLogging::info( QString( "Replaced summary data for %1" ).arg( oldSummaryHeaderFilename ) ); + const auto& newFileName = fileNames.front(); + summaryCase->setSummaryHeaderFileName( newFileName ); + RiaSummaryTools::reloadSummaryCase( summaryCase ); - RicReplaceSummaryCaseFeature::updateRequredCalculatedCurves( summaryCase ); + RiaLogging::info( QString( "Replaced summary data for %1" ).arg( oldSummaryHeaderFilename ) ); - // Find and update all changed calculations - std::set ids; - RimSummaryCalculationCollection* calcColl = RimProject::current()->calculationCollection(); - for ( RimUserDefinedCalculation* summaryCalculation : calcColl->calculations() ) + RiaEclipseFileNameTools helper( newFileName ); + auto newGridFileName = helper.findRelatedGridFile(); + if ( gridModel && !newGridFileName.isEmpty() ) { - bool needsUpdate = checkIfCalculationNeedsUpdate( summaryCalculation, summaryCase ); - if ( needsUpdate ) - { - ids.insert( summaryCalculation->id() ); - } - } + QMessageBox msgBox; + msgBox.setIcon( QMessageBox::Question ); - RimSummaryMultiPlotCollection* summaryPlotColl = RiaSummaryTools::summaryMultiPlotCollection(); - for ( RimSummaryMultiPlot* multiPlot : summaryPlotColl->multiPlots() ) - { - for ( RimSummaryPlot* summaryPlot : multiPlot->summaryPlots() ) + QString questionText; + questionText = + QString( "Found an open grid case for the same reservoir model.\n\nDo you want to replace the file name in the grid case?" ); + + msgBox.setText( questionText ); + msgBox.setStandardButtons( QMessageBox::Yes | QMessageBox::No ); + + int ret = msgBox.exec(); + if ( ret == QMessageBox::Yes ) { - summaryPlot->loadDataAndUpdate(); + auto previousGridFileName = gridModel->gridFileName(); + + gridModel->setGridFileName( newGridFileName ); + + RimReloadCaseTools::reloadEclipseGrid( gridModel ); + + RiaLogging::info( QString( "Replaced grid data for %1" ).arg( previousGridFileName ) ); } - multiPlot->updatePlotTitles(); } } @@ -126,22 +104,3 @@ void RicReplaceSummaryCaseFeature::setupActionLook( QAction* actionToSetup ) actionToSetup->setText( "Replace" ); actionToSetup->setIcon( QIcon( ":/ReplaceCase16x16.png" ) ); } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RicReplaceSummaryCaseFeature::checkIfCalculationNeedsUpdate( const RimUserDefinedCalculation* summaryCalculation, - const RimSummaryCase* summaryCase ) -{ - std::vector variables = summaryCalculation->allVariables(); - for ( RimUserDefinedCalculationVariable* variable : variables ) - { - RimSummaryCalculationVariable* summaryVariable = dynamic_cast( variable ); - if ( summaryVariable->summaryCase() == summaryCase ) - { - return true; - } - } - - return false; -} diff --git a/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.h b/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.h index e4ecee7bef..188483a3e9 100644 --- a/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.h +++ b/ApplicationLibCode/Commands/RicReplaceSummaryCaseFeature.h @@ -27,13 +27,8 @@ class RicReplaceSummaryCaseFeature : public caf::CmdFeature { CAF_CMD_HEADER_INIT; -public: - static void updateRequredCalculatedCurves( RimSummaryCase* sourceSummaryCase ); - protected: bool isCommandEnabled() const override; void onActionTriggered( bool isChecked ) override; void setupActionLook( QAction* actionToSetup ) override; - - static bool checkIfCalculationNeedsUpdate( const RimUserDefinedCalculation* summaryCalculation, const RimSummaryCase* summaryCase ); }; diff --git a/ApplicationLibCode/Commands/RicUserDefinedCalculatorUi.cpp b/ApplicationLibCode/Commands/RicUserDefinedCalculatorUi.cpp index 771f36f912..af596fcd5c 100644 --- a/ApplicationLibCode/Commands/RicUserDefinedCalculatorUi.cpp +++ b/ApplicationLibCode/Commands/RicUserDefinedCalculatorUi.cpp @@ -91,7 +91,9 @@ bool RicUserDefinedCalculatorUi::parseExpression() const notifyCalculatedNameChanged( m_currentCalculation()->id(), currentCurveName ); } - m_currentCalculation()->updateDependentObjects(); + // Always rebuild the case meta data after parsing the expression. A change in name or change in result type will require rebuild of + // case metadata. The rebuild is considered lightweight and should not be a performance issue. + calculationCollection()->rebuildCaseMetaData(); } return true; @@ -198,8 +200,7 @@ void RicUserDefinedCalculatorUi::assignPushButtonEditor( caf::PdmFieldHandle* fi CAF_ASSERT( fieldHandle ); CAF_ASSERT( fieldHandle->uiCapability() ); - fieldHandle->uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - fieldHandle->uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( fieldHandle ); } //-------------------------------------------------------------------------------------------------- @@ -221,17 +222,7 @@ bool RicUserDefinedCalculatorUi::calculate() const { if ( m_currentCalculation() ) { - QString previousCurveName = m_currentCalculation->description(); - if ( !m_currentCalculation()->parseExpression() ) - { - return false; - } - - QString currentCurveName = m_currentCalculation->description(); - if ( previousCurveName != currentCurveName ) - { - notifyCalculatedNameChanged( m_currentCalculation()->id(), currentCurveName ); - } + if ( !parseExpression() ) return false; if ( !m_currentCalculation()->preCalculate() ) { diff --git a/ApplicationLibCode/Commands/SeismicCommands/RicNewSeismicDifferenceFeature.cpp b/ApplicationLibCode/Commands/SeismicCommands/RicNewSeismicDifferenceFeature.cpp index 9e0b15332b..39df6fa9da 100644 --- a/ApplicationLibCode/Commands/SeismicCommands/RicNewSeismicDifferenceFeature.cpp +++ b/ApplicationLibCode/Commands/SeismicCommands/RicNewSeismicDifferenceFeature.cpp @@ -18,7 +18,7 @@ #include "RicNewSeismicDifferenceFeature.h" -#include "RiaApplication.h" +#include "RiaGuiApplication.h" #include "RimOilField.h" #include "RimProject.h" diff --git a/ApplicationLibCode/Commands/SeismicCommands/RicSeismicSectionFromIntersectionFeature.cpp b/ApplicationLibCode/Commands/SeismicCommands/RicSeismicSectionFromIntersectionFeature.cpp index 445ead3336..180db89511 100644 --- a/ApplicationLibCode/Commands/SeismicCommands/RicSeismicSectionFromIntersectionFeature.cpp +++ b/ApplicationLibCode/Commands/SeismicCommands/RicSeismicSectionFromIntersectionFeature.cpp @@ -47,6 +47,7 @@ bool RicSeismicSectionFromIntersectionFeature::isCommandEnabled() const if ( intersection != nullptr ) { return ( ( intersection->type() == RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYLINE ) || + ( intersection->type() == RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYGON ) || ( intersection->type() == RimExtrudedCurveIntersection::CrossSectionEnum::CS_WELL_PATH ) ); } @@ -70,7 +71,8 @@ void RicSeismicSectionFromIntersectionFeature::onActionTriggered( bool isChecked RimSeismicSection* newSection = seisColl->addNewSection(); if ( !newSection ) return; - if ( intersection->type() == RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYLINE ) + if ( ( intersection->type() == RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYLINE ) || + ( intersection->type() == RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYGON ) ) { newSection->setSectionType( RiaDefines::SeismicSectionType::SS_POLYLINE ); newSection->setUserDescription( intersection->name() ); diff --git a/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilFieldEntry.cpp b/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilFieldEntry.cpp index 231bda0172..53c310dd79 100644 --- a/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilFieldEntry.cpp +++ b/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilFieldEntry.cpp @@ -44,7 +44,6 @@ RimOilFieldEntry::RimOilFieldEntry() CAF_PDM_InitFieldNoDefault( &wellsFilePath, "wellsFilePath", "Wells File Path" ); CAF_PDM_InitFieldNoDefault( &wells, "Wells", "" ); - wells.uiCapability()->setUiTreeHidden( true ); wells.uiCapability()->setUiTreeChildrenHidden( true ); } diff --git a/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilRegionEntry.cpp b/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilRegionEntry.cpp index f488d0770a..7a3b7b355b 100644 --- a/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilRegionEntry.cpp +++ b/ApplicationLibCode/Commands/SsiHubImportCommands/RimOilRegionEntry.cpp @@ -31,7 +31,6 @@ RimOilRegionEntry::RimOilRegionEntry() CAF_PDM_InitFieldNoDefault( &name, "OilRegionEntry", "OilRegionEntry" ); CAF_PDM_InitFieldNoDefault( &fields, "Fields", "" ); - fields.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &selected, "Selected", false, "Selected" ); } diff --git a/ApplicationLibCode/Commands/SsiHubImportCommands/RimWellPathImport.cpp b/ApplicationLibCode/Commands/SsiHubImportCommands/RimWellPathImport.cpp index cc436a2e62..97d18bcb89 100644 --- a/ApplicationLibCode/Commands/SsiHubImportCommands/RimWellPathImport.cpp +++ b/ApplicationLibCode/Commands/SsiHubImportCommands/RimWellPathImport.cpp @@ -68,7 +68,6 @@ RimWellPathImport::RimWellPathImport() CAF_PDM_InitField( &west, "UtmWest", 0.0, "West" ); CAF_PDM_InitFieldNoDefault( ®ions, "Regions", "" ); - regions.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Commands/SsiHubImportCommands/RiuWellImportWizard.cpp b/ApplicationLibCode/Commands/SsiHubImportCommands/RiuWellImportWizard.cpp index 6d17e3b49e..7a53b71afe 100644 --- a/ApplicationLibCode/Commands/SsiHubImportCommands/RiuWellImportWizard.cpp +++ b/ApplicationLibCode/Commands/SsiHubImportCommands/RiuWellImportWizard.cpp @@ -841,7 +841,6 @@ WellSelectionPage::WellSelectionPage( RimWellPathImport* wellPathImport, QWidget m_regionsWithVisibleWells = new ObjectGroupWithHeaders; m_regionsWithVisibleWells->objects.uiCapability()->setUiHidden( true ); - m_regionsWithVisibleWells->objects.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- @@ -888,7 +887,6 @@ void WellSelectionPage::buildWellTreeView() { caf::PdmObjectCollection* regGroup = new caf::PdmObjectCollection; regGroup->objects.uiCapability()->setUiHidden( true ); - regGroup->objects.uiCapability()->setUiTreeHidden( true ); regGroup->setUiName( oilRegion->userDescriptionField()->uiCapability()->uiValue().toString() ); @@ -901,7 +899,6 @@ void WellSelectionPage::buildWellTreeView() { caf::PdmObjectCollection* fieldGroup = new caf::PdmObjectCollection; fieldGroup->objects.uiCapability()->setUiHidden( true ); - fieldGroup->objects.uiCapability()->setUiTreeHidden( true ); fieldGroup->setUiName( oilField->userDescriptionField()->uiCapability()->uiValue().toString() ); diff --git a/ApplicationLibCode/Commands/SummaryPlotCommands/RicSummaryPlotEditorUi.cpp b/ApplicationLibCode/Commands/SummaryPlotCommands/RicSummaryPlotEditorUi.cpp index 28b5a8b808..5392e14473 100644 --- a/ApplicationLibCode/Commands/SummaryPlotCommands/RicSummaryPlotEditorUi.cpp +++ b/ApplicationLibCode/Commands/SummaryPlotCommands/RicSummaryPlotEditorUi.cpp @@ -120,7 +120,6 @@ RicSummaryPlotEditorUi::RicSummaryPlotEditorUi() CAF_PDM_InitFieldNoDefault( &m_curveNameConfig, "SummaryCurveNameConfig", "SummaryCurveNameConfig" ); m_curveNameConfig = new RimSummaryCurveAutoName(); - m_curveNameConfig.uiCapability()->setUiTreeHidden( true ); m_curveNameConfig.uiCapability()->setUiTreeChildrenHidden( true ); m_summaryCurveSelectionEditor = std::make_unique(); diff --git a/ApplicationLibCode/Commands/SurfaceCommands/RicImportSurfacesFeature.cpp b/ApplicationLibCode/Commands/SurfaceCommands/RicImportSurfacesFeature.cpp index 5ce21c7273..01e932a15a 100644 --- a/ApplicationLibCode/Commands/SurfaceCommands/RicImportSurfacesFeature.cpp +++ b/ApplicationLibCode/Commands/SurfaceCommands/RicImportSurfacesFeature.cpp @@ -45,7 +45,7 @@ void RicImportSurfacesFeature::onActionTriggered( bool isChecked ) QStringList fileNames = RiuFileDialogTools::getOpenFileNames( Riu3DMainWindowTools::mainWindowWidget(), "Import Surfaces", defaultDir, - "Surface files (*.ptl *.ts *.dat);;All Files (*.*)" ); + "Surface files (*.ptl *.ts *.dat *.xyz);;All Files (*.*)" ); if ( fileNames.isEmpty() ) return; diff --git a/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.cpp b/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.cpp index e8b7d53233..25bb643b7c 100644 --- a/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.cpp +++ b/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.cpp @@ -56,6 +56,7 @@ #include "cafProgressInfo.h" #include "cafSelectionManager.h" #include "cvfAssert.h" +#include "cvfColor3.h" #include "cvfMath.h" #include @@ -63,6 +64,7 @@ #include #include +#include CAF_CMD_SOURCE_INIT( RicNewWellBoreStabilityPlotFeature, "RicNewWellBoreStabilityPlotFeature" ); @@ -262,7 +264,7 @@ void RicNewWellBoreStabilityPlotFeature::createParametersTrack( RimWellBoreStabi paramCurvesTrack->setFormationCase( geoMechCase ); paramCurvesTrack->setShowRegionLabels( true ); paramCurvesTrack->setShowWindow( false ); - std::set parameters = RigWbsParameter::allParameters(); + std::set parameters = parametersForTrack(); caf::ColorTable colors = RiaColorTables::contrastCategoryPaletteColors(); std::vector lineStyles = { RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_SOLID, @@ -284,6 +286,7 @@ void RicNewWellBoreStabilityPlotFeature::createParametersTrack( RimWellBoreStabi curve->setLineThickness( 2 ); curve->loadDataAndUpdate( false ); curve->setAutoNameComponents( false, true, false, false, false ); + curve->updateCurveName(); i++; } @@ -321,6 +324,15 @@ void RicNewWellBoreStabilityPlotFeature::createStabilityCurvesTrack( RimWellBore std::vector lineStyles( resultNames.size(), RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_SOLID ); lineStyles.back() = RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DASH; + std::set defaultOffResults = { + RiaResultNames::wbsSHMkResult(), + RiaResultNames::wbsSHMkExpResult(), + RiaResultNames::wbsSHMkMinResult(), + RiaResultNames::wbsSHMkMaxResult(), + RiaResultNames::wbsFGMkExpResult(), + RiaResultNames::wbsFGMkMinResult(), + }; + for ( size_t i = 0; i < resultNames.size(); ++i ) { const QString& resultName = resultNames[i]; @@ -330,16 +342,18 @@ void RicNewWellBoreStabilityPlotFeature::createStabilityCurvesTrack( RimWellBore curve->setGeoMechResultAddress( resAddr ); curve->setCurrentTimeStep( timeStep ); curve->setAutoNameComponents( false, true, false, false, false ); - curve->setColor( colors[i % colors.size()] ); - curve->setLineStyle( lineStyles[i] ); + auto [color, lineStyle] = getColorAndLineStyle( resultName, i, colors ); + curve->setColor( color ); + curve->setLineStyle( lineStyle ); curve->setLineThickness( 2 ); curve->loadDataAndUpdate( false ); curve->setSmoothCurve( true ); curve->setSmoothingThreshold( 0.002 ); - if ( resultNames[i] == RiaResultNames::wbsSHMkResult() ) + if ( defaultOffResults.count( resultNames[i] ) ) { curve->setCheckState( false ); } + curve->updateCurveName(); } RimWellPathCollection* wellPathCollection = RimTools::wellPathCollection(); @@ -361,6 +375,36 @@ void RicNewWellBoreStabilityPlotFeature::createStabilityCurvesTrack( RimWellBore stabilityCurvesTrack->setAutoScalePropertyValuesEnabled( true ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair + RicNewWellBoreStabilityPlotFeature::getColorAndLineStyle( const QString& resultName, size_t i, const std::vector& colors ) +{ + if ( resultName == RiaResultNames::wbsSHMkResult() ) return { cvf::Color3f::GREEN, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_SOLID }; + if ( resultName == RiaResultNames::wbsSHMkExpResult() ) + return { cvf::Color3f::GREEN, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DASH }; + if ( resultName == RiaResultNames::wbsSHMkMinResult() ) + return { cvf::Color3f::GREEN, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DOT }; + if ( resultName == RiaResultNames::wbsSHMkMaxResult() ) + return { cvf::Color3f::GREEN, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DASH_DOT }; + + if ( resultName == RiaResultNames::wbsFGMkExpResult() ) + return { cvf::Color3f::BLUE, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DASH }; + if ( resultName == RiaResultNames::wbsFGMkMinResult() ) return { cvf::Color3f::BLUE, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DOT }; + + if ( resultName == RiaResultNames::wbsPPInitialResult() ) + return { cvf::Color3f::DEEP_PINK, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_SOLID }; + if ( resultName == RiaResultNames::wbsPPExpResult() ) + return { cvf::Color3f::DEEP_PINK, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DASH }; + if ( resultName == RiaResultNames::wbsPPMinResult() ) + return { cvf::Color3f::DEEP_PINK, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DOT }; + if ( resultName == RiaResultNames::wbsPPMaxResult() ) + return { cvf::Color3f::DEEP_PINK, RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_DASH_DOT }; + + return { colors[i % colors.size()], RiuQwtPlotCurveDefines::LineStyleEnum::STYLE_SOLID }; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -408,3 +452,22 @@ void RicNewWellBoreStabilityPlotFeature::createAnglesTrack( RimWellBoreStability wellPathAnglesTrack->setAnnotationDisplay( RiaDefines::LIGHT_LINES ); wellPathAnglesTrack->setShowRegionLabels( false ); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::set RicNewWellBoreStabilityPlotFeature::parametersForTrack() +{ + return { RigWbsParameter::PP_Reservoir(), + RigWbsParameter::PP_NonReservoir(), + RigWbsParameter::poissonRatio(), + RigWbsParameter::UCS(), + RigWbsParameter::OBG(), + RigWbsParameter::OBG0(), + RigWbsParameter::SH(), + RigWbsParameter::DF(), + RigWbsParameter::K0_FG(), + RigWbsParameter::K0_SH(), + RigWbsParameter::FG_Shale(), + RigWbsParameter::waterDensity() }; +} diff --git a/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.h b/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.h index e9fd749ae0..9fc6dd4162 100644 --- a/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.h +++ b/ApplicationLibCode/Commands/WellLogCommands/RicNewWellBoreStabilityPlotFeature.h @@ -20,6 +20,14 @@ #include "cafCmdFeature.h" +#include "RigWbsParameter.h" + +#include "RimPlotCurveAppearance.h" + +#include "cvfColor3.h" + +#include + class RimGeoMechCase; class RimGeoMechView; class RimWbsParameters; @@ -48,4 +56,8 @@ class RicNewWellBoreStabilityPlotFeature : public caf::CmdFeature static void createParametersTrack( RimWellBoreStabilityPlot* plot, RimWellPath* wellPath, RimGeoMechCase* geoMechCase, int timeStep ); static void createStabilityCurvesTrack( RimWellBoreStabilityPlot* plot, RimWellPath* wellPath, RimGeoMechCase* geoMechCase, int timeStep ); static void createAnglesTrack( RimWellBoreStabilityPlot* plot, RimWellPath* wellPath, RimGeoMechCase* geoMechCase, int timeStep ); + + static std::set parametersForTrack(); + static std::pair + getColorAndLineStyle( const QString& resultName, size_t i, const std::vector& colors ); }; diff --git a/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.cpp b/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.cpp index 50837d80c9..daf5eab195 100644 --- a/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.cpp +++ b/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.cpp @@ -21,7 +21,7 @@ #include "RimViewWindow.h" #include "RimWellAllocationPlot.h" -#include "RimWellLogLasFile.h" +#include "RimWellLogFile.h" #include "RimWellLogPlot.h" #include "RimWellPath.h" #include "RimWellPltPlot.h" @@ -40,7 +40,7 @@ CAF_CMD_SOURCE_INIT( RicWellLogFileCloseFeature, "RicWellLogFileCloseFeature" ); //-------------------------------------------------------------------------------------------------- bool RicWellLogFileCloseFeature::isCommandEnabled() const { - std::vector objects = caf::selectedObjectsByType(); + std::vector objects = caf::selectedObjectsByType(); return !objects.empty(); } @@ -49,7 +49,7 @@ bool RicWellLogFileCloseFeature::isCommandEnabled() const //-------------------------------------------------------------------------------------------------- void RicWellLogFileCloseFeature::onActionTriggered( bool isChecked ) { - std::vector objects = caf::selectedObjectsByType(); + std::vector objects = caf::selectedObjectsByType(); if ( objects.empty() ) return; @@ -85,7 +85,7 @@ void RicWellLogFileCloseFeature::setupActionLook( QAction* actionToSetup ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::set RicWellLogFileCloseFeature::referringWellLogPlots( const RimWellLogLasFile* wellLogFile ) +std::set RicWellLogFileCloseFeature::referringWellLogPlots( const RimWellLogFile* wellLogFile ) { // Remove all curves displaying data from the specified wellLogFile std::vector referringObjects = wellLogFile->objectsWithReferringPtrFields(); diff --git a/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.h b/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.h index 003458ce43..aba98962f1 100644 --- a/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.h +++ b/ApplicationLibCode/Commands/WellLogCommands/RicWellLogFileCloseFeature.h @@ -22,7 +22,7 @@ #include "cafCmdFeature.h" #include -class RimWellLogLasFile; +class RimWellLogFile; class RimViewWindow; //================================================================================================== @@ -37,5 +37,5 @@ class RicWellLogFileCloseFeature : public caf::CmdFeature void onActionTriggered( bool isChecked ) override; void setupActionLook( QAction* actionToSetup ) override; - std::set referringWellLogPlots( const RimWellLogLasFile* wellLogFile ); + std::set referringWellLogPlots( const RimWellLogFile* wellLogFile ); }; diff --git a/ApplicationLibCode/Commands/WellPathCommands/CMakeLists_files.cmake b/ApplicationLibCode/Commands/WellPathCommands/CMakeLists_files.cmake index 57cb2f675e..05d2b44324 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/CMakeLists_files.cmake +++ b/ApplicationLibCode/Commands/WellPathCommands/CMakeLists_files.cmake @@ -30,8 +30,8 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/PointTangentManipulator/RicPointTangentManipulatorPartMgr.h ${CMAKE_CURRENT_LIST_DIR}/PointTangentManipulator/RicPolyline3dEditor.h ${CMAKE_CURRENT_LIST_DIR}/PointTangentManipulator/RicPolylineTarget3dEditor.h - ${CMAKE_CURRENT_LIST_DIR}/RicAppendPointsToPolygonFilterFeature.h ${CMAKE_CURRENT_LIST_DIR}/RicDuplicateWellPathFeature.h + ${CMAKE_CURRENT_LIST_DIR}/RicSetParentWellPathFeature.h ) set(SOURCE_GROUP_SOURCE_FILES @@ -66,8 +66,8 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/PointTangentManipulator/RicPointTangentManipulatorPartMgr.cpp ${CMAKE_CURRENT_LIST_DIR}/PointTangentManipulator/RicPolyline3dEditor.cpp ${CMAKE_CURRENT_LIST_DIR}/PointTangentManipulator/RicPolylineTarget3dEditor.cpp - ${CMAKE_CURRENT_LIST_DIR}/RicAppendPointsToPolygonFilterFeature.cpp ${CMAKE_CURRENT_LIST_DIR}/RicDuplicateWellPathFeature.cpp + ${CMAKE_CURRENT_LIST_DIR}/RicSetParentWellPathFeature.cpp ) list(APPEND COMMAND_CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) diff --git a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.cpp b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.cpp index f67db7f3ff..2c0c094dd0 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.cpp +++ b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.cpp @@ -62,7 +62,7 @@ void RicPolyline3dEditor::configureAndUpdateUi( const QString& uiConfigName ) } m_targetEditors.clear(); - if ( !pickerInterface ) return; + if ( !pickerInterface || !pickerInterface->pickEventHandler() ) return; if ( pickerInterface->pickingEnabled() ) { diff --git a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.cpp b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.cpp index 4c1860e278..6bf4a98b48 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.cpp +++ b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.cpp @@ -21,10 +21,8 @@ #include "RicPointTangentManipulator.h" #include "Rim3dView.h" -#include "RimAnnotationCollectionBase.h" -#include "RimCase.h" +#include "RimPolylinePickerInterface.h" #include "RimPolylineTarget.h" -#include "RimUserDefinedPolylinesAnnotation.h" #include "RiuViewer.h" @@ -57,7 +55,7 @@ RicPolylineTarget3dEditor::~RicPolylineTarget3dEditor() ownerRiuViewer->removeStaticModel( m_cvfModel.p() ); } - RimPolylineTarget* oldTarget = dynamic_cast( pdmObject() ); + auto* oldTarget = dynamic_cast( pdmObject() ); if ( oldTarget ) { oldTarget->targetPointUiCapability()->removeFieldEditor( this ); @@ -71,11 +69,11 @@ RicPolylineTarget3dEditor::~RicPolylineTarget3dEditor() //-------------------------------------------------------------------------------------------------- void RicPolylineTarget3dEditor::configureAndUpdateUi( const QString& uiConfigName ) { - RimPolylineTarget* target = dynamic_cast( pdmObject() ); - RiuViewer* ownerRiuViewer = dynamic_cast( ownerViewer() ); - Rim3dView* view = mainOrComparisonView(); + auto* target = dynamic_cast( pdmObject() ); + RiuViewer* ownerRiuViewer = dynamic_cast( ownerViewer() ); + Rim3dView* view = mainOrComparisonView(); - if ( !target || !target->isEnabled() || !view ) + if ( !target || !view ) { if ( m_cvfModel.notNull() ) m_cvfModel->removeAllParts(); @@ -97,11 +95,17 @@ void RicPolylineTarget3dEditor::configureAndUpdateUi( const QString& uiConfigNam ownerRiuViewer->addStaticModelOnce( m_cvfModel.p(), isInComparisonView() ); } - cvf::ref dispXf = view->displayCoordTransform(); - double handleSize = 0.7 * view->characteristicCellSize(); + cvf::ref dispXf = view->displayCoordTransform(); + + double scalingFactor = 0.7; + if ( auto pickerInterface = target->firstAncestorOrThisOfType() ) + { + scalingFactor *= pickerInterface->scalingFactorForTarget(); + } + + const double handleSize = scalingFactor * view->characteristicCellSize(); m_manipulator->setOrigin( dispXf->transformToDisplayCoord( target->targetPointXYZ() ) ); - // m_manipulator->setTangent(target->tangent()); m_manipulator->setHandleSize( handleSize ); m_cvfModel->removeAllParts(); m_manipulator->appendPartsToModel( m_cvfModel.p() ); @@ -114,7 +118,7 @@ void RicPolylineTarget3dEditor::configureAndUpdateUi( const QString& uiConfigNam //-------------------------------------------------------------------------------------------------- void RicPolylineTarget3dEditor::cleanupBeforeSettingPdmObject() { - RimPolylineTarget* oldTarget = dynamic_cast( pdmObject() ); + auto* oldTarget = dynamic_cast( pdmObject() ); if ( oldTarget ) { oldTarget->targetPointUiCapability()->removeFieldEditor( this ); @@ -126,8 +130,8 @@ void RicPolylineTarget3dEditor::cleanupBeforeSettingPdmObject() //-------------------------------------------------------------------------------------------------- void RicPolylineTarget3dEditor::slotUpdated( const cvf::Vec3d& origin, const cvf::Vec3d& tangent ) { - RimPolylineTarget* target = dynamic_cast( pdmObject() ); - Rim3dView* view = mainOrComparisonView(); + auto* target = dynamic_cast( pdmObject() ); + Rim3dView* view = mainOrComparisonView(); if ( !target || !view ) { @@ -140,9 +144,7 @@ void RicPolylineTarget3dEditor::slotUpdated( const cvf::Vec3d& origin, const cvf domainOrigin.z() = -domainOrigin.z(); QVariant originVariant = caf::PdmValueFieldSpecialization::convert( domainOrigin ); - target->enableFullUpdate( false ); caf::PdmUiCommandSystemProxy::instance()->setUiValueToField( target->targetPointUiCapability(), originVariant ); - target->enableFullUpdate( true ); } //-------------------------------------------------------------------------------------------------- @@ -150,7 +152,7 @@ void RicPolylineTarget3dEditor::slotUpdated( const cvf::Vec3d& origin, const cvf //-------------------------------------------------------------------------------------------------- void RicPolylineTarget3dEditor::slotSelectedIn3D() { - RimPolylineTarget* target = dynamic_cast( pdmObject() ); + auto* target = dynamic_cast( pdmObject() ); if ( !target ) { return; @@ -164,7 +166,7 @@ void RicPolylineTarget3dEditor::slotSelectedIn3D() //-------------------------------------------------------------------------------------------------- void RicPolylineTarget3dEditor::slotDragFinished() { - RimPolylineTarget* target = dynamic_cast( pdmObject() ); + auto* target = dynamic_cast( pdmObject() ); if ( target ) { target->triggerVisualizationUpdate(); diff --git a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.h b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.h index 918d7a631e..3fe127d12d 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.h +++ b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicPolylineTarget3dEditor.h @@ -25,13 +25,14 @@ class RicPointTangentManipulator; #include "cvfObject.h" #include "cvfVector3.h" +#include + namespace cvf { class ModelBasicList; } class QString; -#include class RicPolylineTarget3dEditor : public Ric3dObjectEditorHandle { diff --git a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicWellTarget3dEditor.cpp b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicWellTarget3dEditor.cpp index 05c878c35a..471e5eeebb 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicWellTarget3dEditor.cpp +++ b/ApplicationLibCode/Commands/WellPathCommands/PointTangentManipulator/RicWellTarget3dEditor.cpp @@ -40,6 +40,8 @@ #include "cvfModelBasicList.h" #include "cvfPart.h" +#include + CAF_PDM_UI_3D_OBJECT_EDITOR_SOURCE_INIT( RicWellTarget3dEditor ); //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicAppendPointsToPolygonFilterFeature.cpp b/ApplicationLibCode/Commands/WellPathCommands/RicAppendPointsToPolygonFilterFeature.cpp deleted file mode 100644 index 05908fcacd..0000000000 --- a/ApplicationLibCode/Commands/WellPathCommands/RicAppendPointsToPolygonFilterFeature.cpp +++ /dev/null @@ -1,83 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2021- Equinor ASA -// -// ResInsight 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 3 of the License, or -// (at your option) any later version. -// -// ResInsight 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 at -// for more details. -// -///////////////////////////////////////////////////////////////////////////////// - -#include "RicAppendPointsToPolygonFilterFeature.h" - -#include "RiaTextStringTools.h" - -#include "RimPolygonFilter.h" -#include "RimPolylineTarget.h" - -#include "OperationsUsingObjReferences/RicPasteFeatureImpl.h" - -#include "cafSelectionManager.h" -#include "cafSelectionManagerTools.h" - -#include -#include - -CAF_CMD_SOURCE_INIT( RicAppendPointsToPolygonFilterFeature, "RicAppendPointsToPolygonFilterFeature" ); - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RicAppendPointsToPolygonFilterFeature::isCommandEnabled() const -{ - auto obj = caf::firstAncestorOfTypeFromSelectedObject(); - return obj != nullptr; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RicAppendPointsToPolygonFilterFeature::onActionTriggered( bool isChecked ) -{ - auto polygonFilter = caf::firstAncestorOfTypeFromSelectedObject(); - if ( !polygonFilter ) return; - - QStringList listOfThreeDoubles; - - QClipboard* clipboard = QApplication::clipboard(); - if ( clipboard ) - { - QString content = clipboard->text(); - listOfThreeDoubles = RiaTextStringTools::splitSkipEmptyParts( content, "\n" ); - } - - std::vector points; - caf::PdmValueFieldSpecialization>::setFromVariant( listOfThreeDoubles, points ); - - for ( const auto& p : points ) - { - auto newTarget = new RimPolylineTarget; - newTarget->setAsPointTargetXYD( p ); - polygonFilter->insertTarget( nullptr, newTarget ); - } - - polygonFilter->updateEditorsAndVisualization(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RicAppendPointsToPolygonFilterFeature::setupActionLook( QAction* actionToSetup ) -{ - actionToSetup->setText( "Append Points from Clipboard" ); - - RicPasteFeatureImpl::setIconAndShortcuts( actionToSetup ); -} diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicCreateWellTargetsPickEventHandler.cpp b/ApplicationLibCode/Commands/WellPathCommands/RicCreateWellTargetsPickEventHandler.cpp index 1c60cf8a69..f864f55675 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/RicCreateWellTargetsPickEventHandler.cpp +++ b/ApplicationLibCode/Commands/WellPathCommands/RicCreateWellTargetsPickEventHandler.cpp @@ -18,9 +18,6 @@ #include "RicCreateWellTargetsPickEventHandler.h" -#include "RiaGuiApplication.h" -#include "RiaOffshoreSphericalCoords.h" - #include "RigFemPart.h" #include "RigFemPartCollection.h" #include "RigFemPartGrid.h" @@ -30,26 +27,21 @@ #include "RigWellPathGeometryTools.h" #include "Rim3dView.h" +#include "RimCase.h" #include "RimEclipseView.h" #include "RimGeoMechView.h" #include "RimModeledWellPath.h" -#include "RimWellPath.h" #include "RimWellPathGeometryDef.h" #include "RimWellPathTarget.h" -#include "RiuViewerCommands.h" - #include "RivFemPartGeometryGenerator.h" #include "RivFemPickSourceInfo.h" #include "RivSourceInfo.h" #include "RivWellPathSourceInfo.h" #include "cafDisplayCoordTransform.h" -#include "cafSelectionManager.h" - -#include "cvfStructGridGeometryGenerator.h" -#include +#include #include @@ -130,7 +122,14 @@ bool RicCreateWellTargetsPickEventHandler::handle3dPickEvent( const Ric3dPickEve doSetAzimuthAndInclination = false; cvf::Vec3d domainRayOrigin = rimView->displayCoordTransform()->transformToDomainCoord( firstPickItem.globalRayOrigin() ); - cvf::Vec3d domainRayEnd = targetPointInDomain + ( targetPointInDomain - domainRayOrigin ); + + auto rayVector = ( targetPointInDomain - domainRayOrigin ); + const double minimumRayLength = rimView->ownerCase()->characteristicCellSize() * 2; + if ( rayVector.length() < minimumRayLength ) + { + rayVector = rayVector.getNormalized() * minimumRayLength; + } + cvf::Vec3d domainRayEnd = targetPointInDomain + rayVector; cvf::Vec3d hexElementIntersection = findHexElementIntersection( rimView, firstPickItem, domainRayOrigin, domainRayEnd ); CVF_TIGHT_ASSERT( !hexElementIntersection.isUndefined() ); @@ -241,7 +240,7 @@ cvf::Vec3d RicCreateWellTargetsPickEventHandler::findHexElementIntersection( gsl RigFemPart* femPart = geoMechView->femParts()->part( femPartIndex ); RigElementType elType = femPart->elementType( elementIndex ); - if ( elType == HEX8 || elType == HEX8P ) + if ( RigFemTypes::is8NodeElement( elType ) ) { cellIndex = elementIndex; const RigFemPartGrid* femGrid = femPart->getOrCreateStructGrid(); @@ -255,22 +254,27 @@ cvf::Vec3d RicCreateWellTargetsPickEventHandler::findHexElementIntersection( gsl { std::vector intersectionInfo; RigHexIntersectionTools::lineHexCellIntersection( domainRayOrigin, domainRayEnd, cornerVertices.data(), cellIndex, &intersectionInfo ); - if ( !intersectionInfo.empty() ) + + if ( intersectionInfo.empty() ) return cvf::Vec3d::UNDEFINED; + + if ( intersectionInfo.size() == 1 ) { - // Sort intersection on distance to ray origin - CVF_ASSERT( intersectionInfo.size() > 1 ); - std::sort( intersectionInfo.begin(), - intersectionInfo.end(), - [&domainRayOrigin]( const HexIntersectionInfo& lhs, const HexIntersectionInfo& rhs ) { - return ( lhs.m_intersectionPoint - domainRayOrigin ).lengthSquared() < - ( rhs.m_intersectionPoint - domainRayOrigin ).lengthSquared(); - } ); - const double eps = 1.0e-2; - cvf::Vec3d intersectionRay = intersectionInfo.back().m_intersectionPoint - intersectionInfo.front().m_intersectionPoint; - cvf::Vec3d newPoint = intersectionInfo.front().m_intersectionPoint + intersectionRay * eps; - CVF_ASSERT( RigHexIntersectionTools::isPointInCell( newPoint, cornerVertices.data() ) ); - return newPoint; + return intersectionInfo.front().m_intersectionPoint; } + + // Sort intersection on distance to ray origin + std::sort( intersectionInfo.begin(), + intersectionInfo.end(), + [&domainRayOrigin]( const HexIntersectionInfo& lhs, const HexIntersectionInfo& rhs ) { + return ( lhs.m_intersectionPoint - domainRayOrigin ).lengthSquared() < + ( rhs.m_intersectionPoint - domainRayOrigin ).lengthSquared(); + } ); + const double eps = 1.0e-2; + cvf::Vec3d intersectionRay = intersectionInfo.back().m_intersectionPoint - intersectionInfo.front().m_intersectionPoint; + cvf::Vec3d newPoint = intersectionInfo.front().m_intersectionPoint + intersectionRay * eps; + CVF_ASSERT( RigHexIntersectionTools::isPointInCell( newPoint, cornerVertices.data() ) ); + return newPoint; } + return cvf::Vec3d::UNDEFINED; } diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicIntersectionPickEventHandler.cpp b/ApplicationLibCode/Commands/WellPathCommands/RicIntersectionPickEventHandler.cpp index bcdb1233c1..b699df4383 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/RicIntersectionPickEventHandler.cpp +++ b/ApplicationLibCode/Commands/WellPathCommands/RicIntersectionPickEventHandler.cpp @@ -44,44 +44,41 @@ bool RicIntersectionPickEventHandler::handle3dPickEvent( const Ric3dPickEvent& e std::vector selection; caf::SelectionManager::instance()->objectsByType( &selection ); - if ( selection.size() == 1 ) + if ( selection.size() != 1 ) return false; + + RimExtrudedCurveIntersection* intersection = selection[0]; + + RimGridView* gridView = intersection->firstAncestorOrThisOfTypeAsserted(); + + if ( RiaApplication::instance()->activeMainOrComparisonGridView() != gridView ) + { + return false; + } + + cvf::ref transForm = gridView->displayCoordTransform(); + + cvf::Vec3d domainCoord = transForm->transformToDomainCoord( eventObject.m_pickItemInfos.front().globalPickedPoint() ); + + if ( intersection->inputPolyLineFromViewerEnabled() ) { - { - RimExtrudedCurveIntersection* intersection = selection[0]; - - RimGridView* gridView = intersection->firstAncestorOrThisOfTypeAsserted(); - - if ( RiaApplication::instance()->activeMainOrComparisonGridView() != gridView ) - { - return false; - } - - cvf::ref transForm = gridView->displayCoordTransform(); - - cvf::Vec3d domainCoord = transForm->transformToDomainCoord( eventObject.m_pickItemInfos.front().globalPickedPoint() ); - - if ( intersection->inputPolyLineFromViewerEnabled() ) - { - intersection->appendPointToPolyLine( domainCoord ); - - // Further Ui processing is stopped when true is returned - return true; - } - else if ( intersection->inputExtrusionPointsFromViewerEnabled() ) - { - intersection->appendPointToExtrusionDirection( domainCoord ); - - // Further Ui processing is stopped when true is returned - return true; - } - else if ( intersection->inputTwoAzimuthPointsFromViewerEnabled() ) - { - intersection->appendPointToAzimuthLine( domainCoord ); - - // Further Ui processing is stopped when true is returned - return true; - } - } + intersection->appendPointToPolyLine( domainCoord ); + + // Further Ui processing is stopped when true is returned + return true; + } + else if ( intersection->inputExtrusionPointsFromViewerEnabled() ) + { + intersection->appendPointToExtrusionDirection( domainCoord ); + + // Further Ui processing is stopped when true is returned + return true; + } + else if ( intersection->inputTwoAzimuthPointsFromViewerEnabled() ) + { + intersection->appendPointToAzimuthLine( domainCoord ); + + // Further Ui processing is stopped when true is returned + return true; } return false; diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicNewPolylineTargetFeature.cpp b/ApplicationLibCode/Commands/WellPathCommands/RicNewPolylineTargetFeature.cpp index 013eadff30..eec85c6ce3 100644 --- a/ApplicationLibCode/Commands/WellPathCommands/RicNewPolylineTargetFeature.cpp +++ b/ApplicationLibCode/Commands/WellPathCommands/RicNewPolylineTargetFeature.cpp @@ -21,21 +21,23 @@ CAF_CMD_SOURCE_INIT( RicNewPolylineTargetFeature, "RicNewPolylineTargetFeature" #include "RimCase.h" #include "RimGridView.h" +#include "RimPolylinePickerInterface.h" #include "RimPolylineTarget.h" #include "RimProject.h" -#include "RimUserDefinedPolylinesAnnotation.h" + #include "cafSelectionManager.h" -#include #include "cvfBoundingBox.h" +#include + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- bool RicNewPolylineTargetFeature::isCommandEnabled() const { { - std::vector objects; + std::vector objects; caf::SelectionManager::instance()->objectsByType( &objects ); if ( !objects.empty() ) @@ -66,7 +68,7 @@ void RicNewPolylineTargetFeature::onActionTriggered( bool isChecked ) if ( !selectedTargets.empty() ) { auto firstTarget = selectedTargets.front(); - RimUserDefinedPolylinesAnnotation* polylineDef = firstTarget->firstAncestorOrThisOfTypeAsserted(); + auto polylineDef = firstTarget->firstAncestorOrThisOfTypeAsserted(); auto afterBeforePair = polylineDef->findActiveTargetsAroundInsertionPoint( firstTarget ); @@ -109,49 +111,40 @@ void RicNewPolylineTargetFeature::onActionTriggered( bool isChecked ) return; } - std::vector polylineDefs; + std::vector polylineDefs; caf::SelectionManager::instance()->objectsByType( &polylineDefs ); if ( !polylineDefs.empty() ) { auto* polylineDef = polylineDefs[0]; std::vector activeTargets = polylineDef->activeTargets(); - size_t targetCount = activeTargets.size(); + cvf::Vec3d newPos = cvf::Vec3d::ZERO; - if ( targetCount == 0 ) + size_t targetCount = activeTargets.size(); + if ( targetCount > 1 ) + { + newPos = activeTargets[targetCount - 1]->targetPointXYZ(); + cvf::Vec3d nextLastToLast = newPos - activeTargets[targetCount - 2]->targetPointXYZ(); + newPos += 0.5 * nextLastToLast; + } + else if ( targetCount > 0 ) + { + newPos = activeTargets[targetCount - 1]->targetPointXYZ() + cvf::Vec3d( 0, 0, 200 ); + } + else { - auto defaultPos = cvf::Vec3d::ZERO; - - // Set decent position std::vector gridViews; RimProject::current()->allVisibleGridViews( gridViews ); if ( !gridViews.empty() ) { auto minPos = gridViews.front()->ownerCase()->allCellsBoundingBox().min(); - defaultPos = minPos; + newPos = minPos; } - - polylineDef->appendTarget( defaultPos ); } - else - { - cvf::Vec3d newPos = cvf::Vec3d::ZERO; - - if ( targetCount > 1 ) - { - newPos = activeTargets[targetCount - 1]->targetPointXYZ(); - cvf::Vec3d nextLastToLast = newPos - activeTargets[targetCount - 2]->targetPointXYZ(); - newPos += 0.5 * nextLastToLast; - } - else if ( targetCount > 0 ) - { - newPos = activeTargets[targetCount - 1]->targetPointXYZ() + cvf::Vec3d( 0, 0, 200 ); - } - auto* newTarget = new RimPolylineTarget; - newTarget->setAsPointTargetXYD( { newPos[0], newPos[1], -newPos[2] } ); - polylineDef->insertTarget( nullptr, newTarget ); - } + auto* newTarget = new RimPolylineTarget; + newTarget->setAsPointTargetXYD( { newPos[0], newPos[1], -newPos[2] } ); + polylineDef->insertTarget( nullptr, newTarget ); polylineDef->updateEditorsAndVisualization(); } diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicSetParentWellPathFeature.cpp b/ApplicationLibCode/Commands/WellPathCommands/RicSetParentWellPathFeature.cpp new file mode 100644 index 0000000000..a130320d9b --- /dev/null +++ b/ApplicationLibCode/Commands/WellPathCommands/RicSetParentWellPathFeature.cpp @@ -0,0 +1,149 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RicSetParentWellPathFeature.h" + +#include "RigWellPath.h" + +#include "RimTools.h" +#include "RimWellPath.h" +#include "RimWellPathCollection.h" +#include "RimWellPathTieIn.h" + +#include "RiuMainWindow.h" + +#include "cafPdmUiPropertyViewDialog.h" +#include "cafSelectionManager.h" + +#include + +CAF_PDM_SOURCE_INIT( RicSelectWellPathUi, "RicSelectWellPathUi" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RicSelectWellPathUi::RicSelectWellPathUi() +{ + CAF_PDM_InitObject( "RicSelectWellPathUi" ); + + CAF_PDM_InitFieldNoDefault( &m_selectedWellPath, "SelectedWellPath", "Well Path" ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicSelectWellPathUi::setWellPaths( const std::vector& wellPaths ) +{ + m_wellPaths = wellPaths; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicSelectWellPathUi::setSelectedWell( RimWellPath* selectedWell ) +{ + m_selectedWellPath = selectedWell; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimWellPath* RicSelectWellPathUi::wellPath() const +{ + return m_selectedWellPath(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QList RicSelectWellPathUi::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) +{ + QList options; + + options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); + + RimTools::optionItemsForSpecifiedWellPaths( m_wellPaths, &options ); + return options; +} + +CAF_CMD_SOURCE_INIT( RicSetParentWellPathFeature, "RicSetParentWellPathFeature" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicSetParentWellPathFeature::onActionTriggered( bool isChecked ) +{ + auto selectedWellPath = caf::SelectionManager::instance()->selectedItemOfType(); + if ( !selectedWellPath ) return; + + auto wpc = RimTools::wellPathCollection(); + if ( !wpc ) return; + + std::vector wellPathCandidates; + for ( auto w : wpc->allWellPaths() ) + { + if ( w != selectedWellPath ) wellPathCandidates.push_back( w ); + } + + RicSelectWellPathUi ui; + ui.setWellPaths( wellPathCandidates ); + + RimWellPath* parentWell = nullptr; + if ( selectedWellPath->wellPathTieIn() ) parentWell = selectedWellPath->wellPathTieIn()->parentWell(); + ui.setSelectedWell( parentWell ); + + caf::PdmUiPropertyViewDialog propertyDialog( nullptr, &ui, "Select Parent Well", "" ); + propertyDialog.resize( QSize( 400, 200 ) ); + + if ( propertyDialog.exec() == QDialog::Accepted ) + { + auto parentWellPath = ui.wellPath(); + + double tieInMeasuredDepth = 0.0; + if ( parentWellPath ) + { + if ( !parentWellPath->wellPathGeometry() || parentWellPath->wellPathGeometry()->measuredDepths().size() < 2 ) return; + if ( selectedWellPath->wellPathGeometry()->wellPathPoints().empty() ) return; + + auto headOfLateral = selectedWellPath->wellPathGeometry()->wellPathPoints().front(); + + cvf::Vec3d p1, p2; + parentWellPath->wellPathGeometry()->twoClosestPoints( headOfLateral, &p1, &p2 ); + + tieInMeasuredDepth = parentWellPath->wellPathGeometry()->closestMeasuredDepth( p1 ); + } + + selectedWellPath->connectWellPaths( parentWellPath, tieInMeasuredDepth ); + + wpc->rebuildWellPathNodes(); + wpc->scheduleRedrawAffectedViews(); + wpc->updateAllRequiredEditors(); + + RiuMainWindow::instance()->setExpanded( selectedWellPath ); + RiuMainWindow::instance()->selectAsCurrentItem( selectedWellPath ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RicSetParentWellPathFeature::setupActionLook( QAction* actionToSetup ) +{ + actionToSetup->setText( "Set Parent Well Path" ); + actionToSetup->setIcon( QIcon( ":/Well.svg" ) ); +} diff --git a/ApplicationLibCode/Commands/WellPathCommands/RicSetParentWellPathFeature.h b/ApplicationLibCode/Commands/WellPathCommands/RicSetParentWellPathFeature.h new file mode 100644 index 0000000000..880d067515 --- /dev/null +++ b/ApplicationLibCode/Commands/WellPathCommands/RicSetParentWellPathFeature.h @@ -0,0 +1,66 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafCmdFeature.h" +#include "cafPdmObject.h" +#include "cafPdmPtrField.h" + +#include + +#include + +namespace caf +{ +class PdmOptionItemInfo; +} + +class RimWellPath; + +class RicSelectWellPathUi : public caf::PdmObject +{ + CAF_PDM_HEADER_INIT; + +public: + RicSelectWellPathUi(); + + void setWellPaths( const std::vector& wellPaths ); + void setSelectedWell( RimWellPath* selectedWell ); + + RimWellPath* wellPath() const; + +protected: + QList calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) override; + +private: + caf::PdmPtrField m_selectedWellPath; + std::vector m_wellPaths; +}; + +//================================================================================================== +/// +//================================================================================================== +class RicSetParentWellPathFeature : public caf::CmdFeature +{ + CAF_CMD_HEADER_INIT; + +protected: + void onActionTriggered( bool isChecked ) override; + void setupActionLook( QAction* actionToSetup ) override; +}; diff --git a/ApplicationLibCode/FileInterface/CMakeLists_files.cmake b/ApplicationLibCode/FileInterface/CMakeLists_files.cmake index 310f3cfbd9..8d2d0a8123 100644 --- a/ApplicationLibCode/FileInterface/CMakeLists_files.cmake +++ b/ApplicationLibCode/FileInterface/CMakeLists_files.cmake @@ -95,6 +95,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RifSummaryCalculation.h ${CMAKE_CURRENT_LIST_DIR}/RifSummaryCalculationImporter.h ${CMAKE_CURRENT_LIST_DIR}/RifSummaryCalculationExporter.h + ${CMAKE_CURRENT_LIST_DIR}/RifPolygonReader.h ) set(SOURCE_GROUP_SOURCE_FILES @@ -189,6 +190,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RifGridCalculationExporter.cpp ${CMAKE_CURRENT_LIST_DIR}/RifSummaryCalculationImporter.cpp ${CMAKE_CURRENT_LIST_DIR}/RifSummaryCalculationExporter.cpp + ${CMAKE_CURRENT_LIST_DIR}/RifPolygonReader.cpp ) list(APPEND CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) diff --git a/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.cpp b/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.cpp index f94fa2892a..98600886d4 100644 --- a/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.cpp +++ b/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.cpp @@ -118,7 +118,7 @@ void RifCsvDataTableFormatter::tableCompleted() //-------------------------------------------------------------------------------------------------- void RifCsvDataTableFormatter::outputBuffer() { - if ( !m_columnHeaders.empty() ) + if ( isAnyTextInHeader() ) { for ( size_t i = 0; i < m_columnHeaders.size(); i++ ) { @@ -152,3 +152,21 @@ void RifCsvDataTableFormatter::outputBuffer() m_columnHeaders.clear(); m_buffer.clear(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifCsvDataTableFormatter::isAnyTextInHeader() const +{ + for ( auto& header : m_columnHeaders ) + { + for ( const auto& titleRow : header.titles ) + { + if ( !titleRow.trimmed().isEmpty() ) + { + return true; + } + } + } + return false; +} diff --git a/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.h b/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.h index 57b20d91d3..46f0d9649b 100644 --- a/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.h +++ b/ApplicationLibCode/FileInterface/RifCsvDataTableFormatter.h @@ -42,6 +42,7 @@ class RifCsvDataTableFormatter private: void outputBuffer(); + bool isAnyTextInHeader() const; private: QTextStream& m_out; diff --git a/ApplicationLibCode/FileInterface/RifCsvUserDataParser.cpp b/ApplicationLibCode/FileInterface/RifCsvUserDataParser.cpp index 9c927c9147..c29812c736 100644 --- a/ApplicationLibCode/FileInterface/RifCsvUserDataParser.cpp +++ b/ApplicationLibCode/FileInterface/RifCsvUserDataParser.cpp @@ -315,7 +315,7 @@ bool RifCsvUserDataParser::parseColumnInfo( QTextStream* if ( !columnInfoList ) return false; columnInfoList->clear(); - while ( !headerFound ) + while ( !headerFound && dataStream->status() == QTextStream::Status::Ok ) { QString line = dataStream->readLine(); if ( line.trimmed().isEmpty() ) @@ -341,7 +341,7 @@ bool RifCsvUserDataParser::parseColumnInfo( QTextStream* auto startOfLineWithDataValues = dataStream->pos(); bool hasDataValues = false; QString nameFromData; - while ( !hasDataValues ) + while ( !hasDataValues && !dataStream->atEnd() ) { QString candidateLine = dataStream->readLine(); @@ -374,6 +374,8 @@ bool RifCsvUserDataParser::parseColumnInfo( QTextStream* } } + if ( !hasDataValues ) break; + dataStream->seek( startOfLineWithDataValues ); int colCount = columnHeaders.size(); diff --git a/ApplicationLibCode/FileInterface/RifEclEclipseSummary.h b/ApplicationLibCode/FileInterface/RifEclEclipseSummary.h index d6d51ac789..da75646132 100644 --- a/ApplicationLibCode/FileInterface/RifEclEclipseSummary.h +++ b/ApplicationLibCode/FileInterface/RifEclEclipseSummary.h @@ -56,7 +56,7 @@ class RifEclEclipseSummary : public RifSummaryReaderInterface private: int indexFromAddress( const RifEclipseSummaryAddress& resultAddress ) const; - void buildMetaData(); + void buildMetaData() override; private: ecl_sum_type* m_ecl_sum; diff --git a/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.cpp b/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.cpp index c9d7113380..22cb9bbbc3 100644 --- a/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.cpp +++ b/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.cpp @@ -24,24 +24,34 @@ #include "RiaApplication.h" #include "RiaBaseDefs.h" #include "RiaEclipseUnitTools.h" +#include "RiaFilePathTools.h" #include "RiaVersionInfo.h" #include "RiaWellLogUnitTools.h" #include "RifInpExportTools.h" +#include "RifJsonEncodeDecode.h" + #include "RimFaultReactivationDataAccess.h" #include "RimFaultReactivationEnums.h" #include "RimFaultReactivationModel.h" +#include "RimFaultReactivationTools.h" +#include #include #include +#include //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::pair RifFaultReactivationModelExporter::exportToStream( std::ostream& stream, - const std::string& exportDirectory, - const RimFaultReactivationModel& rimModel ) +std::pair RifFaultReactivationModelExporter::exportToStream( std::ostream& stream, const RimFaultReactivationModel& rimModel ) { + auto [modelOk, errorMsg] = rimModel.validateModel(); + if ( !modelOk ) return { false, errorMsg }; + + auto dataAccess = extractAndExportModelData( rimModel ); + if ( !dataAccess ) return { false, "Unable to get necessary data from the input case." }; + std::string applicationNameAndVersion = std::string( RI_APPLICATION_NAME ) + " " + std::string( STRPRODUCTVER ); using PartBorderSurface = RimFaultReactivation::BorderSurface; @@ -52,13 +62,13 @@ std::pair RifFaultReactivationModelExporter::exportToStream( // The two parts are "mirrored", so face number 4 of the two parts should face eachother. using FaultGridPart = RimFaultReactivation::GridPart; - std::map, int> faces = { { { FaultGridPart::FW, PartBorderSurface::FaultSurface }, 4 }, - { { FaultGridPart::FW, PartBorderSurface::UpperSurface }, 4 }, - { { FaultGridPart::FW, PartBorderSurface::LowerSurface }, 4 }, + std::map, int> faces = { { { FaultGridPart::FW, PartBorderSurface::FaultSurface }, 5 }, + { { FaultGridPart::FW, PartBorderSurface::UpperSurface }, 5 }, + { { FaultGridPart::FW, PartBorderSurface::LowerSurface }, 5 }, { { FaultGridPart::FW, PartBorderSurface::Seabed }, 2 }, - { { FaultGridPart::HW, PartBorderSurface::FaultSurface }, 4 }, - { { FaultGridPart::HW, PartBorderSurface::UpperSurface }, 4 }, - { { FaultGridPart::HW, PartBorderSurface::LowerSurface }, 4 }, + { { FaultGridPart::HW, PartBorderSurface::FaultSurface }, 5 }, + { { FaultGridPart::HW, PartBorderSurface::UpperSurface }, 5 }, + { { FaultGridPart::HW, PartBorderSurface::LowerSurface }, 5 }, { { FaultGridPart::HW, PartBorderSurface::Seabed }, 2 } }; std::map partNames = { @@ -76,36 +86,35 @@ std::pair RifFaultReactivationModelExporter::exportToStream( { RimFaultReactivation::ElementSets::IntraReservoir, "INTRA_RESERVOIR" }, { RimFaultReactivation::ElementSets::Reservoir, "RESERVOIR" }, { RimFaultReactivation::ElementSets::UnderBurden, "UNDERBURDEN" }, + { RimFaultReactivation::ElementSets::FaultZone, "FAULT_ZONE" }, }; - double faultFriction = 0.0; - bool useGridVoidRatio = rimModel.useGridVoidRatio(); - bool useGridPorePressure = rimModel.useGridPorePressure(); - bool useGridTemperature = rimModel.useGridTemperature(); - bool useGridDensity = rimModel.useGridDensity(); - bool useGridElasticProperties = rimModel.useGridElasticProperties(); - bool useGridStress = rimModel.useGridStress(); + bool useGridVoidRatio = rimModel.useGridVoidRatio(); + bool useGridPorePressure = rimModel.useGridPorePressure(); + bool useGridTemperature = rimModel.useGridTemperature(); + bool useGridDensity = rimModel.useGridDensity(); + bool useGridElasticProperties = rimModel.useGridElasticProperties(); - double seaBedDepth = rimModel.seaBedDepth(); - double waterDensity = rimModel.waterDensity(); - double seaWaterLoad = RiaWellLogUnitTools::gravityAcceleration() * seaBedDepth * waterDensity; - - auto dataAccess = rimModel.dataAccess(); + double seaBedDepth = rimModel.seaBedDepth(); + double waterDensity = rimModel.waterDensity(); + double seaWaterLoad = RiaWellLogUnitTools::gravityAcceleration() * seaBedDepth * waterDensity; + double frictionValue = std::tan( ( rimModel.frictionAngleDeg() / 180.0 ) * std::numbers::pi ); auto model = rimModel.model(); CAF_ASSERT( !model.isNull() ); + const std::string basePath = rimModel.baseFilePath(); + std::vector()>> methods = { [&]() { return printHeading( stream, applicationNameAndVersion ); }, [&]() { return printParts( stream, *model, partNames, borders, faces, boundaries, materialNames ); }, - [&]() { return printAssembly( stream, *model, partNames, model->modelLocalNormalsXY() ); }, - [&]() - { - return printMaterials( stream, rimModel, materialNames, *dataAccess, exportDirectory, partNames, useGridDensity, useGridElasticProperties ); + [&]() { return printAssembly( stream, *model, partNames, !rimModel.useLocalCoordinates(), model->modelLocalNormalsXY() ); }, + [&]() { + return printMaterials( stream, rimModel, materialNames, *dataAccess, basePath, partNames, useGridDensity, useGridElasticProperties ); }, - [&]() { return printInteractionProperties( stream, faultFriction ); }, + [&]() { return printInteractionProperties( stream, frictionValue ); }, [&]() { return printBoundaryConditions( stream, *model, partNames, boundaries ); }, - [&]() { return printPredefinedFields( stream, *model, *dataAccess, exportDirectory, partNames, useGridVoidRatio, useGridStress ); }, + [&]() { return printPredefinedFields( stream, *model, *dataAccess, basePath, partNames, useGridVoidRatio ); }, [&]() { return printInteractions( stream, partNames, borders ); }, [&]() { @@ -114,7 +123,7 @@ std::pair RifFaultReactivationModelExporter::exportToStream( *dataAccess, partNames, rimModel.selectedTimeSteps(), - exportDirectory, + basePath, useGridPorePressure, useGridTemperature, seaWaterLoad ); @@ -133,14 +142,10 @@ std::pair RifFaultReactivationModelExporter::exportToStream( //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::pair RifFaultReactivationModelExporter::exportToFile( const std::string& filePath, - const RimFaultReactivationModel& model ) +std::pair RifFaultReactivationModelExporter::exportToFile( const RimFaultReactivationModel& model ) { - std::filesystem::path p( filePath ); - std::string exportDirectory = p.parent_path().generic_string(); - - std::ofstream stream( filePath ); - return exportToStream( stream, exportDirectory, model ); + std::ofstream stream( model.inputFilename() ); + return exportToStream( stream, model ); } //-------------------------------------------------------------------------------------------------- @@ -199,13 +204,13 @@ std::pair RifFaultReactivationModelExporter::printParts( for ( auto [boundary, boundaryName] : boundaries ) { // Create boundary condition sets for each side of the parts (except top). - auto boundaryNodes = grid->boundaryNodes(); - auto boundaryElements = grid->boundaryElements(); + const auto& boundaryNodes = grid->boundaryNodes(); + const auto& boundaryElements = grid->boundaryElements(); - const std::vector& nodes = boundaryNodes[boundary]; + const std::vector& nodes = boundaryNodes.at( boundary ); RifInpExportTools::printNodeSet( stream, boundaryName, false, nodes ); - const std::vector& elements = boundaryElements[boundary]; + const std::vector& elements = boundaryElements.at( boundary ); RifInpExportTools::printElementSet( stream, boundaryName, false, elements ); } @@ -261,6 +266,7 @@ std::pair RifFaultReactivationModelExporter::printAssembly( std::ostream& stream, const RigFaultReactivationModel& model, const std::map& partNames, + bool includeTransform, const std::pair& transform ) { // ASSEMBLY part @@ -280,15 +286,18 @@ std::pair RifInpExportTools::printHeading( stream, "End Instance" ); } - for ( const auto& part : parts ) + if ( includeTransform ) { - auto partNameIt = partNames.find( part ); - CAF_ASSERT( partNameIt != partNames.end() ); - std::string partName = partNameIt->second; + for ( const auto& part : parts ) + { + auto partNameIt = partNames.find( part ); + CAF_ASSERT( partNameIt != partNames.end() ); + std::string partName = partNameIt->second; - RifInpExportTools::printHeading( stream, "Transform, nset=" + partName + ".ALL" ); - auto [dir1, dir2] = transform; - RifInpExportTools::printNumbers( stream, { dir1.x(), dir1.y(), dir1.z(), dir2.x(), dir2.y(), dir2.z() } ); + RifInpExportTools::printHeading( stream, "Transform, nset=" + partName + ".ALL" ); + auto [dir1, dir2] = transform; + RifInpExportTools::printNumbers( stream, { dir1.x(), dir1.y(), dir1.z(), dir2.x(), dir2.y(), dir2.z() } ); + } } RifInpExportTools::printHeading( stream, "End Assembly" ); @@ -304,7 +313,7 @@ std::pair const RimFaultReactivationModel& rimModel, const std::map& materialNames, const RimFaultReactivationDataAccess& dataAccess, - const std::string& exportDirectory, + const std::string& exportBasePath, const std::map& partNames, bool densityFromGrid, bool elasticPropertiesFromGrid ) @@ -318,6 +327,7 @@ std::pair double poissonNumber; double permeability1; double permeability2; + double expansion; }; RifInpExportTools::printSectionComment( stream, "MATERIALS" ); @@ -325,7 +335,7 @@ std::pair for ( auto [element, materialName] : materialNames ) { - std::array parameters = rimModel.materialParameters( element ); + std::array parameters = rimModel.materialParameters( element ); // Incoming unit for Young's Modulus is GPa: convert to Pa. double youngsModulus = RiaEclipseUnitTools::gigaPascalToPascal( parameters[0] ); @@ -336,12 +346,15 @@ std::pair // Unit is already kg/m^3 double density = parameters[2]; + double expansion = parameters[3]; + materials.push_back( Material{ .name = materialName, .density = density, .youngsModulus = youngsModulus, .poissonNumber = poissonNumber, .permeability1 = 1e-09, - .permeability2 = 0.3 } ); + .permeability2 = 0.3, + .expansion = expansion } ); } for ( Material mat : materials ) @@ -369,15 +382,16 @@ std::pair RifInpExportTools::printHeading( stream, "Permeability, specific=1." ); RifInpExportTools::printNumbers( stream, { mat.permeability1, mat.permeability2 } ); + RifInpExportTools::printHeading( stream, "Expansion" ); + RifInpExportTools::printNumbers( stream, { mat.expansion } ); } if ( densityFromGrid ) { // Export the density to a separate inp file - std::string tableName = "DENSITY"; - std::string fileName = tableName + ".inp"; - - std::string filePath = createFilePath( exportDirectory, fileName ); + std::string tableName = "DENSITY"; + std::string fullPath = exportBasePath + "_" + tableName + ".inp"; + auto [filePath, fileName] = RiaFilePathTools::toFolderAndFileName( QString::fromStdString( fullPath ) ); auto model = rimModel.model(); bool isOk = writePropertiesToFile( *model, @@ -385,21 +399,21 @@ std::pair { RimFaultReactivation::Property::Density }, { "DENSITY" }, 0, - filePath, + fullPath, partNames, tableName, ", 1." ); if ( !isOk ) return { false, "Failed to create density file." }; - RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName ); + RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName.toStdString() ); } if ( elasticPropertiesFromGrid ) { // Export the elastic properties to a separate inp file - std::string tableName = "ELASTICS"; - std::string fileName = tableName + ".inp"; - std::string filePath = createFilePath( exportDirectory, fileName ); + std::string tableName = "ELASTICS"; + std::string fullPath = exportBasePath + "_" + tableName + ".inp"; + auto [filePath, fileName] = RiaFilePathTools::toFolderAndFileName( QString::fromStdString( fullPath ) ); auto model = rimModel.model(); bool isOk = writePropertiesToFile( *model, @@ -407,13 +421,13 @@ std::pair { RimFaultReactivation::Property::YoungsModulus, RimFaultReactivation::Property::PoissonsRatio }, { "MODULUS", "RATIO" }, 0, - filePath, + fullPath, partNames, tableName, ", 2." ); if ( !isOk ) return { false, "Failed to create elastic properties file." }; - RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName ); + RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName.toStdString() ); } return { true, "" }; @@ -498,10 +512,9 @@ std::pair RifFaultReactivationModelExporter::printPredefinedFields( std::ostream& stream, const RigFaultReactivationModel& model, const RimFaultReactivationDataAccess& dataAccess, - const std::string& exportDirectory, + const std::string& exportBasePath, const std::map& partNames, - bool voidRatioFromEclipse, - bool stressFromGrid ) + bool voidRatioFromEclipse ) { // PREDEFINED FIELDS struct PredefinedField @@ -519,10 +532,9 @@ std::pair { fields.push_back( PredefinedField{ .initialConditionType = "RATIO", .partName = name, .value = 0.3 } ); } - fields.push_back( PredefinedField{ .initialConditionType = "PORE PRESSURE", .partName = name, .value = 0.0 } ); } - RifInpExportTools::printSectionComment( stream, "PREDEFINED FIELDS" ); + RifInpExportTools::printSectionComment( stream, "INITIAL CONDITIONS" ); for ( auto field : fields ) { @@ -532,28 +544,26 @@ std::pair if ( voidRatioFromEclipse ) { - std::string ratioName = "RATIO"; - // Export the ratio to a separate inp file for each step - std::string fileName = ratioName + ".inp"; - std::string filePath = createFilePath( exportDirectory, fileName ); + std::string ratioName = "RATIO"; + std::string fullPath = exportBasePath + "_" + ratioName + ".inp"; + auto [filePath, fileName] = RiaFilePathTools::toFolderAndFileName( QString::fromStdString( fullPath ) ); // Use void ratio from first time step size_t timeStep = 0; - bool isOk = writePropertyToFile( model, dataAccess, RimFaultReactivation::Property::VoidRatio, timeStep, filePath, partNames, "" ); + bool isOk = writePropertyToFile( model, dataAccess, RimFaultReactivation::Property::VoidRatio, timeStep, fullPath, partNames, "" ); if ( !isOk ) return { false, "Failed to create " + ratioName + " file." }; RifInpExportTools::printHeading( stream, "Initial Conditions, TYPE=" + ratioName ); - RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName ); + RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName.toStdString() ); } - if ( stressFromGrid ) + // stress export { - std::string stressName = "STRESS"; - // Export the stress to a separate inp file - std::string fileName = stressName + ".inp"; - std::string filePath = createFilePath( exportDirectory, fileName ); + std::string stressName = "STRESS"; + std::string fullPath = exportBasePath + "_" + stressName + ".inp"; + auto [filePath, fileName] = RiaFilePathTools::toFolderAndFileName( QString::fromStdString( fullPath ) ); // Use stress from first time step size_t timeStep = 0; @@ -567,15 +577,15 @@ std::pair RimFaultReactivation::Property::LateralStressComponentY }, {}, timeStep, - filePath, + fullPath, partNames, "", "" ); if ( !isOk ) return { false, "Failed to create " + stressName + " file." }; - RifInpExportTools::printHeading( stream, "Initial Conditions, TYPE=" + stressName ); - RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName ); + RifInpExportTools::printHeading( stream, "Initial Conditions, TYPE=" + stressName + ", geostatic" ); + RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName.toStdString() ); } return { true, "" }; @@ -589,7 +599,7 @@ std::pair RifFaultReactivationModelExporter::printSteps( std: const RimFaultReactivationDataAccess& dataAccess, const std::map& partNames, const std::vector& timeSteps, - const std::string& exportDirectory, + const std::string& exportBasePath, bool useGridPorePressure, bool useGridTemperature, double seaWaterLoad ) @@ -601,17 +611,21 @@ std::pair RifFaultReactivationModelExporter::printSteps( std: { std::string stepNum = std::to_string( i + 1 ); std::string stepName = timeSteps[i].toString( "yyyy-MM-dd" ).toStdString(); + if ( i == 0 ) stepName = "Geostatic_" + stepName; + std::string stepType = i == 0 ? "Geostatic, utol" : "Soils, utol=1.0"; + RifInpExportTools::printComment( stream, "----------------------------------------------------------------" ); RifInpExportTools::printSectionComment( stream, "STEP: " + stepName ); RifInpExportTools::printHeading( stream, "Step, name=" + stepName + ", nlgeom=NO" ); - std::string stepType = i == 0 ? "Geostatic, utol" : "Soils, utol=1.0"; RifInpExportTools::printHeading( stream, stepType ); RifInpExportTools::printNumbers( stream, { 1.0, 1.0, 1e-05, 1.0 } ); if ( i == 0 ) { + RifInpExportTools::printComment( stream, "GRAVITY LOADS FROM ROCK AND SEAWATER" ); + RifInpExportTools::printHeading( stream, "Dload" ); RifInpExportTools::printLine( stream, ",GRAV, 9.80665, 0., 0., -1." ); @@ -630,15 +644,16 @@ std::pair RifFaultReactivationModelExporter::printSteps( std: RifInpExportTools::printSectionComment( stream, "BOUNDARY CONDITIONS" ); // Export the pore pressure to a separate inp file for each step - std::string fileName = createFileName( "PORE_PRESSURE", stepName ); - std::string filePath = createFilePath( exportDirectory, fileName ); + std::string postfix = createFilePostfix( "PORE_PRESSURE", stepName ); + std::string fullPath = exportBasePath + postfix; + auto [filePath, fileName] = RiaFilePathTools::toFolderAndFileName( QString::fromStdString( fullPath ) ); bool isOk = - writePropertyToFile( model, dataAccess, RimFaultReactivation::Property::PorePressure, i, filePath, partNames, "8, 8, " ); + writePropertyToFile( model, dataAccess, RimFaultReactivation::Property::PorePressure, i, fullPath, partNames, "8, 8, " ); if ( !isOk ) return { false, "Failed to create pore pressure file." }; RifInpExportTools::printHeading( stream, "Boundary, type=displacement" ); - RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName ); + RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName.toStdString() ); } if ( useGridTemperature ) @@ -646,23 +661,25 @@ std::pair RifFaultReactivationModelExporter::printSteps( std: RifInpExportTools::printSectionComment( stream, "TEMPERATURE" ); // Export the temperature to a separate inp file for each step - std::string fileName = createFileName( "TEMPERATURE", stepName ); - std::string filePath = createFilePath( exportDirectory, fileName ); + std::string postfix = createFilePostfix( "TEMPERATURE", stepName ); + std::string fullPath = exportBasePath + postfix; + auto [filePath, fileName] = RiaFilePathTools::toFolderAndFileName( QString::fromStdString( fullPath ) ); - bool isOk = writePropertyToFile( model, dataAccess, RimFaultReactivation::Property::Temperature, i, filePath, partNames, "" ); + bool isOk = writePropertyToFile( model, dataAccess, RimFaultReactivation::Property::Temperature, i, fullPath, partNames, "" ); if ( !isOk ) return { false, "Failed to create temperature file." }; RifInpExportTools::printHeading( stream, "Temperature" ); - RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName ); + RifInpExportTools::printHeading( stream, "INCLUDE, input=" + fileName.toStdString() ); } - RifInpExportTools::printSectionComment( stream, "OUTPUT REQUESTS" ); - RifInpExportTools::printHeading( stream, "Restart, write, frequency=0" ); - - RifInpExportTools::printSectionComment( stream, "FIELD OUTPUT: F-Output-" + stepNum ); - RifInpExportTools::printHeading( stream, "Output, field, variable=PRESELECT" ); + RifInpExportTools::printSectionComment( stream, "OUTPUT" ); + RifInpExportTools::printHeading( stream, "Output, field" ); + RifInpExportTools::printHeading( stream, "Node Output" ); + RifInpExportTools::printLine( stream, "COORD, POR, U" ); + RifInpExportTools::printHeading( stream, "Element Output" ); + RifInpExportTools::printLine( stream, "COORD, VOIDR, S, E, TEMP" ); - RifInpExportTools::printSectionComment( stream, "HISTORY OUTPUT: H-Output-" + stepNum ); + RifInpExportTools::printComment( stream, "" ); RifInpExportTools::printHeading( stream, "Output, history, variable=PRESELECT" ); RifInpExportTools::printHeading( stream, "End Step" ); @@ -797,15 +814,56 @@ std::pair //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::string RifFaultReactivationModelExporter::createFileName( const std::string& title, const std::string& stepName ) +std::string RifFaultReactivationModelExporter::createFilePostfix( const std::string& title, const std::string& stepName ) { - return QString( "%1_%2.inp" ).arg( QString::fromStdString( title ) ).arg( QString::fromStdString( stepName ) ).toStdString(); + return QString( "_%1_%2.inp" ).arg( QString::fromStdString( title ) ).arg( QString::fromStdString( stepName ) ).toStdString(); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::string RifFaultReactivationModelExporter::createFilePath( const std::string& dir, const std::string& fileName ) +bool RifFaultReactivationModelExporter::exportModelSettings( const RimFaultReactivationModel& rimModel ) { - return dir + "/" + fileName; -}; + auto model = rimModel.model(); + + if ( model.isNull() ) return false; + if ( !model->isValid() ) return false; + + QMap settings; + + auto [topPosition, bottomPosition] = model->faultTopBottom(); + auto faultNormal = model->modelNormal(); + + // make sure we export in local coordinates, if that is used + topPosition = model->transformPointIfNeeded( topPosition ); + bottomPosition = model->transformPointIfNeeded( bottomPosition ); + + // make sure we move horizontally, and along the 2D model + faultNormal.z() = 0.0; + faultNormal.normalize(); + faultNormal = faultNormal ^ cvf::Vec3d::Z_AXIS; + + RimFaultReactivationTools::addSettingsToMap( settings, faultNormal, topPosition, bottomPosition ); + return ResInsightInternalJson::JsonWriter::encodeFile( QString::fromStdString( rimModel.settingsFilename() ), settings ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::shared_ptr + RifFaultReactivationModelExporter::extractAndExportModelData( const RimFaultReactivationModel& rimModel ) +{ + if ( !exportModelSettings( rimModel ) ) return nullptr; + + auto eCase = rimModel.eclipseCase(); + if ( eCase == nullptr ) return nullptr; + + // extract data for each timestep + auto dataAccess = std::make_shared( rimModel, + eCase, + rimModel.geoMechCase(), + rimModel.selectedTimeStepIndexes(), + rimModel.stressSource() ); + dataAccess->extractModelData( *rimModel.model() ); + return dataAccess; +} diff --git a/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.h b/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.h index 14dffd1e79..033cdf091a 100644 --- a/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.h +++ b/ApplicationLibCode/FileInterface/RifFaultReactivationModelExporter.h @@ -21,6 +21,7 @@ #include "RigFaultReactivationModel.h" #include "RigGriddedPart3d.h" +#include "RimFaultReactivationDataAccess.h" #include "RimFaultReactivationModel.h" #include @@ -34,9 +35,8 @@ class RifFaultReactivationModelExporter { public: - static std::pair - exportToStream( std::ostream& stream, const std::string& exportDirecotry, const RimFaultReactivationModel& model ); - static std::pair exportToFile( const std::string& filePath, const RimFaultReactivationModel& model ); + static std::pair exportToStream( std::ostream& stream, const RimFaultReactivationModel& model ); + static std::pair exportToFile( const RimFaultReactivationModel& model ); private: static std::pair printHeading( std::ostream& stream, const std::string& applicationNameAndVersion ); @@ -52,6 +52,7 @@ class RifFaultReactivationModelExporter static std::pair printAssembly( std::ostream& stream, const RigFaultReactivationModel& model, const std::map& partNames, + bool includeTransform, const std::pair& transform ); static std::pair printMaterials( std::ostream& stream, @@ -73,8 +74,7 @@ class RifFaultReactivationModelExporter const RimFaultReactivationDataAccess& dataAccess, const std::string& exportDirectory, const std::map& partNames, - bool useGridVoidRatio, - bool useGridStress ); + bool useGridVoidRatio ); static std::pair printSteps( std::ostream& stream, const RigFaultReactivationModel& model, const RimFaultReactivationDataAccess& dataAccess, @@ -108,7 +108,8 @@ class RifFaultReactivationModelExporter const std::string& tableName, const std::string& heading ); - static std::string createFileName( const std::string& title, const std::string& stepName ); + static std::string createFilePostfix( const std::string& title, const std::string& stepName ); - static std::string createFilePath( const std::string& dir, const std::string& fileName ); + static bool exportModelSettings( const RimFaultReactivationModel& model ); + static std::shared_ptr extractAndExportModelData( const RimFaultReactivationModel& model ); }; diff --git a/ApplicationLibCode/FileInterface/RifInpExportTools.cpp b/ApplicationLibCode/FileInterface/RifInpExportTools.cpp index 19c792f37d..f4a7957e11 100644 --- a/ApplicationLibCode/FileInterface/RifInpExportTools.cpp +++ b/ApplicationLibCode/FileInterface/RifInpExportTools.cpp @@ -61,7 +61,7 @@ bool RifInpExportTools::printNodes( std::ostream& stream, const std::vector map ) { QFile file; file.setFileName( filePath ); - if ( file.open( QIODevice::ReadWrite | QIODevice::Text ) ) + if ( file.open( QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate ) ) { QString content = Json::encode( map, true ); QTextStream out( &file ); diff --git a/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.cpp b/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.cpp index 785220b1f2..98df37a642 100644 --- a/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.cpp +++ b/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.cpp @@ -36,7 +36,7 @@ void RifMultipleSummaryReaders::addReader( RifSummaryReaderInterface* reader ) m_readers.push_back( reader ); - rebuildMetaData(); + buildMetaData(); } //-------------------------------------------------------------------------------------------------- @@ -45,7 +45,7 @@ void RifMultipleSummaryReaders::addReader( RifSummaryReaderInterface* reader ) void RifMultipleSummaryReaders::removeReader( RifSummaryReaderInterface* reader ) { m_readers.erase( reader ); - rebuildMetaData(); + buildMetaData(); } //-------------------------------------------------------------------------------------------------- @@ -100,7 +100,7 @@ RiaDefines::EclipseUnitSystem RifMultipleSummaryReaders::unitSystem() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RifMultipleSummaryReaders::rebuildMetaData() +void RifMultipleSummaryReaders::buildMetaData() { m_allErrorAddresses.clear(); m_allResultAddresses.clear(); diff --git a/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.h b/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.h index a18d91fa09..996fa4e66a 100644 --- a/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.h +++ b/ApplicationLibCode/FileInterface/RifMultipleSummaryReaders.h @@ -40,7 +40,7 @@ class RifMultipleSummaryReaders : public RifSummaryReaderInterface std::string unitName( const RifEclipseSummaryAddress& resultAddress ) const override; RiaDefines::EclipseUnitSystem unitSystem() const override; - void rebuildMetaData(); + void buildMetaData() override; private: cvf::Collection m_readers; diff --git a/ApplicationLibCode/FileInterface/RifOpmCommonSummary.cpp b/ApplicationLibCode/FileInterface/RifOpmCommonSummary.cpp index 6b411262b9..bfad38a75b 100644 --- a/ApplicationLibCode/FileInterface/RifOpmCommonSummary.cpp +++ b/ApplicationLibCode/FileInterface/RifOpmCommonSummary.cpp @@ -398,9 +398,9 @@ std::pair, std::map threadAddresses; - std::map threadAddressToKeywordMap; - std::vector threadInvalidKeywords; + std::vector threadAddresses; + std::vector> threadAddressToKeywordMap; + std::vector threadInvalidKeywords; #pragma omp for for ( int index = 0; index < (int)keywords.size(); index++ ) @@ -418,8 +418,8 @@ std::pair, std::map +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RifPolygonReader.h" + +#include "RiaTextStringTools.h" + +#include "SummaryPlotCommands/RicPasteAsciiDataToSummaryPlotFeatureUi.h" + +#include "RifCsvUserDataParser.h" + +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector>> RifPolygonReader::parsePolygonFile( const QString& fileName, QString* errorMessage ) +{ + QFileInfo fi( fileName ); + + QFile dataFile( fileName ); + + if ( !dataFile.open( QFile::ReadOnly ) ) + { + if ( errorMessage ) ( *errorMessage ) += "Could not open file: " + fileName + "\n"; + return {}; + } + + QTextStream stream( &dataFile ); + auto fileContent = stream.readAll(); + + if ( fi.suffix().trimmed().toLower() == "csv" ) + { + return parseTextCsv( fileContent, errorMessage ); + } + else + { + auto polygons = parseText( fileContent, errorMessage ); + + std::vector>> polygonsWithIds; + for ( auto& polygon : polygons ) + { + polygonsWithIds.push_back( std::make_pair( -1, polygon ) ); + } + + return polygonsWithIds; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector> RifPolygonReader::parseText( const QString& content, QString* errorMessage ) +{ + std::vector> polylines( 1 ); + + QString myString = content; + QTextStream stream( &myString ); + int lineNumber = 1; + while ( !stream.atEnd() ) + { + QString line = stream.readLine(); + QStringList commentLineSegs = line.split( "#" ); + if ( commentLineSegs.empty() ) continue; // Empty line + + QStringList lineSegs = RiaTextStringTools::splitSkipEmptyParts( commentLineSegs[0], QRegExp( "\\s+" ) ); + + if ( lineSegs.empty() ) continue; // No data + + if ( lineSegs.size() != 3 ) + { + if ( errorMessage ) ( *errorMessage ) += "Unexpected number of words on line: " + QString::number( lineNumber ) + "\n"; + continue; + } + + { + bool isNumberParsingOk = true; + bool isOk = true; + double x = lineSegs[0].toDouble( &isOk ); + isNumberParsingOk &= isOk; + double y = lineSegs[1].toDouble( &isOk ); + isNumberParsingOk &= isOk; + double z = lineSegs[2].toDouble( &isOk ); + isNumberParsingOk &= isOk; + + if ( !isNumberParsingOk ) + { + if ( errorMessage ) ( *errorMessage ) += "Could not read the point at line: " + QString::number( lineNumber ) + "\n"; + continue; + } + + if ( x == 999.0 && y == 999.0 && z == 999.0 ) // New PolyLine + { + polylines.push_back( std::vector() ); + continue; + } + + cvf::Vec3d point( x, y, -z ); + polylines.back().push_back( point ); + } + + ++lineNumber; + } + + if ( polylines.back().empty() ) + { + polylines.pop_back(); + } + + return polylines; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector>> RifPolygonReader::parseTextCsv( const QString& content, QString* errorMessage ) +{ + RifCsvUserDataPastedTextParser parser( content, errorMessage ); + + AsciiDataParseOptions parseOptions; + parseOptions.cellSeparator = ","; + parseOptions.decimalSeparator = "."; + + std::vector>> readValues; + + if ( parser.parse( parseOptions ) ) + { + for ( auto s : parser.tableData().columnInfos() ) + { + if ( s.dataType != Column::NUMERIC ) continue; + + QString columnName = QString::fromStdString( s.columnName() ); + bool isNumber = false; + auto value = columnName.toDouble( &isNumber ); + std::vector values = s.values; + if ( isNumber ) + { + values.insert( values.begin(), value ); + } + readValues.push_back( { columnName, values } ); + } + } + + if ( readValues.size() == 4 ) + { + // Three first columns represent XYZ, last column polygon ID + + const auto firstSize = readValues[0].second.size(); + if ( ( firstSize == readValues[1].second.size() ) && ( firstSize == readValues[2].second.size() ) && + ( firstSize == readValues[3].second.size() ) ) + { + std::vector>> polylines; + + std::vector polygon; + + int polygonId = -1; + for ( size_t i = 0; i < firstSize; i++ ) + { + int currentPolygonId = static_cast( readValues[3].second[i] ); + if ( polygonId != currentPolygonId ) + { + if ( !polygon.empty() ) polylines.push_back( std::make_pair( polygonId, polygon ) ); + polygon.clear(); + polygonId = currentPolygonId; + } + + cvf::Vec3d point( readValues[0].second[i], readValues[1].second[i], -readValues[2].second[i] ); + + polygon.push_back( point ); + } + + if ( !polygon.empty() ) polylines.push_back( std::make_pair( polygonId, polygon ) ); + + return polylines; + } + } + + if ( readValues.size() == 3 ) + { + std::vector points; + + for ( size_t i = 0; i < readValues[0].second.size(); i++ ) + { + cvf::Vec3d point( readValues[0].second[i], readValues[1].second[i], -readValues[2].second[i] ); + points.push_back( point ); + } + + int polygonId = -1; + return { std::make_pair( polygonId, points ) }; + } + + return {}; +} diff --git a/ApplicationLibCode/FileInterface/RifPolygonReader.h b/ApplicationLibCode/FileInterface/RifPolygonReader.h new file mode 100644 index 0000000000..da7a91b78f --- /dev/null +++ b/ApplicationLibCode/FileInterface/RifPolygonReader.h @@ -0,0 +1,40 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cvfVector3.h" + +#include + +#include + +//================================================================================================== +// +// +//================================================================================================== +class RifPolygonReader +{ +public: + static std::vector>> parsePolygonFile( const QString& fileName, QString* errorMessage ); + + // Defined public for testing purposes +public: + static std::vector> parseText( const QString& content, QString* errorMessage ); + static std::vector>> parseTextCsv( const QString& content, QString* errorMessage ); +}; diff --git a/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.cpp b/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.cpp index cfeb6c8b70..f1d068205f 100644 --- a/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.cpp +++ b/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.cpp @@ -19,15 +19,13 @@ #include "RifPressureDepthTextFileReader.h" #include "RiaDateStringParser.h" -#include "RiaDefines.h" #include "RigPressureDepthData.h" #include "RifFileParseTools.h" -#include "cafAssert.h" - #include +#include #include //-------------------------------------------------------------------------------------------------- @@ -43,9 +41,20 @@ std::pair, QString> RifPressureDepthTextFileRe return std::make_pair( items, QString( "Unable to open file: %1" ).arg( filePath ) ); } + return parse( file.readAll() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair, QString> RifPressureDepthTextFileReader::parse( const QString& content ) +{ + std::vector items; + QString separator = " "; - QTextStream in( &file ); + QString streamContent( content ); + QTextStream in( &streamContent ); while ( !in.atEnd() ) { QString line = in.readLine(); @@ -64,7 +73,7 @@ std::pair, QString> RifPressureDepthTextFileRe items.back().setTimeStep( date.value() ); } } - else if ( isPropertiesLine( line ) || isUnitsLine( line ) || isCommentLine( line ) ) + else if ( containsLetters( line ) || isCommentLine( line ) ) { // Ignored. } @@ -105,19 +114,10 @@ bool RifPressureDepthTextFileReader::isDateLine( const QString& line ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RifPressureDepthTextFileReader::isPropertiesLine( const QString& line ) -{ - // TODO: this might be to strict.. - return line.startsWith( "PRESSURE DEPTH" ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RifPressureDepthTextFileReader::isUnitsLine( const QString& line ) +bool RifPressureDepthTextFileReader::containsLetters( const QString& line ) { - // TODO: this might be to strict.. - return line.startsWith( "BARSA METRES" ); + QRegularExpression regex( "[a-zA-Z]" ); + return regex.match( line ).hasMatch(); } //-------------------------------------------------------------------------------------------------- @@ -152,8 +152,6 @@ std::optional RifPressureDepthTextFileReader::parseDateLine( const QS QStringList values = RifFileParseTools::splitLineAndTrim( line, " ", skipEmptyParts ); if ( values.size() != 2 ) return {}; - CAF_ASSERT( values[0] == "DATE" ); - // Second value is depth QDateTime dateTime = RiaDateStringParser::parseDateString( values[1], RiaDateStringParser::OrderPreference::DAY_FIRST ); if ( !dateTime.isValid() ) return {}; diff --git a/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.h b/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.h index 030cec4b4c..69f58bd996 100644 --- a/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.h +++ b/ApplicationLibCode/FileInterface/RifPressureDepthTextFileReader.h @@ -21,7 +21,6 @@ #include #include -#include #include #include @@ -34,13 +33,13 @@ class RifPressureDepthTextFileReader { public: static std::pair, QString> readFile( const QString& fileName ); + static std::pair, QString> parse( const QString& content ); private: static bool isHeaderLine( const QString& line ); static bool isCommentLine( const QString& line ); static bool isDateLine( const QString& line ); - static bool isPropertiesLine( const QString& line ); - static bool isUnitsLine( const QString& line ); + static bool containsLetters( const QString& line ); static std::optional> parseDataLine( const QString& line ); static std::optional parseDateLine( const QString& line ); diff --git a/ApplicationLibCode/FileInterface/RifReaderEclipseInput.cpp b/ApplicationLibCode/FileInterface/RifReaderEclipseInput.cpp index 852d6b594c..c737a7a75d 100644 --- a/ApplicationLibCode/FileInterface/RifReaderEclipseInput.cpp +++ b/ApplicationLibCode/FileInterface/RifReaderEclipseInput.cpp @@ -73,7 +73,7 @@ bool RifReaderEclipseInput::open( const QString& fileName, RigEclipseCaseData* e // create InputProperty object bool isOk = false; - if ( eclipseCase->mainGrid()->gridPointDimensions() == cvf::Vec3st( 0, 0, 0 ) ) + if ( eclipseCase->mainGrid()->cellCount() == 0 ) { QString errorMesssages; isOk = RifEclipseInputFileTools::openGridFile( fileName, eclipseCase, isFaultImportEnabled(), &errorMesssages ); diff --git a/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.cpp b/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.cpp index b4ee519238..78621b4e02 100644 --- a/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.cpp +++ b/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.cpp @@ -379,14 +379,13 @@ bool RifReaderEclipseOutput::open( const QString& fileName, RigEclipseCaseData* if ( !RifEclipseOutputFileTools::findSiblingFilesWithSameBaseName( fileName, &fileSet ) ) return false; - m_fileName = fileName; + m_fileName = fileName; + m_filesWithSameBaseName = fileSet; } ecl_grid_type* mainEclGrid = nullptr; { auto task = progress.task( "Open Init File and Load Main Grid", 19 ); - // Keep the set of files of interest - m_filesWithSameBaseName = fileSet; openInitFile(); @@ -608,39 +607,6 @@ const size_t* RifReaderEclipseOutput::eclipseCellIndexMapping() return cellMappingECLRi; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RifReaderEclipseOutput::importFaults( const QStringList& fileSet, cvf::Collection* faults ) -{ - if ( !filenamesWithFaults().empty() ) - { - for ( size_t i = 0; i < filenamesWithFaults().size(); i++ ) - { - QString faultFilename = filenamesWithFaults()[i]; - - RifEclipseInputFileTools::parseAndReadFaults( faultFilename, faults ); - } - } - else - { - foreach ( QString fname, fileSet ) - { - if ( fname.endsWith( ".DATA" ) ) - { - std::vector filenamesWithFaults; - RifEclipseInputFileTools::readFaultsInGridSection( fname, faults, &filenamesWithFaults, faultIncludeFileAbsolutePathPrefix() ); - - std::sort( filenamesWithFaults.begin(), filenamesWithFaults.end() ); - std::vector::iterator last = std::unique( filenamesWithFaults.begin(), filenamesWithFaults.end() ); - filenamesWithFaults.erase( last, filenamesWithFaults.end() ); - - setFilenamesWithFaults( filenamesWithFaults ); - } - } - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.h b/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.h index 7984fc88b7..39d976de4b 100644 --- a/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.h +++ b/ApplicationLibCode/FileInterface/RifReaderEclipseOutput.h @@ -103,8 +103,6 @@ class RifReaderEclipseOutput : public RifReaderInterface const well_segment_type* segment, const char* wellName ); - void importFaults( const QStringList& fileSet, cvf::Collection* faults ); - void openInitFile(); void extractResultValuesBasedOnPorosityModel( RiaDefines::PorosityModelType matrixOrFracture, diff --git a/ApplicationLibCode/FileInterface/RifReaderEclipseSummary.h b/ApplicationLibCode/FileInterface/RifReaderEclipseSummary.h index 7028e384d3..769aaf1251 100644 --- a/ApplicationLibCode/FileInterface/RifReaderEclipseSummary.h +++ b/ApplicationLibCode/FileInterface/RifReaderEclipseSummary.h @@ -54,10 +54,9 @@ class RifReaderEclipseSummary : public RifSummaryReaderInterface std::pair> values( const RifEclipseSummaryAddress& resultAddress ) const override; std::string unitName( const RifEclipseSummaryAddress& resultAddress ) const override; RiaDefines::EclipseUnitSystem unitSystem() const override; + void buildMetaData() override; private: - void buildMetaData(); - RifSummaryReaderInterface* currentSummaryReader() const; private: diff --git a/ApplicationLibCode/FileInterface/RifReaderEnsembleStatisticsRft.h b/ApplicationLibCode/FileInterface/RifReaderEnsembleStatisticsRft.h index 086d2aa30f..e343d0b618 100644 --- a/ApplicationLibCode/FileInterface/RifReaderEnsembleStatisticsRft.h +++ b/ApplicationLibCode/FileInterface/RifReaderEnsembleStatisticsRft.h @@ -29,7 +29,7 @@ class RimSummaryCaseCollection; class RimEclipseCase; class RigWellPath; -class RifReaderEnsembleStatisticsRft : public RifReaderRftInterface, public cvf::Object +class RifReaderEnsembleStatisticsRft : public RifReaderRftInterface { public: RifReaderEnsembleStatisticsRft( const RimSummaryCaseCollection* summaryCaseCollection, RimEclipseCase* eclipseCase ); diff --git a/ApplicationLibCode/FileInterface/RifReaderInterface.cpp b/ApplicationLibCode/FileInterface/RifReaderInterface.cpp index 9012df12ca..341f172dbb 100644 --- a/ApplicationLibCode/FileInterface/RifReaderInterface.cpp +++ b/ApplicationLibCode/FileInterface/RifReaderInterface.cpp @@ -21,6 +21,7 @@ #include "RiaPreferences.h" +#include "RifEclipseInputFileTools.h" #include "RifReaderSettings.h" //-------------------------------------------------------------------------------------------------- @@ -144,3 +145,36 @@ void RifReaderInterface::setReaderSettings( std::shared_ptr r { m_readerSettings = readerSettings; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifReaderInterface::importFaults( const QStringList& fileSet, cvf::Collection* faults ) +{ + if ( !filenamesWithFaults().empty() ) + { + for ( size_t i = 0; i < filenamesWithFaults().size(); i++ ) + { + QString faultFilename = filenamesWithFaults()[i]; + + RifEclipseInputFileTools::parseAndReadFaults( faultFilename, faults ); + } + } + else + { + foreach ( QString fname, fileSet ) + { + if ( fname.endsWith( ".DATA" ) ) + { + std::vector filenamesWithFaults; + RifEclipseInputFileTools::readFaultsInGridSection( fname, faults, &filenamesWithFaults, faultIncludeFileAbsolutePathPrefix() ); + + std::sort( filenamesWithFaults.begin(), filenamesWithFaults.end() ); + std::vector::iterator last = std::unique( filenamesWithFaults.begin(), filenamesWithFaults.end() ); + filenamesWithFaults.erase( last, filenamesWithFaults.end() ); + + setFilenamesWithFaults( filenamesWithFaults ); + } + } + } +} diff --git a/ApplicationLibCode/FileInterface/RifReaderInterface.h b/ApplicationLibCode/FileInterface/RifReaderInterface.h index 9bd4e4477b..7619b392e3 100644 --- a/ApplicationLibCode/FileInterface/RifReaderInterface.h +++ b/ApplicationLibCode/FileInterface/RifReaderInterface.h @@ -23,6 +23,7 @@ #include "RiaDefines.h" #include "RiaPorosityModel.h" +#include "cvfCollection.h" #include "cvfObject.h" #include "cafPdmPointer.h" @@ -36,6 +37,7 @@ class RigEclipseCaseData; class RifReaderSettings; +class RigFault; //================================================================================================== // @@ -77,6 +79,7 @@ class RifReaderInterface : public cvf::Object protected: bool isTimeStepIncludedByFilter( size_t timeStepIndex ) const; size_t timeStepIndexOnFile( size_t timeStepIndex ) const; + void importFaults( const QStringList& fileSet, cvf::Collection* faults ); private: const RifReaderSettings* readerSettings() const; diff --git a/ApplicationLibCode/FileInterface/RifReaderOpmCommon.cpp b/ApplicationLibCode/FileInterface/RifReaderOpmCommon.cpp index 546f7c21bd..a71d9b4a04 100644 --- a/ApplicationLibCode/FileInterface/RifReaderOpmCommon.cpp +++ b/ApplicationLibCode/FileInterface/RifReaderOpmCommon.cpp @@ -31,6 +31,8 @@ #include "RigSimWellData.h" #include "RigWellResultFrame.h" +#include "cafProgressInfo.h" + #include "opm/input/eclipse/Deck/Deck.hpp" #include "opm/input/eclipse/EclipseState/Runspec.hpp" #include "opm/input/eclipse/Parser/Parser.hpp" @@ -41,6 +43,7 @@ #include "opm/io/eclipse/RestartFileView.hpp" #include "opm/io/eclipse/rst/state.hpp" #include "opm/output/eclipse/VectorItems/group.hpp" +#include "opm/output/eclipse/VectorItems/intehead.hpp" #include "opm/output/eclipse/VectorItems/well.hpp" using namespace Opm; @@ -64,6 +67,8 @@ RifReaderOpmCommon::~RifReaderOpmCommon() //-------------------------------------------------------------------------------------------------- bool RifReaderOpmCommon::open( const QString& fileName, RigEclipseCaseData* eclipseCase ) { + caf::ProgressInfo progress( 100, "Reading Grid" ); + QStringList fileSet; if ( !RifEclipseOutputFileTools::findSiblingFilesWithSameBaseName( fileName, &fileSet ) ) return false; @@ -78,7 +83,24 @@ bool RifReaderOpmCommon::open( const QString& fileName, RigEclipseCaseData* ecli return false; } - buildMetaData( eclipseCase ); + { + auto task = progress.task( "Reading faults", 25 ); + + if ( isFaultImportEnabled() ) + { + cvf::Collection faults; + + importFaults( fileSet, &faults ); + + RigMainGrid* mainGrid = eclipseCase->mainGrid(); + mainGrid->setFaults( faults ); + } + } + + { + auto task = progress.task( "Reading Results Meta data", 50 ); + buildMetaData( eclipseCase ); + } return true; } @@ -125,6 +147,10 @@ bool RifReaderOpmCommon::staticResult( const QString& result, RiaDefines::Porosi } } } + + // Always clear data after reading to avoid memory use + m_initFile->clearData(); + return true; } catch ( std::exception& e ) @@ -177,6 +203,9 @@ bool RifReaderOpmCommon::dynamicResult( const QString& result, } } + // Always clear data after reading to avoid memory use + m_restartFile->clearData(); + return true; } catch ( std::exception& e ) @@ -264,7 +293,7 @@ void RifReaderOpmCommon::buildMetaData( RigEclipseCaseData* eclipseCase ) QDate date( timeStep.year, timeStep.month, timeStep.day ); QDateTime dateTime = RiaQDateTimeTools::createDateTime( date ); dateTimes.push_back( dateTime ); - timeStepInfos.emplace_back( dateTime, timeStep.sequenceNumber, 0.0 ); + timeStepInfos.emplace_back( dateTime, timeStep.sequenceNumber, timeStep.simulationTimeFromStart ); } m_timeSteps = dateTimes; @@ -434,31 +463,40 @@ void RifReaderOpmCommon::readWellCells( std::shared_ptr restartFil //-------------------------------------------------------------------------------------------------- std::vector RifReaderOpmCommon::readTimeSteps( std::shared_ptr restartFile ) { - // It is required to create a deck as the input parameter to runspec. The default() initialization of the runspec keyword does not - // initialize the object as expected. - - Deck deck; - Runspec runspec( deck ); - Parser parser( false ); - std::vector reportTimeData; try { - for ( auto seqNumber : restartFile->listOfReportStepNumbers() ) + namespace VI = Opm::RestartIO::Helpers::VectorItems; + + for ( auto seqNum : restartFile->listOfReportStepNumbers() ) { - auto fileView = std::make_shared( restartFile, seqNumber ); + const std::string inteheadString = "INTEHEAD"; + const std::string doubheadString = "DOUBHEAD"; - auto state = RestartIO::RstState::load( fileView, runspec, parser ); - auto header = state.header; + if ( restartFile->hasArray( inteheadString, seqNum ) ) + { + auto intehead = restartFile->getRestartData( inteheadString, seqNum ); + auto year = intehead[VI::intehead::YEAR]; + auto month = intehead[VI::intehead::MONTH]; + auto day = intehead[VI::intehead::DAY]; - int year = header.year; - int month = header.month; - int day = header.mday; + double daySinceSimStart = 0.0; - double daySinceSimStart = header.next_timestep1; + if ( restartFile->hasArray( doubheadString, seqNum ) ) + { + auto doubhead = restartFile->getRestartData( doubheadString, seqNum ); + if ( !doubhead.empty() ) + { + // Read out the simulation time from start from DOUBHEAD. There is no enum defined to access this value. + // https://github.com/OPM/ResInsight/issues/11092 - reportTimeData.emplace_back( - TimeDataFile{ .sequenceNumber = seqNumber, .year = year, .month = month, .day = day, .simulationTimeFromStart = daySinceSimStart } ); + daySinceSimStart = doubhead[0]; + } + } + + reportTimeData.emplace_back( + TimeDataFile{ .sequenceNumber = seqNum, .year = year, .month = month, .day = day, .simulationTimeFromStart = daySinceSimStart } ); + } } } catch ( std::exception& e ) diff --git a/ApplicationLibCode/FileInterface/RifReaderOpmCommon.h b/ApplicationLibCode/FileInterface/RifReaderOpmCommon.h index 4f7bbb121b..457d69d12f 100644 --- a/ApplicationLibCode/FileInterface/RifReaderOpmCommon.h +++ b/ApplicationLibCode/FileInterface/RifReaderOpmCommon.h @@ -35,15 +35,6 @@ class ERst; class RifReaderOpmCommon : public RifReaderInterface { public: - struct TimeDataFile - { - int sequenceNumber; - int year; - int month; - int day; - double simulationTimeFromStart; - }; - RifReaderOpmCommon(); ~RifReaderOpmCommon() override; @@ -55,6 +46,15 @@ class RifReaderOpmCommon : public RifReaderInterface private: void buildMetaData( RigEclipseCaseData* eclipseCase ); + struct TimeDataFile + { + int sequenceNumber; + int year; + int month; + int day; + double simulationTimeFromStart; + }; + static std::vector readTimeSteps( std::shared_ptr restartFile ); static void readWellCells( std::shared_ptr restartFile, RigEclipseCaseData* eclipseCase, diff --git a/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.cpp b/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.cpp index 599ab33b0e..01ee289adb 100644 --- a/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.cpp +++ b/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.cpp @@ -49,6 +49,13 @@ RifEclipseSummaryAddress RifSummaryReaderInterface::errorAddress( const RifEclip return m_allErrorAddresses.find( errAddr ) != m_allErrorAddresses.end() ? errAddr : RifEclipseSummaryAddress(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifSummaryReaderInterface::buildMetaData() +{ +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.h b/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.h index 1c7c3b32a4..efdd2973c6 100644 --- a/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.h +++ b/ApplicationLibCode/FileInterface/RifSummaryReaderInterface.h @@ -51,6 +51,8 @@ class RifSummaryReaderInterface : public cvf::Object virtual std::string unitName( const RifEclipseSummaryAddress& resultAddress ) const = 0; virtual RiaDefines::EclipseUnitSystem unitSystem() const = 0; + virtual void buildMetaData(); + protected: std::set m_allResultAddresses; // Result and error addresses std::set m_allErrorAddresses; // Error addresses diff --git a/ApplicationLibCode/FileInterface/RifSurfaceImporter.cpp b/ApplicationLibCode/FileInterface/RifSurfaceImporter.cpp index 6cea5ba1a3..0982f47799 100644 --- a/ApplicationLibCode/FileInterface/RifSurfaceImporter.cpp +++ b/ApplicationLibCode/FileInterface/RifSurfaceImporter.cpp @@ -465,6 +465,8 @@ std::pair, std::vector> RifSurfaceImporter::re } } + if ( surfacePoints.empty() ) return { {}, {} }; + // Determine axes vectors std::vector> pairs; for ( auto itr = axesVectorCandidatesNum.begin(); itr != axesVectorCandidatesNum.end(); ++itr ) @@ -478,7 +480,6 @@ std::pair, std::vector> RifSurfaceImporter::re cvf::Vec2d primaryAxisVector = pairs[0].first * axesVectorCandidates[pairs[0].first]; - size_t row = 0; size_t column = 0; std::vector> indexToPointData; std::vector startOffsets; @@ -512,7 +513,6 @@ std::pair, std::vector> RifSurfaceImporter::re { indexToPointData.push_back( std::vector() ); } - row = 0; int offset = distanceOnLine( lineStartPoint, lineEndPoint, to2d( surfacePoints[index] ) ); if ( offset < 0 ) { @@ -524,7 +524,6 @@ std::pair, std::vector> RifSurfaceImporter::re for ( int i = 0; i < offset; i++ ) { indexToPointData[column].push_back( -1 ); - row++; } startOffsets.push_back( 0 ); } @@ -537,7 +536,6 @@ std::pair, std::vector> RifSurfaceImporter::re for ( size_t i = 1; i < rowDiff; i++ ) { indexToPointData[column].push_back( -1 ); - row++; } } int offset = distanceOnLine( lineStartPoint, lineEndPoint, to2d( surfacePoints[index] ) ); @@ -555,7 +553,6 @@ std::pair, std::vector> RifSurfaceImporter::re indexToPointData.push_back( std::vector() ); } indexToPointData[column].push_back( static_cast( index ) ); - row++; } for ( size_t i = 0; i < startOffsets.size(); i++ ) diff --git a/ApplicationLibCode/FileInterface/RifTextDataTableFormatter.cpp b/ApplicationLibCode/FileInterface/RifTextDataTableFormatter.cpp index 811deb01e4..b3756e3ce8 100644 --- a/ApplicationLibCode/FileInterface/RifTextDataTableFormatter.cpp +++ b/ApplicationLibCode/FileInterface/RifTextDataTableFormatter.cpp @@ -320,7 +320,13 @@ bool RifTextDataTableFormatter::isAllHeadersEmpty( const std::vector( m_elementId.size() ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RigFemPart::nodeCount() const +{ + return static_cast( m_nodes.nodeIds.size() ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -442,7 +450,7 @@ float RigFemPart::characteristicElementSize() const { if ( m_characteristicElementSize != std::numeric_limits::infinity() ) return m_characteristicElementSize; - std::vector elementPriority = { HEX8P, HEX8 }; + std::vector elementPriority = { RigElementType::HEX8P, RigElementType::HEX8 }; for ( auto elmType : elementPriority ) { @@ -508,19 +516,21 @@ cvf::BoundingBox RigFemPart::boundingBox() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFemPart::findIntersectingElementIndices( const cvf::BoundingBox& inputBB, std::vector* elementIndices ) const +std::vector RigFemPart::findIntersectingElementIndices( const cvf::BoundingBox& inputBB ) const { ensureIntersectionSearchTreeIsBuilt(); - findIntersectingElementsWithExistingSearchTree( inputBB, elementIndices ); + return findIntersectingElementsWithExistingSearchTree( inputBB ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFemPart::findIntersectingElementsWithExistingSearchTree( const cvf::BoundingBox& inputBB, std::vector* elementIndices ) const +std::vector RigFemPart::findIntersectingElementsWithExistingSearchTree( const cvf::BoundingBox& inputBB ) const { CVF_ASSERT( m_elementSearchTree.notNull() ); - m_elementSearchTree->findIntersections( inputBB, elementIndices ); + std::vector elementIndices; + m_elementSearchTree->findIntersections( inputBB, &elementIndices ); + return elementIndices; } //-------------------------------------------------------------------------------------------------- @@ -604,7 +614,7 @@ size_t RigFemPart::resultValueIdxFromResultPosType( RigFemResultPosEnum resultPo bool RigFemPart::isHexahedron( size_t elementIdx ) const { RigElementType elType = elementType( elementIdx ); - return elType == HEX8 || elType == HEX8P; + return RigFemTypes::is8NodeElement( elType ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPart.h b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPart.h index 06aa53b17c..94ce09cbd9 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPart.h +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPart.h @@ -58,6 +58,7 @@ class RigFemPart : public cvf::Object void appendElement( RigElementType elmType, int elementId, const int* connectivities ); int elementCount() const; + int nodeCount() const; int allConnectivitiesCount() const; int elmId( size_t elementIdx ) const; @@ -86,8 +87,8 @@ class RigFemPart : public cvf::Object cvf::BoundingBox boundingBox() const; float characteristicElementSize() const; const std::vector& possibleGridCornerElements() const; - void findIntersectingElementIndices( const cvf::BoundingBox& inputBB, std::vector* elementIndices ) const; - void findIntersectingElementsWithExistingSearchTree( const cvf::BoundingBox& inputBB, std::vector* elementIndices ) const; + std::vector findIntersectingElementIndices( const cvf::BoundingBox& inputBB ) const; + std::vector findIntersectingElementsWithExistingSearchTree( const cvf::BoundingBox& inputBB ) const; void ensureIntersectionSearchTreeIsBuilt() const; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.cpp index 6a932d88c9..1890dafe2f 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.cpp @@ -18,6 +18,9 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RigFemPartCollection.h" + +#include "RigHexIntersectionTools.h" + #include "cvfBoundingBox.h" //-------------------------------------------------------------------------------------------------- @@ -166,19 +169,53 @@ size_t RigFemPartCollection::globalElementIndex( int partId, size_t localIndex ) //-------------------------------------------------------------------------------------------------- /// Find intersecting global element indexes for a given bounding box //-------------------------------------------------------------------------------------------------- -void RigFemPartCollection::findIntersectingGlobalElementIndices( const cvf::BoundingBox& intersectingBB, - std::vector* intersectedGlobalElementIndices ) const +std::vector RigFemPartCollection::findIntersectingGlobalElementIndices( const cvf::BoundingBox& intersectingBB ) const { + std::vector intersectedGlobalElementIndices; for ( const auto& part : m_femParts ) { - std::vector foundElements; - part->findIntersectingElementIndices( intersectingBB, &foundElements ); + std::vector foundElements = part->findIntersectingElementIndices( intersectingBB ); for ( const auto& foundElement : foundElements ) { const size_t globalIdx = globalElementIndex( part->elementPartId(), foundElement ); - intersectedGlobalElementIndices->push_back( globalIdx ); + intersectedGlobalElementIndices.push_back( globalIdx ); + } + } + + return intersectedGlobalElementIndices; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RigFemPartCollection::getPartIndexFromPoint( const cvf::Vec3d& point ) const +{ + const int idx = -1; + + // Find candidates for intersected global elements + const cvf::BoundingBox intersectingBb( point, point ); + std::vector intersectedGlobalElementIndexCandidates = findIntersectingGlobalElementIndices( intersectingBb ); + + if ( intersectedGlobalElementIndexCandidates.empty() ) return idx; + + // Iterate through global element candidates and check if point is in hexCorners + for ( const auto& globalElementIndex : intersectedGlobalElementIndexCandidates ) + { + const auto [part, elementIndex] = partAndElementIndex( globalElementIndex ); + + // Find nodes from element + std::array coordinates; + if ( part->fillElementCoordinates( elementIndex, coordinates ) ) + { + if ( RigHexIntersectionTools::isPointInCell( point, coordinates.data() ) ) + { + return part->elementPartId(); + } } } + + // Utilize first part to have an id + return idx; } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.h b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.h index 8c4dfd9fb7..2c23bb008c 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.h +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartCollection.h @@ -42,13 +42,14 @@ class RigFemPartCollection : public cvf::Object std::pair partAndElementIndex( size_t globalIndex ) const; size_t globalElementIndex( int partId, size_t localIndex ) const; - void findIntersectingGlobalElementIndices( const cvf::BoundingBox& intersectingBB, - std::vector* intersectedGlobalElementIndices ) const; + std::vector findIntersectingGlobalElementIndices( const cvf::BoundingBox& intersectingBB ) const; int nodeIdxFromElementNodeResultIdx( size_t globalResultIdx ) const; size_t globalElementNodeResultIdx( int part, int elementIdx, int elmLocalNodeIdx ) const; + int getPartIndexFromPoint( const cvf::Vec3d& point ) const; + private: cvf::Collection m_femParts; std::vector m_partElementOffset; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.cpp index 52cdcef5ff..c5d0636398 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.cpp @@ -200,7 +200,7 @@ void RigFemPartGrid::generateStructGridData() RigElementType elementType = m_femPart->elementType( elmIdx ); size_t i, j, k; bool validIndex = ijkFromCellIndex( elmIdx, &i, &j, &k ); - if ( elementType == HEX8P && validIndex ) + if ( ( elementType == RigElementType::HEX8P ) && validIndex ) { if ( i < min.x() ) min.x() = i; if ( j < min.y() ) min.y() = j; @@ -254,7 +254,7 @@ cvf::Vec3i RigFemPartGrid::findMainIJKFaces( int elementIndex ) const // Record three independent main direction vectors for the element, and what face they are created from cvf::Vec3f mainElmDirections[3]; int mainElmDirOriginFaces[3]; - if ( eType == HEX8 || eType == HEX8P ) + if ( RigFemTypes::is8NodeElement( eType ) ) { mainElmDirections[0] = normals[0] - normals[1]; // To get a better "average" direction vector mainElmDirections[1] = normals[2] - normals[3]; @@ -362,30 +362,6 @@ int RigFemPartGrid::perpendicularFaceInDirection( cvf::Vec3f direction, int perp return bestFace; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigFemPartGrid::gridPointCountI() const -{ - return m_elementIJKCounts[0] + 1; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigFemPartGrid::gridPointCountJ() const -{ - return m_elementIJKCounts[1] + 1; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigFemPartGrid::gridPointCountK() const -{ - return m_elementIJKCounts[2] + 1; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -491,6 +467,30 @@ cvf::Vec3d RigFemPartGrid::cellCentroid( size_t cellIndex ) const return centroid / 8.0; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigFemPartGrid::cellCountI() const +{ + return m_elementIJKCounts[0]; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigFemPartGrid::cellCountJ() const +{ + return m_elementIJKCounts[1]; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigFemPartGrid::cellCountK() const +{ + return m_elementIJKCounts[2]; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.h b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.h index fe9146ac35..bafa6b92fc 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.h +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartGrid.h @@ -31,13 +31,13 @@ class RigFemPartGrid : public cvf::StructGridInterface void setFemPart( const RigFemPart* femPart ); + size_t cellCountI() const override; + size_t cellCountJ() const override; + size_t cellCountK() const override; + bool ijkFromCellIndex( size_t cellIndex, size_t* i, size_t* j, size_t* k ) const override; size_t cellIndexFromIJK( size_t i, size_t j, size_t k ) const override; - size_t gridPointCountI() const override; - size_t gridPointCountJ() const override; - size_t gridPointCountK() const override; - cvf::Vec3i findMainIJKFaces( int elementIndex ) const; std::pair reservoirIJKBoundingBox() const; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorCompaction.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorCompaction.cpp index 29a19cb77a..bc09c421bf 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorCompaction.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorCompaction.cpp @@ -163,8 +163,7 @@ void findReferenceElementForNode( const RigFemPart& part, size_t nodeIdx, size_t bb.add( p1 ); bb.add( p2 ); - std::vector refElementCandidates; - part.findIntersectingElementIndices( bb, &refElementCandidates ); + std::vector refElementCandidates = part.findIntersectingElementIndices( bb ); const RigFemPartGrid* grid = part.getOrCreateStructGrid(); diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorEnIpPorBar.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorEnIpPorBar.cpp index c2a643ba4b..7d421f643a 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorEnIpPorBar.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorEnIpPorBar.cpp @@ -92,7 +92,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorEnIpPorBar::calculate( int p { RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { int elmNodeCount = RigFemTypes::elementNodeCount( elmType ); for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorGamma.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorGamma.cpp index eb17f6201d..e8f706e52e 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorGamma.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorGamma.cpp @@ -135,7 +135,7 @@ void RigFemPartResultCalculatorGamma::calculateGammaFromFrames( int int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorInitialPorosity.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorInitialPorosity.cpp index e7feee3f55..bd64955ccc 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorInitialPorosity.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorInitialPorosity.cpp @@ -94,7 +94,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorInitialPorosity::calculate( int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNodalGradients.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNodalGradients.cpp index acce939115..7bf0874e6f 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNodalGradients.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNodalGradients.cpp @@ -124,7 +124,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorNodalGradients::calculate( i for ( int elmIdx : elements ) { RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { // Find the corner coordinates and values for the node std::array hexCorners; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalSE.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalSE.cpp index de914efa9f..6964643ad7 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalSE.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalSE.cpp @@ -94,7 +94,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorNormalSE::calculate( int par int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalST.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalST.cpp index 20ce822237..010ae24675 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalST.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalST.cpp @@ -102,7 +102,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorNormalST::calculate( int par int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalized.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalized.cpp index 40b830484e..89ad4320b5 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalized.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorNormalized.cpp @@ -123,7 +123,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorNormalized::calculate( int p for ( int elmIdx = 0; elmIdx < femPart->elementCount(); ++elmIdx ) { RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType != HEX8 && elmType != HEX8P ) continue; + if ( !RigFemTypes::is8NodeElement( elmType ) ) continue; bool porRegion = false; for ( int elmLocalNodeIdx = 0; elmLocalNodeIdx < 8; ++elmLocalNodeIdx ) diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPoreCompressibility.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPoreCompressibility.cpp index 09a941f5f3..e4cca5e513 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPoreCompressibility.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPoreCompressibility.cpp @@ -170,7 +170,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorPoreCompressibility::calcula int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPorosityPermeability.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPorosityPermeability.cpp index e97eb56752..56afae59e1 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPorosityPermeability.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorPorosityPermeability.cpp @@ -165,7 +165,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorPorosityPermeability::calcul int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorShearSE.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorShearSE.cpp index 4a74500d4c..d3d75b9c55 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorShearSE.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorShearSE.cpp @@ -96,7 +96,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorShearSE::calculate( int part int elmNodeCount = RigFemTypes::elementNodeCount( femPart->elementType( elmIdx ) ); - if ( elmType == HEX8P ) + if ( elmType == RigElementType::HEX8P ) { for ( int elmNodIdx = 0; elmNodIdx < elmNodeCount; ++elmNodIdx ) { diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorStressGradients.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorStressGradients.cpp index 2bfdf03486..6d2f611982 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorStressGradients.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultCalculatorStressGradients.cpp @@ -133,7 +133,7 @@ RigFemScalarResultFrames* RigFemPartResultCalculatorStressGradients::calculate( const int* cornerIndices = femPart->connectivities( elmIdx ); RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType != HEX8P && elmType != HEX8 ) continue; + if ( !RigFemTypes::is8NodeElement( elmType ) ) continue; // Find the corner coordinates for element std::array hexCorners; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultsCollection.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultsCollection.cpp index 278078cc6c..e723f5e4c4 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultsCollection.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemPartResultsCollection.cpp @@ -73,10 +73,6 @@ #include "Riu3DMainWindowTools.h" -#ifdef USE_ODB_API -#include "RifOdbReader.h" -#endif - #include "cafProgressInfo.h" #include "cafTensor3.h" @@ -159,6 +155,11 @@ RigFemPartResultsCollection::RigFemPartResultsCollection( RifGeoMechReaderInterf m_waterDensityShearSlipIndicator = 1.03; + m_fractureGradientCalculationTypeMudWeightWindow = RimMudWeightWindowParameters::FractureGradientCalculationType::DERIVED_FROM_K0FG; + m_lowerLimitParameterMudWeightWindow = RimMudWeightWindowParameters::LowerLimitType::PORE_PRESSURE; + m_upperLimitParameterMudWeightWindow = RimMudWeightWindowParameters::UpperLimitType::FG; + m_nonReservoirPorePressureTypeMudWeightWindow = RimMudWeightWindowParameters::NonReservoirPorePressureType::PER_ELEMENT; + m_resultCalculators.push_back( std::unique_ptr( new RigFemPartResultCalculatorTimeLapse( *this ) ) ); m_resultCalculators.push_back( std::unique_ptr( new RigFemPartResultCalculatorSurfaceAngles( *this ) ) ); m_resultCalculators.push_back( std::unique_ptr( new RigFemPartResultCalculatorSurfaceAlignedStress( *this ) ) ); @@ -443,6 +444,7 @@ RigFemScalarResultFrames* RigFemPartResultsCollection::findOrLoadScalarResult( i frames = calculateDerivedResult( partIndex, resVarAddr ); if ( frames ) return frames; + // is it available as an imported property if ( resVarAddr.resultPosType == RIG_ELEMENT ) { std::map> elementProperties = @@ -463,11 +465,6 @@ RigFemScalarResultFrames* RigFemPartResultsCollection::findOrLoadScalarResult( i { return frames; } - else - { - // Create a dummy empty result - return m_femPartResults[partIndex]->createScalarResult( resVarAddr ); - } } // We need to read the data as bulk fields, and populate the correct scalar caches @@ -504,6 +501,9 @@ RigFemScalarResultFrames* RigFemPartResultsCollection::findOrLoadScalarResult( i case RIG_NODAL: m_readerInterface->readNodeField( resVarAddr.fieldName, partIndex, stepIndex, frameIndex, &componentDataVectors ); break; + case RIG_ELEMENT: + m_readerInterface->readElementField( resVarAddr.fieldName, partIndex, stepIndex, frameIndex, &componentDataVectors ); + break; case RIG_ELEMENT_NODAL: m_readerInterface->readElementNodeField( resVarAddr.fieldName, partIndex, stepIndex, frameIndex, &componentDataVectors ); break; @@ -573,14 +573,24 @@ std::map> RigFemPartResultsCollection::sca if ( resPos == RIG_NODAL ) { fieldCompNames = m_readerInterface->scalarNodeFieldAndComponentNames(); - if ( fieldCompNames.contains( "U" ) ) fieldCompNames["U"].push_back( "U_LENGTH" ); fieldCompNames[RigFemAddressDefines::porBar()]; - fieldCompNames[FIELD_NAME_COMPACTION]; + if ( fieldCompNames.contains( "VOIDR" ) ) fieldCompNames["PORO-PERM"].push_back( "PHI0" ); + + if ( m_readerInterface->populateDerivedResultNames() ) + { + if ( fieldCompNames.contains( "U" ) ) fieldCompNames["U"].push_back( "U_LENGTH" ); + fieldCompNames[FIELD_NAME_COMPACTION]; + } } else if ( resPos == RIG_ELEMENT_NODAL ) { fieldCompNames = m_readerInterface->scalarElementNodeFieldAndComponentNames(); + if ( !m_readerInterface->populateDerivedResultNames() ) + { + return fieldCompNames; + } + fieldCompNames["SE"].push_back( "SM" ); fieldCompNames["SE"].push_back( "SFI" ); fieldCompNames["SE"].push_back( "DSM" ); @@ -677,6 +687,8 @@ std::map> RigFemPartResultsCollection::sca { fieldCompNames = m_readerInterface->scalarIntegrationPointFieldAndComponentNames(); + if ( !m_readerInterface->populateDerivedResultNames() ) return fieldCompNames; + fieldCompNames["SE"].push_back( "SM" ); fieldCompNames["SE"].push_back( "SFI" ); fieldCompNames["SE"].push_back( "DSM" ); @@ -779,6 +791,8 @@ std::map> RigFemPartResultsCollection::sca } else if ( resPos == RIG_ELEMENT_NODAL_FACE ) { + if ( !m_readerInterface->populateDerivedResultNames() ) return fieldCompNames; + fieldCompNames["Plane"].push_back( "Pinc" ); fieldCompNames["Plane"].push_back( "Pazi" ); @@ -799,9 +813,11 @@ std::map> RigFemPartResultsCollection::sca } else if ( resPos == RIG_ELEMENT ) { + fieldCompNames = m_readerInterface->scalarElementFieldAndComponentNames(); + for ( const std::string& field : m_elementPropertyReader->scalarElementFields() ) { - fieldCompNames[field]; + fieldCompNames[field] = {}; } } else if ( resPos == RIG_WELLPATH_DERIVED ) @@ -883,6 +899,9 @@ std::vector RigFemPartResultsCollection::getResAddrToCompon case RIG_NODAL: fieldAndComponentNames = m_readerInterface->scalarNodeFieldAndComponentNames(); break; + case RIG_ELEMENT: + fieldAndComponentNames = m_readerInterface->scalarElementFieldAndComponentNames(); + break; case RIG_ELEMENT_NODAL: fieldAndComponentNames = m_readerInterface->scalarElementNodeFieldAndComponentNames(); break; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.cpp index 5cb8003311..fb5520bff5 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.cpp @@ -30,7 +30,7 @@ int RigFemTypes::elementNodeCount( RigElementType elmType ) { static int elementTypeCounts[3] = { 8, 8, 4 }; - return elementTypeCounts[elmType]; + return elementTypeCounts[(unsigned int)elmType]; } //-------------------------------------------------------------------------------------------------- @@ -40,7 +40,7 @@ int RigFemTypes::elementFaceCount( RigElementType elmType ) { const static int elementFaceCounts[3] = { 6, 6, 1 }; - return elementFaceCounts[elmType]; + return elementFaceCounts[(unsigned int)elmType]; } //-------------------------------------------------------------------------------------------------- @@ -63,12 +63,12 @@ const int* RigFemTypes::localElmNodeIndicesForFace( RigElementType elmType, int switch ( elmType ) { - case HEX8: - case HEX8P: + case RigElementType::HEX8: + case RigElementType::HEX8P: ( *faceNodeCount ) = 4; return HEX8_Faces[faceIdx]; break; - case CAX4: + case RigElementType::CAX4: ( *faceNodeCount ) = 4; return CAX4_Faces; break; @@ -86,11 +86,11 @@ int RigFemTypes::oppositeFace( RigElementType elmType, int faceIdx ) switch ( elmType ) { - case HEX8: - case HEX8P: + case RigElementType::HEX8: + case RigElementType::HEX8P: return HEX8_OppositeFaces[faceIdx]; break; - case CAX4: + case RigElementType::CAX4: return faceIdx; break; default: @@ -111,11 +111,11 @@ const int* RigFemTypes::localElmNodeToIntegrationPointMapping( RigElementType el switch ( elmType ) { - case HEX8: - case HEX8P: + case RigElementType::HEX8: + case RigElementType::HEX8P: return HEX8_Mapping; break; - case CAX4: + case RigElementType::CAX4: return HEX8_Mapping; // First four is identical to HEX8 break; default: @@ -129,22 +129,22 @@ const int* RigFemTypes::localElmNodeToIntegrationPointMapping( RigElementType el //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QString RigFemTypes::elementTypeText( RigElementType elemType ) +std::string RigFemTypes::elementTypeText( RigElementType elemType ) { - QString txt = "UNKNOWN_ELM_TYPE"; + std::string txt = "UNKNOWN_ELM_TYPE"; switch ( elemType ) { - case HEX8: + case RigElementType::HEX8: txt = "HEX8"; break; - case HEX8P: + case RigElementType::HEX8P: txt = "HEX8P"; break; - case CAX4: + case RigElementType::CAX4: txt = "CAX4"; break; - case UNKNOWN_ELM_TYPE: + case RigElementType::UNKNOWN_ELM_TYPE: break; default: break; @@ -152,3 +152,45 @@ QString RigFemTypes::elementTypeText( RigElementType elemType ) return txt; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::map RigFemTypes::femTypeMap() +{ + std::map typeMap; + typeMap["C3D8R"] = RigElementType::HEX8; + typeMap["C3D8"] = RigElementType::HEX8; + typeMap["C3D8P"] = RigElementType::HEX8P; + typeMap["CAX4"] = RigElementType::CAX4; + typeMap["C3D20RT"] = RigElementType::HEX8; + typeMap["C3D8RT"] = RigElementType::HEX8; + typeMap["C3D8T"] = RigElementType::HEX8; + + return typeMap; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigElementType RigFemTypes::toRigElementType( const std::string odbTypeName ) +{ + static std::map odbElmTypeToRigElmTypeMap = femTypeMap(); + + std::map::iterator it = odbElmTypeToRigElmTypeMap.find( odbTypeName ); + + if ( it == odbElmTypeToRigElmTypeMap.end() ) + { + return RigElementType::UNKNOWN_ELM_TYPE; + } + + return it->second; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RigFemTypes::is8NodeElement( RigElementType elmType ) +{ + return ( elmType == RigElementType::HEX8 ) || ( elmType == RigElementType::HEX8P ); +} diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.h b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.h index 2a053923a0..f7ffde404c 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.h +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigFemTypes.h @@ -19,9 +19,10 @@ #pragma once -class QString; +#include +#include -enum RigElementType +enum class RigElementType { HEX8, HEX8P, @@ -32,10 +33,15 @@ enum RigElementType class RigFemTypes { public: - static int elementNodeCount( RigElementType elmType ); - static int elementFaceCount( RigElementType elmType ); - static const int* localElmNodeIndicesForFace( RigElementType elmType, int faceIdx, int* faceNodeCount ); - static int oppositeFace( RigElementType elmType, int faceIdx ); - static const int* localElmNodeToIntegrationPointMapping( RigElementType elmType ); - static QString elementTypeText( RigElementType elemType ); + static int elementNodeCount( RigElementType elmType ); + static int elementFaceCount( RigElementType elmType ); + static const int* localElmNodeIndicesForFace( RigElementType elmType, int faceIdx, int* faceNodeCount ); + static int oppositeFace( RigElementType elmType, int faceIdx ); + static const int* localElmNodeToIntegrationPointMapping( RigElementType elmType ); + static std::string elementTypeText( RigElementType elemType ); + static RigElementType toRigElementType( const std::string odbTypeName ); + static bool is8NodeElement( RigElementType elmType ); + +private: + static std::map femTypeMap(); }; diff --git a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigGeoMechCaseData.cpp b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigGeoMechCaseData.cpp index 282e278c7c..8d61dc25b1 100644 --- a/ApplicationLibCode/GeoMech/GeoMechDataModel/RigGeoMechCaseData.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechDataModel/RigGeoMechCaseData.cpp @@ -25,8 +25,8 @@ #include "RigFemPartResultsCollection.h" #include "RigGeoMechCaseData.h" -#ifdef USE_ODB_API #include "RifInpReader.h" +#ifdef USE_ODB_API #include "RifOdbReader.h" #endif @@ -86,19 +86,23 @@ RigFemPartResultsCollection* RigGeoMechCaseData::femPartResults() return m_femPartResultsColl.p(); } +#include "RiaStdStringTools.h" + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- bool RigGeoMechCaseData::open( std::string* errorMessage ) { -#ifdef USE_ODB_API - if ( m_geoMechCaseFileName.ends_with( ".odb" ) ) + auto filename = RiaStdStringTools::toUpper( m_geoMechCaseFileName ); + + if ( filename.ends_with( ".INP" ) ) { - m_readerInterface = new RifOdbReader; + m_readerInterface = new RifInpReader(); } - else +#ifdef USE_ODB_API + else if ( filename.ends_with( ".ODB" ) ) { - m_readerInterface = new RifInpReader; + m_readerInterface = new RifOdbReader(); } #endif @@ -111,13 +115,11 @@ bool RigGeoMechCaseData::open( std::string* errorMessage ) bool RigGeoMechCaseData::readTimeSteps( std::string* errorMessage, std::vector* stepNames ) { CVF_ASSERT( stepNames ); -#ifdef USE_ODB_API if ( m_readerInterface.notNull() && m_readerInterface->isOpen() ) { *stepNames = m_readerInterface->allStepNames(); return true; } -#endif *errorMessage = std::string( "Could not read time steps" ); return false; } @@ -128,7 +130,7 @@ bool RigGeoMechCaseData::readTimeSteps( std::string* errorMessage, std::vector& timeStepFilter, bool readOnlyLastFrame ) { CVF_ASSERT( errorMessage ); -#ifdef USE_ODB_API + if ( m_readerInterface.notNull() && m_readerInterface->isOpen() ) { m_readerInterface->setTimeStepFilter( timeStepFilter, readOnlyLastFrame ); @@ -154,7 +156,7 @@ bool RigGeoMechCaseData::readFemParts( std::string* errorMessage, const std::vec return true; } } -#endif + *errorMessage = std::string( "Could not read FEM parts" ); return false; } @@ -165,14 +167,13 @@ bool RigGeoMechCaseData::readFemParts( std::string* errorMessage, const std::vec bool RigGeoMechCaseData::readDisplacements( std::string* errorMessage, int partId, int timeStep, int frameIndex, std::vector* displacements ) { CVF_ASSERT( errorMessage ); -#ifdef USE_ODB_API + if ( m_readerInterface.notNull() && m_readerInterface->isOpen() ) { m_readerInterface->readDisplacements( partId, timeStep, frameIndex, displacements ); return true; } -#endif *errorMessage = std::string( "Could not read displacements." ); return false; } diff --git a/ApplicationLibCode/GeoMech/GeoMechFileInterface/CMakeLists.txt b/ApplicationLibCode/GeoMech/GeoMechFileInterface/CMakeLists.txt new file mode 100644 index 0000000000..2832dab452 --- /dev/null +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/CMakeLists.txt @@ -0,0 +1,21 @@ +project(RifGeoMechFileInterface) + +# Unity Build +if(RESINSIGHT_ENABLE_UNITY_BUILD) + message("Cmake Unity build is enabled on : ${PROJECT_NAME}") + set(CMAKE_UNITY_BUILD true) +endif() + +add_library( + ${PROJECT_NAME} + RifInpReader.h RifInpReader.cpp RifGeoMechReaderInterface.h + RifGeoMechReaderInterface.cpp RifInpIncludeReader.h RifInpIncludeReader.cpp +) + +target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + +set(LINK_LIBRARIES RigGeoMechDataModel LibCore) + +target_link_libraries(${PROJECT_NAME} ${LINK_LIBRARIES}) + +source_group("" FILES ${PROJECT_FILES}) diff --git a/ApplicationLibCode/GeoMech/OdbReader/RifGeoMechReaderInterface.cpp b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifGeoMechReaderInterface.cpp similarity index 98% rename from ApplicationLibCode/GeoMech/OdbReader/RifGeoMechReaderInterface.cpp rename to ApplicationLibCode/GeoMech/GeoMechFileInterface/RifGeoMechReaderInterface.cpp index 42006d983b..3af889ce8f 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/RifGeoMechReaderInterface.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifGeoMechReaderInterface.cpp @@ -58,7 +58,7 @@ bool RifGeoMechReaderInterface::isTimeStepIncludedByFilter( int timeStepIndex ) for ( auto i : m_fileTimeStepIndices ) { - if ( i == static_cast( timeStepIndex ) ) + if ( i == timeStepIndex ) { return true; } diff --git a/ApplicationLibCode/GeoMech/OdbReader/RifGeoMechReaderInterface.h b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifGeoMechReaderInterface.h similarity index 88% rename from ApplicationLibCode/GeoMech/OdbReader/RifGeoMechReaderInterface.h rename to ApplicationLibCode/GeoMech/GeoMechFileInterface/RifGeoMechReaderInterface.h index ed983ecd1e..aa814273da 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/RifGeoMechReaderInterface.h +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifGeoMechReaderInterface.h @@ -51,6 +51,7 @@ class RifGeoMechReaderInterface : public cvf::Object virtual std::vector elementSet( int partIndex, std::string partName, int setIndex ) = 0; virtual std::map> scalarNodeFieldAndComponentNames() = 0; + virtual std::map> scalarElementFieldAndComponentNames() = 0; virtual std::map> scalarElementNodeFieldAndComponentNames() = 0; virtual std::map> scalarIntegrationPointFieldAndComponentNames() = 0; @@ -61,6 +62,11 @@ class RifGeoMechReaderInterface : public cvf::Object int stepIndex, int frameIndex, std::vector*>* resultValues ) = 0; + virtual void readElementField( const std::string& fieldName, + int partIndex, + int stepIndex, + int frameIndex, + std::vector*>* resultValues ) = 0; virtual void readElementNodeField( const std::string& fieldName, int partIndex, int stepIndex, @@ -72,6 +78,8 @@ class RifGeoMechReaderInterface : public cvf::Object int frameIndex, std::vector*>* resultValues ) = 0; + virtual bool populateDerivedResultNames() const = 0; + void setTimeStepFilter( const std::vector& fileTimeStepIndices, bool readOnlyLastFrame ); bool isTimeStepIncludedByFilter( int timeStepIndex ) const; int timeStepIndexOnFile( int timeStepIndex ) const; diff --git a/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpIncludeReader.cpp b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpIncludeReader.cpp new file mode 100644 index 0000000000..d24afcba7c --- /dev/null +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpIncludeReader.cpp @@ -0,0 +1,115 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RifInpIncludeReader.h" + +#include "RiaStdStringTools.h" + +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RifInpIncludeReader::RifInpIncludeReader() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RifInpIncludeReader::~RifInpIncludeReader() +{ + if ( isOpen() ) close(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifInpIncludeReader::openFile( const std::string& fileName ) +{ + m_stream.open( fileName ); + return m_stream.good(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifInpIncludeReader::isOpen() const +{ + return m_stream.is_open(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifInpIncludeReader::close() +{ + m_stream.close(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifInpIncludeReader::readData( int columnIndex, const std::map& parts, std::map>& data ) +{ + std::map nameToPartId; + for ( auto p : parts ) + { + nameToPartId[p.second] = p.first; + } + + std::string line; + + while ( true ) + { + std::getline( m_stream, line ); + + if ( m_stream ) + { + if ( line.starts_with( '*' ) ) continue; + if ( line.starts_with( ',' ) ) continue; + + // is the requested column present? + auto columns = RiaStdStringTools::splitString( line, ',' ); + if ( columnIndex >= (int)columns.size() ) continue; + + // split part/set/node/element in first column + auto partNode = RiaStdStringTools::splitString( columns[0], '.' ); + if ( partNode.size() != 3 ) continue; + auto& partName = partNode[0]; + int nodeOrElmIndex = RiaStdStringTools::toInt( partNode[2] ) - 1; + if ( nodeOrElmIndex < 0 ) continue; + + // is it a valid part name? + if ( nameToPartId.count( partName ) == 0 ) continue; + int partId = nameToPartId[partName]; + + // is the index as expected? + if ( nodeOrElmIndex >= (int)data[partId].size() ) continue; + + // is it a valid value? + double value = std::numeric_limits::infinity(); + RiaStdStringTools::toDouble( RiaStdStringTools::trimString( columns[columnIndex] ), value ); + + data[partId][nodeOrElmIndex] = value; + } + + if ( m_stream.eof() ) break; + } +} diff --git a/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpIncludeReader.h b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpIncludeReader.h new file mode 100644 index 0000000000..a66e762b3a --- /dev/null +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpIncludeReader.h @@ -0,0 +1,45 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include +#include +#include +#include + +//================================================================================================== +// +//================================================================================================== +class RifInpIncludeReader +{ +public: + RifInpIncludeReader(); + ~RifInpIncludeReader(); + + bool openFile( const std::string& fileName ); + bool isOpen() const; + + void readData( int column, const std::map& parts, std::map>& data ); + +private: + void close(); + +private: + std::ifstream m_stream; +}; diff --git a/ApplicationLibCode/GeoMech/OdbReader/RifInpReader.cpp b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpReader.cpp similarity index 59% rename from ApplicationLibCode/GeoMech/OdbReader/RifInpReader.cpp rename to ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpReader.cpp index 4908f9e95b..27aee18007 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/RifInpReader.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpReader.cpp @@ -18,6 +18,8 @@ #include "RifInpReader.h" +#include "RifInpIncludeReader.h" + #include "RigFemPart.h" #include "RigFemPartCollection.h" #include "RigFemTypes.h" @@ -38,6 +40,7 @@ /// //-------------------------------------------------------------------------------------------------- RifInpReader::RifInpReader() + : m_enableIncludes( true ) { } @@ -48,6 +51,14 @@ RifInpReader::~RifInpReader() { } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifInpReader::enableIncludes( bool enable ) +{ + m_enableIncludes = enable; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -56,13 +67,28 @@ void RifInpReader::close() m_stream.close(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifInpReader::populateDerivedResultNames() const +{ + return false; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- bool RifInpReader::openFile( const std::string& fileName, std::string* errorMessage ) { m_stream.open( fileName ); - return m_stream.good(); + bool bOK = m_stream.good(); + + if ( bOK ) + { + m_inputPath = std::filesystem::path( fileName ).parent_path(); + } + + return bOK; } //-------------------------------------------------------------------------------------------------- @@ -86,9 +112,25 @@ bool RifInpReader::readFemParts( RigFemPartCollection* femParts ) std::map>>> elements; std::map>>> elementSets; - read( m_stream, parts, nodes, elements, elementSets ); + auto elementType = read( m_stream, parts, nodes, elements, elementSets, m_stepNames, m_enableIncludes, m_includeEntries ); + + for ( int i = 0; i < (int)m_includeEntries.size(); i++ ) + { + m_includeEntries[i].fileName = ( m_inputPath / m_includeEntries[i].fileName ).string(); + } + + if ( m_stepNames.empty() ) m_stepNames.push_back( "Geostatic" ); + + RiaLogging::debug( QString( "Read FEM parts: %1, steps: %2, element type: %3" ) + .arg( parts.size() ) + .arg( m_stepNames.size() ) + .arg( QString::fromStdString( RigFemTypes::elementTypeText( elementType ) ) ) ); - RiaLogging::debug( QString( "Read FEM parts: %1 nodes: %2 elements: %3" ).arg( parts.size() ).arg( nodes.size() ).arg( elements.size() ) ); + if ( !RigFemTypes::is8NodeElement( elementType ) ) + { + RiaLogging::error( QString( "Unsupported element type." ) ); + return false; + } caf::ProgressInfo modelProgress( parts.size() * 2, "Reading Inp Parts" ); @@ -135,9 +177,7 @@ bool RifInpReader::readFemParts( RigFemPartCollection* femParts ) elementIdToIdxMap[elmId] = elmIdx; - // TODO: handle more types? - RigElementType elmType = RigElementType::HEX8; - int nodeCount = RigFemTypes::elementNodeCount( elmType ); + int nodeCount = RigFemTypes::elementNodeCount( elementType ); indexBasedConnectivities.resize( nodeCount ); for ( int lnIdx = 0; lnIdx < nodeCount; ++lnIdx ) @@ -145,12 +185,12 @@ bool RifInpReader::readFemParts( RigFemPartCollection* femParts ) indexBasedConnectivities[lnIdx] = nodeIdToIdxMap[nodesInElement[lnIdx]]; } - femPart->appendElement( elmType, elmId, indexBasedConnectivities.data() ); + femPart->appendElement( elementType, elmId, indexBasedConnectivities.data() ); } // read element sets - auto elementSetsForPart = elementSets[partId]; - for ( auto [setName, elementSet] : elementSetsForPart ) + auto& elementSetsForPart = elementSets[partId]; + for ( auto& [setName, elementSet] : elementSetsForPart ) { femPart->addElementSet( setName, elementSet ); } @@ -161,22 +201,33 @@ bool RifInpReader::readFemParts( RigFemPartCollection* femParts ) modelProgress.incrementProgress(); } + readScalarData( femParts, parts, m_includeEntries ); + return true; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RifInpReader::read( std::istream& stream, - std::map& parts, - std::map>>& nodes, - std::map>>>& elements, - std::map>>>& elementSets ) +RigElementType RifInpReader::read( std::istream& stream, + std::map& parts, + std::map>>& nodes, + std::map>>>& elements, + std::map>>>& elementSets, + std::vector& stepNames, + bool enableIncludes, + std::vector& includeEntries ) { std::string line; + std::string prevline; + + RigElementType elementType = RigElementType::UNKNOWN_ELM_TYPE; int partId = 0; std::string partName; + int stepId = -1; + std::string stepName; + int timeSteps = 0; while ( true ) { @@ -208,8 +259,17 @@ void RifInpReader::read( std::istream& // "Element" section. else if ( uppercasedLine.starts_with( "*ELEMENT," ) ) { + auto nodeType = parseLabel( line, "type" ); + elementType = RigFemTypes::toRigElementType( nodeType ); skipComments( stream ); - elements[partId] = readElements( stream ); + + if ( !elements.contains( partId ) ) elements[partId] = {}; + + auto newElements = readElements( stream ); + for ( const auto& e : newElements ) + { + elements[partId].push_back( e ); + } } else if ( uppercasedLine.starts_with( "*ELSET," ) ) { @@ -219,12 +279,85 @@ void RifInpReader::read( std::istream& auto elementSet = isGenerateSet ? readElementSetGenerate( stream ) : readElementSet( stream ); elementSets[partId].push_back( { setName, elementSet } ); } + else if ( uppercasedLine.starts_with( "*STEP" ) ) + { + stepName = parseLabel( line, "name" ); + stepNames.push_back( stepName ); + stepId = stepNames.size() - 1; + } + else if ( uppercasedLine.starts_with( "*END STEP" ) ) + { + stepId = -1; + stepName = ""; + } + else if ( enableIncludes && uppercasedLine.starts_with( "*INCLUDE" ) ) + { + auto filename = parseLabel( line, "input" ); + RigFemResultPosEnum resultType = RigFemResultPosEnum::RIG_ELEMENT; + std::string propertyName( "" ); + int columnIndex = 1; + if ( prevline.starts_with( "*BOUNDARY" ) ) + { + propertyName = "POR"; + resultType = RigFemResultPosEnum::RIG_NODAL; + columnIndex = 3; + } + else if ( prevline.starts_with( "*TEMPERATURE" ) ) + { + propertyName = "TEMP"; + resultType = RigFemResultPosEnum::RIG_NODAL; + } + else if ( prevline.starts_with( "*INITIAL" ) ) + { + auto label = parseLabel( prevline, "type" ); + if ( label == "RATIO" ) + { + propertyName = "VOIDR"; + resultType = RigFemResultPosEnum::RIG_NODAL; + } + else if ( label == "STRESS" ) + { + includeEntries.push_back( RifInpIncludeEntry( "STRESS_TOP", RigFemResultPosEnum::RIG_ELEMENT, stepId, filename, 1 ) ); + includeEntries.push_back( RifInpIncludeEntry( "DEPTH_TOP", RigFemResultPosEnum::RIG_ELEMENT, stepId, filename, 2 ) ); + includeEntries.push_back( RifInpIncludeEntry( "STRESS_BOTTOM", RigFemResultPosEnum::RIG_ELEMENT, stepId, filename, 3 ) ); + includeEntries.push_back( RifInpIncludeEntry( "DEPTH_BOTTOM", RigFemResultPosEnum::RIG_ELEMENT, stepId, filename, 4 ) ); + includeEntries.push_back( + RifInpIncludeEntry( "LATERAL_STRESS_X", RigFemResultPosEnum::RIG_ELEMENT, stepId, filename, 5 ) ); + + propertyName = "LATERAL_STRESS_Y"; + columnIndex = 6; + } + } + if ( propertyName.empty() ) + { + std::string uppercasedFilename = RiaStdStringTools::toUpper( filename ); + + if ( uppercasedFilename.find( "DENSITY" ) != std::string::npos ) + { + propertyName = "DENSITY"; + } + else if ( uppercasedFilename.find( "ELASTICS" ) != std::string::npos ) + { + includeEntries.push_back( RifInpIncludeEntry( "MODULUS", RigFemResultPosEnum::RIG_ELEMENT, stepId, filename, 1 ) ); + + propertyName = "RATIO"; + columnIndex = 2; + } + } + if ( !propertyName.empty() ) + { + includeEntries.push_back( RifInpIncludeEntry( propertyName, resultType, stepId, filename, columnIndex ) ); + } + } + prevline = uppercasedLine; continue; } if ( stream.eof() ) break; } + + return elementType; } //-------------------------------------------------------------------------------------------------- @@ -261,7 +394,7 @@ std::vector>> RifInpReader::readElements( std::i { std::vector>> partElements; - // TODO: maybe support more element types + // only support C3D8* element type unsigned numNodesPerElement = 8; // Read until we find a new section (which should start with a '*'). @@ -431,11 +564,7 @@ void RifInpReader::skipComments( std::istream& stream ) //-------------------------------------------------------------------------------------------------- std::vector RifInpReader::allStepNames() const { - // TODO: read step names from file. - std::vector stepNames; - stepNames.push_back( "step 1" ); - - return stepNames; + return m_stepNames; } //-------------------------------------------------------------------------------------------------- @@ -443,7 +572,7 @@ std::vector RifInpReader::allStepNames() const //-------------------------------------------------------------------------------------------------- std::vector RifInpReader::filteredStepNames() const { - // TODO: add filtering. + // no filter supported return RifInpReader::allStepNames(); } @@ -452,9 +581,8 @@ std::vector RifInpReader::filteredStepNames() const //-------------------------------------------------------------------------------------------------- std::vector RifInpReader::frameTimes( int stepIndex ) const { - // TODO: get from file? - std::vector frameValues; - frameValues.push_back( 1.0 ); + // only one frame from INP file + std::vector frameValues( { 1.0 } ); return frameValues; } @@ -463,8 +591,6 @@ std::vector RifInpReader::frameTimes( int stepIndex ) const //-------------------------------------------------------------------------------------------------- int RifInpReader::frameCount( int stepIndex ) const { - if ( shouldReadOnlyLastFrame() ) return 1; - return frameTimes( stepIndex ).size(); } @@ -473,9 +599,7 @@ int RifInpReader::frameCount( int stepIndex ) const //-------------------------------------------------------------------------------------------------- std::vector RifInpReader::elementSetNames( int partIndex, std::string partName ) { - // TODO: not implemented yet - if ( partIndex >= m_partElementSetNames.size() ) return {}; - + if ( partIndex >= (int)m_partElementSetNames.size() ) return {}; return m_partElementSetNames.at( partIndex ); } @@ -489,12 +613,34 @@ std::vector RifInpReader::elementSet( int partIndex, std::string partNam return elementIndexes; } -// //-------------------------------------------------------------------------------------------------- -// /// -// //-------------------------------------------------------------------------------------------------- +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- std::map> RifInpReader::scalarNodeFieldAndComponentNames() { - return {}; + std::map> retVal; + + for ( auto& entry : m_propertyPartDataNodes ) + { + retVal[entry.first] = {}; + } + + return retVal; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::map> RifInpReader::scalarElementFieldAndComponentNames() +{ + std::map> retVal; + + for ( auto& entry : m_propertyPartDataElements ) + { + retVal[entry.first] = {}; + } + + return retVal; } //-------------------------------------------------------------------------------------------------- @@ -521,6 +667,41 @@ void RifInpReader::readDisplacements( int partIndex, int stepIndex, int frameInd CVF_ASSERT( displacements ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifInpReader::readField( RigFemResultPosEnum resultType, + const std::string& fieldName, + int partIndex, + int stepIndex, + std::vector*>* resultValues ) +{ + CVF_ASSERT( resultValues ); + + auto dataMap = propertyDataMap( resultType ); + if ( dataMap == nullptr ) return; + + if ( dataMap->count( fieldName ) == 0 ) return; + + // is there only a static result? Use it for all steps. + if ( ( *dataMap )[fieldName].count( stepIndex ) == 0 ) + { + if ( ( *dataMap )[fieldName].count( -1 ) == 0 ) return; + stepIndex = -1; + } + if ( ( *dataMap )[fieldName][stepIndex].count( partIndex ) == 0 ) return; + + auto dataSize = ( *dataMap )[fieldName][stepIndex][partIndex].size(); + + ( *resultValues )[0]->resize( dataSize ); + + std::vector* singleComponentValues = ( *resultValues )[0]; + for ( size_t i = 0; i < dataSize; i++ ) + { + ( *singleComponentValues )[i] = (float)( *dataMap )[fieldName][stepIndex][partIndex][i]; + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -530,7 +711,19 @@ void RifInpReader::readNodeField( const std::string& fieldName, int frameIndex, std::vector*>* resultValues ) { - CVF_ASSERT( resultValues ); + readField( RigFemResultPosEnum::RIG_NODAL, fieldName, partIndex, stepIndex, resultValues ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifInpReader::readElementField( const std::string& fieldName, + int partIndex, + int stepIndex, + int frameIndex, + std::vector*>* resultValues ) +{ + readField( RigFemResultPosEnum::RIG_ELEMENT, fieldName, partIndex, stepIndex, resultValues ); } //-------------------------------------------------------------------------------------------------- @@ -542,7 +735,7 @@ void RifInpReader::readElementNodeField( const std::string& field int frameIndex, std::vector*>* resultValues ) { - CVF_ASSERT( resultValues ); + readField( RigFemResultPosEnum::RIG_ELEMENT_NODAL, fieldName, partIndex, stepIndex, resultValues ); } //-------------------------------------------------------------------------------------------------- @@ -554,5 +747,61 @@ void RifInpReader::readIntegrationPointField( const std::string& int frameIndex, std::vector*>* resultValues ) { - CVF_ASSERT( resultValues ); + readField( RigFemResultPosEnum::RIG_INTEGRATION_POINT, fieldName, partIndex, stepIndex, resultValues ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifInpReader::readScalarData( RigFemPartCollection* femParts, + std::map& parts, + std::vector& includeEntries ) +{ + for ( auto& entry : includeEntries ) + { + auto map = propertyDataMap( entry.resultType ); + if ( map == nullptr ) continue; + if ( map->count( entry.propertyName ) == 0 ) + { + ( *map )[entry.propertyName] = {}; + } + + int stepId = entry.stepId; + + if ( ( *map )[entry.propertyName].count( stepId ) == 0 ) + { + ( *map )[entry.propertyName][stepId] = {}; + } + + for ( int partId = 0; partId < femParts->partCount(); partId++ ) + { + ( *map )[entry.propertyName][stepId][partId] = {}; + size_t dataSize = 0; + if ( entry.resultType == RigFemResultPosEnum::RIG_NODAL ) + { + dataSize = femParts->part( partId )->nodeCount(); + } + if ( entry.resultType == RigFemResultPosEnum::RIG_ELEMENT ) + { + dataSize = femParts->part( partId )->elementCount(); + } + ( *map )[entry.propertyName][stepId][partId].resize( dataSize, 0.0 ); + } + RifInpIncludeReader reader; + if ( !reader.openFile( entry.fileName ) ) continue; + reader.readData( entry.columnIndex, parts, ( *map )[entry.propertyName][stepId] ); + } + + return; +} + +//-------------------------------------------------------------------------------------------------- +/// Map keys: result name / time step / part id +//-------------------------------------------------------------------------------------------------- +std::map>>>* RifInpReader::propertyDataMap( RigFemResultPosEnum resultType ) +{ + if ( resultType == RigFemResultPosEnum::RIG_ELEMENT ) return &m_propertyPartDataElements; + if ( resultType == RigFemResultPosEnum::RIG_NODAL ) return &m_propertyPartDataNodes; + + return nullptr; } diff --git a/ApplicationLibCode/GeoMech/OdbReader/RifInpReader.h b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpReader.h similarity index 54% rename from ApplicationLibCode/GeoMech/OdbReader/RifInpReader.h rename to ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpReader.h index b28c2fcf9e..d1d94b0ed1 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/RifInpReader.h +++ b/ApplicationLibCode/GeoMech/GeoMechFileInterface/RifInpReader.h @@ -20,16 +20,39 @@ #include "RifGeoMechReaderInterface.h" +#include "RigFemResultPosEnum.h" +#include "RigFemTypes.h" + +#include #include #include #include +#include class RigFemPartCollection; +struct RifInpIncludeEntry +{ +public: + RifInpIncludeEntry( std::string propertyName, RigFemResultPosEnum resultType, int stepId, std::string fileName, int columnIndex ) + { + this->propertyName = propertyName; + this->stepId = stepId; + this->fileName = fileName; + this->resultType = resultType; + this->columnIndex = columnIndex; + } + +public: + std::string propertyName; + int stepId; + std::string fileName; + RigFemResultPosEnum resultType; + int columnIndex; +}; + //================================================================================================== // -// Data interface base class -// //================================================================================================== class RifInpReader : public RifGeoMechReaderInterface { @@ -37,6 +60,8 @@ class RifInpReader : public RifGeoMechReaderInterface RifInpReader(); ~RifInpReader() override; + void enableIncludes( bool enable ); + bool openFile( const std::string& fileName, std::string* errorMessage ) override; bool isOpen() const override; bool readFemParts( RigFemPartCollection* geoMechCase ) override; @@ -49,6 +74,7 @@ class RifInpReader : public RifGeoMechReaderInterface std::vector elementSet( int partIndex, std::string partName, int setIndex ) override; std::map> scalarNodeFieldAndComponentNames() override; + std::map> scalarElementFieldAndComponentNames() override; std::map> scalarElementNodeFieldAndComponentNames() override; std::map> scalarIntegrationPointFieldAndComponentNames() override; @@ -59,6 +85,11 @@ class RifInpReader : public RifGeoMechReaderInterface int stepIndex, int frameIndex, std::vector*>* resultValues ) override; + void readElementField( const std::string& fieldName, + int partIndex, + int stepIndex, + int frameIndex, + std::vector*>* resultValues ) override; void readElementNodeField( const std::string& fieldName, int partIndex, int stepIndex, @@ -70,9 +101,21 @@ class RifInpReader : public RifGeoMechReaderInterface int frameIndex, std::vector*>* resultValues ) override; + bool populateDerivedResultNames() const override; + private: void close(); + void readField( RigFemResultPosEnum resultType, + const std::string& fieldName, + int partIndex, + int stepIndex, + std::vector*>* resultValues ); + + void readScalarData( RigFemPartCollection* femParts, std::map& parts, std::vector& includeEntries ); + + std::map>>>* propertyDataMap( RigFemResultPosEnum resultType ); + static void skipComments( std::istream& stream ); static std::string parseLabel( const std::string& line, const std::string& labelName ); static std::vector> readNodes( std::istream& stream ); @@ -80,14 +123,22 @@ class RifInpReader : public RifGeoMechReaderInterface static std::vector readElementSet( std::istream& stream ); static std::vector readElementSetGenerate( std::istream& stream ); - static void read( std::istream& stream, - std::map& parts, - std::map>>& nodes, - std::map>>>& elements, - std::map>>>& elementSets ); + static RigElementType read( std::istream& stream, + std::map& parts, + std::map>>& nodes, + std::map>>>& elements, + std::map>>>& elementSets, + std::vector& stepNames, + bool enableIncludes, + std::vector& includeEntries ); private: - std::map> m_partElementSetNames; - - std::ifstream m_stream; + bool m_enableIncludes; + std::map> m_partElementSetNames; + std::vector m_stepNames; + std::vector m_includeEntries; + std::ifstream m_stream; + std::filesystem::path m_inputPath; + std::map>>> m_propertyPartDataNodes; + std::map>>> m_propertyPartDataElements; }; diff --git a/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.cpp b/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.cpp index ece33dd2d1..02791790cc 100644 --- a/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.cpp @@ -57,7 +57,8 @@ void RivFemElmVisibilityCalculator::computeRangeVisibility( cvf::UByteArray* const cvf::CellRangeFilter& rangeFilter, const cvf::UByteArray* indexIncludeVisibility, const cvf::UByteArray* indexExcludeVisibility, - bool useIndexInclude ) + bool useIndexInclude, + bool useAndOperation ) { elmVisibilities->resize( femPart->elementCount() ); @@ -74,9 +75,19 @@ void RivFemElmVisibilityCalculator::computeRangeVisibility( cvf::UByteArray* for ( int elmIdx = 0; elmIdx < femPart->elementCount(); ++elmIdx ) { grid->ijkFromCellIndex( elmIdx, &mainGridI, &mainGridJ, &mainGridK ); - ( *elmVisibilities )[elmIdx] = - ( ( *indexIncludeVisibility )[elmIdx] || rangeFilter.isCellVisible( mainGridI, mainGridJ, mainGridK, false ) ) && - ( *indexExcludeVisibility )[elmIdx]; + + if ( useAndOperation ) + { + ( *elmVisibilities )[elmIdx] = + ( ( *indexIncludeVisibility )[elmIdx] && rangeFilter.isCellVisible( mainGridI, mainGridJ, mainGridK, false ) ) && + ( *indexExcludeVisibility )[elmIdx]; + } + else + { + ( *elmVisibilities )[elmIdx] = + ( ( *indexIncludeVisibility )[elmIdx] || rangeFilter.isCellVisible( mainGridI, mainGridJ, mainGridK, false ) ) && + ( *indexExcludeVisibility )[elmIdx]; + } } } else diff --git a/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.h b/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.h index 1b2529ad75..a0d3a567bd 100644 --- a/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.h +++ b/ApplicationLibCode/GeoMech/GeoMechVisualization/RivFemElmVisibilityCalculator.h @@ -41,7 +41,8 @@ class RivFemElmVisibilityCalculator const cvf::CellRangeFilter& rangeFilter, const cvf::UByteArray* indexIncludeVisibility, const cvf::UByteArray* indexExcludeVisibility, - bool useIndexInclude ); + bool useIndexInclude, + bool useAndOperation ); static void computePropertyVisibility( cvf::UByteArray* cellVisibility, const RigFemPart* grid, diff --git a/ApplicationLibCode/GeoMech/GeoMechVisualization/RivGeoMechVizLogic.cpp b/ApplicationLibCode/GeoMech/GeoMechVisualization/RivGeoMechVizLogic.cpp index dca38c6410..223ef6f37a 100644 --- a/ApplicationLibCode/GeoMech/GeoMechVisualization/RivGeoMechVizLogic.cpp +++ b/ApplicationLibCode/GeoMech/GeoMechVisualization/RivGeoMechVizLogic.cpp @@ -251,7 +251,8 @@ RivGeoMechPartMgr* RivGeoMechVizLogic::getUpdatedPartMgr( RivGeoMechPartMgrCache cellRangeFilter, &indexIncludeVisibility, &indexExcludeVisibility, - m_geomechView->cellFilterCollection()->hasActiveIncludeIndexFilters() ); + m_geomechView->cellFilterCollection()->hasActiveIncludeIndexFilters(), + m_geomechView->cellFilterCollection()->useAndOperation() ); } else if ( pMgrKey.geometryType() == PROPERTY_FILTERED ) { diff --git a/ApplicationLibCode/GeoMech/OdbReader/CMakeLists.txt b/ApplicationLibCode/GeoMech/OdbReader/CMakeLists.txt index f3165f1c96..80568a52ad 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/CMakeLists.txt +++ b/ApplicationLibCode/GeoMech/OdbReader/CMakeLists.txt @@ -1,11 +1,5 @@ project(RifOdbReader) -# Unity Build -if(RESINSIGHT_ENABLE_UNITY_BUILD) - message("Cmake Unity build is enabled on : ${PROJECT_NAME}") - set(CMAKE_UNITY_BUILD true) -endif() - if(MSVC) add_definitions(-DHKS_NT) add_definitions(-DABQ_WIN86_64) @@ -38,16 +32,7 @@ else() add_definitions(-DABQ_MPI_PMPI) endif(MSVC) -add_library( - ${PROJECT_NAME} - RifOdbReader.h - RifOdbReader.cpp - RifInpReader.h - RifInpReader.cpp - RifGeoMechReaderInterface.h - RifGeoMechReaderInterface.cpp - OdbSetup.cmake -) +add_library(${PROJECT_NAME} RifOdbReader.h RifOdbReader.cpp OdbSetup.cmake) target_include_directories( ${PROJECT_NAME} PRIVATE ${RESINSIGHT_ODB_API_DIR}/include @@ -92,7 +77,8 @@ endif(MSVC) target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries( - ${PROJECT_NAME} ${RI_ODB_LIBS} RigGeoMechDataModel LibCore + ${PROJECT_NAME} ${RI_ODB_LIBS} RigGeoMechDataModel RifGeoMechFileInterface + LibCore ) source_group("" FILES ${PROJECT_FILES}) diff --git a/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.cpp b/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.cpp index 02a5a853b1..cf5bd13f84 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.cpp +++ b/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.cpp @@ -101,43 +101,6 @@ class RifOdbBulkDataGetter size_t RifOdbReader::sm_instanceCount = 0; -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -std::map initFemTypeMap() -{ - std::map typeMap; - typeMap["C3D8R"] = HEX8; - typeMap["C3D8"] = HEX8; - typeMap["C3D8P"] = HEX8P; - typeMap["CAX4"] = CAX4; - typeMap["C3D20RT"] = HEX8; - typeMap["C3D8RT"] = HEX8; - typeMap["C3D8T"] = HEX8; - - return typeMap; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RigElementType toRigElementType( const odb_String& odbTypeName ) -{ - static std::map odbElmTypeToRigElmTypeMap = initFemTypeMap(); - - std::map::iterator it = odbElmTypeToRigElmTypeMap.find( odbTypeName.cStr() ); - - if ( it == odbElmTypeToRigElmTypeMap.end() ) - { -#if 0 - std::cout << "Unsupported element type :" << odbElm.type().cStr() << std::endl; -#endif - return UNKNOWN_ELM_TYPE; - } - - return it->second; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -176,6 +139,14 @@ void RifOdbReader::close() } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RifOdbReader::populateDerivedResultNames() const +{ + return true; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -380,8 +351,8 @@ bool RifOdbReader::readFemParts( RigFemPartCollection* femParts ) elementIdToIdxMap[odbElm.label()] = elmIdx; - RigElementType elmType = toRigElementType( odbElm.type() ); - if ( elmType == UNKNOWN_ELM_TYPE ) continue; + RigElementType elmType = RigFemTypes::toRigElementType( std::string( odbElm.type().cStr() ) ); + if ( elmType == RigElementType::UNKNOWN_ELM_TYPE ) continue; int nodeCount = 0; const int* idBasedConnectivities = odbElm.connectivity( nodeCount ); @@ -594,6 +565,15 @@ std::map> RifOdbReader::scalarNodeFieldAnd return fieldAndComponentNames( NODAL ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::map> RifOdbReader::scalarElementFieldAndComponentNames() +{ + // not supported, yet + return {}; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -864,6 +844,20 @@ void RifOdbReader::readNodeField( const std::string& fieldName, } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RifOdbReader::readElementField( const std::string& fieldName, + int partIndex, + int stepIndex, + int frameIndex, + std::vector*>* resultValues ) +{ + CVF_ASSERT( resultValues ); + + // Not supported, yet +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -986,7 +980,7 @@ void RifOdbReader::readIntegrationPointField( const std::string& int* elementLabels = bulkData.elementLabels(); float* data = bulkDataGetter.data(); - RigElementType eType = toRigElementType( bulkData.baseElementType() ); + RigElementType eType = RigFemTypes::toRigElementType( bulkData.baseElementType().cStr() ); const int* elmNodeToIpResultMapping = RigFemTypes::localElmNodeToIntegrationPointMapping( eType ); for ( int elem = 0; elem < elemCount; elem++ ) diff --git a/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.h b/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.h index 02193b43cf..1ca07b766c 100644 --- a/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.h +++ b/ApplicationLibCode/GeoMech/OdbReader/RifOdbReader.h @@ -53,6 +53,7 @@ class RifOdbReader : public RifGeoMechReaderInterface std::vector elementSet( int partIndex, std::string partName, int setIndex ) override; std::map> scalarNodeFieldAndComponentNames() override; + std::map> scalarElementFieldAndComponentNames() override; std::map> scalarElementNodeFieldAndComponentNames() override; std::map> scalarIntegrationPointFieldAndComponentNames() override; @@ -63,6 +64,11 @@ class RifOdbReader : public RifGeoMechReaderInterface int stepIndex, int frameIndex, std::vector*>* resultValues ) override; + void readElementField( const std::string& fieldName, + int partIndex, + int stepIndex, + int frameIndex, + std::vector*>* resultValues ) override; void readElementNodeField( const std::string& fieldName, int partIndex, int stepIndex, @@ -74,6 +80,8 @@ class RifOdbReader : public RifGeoMechReaderInterface int frameIndex, std::vector*>* resultValues ) override; + bool populateDerivedResultNames() const override; + private: enum ResultPosition { diff --git a/ApplicationLibCode/GeoMech/OdbReader_UnitTests/CMakeLists.txt b/ApplicationLibCode/GeoMech/OdbReader_UnitTests/CMakeLists.txt deleted file mode 100644 index 95e17c3061..0000000000 --- a/ApplicationLibCode/GeoMech/OdbReader_UnitTests/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -cmake_minimum_required(VERSION 2.8) - -project(OdbReader_UnitTests) - -set(RI_VIZ_FWK_ROOT - ../../../Fwk/VizFwk - CACHE PATH "Path to VizFwk" -) -set(RI_GTEST_ROOT - ../../../ThirdParty - CACHE PATH "Path to folder containing gtest folder" -) -set(RI_TEST_FILE - "" - CACHE FILEPATH "Path to test file" -) - -include(${RI_VIZ_FWK_ROOT}/CMake/Utils/ceeDetermineCompilerFlags.cmake) - -add_subdirectory(${RI_VIZ_FWK_ROOT}/LibCore buildVizFwk) -add_subdirectory(../../ResultStatisticsCache buildResultStatisticsCache) -add_subdirectory(../OdbReader buildOdbReader) -add_subdirectory(../GeoMechDataModel buildGeoMechDataModel) - -add_definitions(-DTEST_FILE="${RI_TEST_FILE}") - -include_directories(${RI_VIZ_FWK_ROOT}/LibCore) -include_directories(../../ResultStatisticsCache) -include_directories(../../ReservoirDataModel) -include_directories(../OdbReader) -include_directories(../GeoMechDataModel) -include_directories(${RI_GTEST_ROOT}) - -set(UNIT_TEST_CPP_SOURCES main.cpp RifOdbReader-Test.cpp - ${RI_GTEST_ROOT}/gtest/gtest-all.cc -) - -add_executable(${PROJECT_NAME} ${UNIT_TEST_CPP_SOURCES}) -target_link_libraries(${PROJECT_NAME} RifOdbReader) - -include(../OdbReader/OdbSetup.cmake) diff --git a/ApplicationLibCode/ModelVisualization/CMakeLists_files.cmake b/ApplicationLibCode/ModelVisualization/CMakeLists_files.cmake index 36c5f0a7b6..83fa8fa67f 100644 --- a/ApplicationLibCode/ModelVisualization/CMakeLists_files.cmake +++ b/ApplicationLibCode/ModelVisualization/CMakeLists_files.cmake @@ -54,7 +54,6 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RivWellDiskPartMgr.h ${CMAKE_CURRENT_LIST_DIR}/RivElementVectorResultPartMgr.h ${CMAKE_CURRENT_LIST_DIR}/RivPolylinePartMgr.h - ${CMAKE_CURRENT_LIST_DIR}/RivCellFilterPartMgr.h ${CMAKE_CURRENT_LIST_DIR}/RivDrawableSpheres.h ${CMAKE_CURRENT_LIST_DIR}/RivBoxGeometryGenerator.h ${CMAKE_CURRENT_LIST_DIR}/RivAnnotationTools.h @@ -112,7 +111,6 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RivWellDiskPartMgr.cpp ${CMAKE_CURRENT_LIST_DIR}/RivElementVectorResultPartMgr.cpp ${CMAKE_CURRENT_LIST_DIR}/RivPolylinePartMgr.cpp - ${CMAKE_CURRENT_LIST_DIR}/RivCellFilterPartMgr.cpp ${CMAKE_CURRENT_LIST_DIR}/RivDrawableSpheres.cpp ${CMAKE_CURRENT_LIST_DIR}/RivBoxGeometryGenerator.cpp ${CMAKE_CURRENT_LIST_DIR}/RivAnnotationTools.cpp diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivBoxIntersectionGeometryGenerator.cpp b/ApplicationLibCode/ModelVisualization/Intersections/RivBoxIntersectionGeometryGenerator.cpp index b4d4c7d91d..8f50a5bb9d 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivBoxIntersectionGeometryGenerator.cpp +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivBoxIntersectionGeometryGenerator.cpp @@ -289,8 +289,7 @@ void RivBoxIntersectionGeometryGenerator::calculateArrays( cvf::UByteArray* visi // Similar code as IntersectionGenerator : - std::vector columnCellCandidates; - m_hexGrid->findIntersectingCells( sectionBBox, &columnCellCandidates ); + std::vector columnCellCandidates = m_hexGrid->findIntersectingCells( sectionBBox ); std::vector hexPlaneCutTriangleVxes; hexPlaneCutTriangleVxes.reserve( 5 * 3 ); diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.cpp b/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.cpp index 3287749199..04c9d8ebed 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.cpp +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.cpp @@ -51,9 +51,9 @@ cvf::BoundingBox RivEclipseIntersectionGrid::boundingBox() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RivEclipseIntersectionGrid::findIntersectingCells( const cvf::BoundingBox& intersectingBB, std::vector* intersectedCells ) const +std::vector RivEclipseIntersectionGrid::findIntersectingCells( const cvf::BoundingBox& intersectingBB ) const { - m_mainGrid->findIntersectingCells( intersectingBB, intersectedCells ); + return m_mainGrid->findIntersectingCells( intersectingBB ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.h b/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.h index 4d65c1b3fb..8e607a5e46 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.h +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivEclipseIntersectionGrid.h @@ -40,14 +40,14 @@ class RivEclipseIntersectionGrid : public RivIntersectionHexGridInterface public: RivEclipseIntersectionGrid( const RigMainGrid* mainGrid, const RigActiveCellInfo* activeCellInfo, bool showInactiveCells ); - cvf::Vec3d displayOffset() const override; - cvf::BoundingBox boundingBox() const override; - void findIntersectingCells( const cvf::BoundingBox& intersectingBB, std::vector* intersectedCells ) const override; - bool useCell( size_t cellIndex ) const override; - void cellCornerVertices( size_t cellIndex, cvf::Vec3d cellCorners[8] ) const override; - void cellCornerIndices( size_t cellIndex, size_t cornerIndices[8] ) const override; - const RigFault* findFaultFromCellIndexAndCellFace( size_t reservoirCellIndex, cvf::StructGridInterface::FaceType face ) const override; - void setKIntervalFilter( bool enabled, std::string kIntervalStr ) override; + cvf::Vec3d displayOffset() const override; + cvf::BoundingBox boundingBox() const override; + std::vector findIntersectingCells( const cvf::BoundingBox& intersectingBB ) const override; + bool useCell( size_t cellIndex ) const override; + void cellCornerVertices( size_t cellIndex, cvf::Vec3d cellCorners[8] ) const override; + void cellCornerIndices( size_t cellIndex, size_t cornerIndices[8] ) const override; + const RigFault* findFaultFromCellIndexAndCellFace( size_t reservoirCellIndex, cvf::StructGridInterface::FaceType face ) const override; + void setKIntervalFilter( bool enabled, std::string kIntervalStr ) override; private: cvf::cref m_mainGrid; diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivExtrudedCurveIntersectionGeometryGenerator.cpp b/ApplicationLibCode/ModelVisualization/Intersections/RivExtrudedCurveIntersectionGeometryGenerator.cpp index adbf53ba60..d30e0b6d9c 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivExtrudedCurveIntersectionGeometryGenerator.cpp +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivExtrudedCurveIntersectionGeometryGenerator.cpp @@ -363,8 +363,7 @@ void RivExtrudedCurveIntersectionGeometryGenerator::calculateArrays( cvf::UByteA sectionBBox.cutBelow( bottomDepth ); sectionBBox.cutAbove( topDepth ); - std::vector columnCellCandidates; - m_hexGrid->findIntersectingCells( sectionBBox, &columnCellCandidates ); + std::vector columnCellCandidates = m_hexGrid->findIntersectingCells( sectionBBox ); cvf::Plane plane; plane.setFromPoints( p1, p2, p2 + maxHeightVec ); diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.cpp b/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.cpp index b9219fa01d..3ea150cc26 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.cpp +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.cpp @@ -51,14 +51,11 @@ cvf::BoundingBox RivFemIntersectionGrid::boundingBox() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RivFemIntersectionGrid::findIntersectingCells( const cvf::BoundingBox& intersectingBB, std::vector* intersectedCells ) const +std::vector RivFemIntersectionGrid::findIntersectingCells( const cvf::BoundingBox& intersectingBB ) const { // For FEM models the term element is used instead of cell. // Each FEM part has a local element index which is transformed into global index for a FEM part collection. - std::vector intersectedGlobalElementIndices; - m_femParts->findIntersectingGlobalElementIndices( intersectingBB, &intersectedGlobalElementIndices ); - - *intersectedCells = intersectedGlobalElementIndices; + return m_femParts->findIntersectingGlobalElementIndices( intersectingBB ); } //-------------------------------------------------------------------------------------------------- @@ -110,7 +107,7 @@ void RivFemIntersectionGrid::cellCornerIndices( size_t globalCellIndex, size_t c auto [part, elementIdx] = m_femParts->partAndElementIndex( globalCellIndex ); RigElementType elmType = part->elementType( elementIdx ); - if ( elmType != HEX8 && elmType != HEX8P ) return; + if ( !RigFemTypes::is8NodeElement( elmType ) ) return; int elmIdx = static_cast( elementIdx ); const int partId = part->elementPartId(); diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.h b/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.h index 5a3d03f0aa..f2751a9814 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.h +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivFemIntersectionGrid.h @@ -38,14 +38,14 @@ class RivFemIntersectionGrid : public RivIntersectionHexGridInterface public: explicit RivFemIntersectionGrid( const RigFemPartCollection* femParts, const RimGeoMechPartCollection* parts ); - cvf::Vec3d displayOffset() const override; - cvf::BoundingBox boundingBox() const override; - void findIntersectingCells( const cvf::BoundingBox& intersectingBB, std::vector* intersectedCells ) const override; - bool useCell( size_t cellIndex ) const override; - void cellCornerVertices( size_t cellIndex, cvf::Vec3d cellCorners[8] ) const override; - void cellCornerIndices( size_t cellIndex, size_t cornerIndices[8] ) const override; - const RigFault* findFaultFromCellIndexAndCellFace( size_t reservoirCellIndex, cvf::StructGridInterface::FaceType face ) const override; - void setKIntervalFilter( bool enabled, std::string kIntervalStr ) override; + cvf::Vec3d displayOffset() const override; + cvf::BoundingBox boundingBox() const override; + std::vector findIntersectingCells( const cvf::BoundingBox& intersectingBB ) const override; + bool useCell( size_t cellIndex ) const override; + void cellCornerVertices( size_t cellIndex, cvf::Vec3d cellCorners[8] ) const override; + void cellCornerIndices( size_t cellIndex, size_t cornerIndices[8] ) const override; + const RigFault* findFaultFromCellIndexAndCellFace( size_t reservoirCellIndex, cvf::StructGridInterface::FaceType face ) const override; + void setKIntervalFilter( bool enabled, std::string kIntervalStr ) override; private: cvf::cref m_femParts; diff --git a/ApplicationLibCode/ModelVisualization/Intersections/RivIntersectionHexGridInterface.h b/ApplicationLibCode/ModelVisualization/Intersections/RivIntersectionHexGridInterface.h index 41e86c8d79..0fcf5ed761 100644 --- a/ApplicationLibCode/ModelVisualization/Intersections/RivIntersectionHexGridInterface.h +++ b/ApplicationLibCode/ModelVisualization/Intersections/RivIntersectionHexGridInterface.h @@ -35,12 +35,12 @@ class RigFault; class RivIntersectionHexGridInterface : public cvf::Object { public: - virtual cvf::Vec3d displayOffset() const = 0; - virtual cvf::BoundingBox boundingBox() const = 0; - virtual void findIntersectingCells( const cvf::BoundingBox& intersectingBB, std::vector* intersectedCells ) const = 0; - virtual bool useCell( size_t cellIndex ) const = 0; - virtual void cellCornerVertices( size_t cellIndex, cvf::Vec3d cellCorners[8] ) const = 0; - virtual void cellCornerIndices( size_t cellIndex, size_t cornerIndices[8] ) const = 0; + virtual cvf::Vec3d displayOffset() const = 0; + virtual cvf::BoundingBox boundingBox() const = 0; + virtual std::vector findIntersectingCells( const cvf::BoundingBox& intersectingBB ) const = 0; + virtual bool useCell( size_t cellIndex ) const = 0; + virtual void cellCornerVertices( size_t cellIndex, cvf::Vec3d cellCorners[8] ) const = 0; + virtual void cellCornerIndices( size_t cellIndex, size_t cornerIndices[8] ) const = 0; virtual const RigFault* findFaultFromCellIndexAndCellFace( size_t reservoirCellIndex, cvf::StructGridInterface::FaceType face ) const = 0; virtual void setKIntervalFilter( bool enabled, std::string kIntervalStr ) = 0; }; diff --git a/ApplicationLibCode/ModelVisualization/RivCellFilterPartMgr.cpp b/ApplicationLibCode/ModelVisualization/RivCellFilterPartMgr.cpp deleted file mode 100644 index e8d82cd12f..0000000000 --- a/ApplicationLibCode/ModelVisualization/RivCellFilterPartMgr.cpp +++ /dev/null @@ -1,88 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2021 Equinor ASA -// -// ResInsight 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 3 of the License, or -// (at your option) any later version. -// -// ResInsight 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 at -// for more details. -// -///////////////////////////////////////////////////////////////////////////////// - -#include "RivCellFilterPartMgr.h" - -#include "Rim3dView.h" -#include "RimCellFilterCollection.h" -#include "RimPolygonFilter.h" - -#include "RivPolylinePartMgr.h" - -#include "cafPdmObject.h" - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RivCellFilterPartMgr::RivCellFilterPartMgr( Rim3dView* view ) - : m_rimView( view ) -{ -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RivCellFilterPartMgr::~RivCellFilterPartMgr() -{ -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RivCellFilterPartMgr::appendGeometryPartsToModel( cvf::ModelBasicList* model, - const caf::DisplayCoordTransform* displayCoordTransform, - const cvf::BoundingBox& boundingBox ) -{ - createCellFilterPartManagers(); - - for ( auto& partMgr : m_cellFilterPartMgrs ) - { - partMgr->appendDynamicGeometryPartsToModel( model, displayCoordTransform, boundingBox ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RivCellFilterPartMgr::createCellFilterPartManagers() -{ - std::vector colls = m_rimView->descendantsIncludingThisOfType(); - - if ( colls.empty() ) return; - auto coll = colls.front(); - - clearGeometryCache(); - - for ( auto filter : coll->filters() ) - { - RimPolygonFilter* polyFilter = dynamic_cast( filter ); - if ( polyFilter ) - { - RivPolylinePartMgr* ppm = new RivPolylinePartMgr( m_rimView, polyFilter, coll ); - m_cellFilterPartMgrs.push_back( ppm ); - } - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RivCellFilterPartMgr::clearGeometryCache() -{ - m_cellFilterPartMgrs.clear(); -} diff --git a/ApplicationLibCode/ModelVisualization/RivCellFilterPartMgr.h b/ApplicationLibCode/ModelVisualization/RivCellFilterPartMgr.h deleted file mode 100644 index a58d0d1916..0000000000 --- a/ApplicationLibCode/ModelVisualization/RivCellFilterPartMgr.h +++ /dev/null @@ -1,60 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2021 Equinor ASA -// -// ResInsight 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 3 of the License, or -// (at your option) any later version. -// -// ResInsight 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 at -// for more details. -// -///////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "cafPdmPointer.h" -#include "cvfAssert.h" -#include "cvfCollection.h" -#include "cvfObject.h" - -namespace cvf -{ -class BoundingBox; -class Part; -class ModelBasicList; -class Transform; -class Font; -} // namespace cvf -namespace caf -{ -class DisplayCoordTransform; -} - -class Rim3dView; -class RivPolylinePartMgr; - -class RivCellFilterPartMgr : public cvf::Object -{ -public: - RivCellFilterPartMgr( Rim3dView* view ); - ~RivCellFilterPartMgr() override; - - void appendGeometryPartsToModel( cvf::ModelBasicList* model, - const caf::DisplayCoordTransform* displayCoordTransform, - const cvf::BoundingBox& boundingBox ); - - void clearGeometryCache(); - -private: - void createCellFilterPartManagers(); - -private: - caf::PdmPointer m_rimView; - cvf::Collection m_cellFilterPartMgrs; -}; diff --git a/ApplicationLibCode/ModelVisualization/RivPolylinePartMgr.cpp b/ApplicationLibCode/ModelVisualization/RivPolylinePartMgr.cpp index 12ba78f953..d7c15ced50 100644 --- a/ApplicationLibCode/ModelVisualization/RivPolylinePartMgr.cpp +++ b/ApplicationLibCode/ModelVisualization/RivPolylinePartMgr.cpp @@ -82,7 +82,7 @@ bool RivPolylinePartMgr::isPolylinesInBoundingBox( std::vectorpolyLinesData(); - if ( polylineDef.isNull() || polylineDef->polyLines().empty() ) + if ( polylineDef.isNull() || polylineDef->rawPolyLines().empty() ) { clearAllGeometry(); return; @@ -107,6 +107,7 @@ void RivPolylinePartMgr::buildPolylineParts( const caf::DisplayCoordTransform* d cvf::ref part = new cvf::Part; part->setName( "RivPolylinePartMgr" ); part->setDrawable( drawableGeo.p() ); + part->updateBoundingBox(); caf::MeshEffectGenerator effgen( polylineDef->lineColor() ); effgen.setLineWidth( polylineDef->lineThickness() ); @@ -177,6 +178,7 @@ void RivPolylinePartMgr::buildPolylineParts( const caf::DisplayCoordTransform* d cvf::ref part = new cvf::Part; part->setName( "RivPolylinePartMgr" ); part->setDrawable( vectorDrawable.p() ); + part->updateBoundingBox(); part->setEffect( new cvf::Effect() ); part->setPriority( RivPartPriority::PartType::MeshLines ); @@ -190,7 +192,7 @@ void RivPolylinePartMgr::buildPolylineParts( const caf::DisplayCoordTransform* d //-------------------------------------------------------------------------------------------------- std::vector> RivPolylinePartMgr::getPolylinesPointsInDomain( RigPolyLinesData* lineDef ) { - auto polylines = lineDef->polyLines(); + auto polylines = lineDef->rawPolyLines(); if ( !lineDef->lockToZPlane() ) return polylines; const double planeZ = lineDef->lockedZValue(); diff --git a/ApplicationLibCode/ModelVisualization/RivReservoirViewPartMgr.cpp b/ApplicationLibCode/ModelVisualization/RivReservoirViewPartMgr.cpp index ac55abb8f4..5e39ce8166 100644 --- a/ApplicationLibCode/ModelVisualization/RivReservoirViewPartMgr.cpp +++ b/ApplicationLibCode/ModelVisualization/RivReservoirViewPartMgr.cpp @@ -749,9 +749,11 @@ void RivReservoirViewPartMgr::computeFilterVisibility( RivCellSetEnum parentGridVisibilities = reservoirGridPartMgr->cellVisibility( parentGridIndex ); } - bool hasAdditiveRangeFilters = cellFilterColl->hasActiveIncludeRangeFilters() || - m_reservoirView->wellCollection()->hasVisibleWellCells(); - bool hasAdditiveIndexFilters = cellFilterColl->hasActiveIncludeIndexFilters(); + const bool hasAdditiveRangeFilters = cellFilterColl->hasActiveIncludeRangeFilters() || + m_reservoirView->wellCollection()->hasVisibleWellCells(); + const bool hasAdditiveIndexFilters = cellFilterColl->hasActiveIncludeIndexFilters(); + + const bool useAndOperation = cellFilterColl->useAndOperation(); #pragma omp parallel for for ( int cellIndex = 0; cellIndex < static_cast( grid->cellCount() ); cellIndex++ ) @@ -771,7 +773,7 @@ void RivReservoirViewPartMgr::computeFilterVisibility( RivCellSetEnum size_t mainGridJ; size_t mainGridK; - bool isInSubGridArea = cell.subGrid() != nullptr; + const bool isInSubGridArea = cell.subGrid() != nullptr; grid->ijkFromCellIndex( cellIndex, &mainGridI, &mainGridJ, &mainGridK ); bool nativeRangeVisibility = false; @@ -780,8 +782,16 @@ void RivReservoirViewPartMgr::computeFilterVisibility( RivCellSetEnum { if ( hasAdditiveIndexFilters ) { - nativeRangeVisibility = indexIncludeVisibility[cellIndex] || - gridCellRangeFilter.isCellVisible( mainGridI, mainGridJ, mainGridK, isInSubGridArea ); + if ( useAndOperation ) + { + nativeRangeVisibility = indexIncludeVisibility[cellIndex] && + gridCellRangeFilter.isCellVisible( mainGridI, mainGridJ, mainGridK, isInSubGridArea ); + } + else + { + nativeRangeVisibility = indexIncludeVisibility[cellIndex] || + gridCellRangeFilter.isCellVisible( mainGridI, mainGridJ, mainGridK, isInSubGridArea ); + } } else { diff --git a/ApplicationLibCode/ModelVisualization/RivSimWellPipesPartMgr.cpp b/ApplicationLibCode/ModelVisualization/RivSimWellPipesPartMgr.cpp index 9e96ff708f..9ec86ad276 100644 --- a/ApplicationLibCode/ModelVisualization/RivSimWellPipesPartMgr.cpp +++ b/ApplicationLibCode/ModelVisualization/RivSimWellPipesPartMgr.cpp @@ -166,23 +166,7 @@ void RivSimWellPipesPartMgr::buildWellPipeParts( const caf::DisplayCoordTransfor m_wellBranches.clear(); m_flattenedBranchWellHeadOffsets.clear(); - auto createSimWells = []( RimSimWellInView* simWellInView ) -> std::vector - { - std::vector simWellBranches; - const RigSimWellData* simWellData = simWellInView->simWellData(); - if ( simWellData && simWellData->isMultiSegmentWell() ) - { - simWellBranches = RigMswCenterLineCalculator::calculateMswWellPipeGeometry( simWellInView ); - } - else - { - simWellBranches = RigSimulationWellCenterLineCalculator::calculateWellPipeStaticCenterline( simWellInView ); - } - - return simWellBranches; - }; - - auto simWells = createSimWells( m_simWellInView ); + auto simWells = m_simWellInView->wellBranchesForVisualization(); const auto& [coords, wellCells] = RigSimulationWellCenterLineCalculator::extractBranchData( simWells ); auto pipeBranchesCLCoords = coords; diff --git a/ApplicationLibCode/ModelVisualization/RivWellFracturePartMgr.cpp b/ApplicationLibCode/ModelVisualization/RivWellFracturePartMgr.cpp index 6c176fee00..2580c08c48 100644 --- a/ApplicationLibCode/ModelVisualization/RivWellFracturePartMgr.cpp +++ b/ApplicationLibCode/ModelVisualization/RivWellFracturePartMgr.cpp @@ -653,8 +653,7 @@ cvf::ref RivWellFracturePartMgr::createContainmentMaskPart( const Rim frBBox.add( pvd ); } - std::vector cellCandidates; - activeView.mainGrid()->findIntersectingCells( frBBox, &cellCandidates ); + std::vector cellCandidates = activeView.mainGrid()->findIntersectingCells( frBBox ); auto displCoordTrans = activeView.displayCoordTransform(); @@ -780,8 +779,7 @@ cvf::ref RivWellFracturePartMgr::createMaskOfFractureOutsideGrid( con std::vector> clippedPolygons; - std::vector cellCandidates; - activeView.mainGrid()->findIntersectingCells( frBBox, &cellCandidates ); + std::vector cellCandidates = activeView.mainGrid()->findIntersectingCells( frBBox ); if ( cellCandidates.empty() ) { clippedPolygons.push_back( borderOfFractureCellPolygonLocalCsd ); diff --git a/ApplicationLibCode/ModelVisualization/RivWellPathPartMgr.h b/ApplicationLibCode/ModelVisualization/RivWellPathPartMgr.h index f718729824..3fd557914a 100644 --- a/ApplicationLibCode/ModelVisualization/RivWellPathPartMgr.h +++ b/ApplicationLibCode/ModelVisualization/RivWellPathPartMgr.h @@ -132,8 +132,6 @@ class RivWellPathPartMgr : public cvf::Object bool isWellPathWithinBoundingBox( const cvf::BoundingBox& wellPathClipBoundingBox ) const; - static cvf::Color3f mapWellMeasurementToColor( const QString& measurementKind, double value ); - bool isWellPathEnabled( const cvf::BoundingBox& wellPathClipBoundingBox ) const; private: diff --git a/ApplicationLibCode/ModelVisualization/Surfaces/RivSurfaceIntersectionGeometryGenerator.cpp b/ApplicationLibCode/ModelVisualization/Surfaces/RivSurfaceIntersectionGeometryGenerator.cpp index 9898fe28d6..a799cffe53 100644 --- a/ApplicationLibCode/ModelVisualization/Surfaces/RivSurfaceIntersectionGeometryGenerator.cpp +++ b/ApplicationLibCode/ModelVisualization/Surfaces/RivSurfaceIntersectionGeometryGenerator.cpp @@ -154,8 +154,7 @@ void RivSurfaceIntersectionGeometryGenerator::calculateArrays() // Ensure AABB search tree is constructed outside parallel loop { - std::vector triIntersectedCellCandidates; - m_hexGrid->findIntersectingCells( cvf::BoundingBox(), &triIntersectedCellCandidates ); + std::vector triIntersectedCellCandidates = m_hexGrid->findIntersectingCells( cvf::BoundingBox() ); } #pragma omp parallel num_threads( 6 ) // More threads have nearly no effect @@ -193,8 +192,7 @@ void RivSurfaceIntersectionGeometryGenerator::calculateArrays() cvf::Vec3d maxHeightVec; - std::vector triIntersectedCellCandidates; - m_hexGrid->findIntersectingCells( triangleBBox, &triIntersectedCellCandidates ); + std::vector triIntersectedCellCandidates = m_hexGrid->findIntersectingCells( triangleBBox ); cvf::Plane plane; plane.setFromPoints( p0, p1, p2 ); diff --git a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlot.cpp b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlot.cpp index e152671799..d69bc2fa9b 100644 --- a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlot.cpp @@ -109,7 +109,6 @@ RimAnalysisPlot::RimAnalysisPlot() CAF_PDM_InitFieldNoDefault( &m_analysisPlotDataSelection, "AnalysisPlotData", "" ); m_analysisPlotDataSelection.uiCapability()->setUiTreeChildrenHidden( true ); - m_analysisPlotDataSelection.uiCapability()->setUiTreeHidden( true ); // Time Step Selection CAF_PDM_InitFieldNoDefault( &m_timeStepFilter, "TimeStepFilter", "Available Time Steps" ); @@ -161,13 +160,11 @@ RimAnalysisPlot::RimAnalysisPlot() CAF_PDM_InitFieldNoDefault( &m_barTextFontSize, "BarTextFontSize", "Font Size" ); CAF_PDM_InitFieldNoDefault( &m_valueAxisProperties, "ValueAxisProperties", "ValueAxisProperties" ); - m_valueAxisProperties.uiCapability()->setUiTreeHidden( true ); m_valueAxisProperties = new RimPlotAxisProperties; m_valueAxisProperties->setNameAndAxis( "Value-Axis", "Value-Axis", RiuQwtPlotTools::fromQwtPlotAxis( QwtAxis::YLeft ) ); m_valueAxisProperties->enableRangeSettings( false ); CAF_PDM_InitFieldNoDefault( &m_plotDataFilterCollection, "PlotDataFilterCollection", "PlotDataFilterCollection" ); - m_plotDataFilterCollection.uiCapability()->setUiTreeHidden( true ); m_plotDataFilterCollection = new RimPlotDataFilterCollection; connectAxisSignals( m_valueAxisProperties() ); diff --git a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotCollection.cpp index b396b58870..7ca063932c 100644 --- a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotCollection.cpp @@ -36,7 +36,6 @@ RimAnalysisPlotCollection::RimAnalysisPlotCollection() CAF_PDM_InitObject( "Analysis Plots", ":/AnalysisPlots16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_analysisPlots, "AnalysisPlots", "Analysis Plots" ); - m_analysisPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotDataEntry.cpp b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotDataEntry.cpp index 84d99745e4..0270c25904 100644 --- a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotDataEntry.cpp +++ b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimAnalysisPlotDataEntry.cpp @@ -44,7 +44,6 @@ RimAnalysisPlotDataEntry::RimAnalysisPlotDataEntry() m_ensemble.uiCapability()->setAutoAddingOptionFromValue( false ); CAF_PDM_InitFieldNoDefault( &m_summaryAddress, "SummaryAddress", "Summary Address" ); - m_summaryAddress.uiCapability()->setUiTreeHidden( true ); m_summaryAddress.uiCapability()->setUiTreeChildrenHidden( true ); m_summaryAddress = new RimSummaryAddress; diff --git a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterCollection.cpp b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterCollection.cpp index 2e05e9cd03..25e834e3c8 100644 --- a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterCollection.cpp @@ -32,7 +32,6 @@ RimPlotDataFilterCollection::RimPlotDataFilterCollection() CAF_PDM_InitField( &m_isActive, "IsActive", true, "IsActive" ); m_isActive.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_filters, "PlotDataFiltersField", "" ); - m_filters.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterItem.cpp b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterItem.cpp index 6cf447df64..612d97c63a 100644 --- a/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterItem.cpp +++ b/ApplicationLibCode/ProjectDataModel/AnalysisPlots/RimPlotDataFilterItem.cpp @@ -92,7 +92,6 @@ RimPlotDataFilterItem::RimPlotDataFilterItem() CAF_PDM_InitFieldNoDefault( &m_filterTarget, "FilterTarget", "Use only the" ); CAF_PDM_InitFieldNoDefault( &m_filterAddress, "FilterAddressField", "Filter Address" ); - m_filterAddress.uiCapability()->setUiTreeHidden( true ); m_filterAddress.uiCapability()->setUiTreeChildrenHidden( true ); m_filterAddress = new RimSummaryAddress(); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollection.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollection.cpp index e02d4e9075..02c209b37f 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollection.cpp @@ -47,10 +47,6 @@ RimAnnotationCollection::RimAnnotationCollection() CAF_PDM_InitFieldNoDefault( &m_userDefinedPolylineAnnotations, "UserDefinedPolylineAnnotations", "User Defined Polyline Annotations" ); CAF_PDM_InitFieldNoDefault( &m_polylineFromFileAnnotations, "PolylineFromFileAnnotations", "Polylines From File" ); - m_reachCircleAnnotations.uiCapability()->setUiTreeHidden( true ); - m_userDefinedPolylineAnnotations.uiCapability()->setUiTreeHidden( true ); - m_polylineFromFileAnnotations.uiCapability()->setUiTreeHidden( true ); - m_reachCircleAnnotations = new RimAnnotationGroupCollection(); m_userDefinedPolylineAnnotations = new RimAnnotationGroupCollection(); m_polylineFromFileAnnotations = new RimAnnotationGroupCollection(); @@ -164,7 +160,6 @@ RimPolylinesFromFileAnnotation* RimAnnotationCollection::importOrUpdatePolylines } } - size_t newLinesIdx = 0; for ( const QString& newFileName : newFileNames ) { RimPolylinesFromFileAnnotation* newPolyLinesAnnot = new RimPolylinesFromFileAnnotation; @@ -177,8 +172,6 @@ RimPolylinesFromFileAnnotation* RimAnnotationCollection::importOrUpdatePolylines m_polylineFromFileAnnotations->addAnnotation( newPolyLinesAnnot ); polyLinesObjsToReload.push_back( newPolyLinesAnnot ); - - ++newLinesIdx; } updateViewAnnotationCollections(); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollectionBase.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollectionBase.cpp index 39ee3697c4..79d1e39d19 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollectionBase.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationCollectionBase.cpp @@ -43,7 +43,6 @@ RimAnnotationCollectionBase::RimAnnotationCollectionBase() CAF_PDM_InitFieldNoDefault( &m_textAnnotations, "TextAnnotations", "Text Annotations" ); - m_textAnnotations.uiCapability()->setUiTreeHidden( true ); m_textAnnotations = new RimAnnotationGroupCollection(); m_textAnnotations->uiCapability()->setUiName( RimAnnotationGroupCollection::TEXT_ANNOTATION_UI_NAME ); m_textAnnotations->uiCapability()->setUiIconFromResourceString( ":/TextAnnotation16x16.png" ); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationGroupCollection.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationGroupCollection.cpp index 01134684d2..7e1e834f8a 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationGroupCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationGroupCollection.cpp @@ -49,7 +49,6 @@ RimAnnotationGroupCollection::RimAnnotationGroupCollection() CAF_PDM_InitFieldNoDefault( &m_annotations, "Annotations", "Annotations" ); m_isActive.uiCapability()->setUiHidden( true ); - m_annotations.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationInViewCollection.cpp index b41339e209..b8234e9da9 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationInViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimAnnotationInViewCollection.cpp @@ -97,11 +97,6 @@ RimAnnotationInViewCollection::RimAnnotationInViewCollection() CAF_PDM_InitFieldNoDefault( &m_annotationFontSize, "AnnotationFontSize", "Default Font Size" ); - m_globalTextAnnotations.uiCapability()->setUiTreeHidden( true ); - m_globalReachCircleAnnotations.uiCapability()->setUiTreeHidden( true ); - m_globalUserDefinedPolylineAnnotations.uiCapability()->setUiTreeHidden( true ); - m_globalPolylineFromFileAnnotations.uiCapability()->setUiTreeHidden( true ); - m_globalTextAnnotations = new RimAnnotationGroupCollection(); m_globalReachCircleAnnotations = new RimAnnotationGroupCollection(); m_globalUserDefinedPolylineAnnotations = new RimAnnotationGroupCollection(); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.cpp index 009b87bc3e..b2c48b8ffc 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.cpp @@ -29,9 +29,7 @@ CAF_PDM_SOURCE_INIT( RimPolylineTarget, "PolylineTarget" ); /// //-------------------------------------------------------------------------------------------------- RimPolylineTarget::RimPolylineTarget() - : m_isFullUpdateEnabled( true ) { - CAF_PDM_InitField( &m_isEnabled, "IsEnabled", true, "" ); CAF_PDM_InitFieldNoDefault( &m_targetPointXyd, "TargetPointXyd", "Point" ); } @@ -42,14 +40,6 @@ RimPolylineTarget::~RimPolylineTarget() { } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimPolylineTarget::isEnabled() const -{ - return m_isEnabled; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -84,14 +74,6 @@ caf::PdmUiFieldHandle* RimPolylineTarget::targetPointUiCapability() return m_targetPointXyd.uiCapability(); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimPolylineTarget::enableFullUpdate( bool enable ) -{ - m_isFullUpdateEnabled = enable; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.h index 272362deb4..799c983b58 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylineTarget.h @@ -38,14 +38,11 @@ class RimPolylineTarget : public caf::PdmObject RimPolylineTarget(); ~RimPolylineTarget() override; - bool isEnabled() const; - void setAsPointTargetXYD( const cvf::Vec3d& point ); void setAsPointXYZ( const cvf::Vec3d& point ); cvf::Vec3d targetPointXYZ() const; caf::PdmUiFieldHandle* targetPointUiCapability(); - void enableFullUpdate( bool enable ); void triggerVisualizationUpdate() const; @@ -54,7 +51,5 @@ class RimPolylineTarget : public caf::PdmObject void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; private: - bool m_isFullUpdateEnabled; - caf::PdmField m_isEnabled; caf::PdmField m_targetPointXyd; }; diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotation.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotation.cpp index 96abd0982e..3e9c6b98b8 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotation.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotation.cpp @@ -47,7 +47,6 @@ RimPolylinesAnnotation::RimPolylinesAnnotation() CAF_PDM_InitFieldNoDefault( &m_appearance, "Appearance", "Appearance" ); m_appearance = new RimPolylineAppearance(); - m_appearance.uiCapability()->setUiTreeHidden( true ); m_appearance.uiCapability()->setUiTreeChildrenHidden( true ); setDeletable( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotationInView.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotationInView.h index aba72d219a..83852d2f6e 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotationInView.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesAnnotationInView.h @@ -28,7 +28,6 @@ #include "cafPdmObject.h" #include "cafPdmPointer.h" #include "cafPdmPtrField.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotation.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotation.cpp index a78843ddd0..ca7a0c6efc 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotation.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotation.cpp @@ -158,7 +158,7 @@ bool RimPolylinesFromFileAnnotation::isEmpty() { if ( m_polyLinesData.isNull() ) return true; - for ( const std::vector& line : m_polyLinesData->polyLines() ) + for ( const std::vector& line : m_polyLinesData->rawPolyLines() ) { if ( !line.empty() ) return false; } diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotationInView.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotationInView.h index 213d4cfddd..2562dfb70e 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotationInView.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimPolylinesFromFileAnnotationInView.h @@ -26,7 +26,6 @@ #include "cafPdmObject.h" #include "cafPdmPointer.h" #include "cafPdmPtrField.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.cpp index 3bb69c5eab..005b771caf 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.cpp @@ -44,8 +44,7 @@ RimReachCircleAnnotation::RimReachCircleAnnotation() CAF_PDM_InitField( &m_centerPointXyd, "CenterPointXyd", Vec3d::ZERO, "Center Point" ); m_centerPointXyd.uiCapability()->setUiEditorTypeName( caf::PdmUiPickableLineEditor::uiEditorTypeName() ); CAF_PDM_InitField( &m_centerPointPickEnabled, "AnchorPointPick", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_centerPointPickEnabled ); - m_centerPointPickEnabled.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_centerPointPickEnabled ); CAF_PDM_InitField( &m_radius, "Radius", 100.0, "Radius" ); CAF_PDM_InitField( &m_name, "Name", QString( "Circle Annotation" ), "Name" ); @@ -53,7 +52,6 @@ RimReachCircleAnnotation::RimReachCircleAnnotation() CAF_PDM_InitFieldNoDefault( &m_appearance, "Appearance", "Appearance" ); m_appearance = new RimReachCircleLineAppearance(); - m_appearance.uiCapability()->setUiTreeHidden( true ); m_appearance.uiCapability()->setUiTreeChildrenHidden( true ); m_centerPointEventHandler.reset( new RicVec3dPickEventHandler( &m_centerPointXyd ) ); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.h index c642077f30..d08ec594db 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotation.h @@ -23,7 +23,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmPointer.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotationInView.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotationInView.h index 8cbca90336..1988f7b81c 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotationInView.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimReachCircleAnnotationInView.h @@ -26,7 +26,6 @@ #include "cafPdmObject.h" #include "cafPdmPointer.h" #include "cafPdmPtrField.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.cpp index 4cf8a14fb1..5c18975bce 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.cpp @@ -51,14 +51,12 @@ RimTextAnnotation::RimTextAnnotation() CAF_PDM_InitField( &m_anchorPointXyd, "AnchorPointXyd", Vec3d::ZERO, "Anchor Point" ); m_anchorPointXyd.uiCapability()->setUiEditorTypeName( caf::PdmUiPickableLineEditor::uiEditorTypeName() ); CAF_PDM_InitField( &m_anchorPointPickEnabledButtonField, "AnchorPointPick", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_anchorPointPickEnabledButtonField ); - m_anchorPointPickEnabledButtonField.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_anchorPointPickEnabledButtonField ); CAF_PDM_InitField( &m_labelPointXyd, "LabelPointXyd", Vec3d::ZERO, "Label Point" ); m_labelPointXyd.uiCapability()->setUiEditorTypeName( caf::PdmUiPickableLineEditor::uiEditorTypeName() ); CAF_PDM_InitField( &m_labelPointPickEnabledButtonField, "LabelPointPick", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_labelPointPickEnabledButtonField ); - m_labelPointPickEnabledButtonField.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_labelPointPickEnabledButtonField ); CAF_PDM_InitField( &m_text, "Text", QString( "(New text)" ), "Text" ); m_text.uiCapability()->setUiEditorTypeName( caf::PdmUiTextEditor::uiEditorTypeName() ); @@ -68,7 +66,6 @@ RimTextAnnotation::RimTextAnnotation() CAF_PDM_InitFieldNoDefault( &m_textAppearance, "TextAppearance", "Text Appearance" ); m_textAppearance = new RimAnnotationTextAppearance(); - m_textAppearance.uiCapability()->setUiTreeHidden( true ); m_textAppearance.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_nameProxy, "NameProxy", "Name Proxy" ); diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.h index 998418ed39..dc457a1b1b 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotation.h @@ -23,7 +23,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmPointer.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotationInView.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotationInView.h index 6add6a3570..0d3548a269 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotationInView.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimTextAnnotationInView.h @@ -24,7 +24,6 @@ #include "cafPdmObject.h" #include "cafPdmPointer.h" #include "cafPdmPtrField.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.cpp b/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.cpp index 82916de56c..d86ab4b699 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.cpp +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.cpp @@ -49,7 +49,7 @@ RimUserDefinedPolylinesAnnotation::RimUserDefinedPolylinesAnnotation() CAF_PDM_InitField( &m_name, "Name", QString( "User Defined Polyline" ), "Name" ); CAF_PDM_InitField( &m_enablePicking, "EnablePicking", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_enablePicking ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_enablePicking ); m_enablePicking.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); CAF_PDM_InitFieldNoDefault( &m_targets, "Targets", "Targets" ); @@ -152,31 +152,6 @@ void RimUserDefinedPolylinesAnnotation::deleteTarget( RimPolylineTarget* targetT delete targetToDelete; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -std::pair - RimUserDefinedPolylinesAnnotation::findActiveTargetsAroundInsertionPoint( const RimPolylineTarget* targetToInsertBefore ) -{ - RimPolylineTarget* before = nullptr; - RimPolylineTarget* after = nullptr; - - bool foundTarget = false; - for ( const auto& wt : m_targets ) - { - if ( wt == targetToInsertBefore ) - { - foundTarget = true; - } - - if ( wt->isEnabled() && !after && foundTarget ) after = wt; - - if ( wt->isEnabled() && !foundTarget ) before = wt; - } - - return { before, after }; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.h index 9afb83e562..000a2492e2 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotation.h @@ -60,8 +60,6 @@ class RimUserDefinedPolylinesAnnotation : public RimPolylinesAnnotation, public void appendTarget( const cvf::Vec3d& defaultPos = cvf::Vec3d::ZERO ); - std::pair findActiveTargetsAroundInsertionPoint( const RimPolylineTarget* targetToInsertBefore ); - void enablePicking( bool enable ); protected: diff --git a/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotationInView.h b/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotationInView.h index 667258b8fb..8a707a46a2 100644 --- a/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotationInView.h +++ b/ApplicationLibCode/ProjectDataModel/Annotations/RimUserDefinedPolylinesAnnotationInView.h @@ -26,7 +26,6 @@ #include "cafPdmObject.h" #include "cafPdmPointer.h" #include "cafPdmPtrField.h" -#include "cafPdmUiOrdering.h" // Include to make Pdm work for cvf::Color #include "cafPdmChildField.h" diff --git a/ApplicationLibCode/ProjectDataModel/CMakeLists_files.cmake b/ApplicationLibCode/ProjectDataModel/CMakeLists_files.cmake index ad087f3367..d3366768f1 100644 --- a/ApplicationLibCode/ProjectDataModel/CMakeLists_files.cmake +++ b/ApplicationLibCode/ProjectDataModel/CMakeLists_files.cmake @@ -133,6 +133,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RimEclipseResultDefinitionTools.h ${CMAKE_CURRENT_LIST_DIR}/RimResultSelectionUi.h ${CMAKE_CURRENT_LIST_DIR}/RimPlotRectAnnotation.h + ${CMAKE_CURRENT_LIST_DIR}/RimEmCase.h ) set(SOURCE_GROUP_SOURCE_FILES @@ -265,6 +266,8 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RimEclipseResultDefinitionTools.cpp ${CMAKE_CURRENT_LIST_DIR}/RimResultSelectionUi.cpp ${CMAKE_CURRENT_LIST_DIR}/RimPlotRectAnnotation.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimEmCase.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolylinePickerInterface.cpp ) if(RESINSIGHT_USE_QT_CHARTS) diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.cpp index 0b1cdc212e..c78d1a630f 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.cpp @@ -130,6 +130,14 @@ bool RimCellFilter::isActive() const return m_isActive(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimCellFilter::triggerFilterChanged() const +{ + filterChanged.send(); +} + //-------------------------------------------------------------------------------------------------- /// Is the cell filter doing active filtering, or is it just showning outline, etc. in the view /// - isActive == true -> filter enabled in explorer diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.h b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.h index f61474d541..97dc94cb4e 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.h +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilter.h @@ -70,6 +70,8 @@ class RimCellFilter : public caf::PdmObject bool isActive() const; void setActive( bool active ); + void triggerFilterChanged() const; + virtual void setCase( RimCase* srcCase ); bool isRangeFilter() const; diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.cpp index 4625282d4e..5fe2bb0774 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.cpp @@ -24,6 +24,7 @@ #include "RimCellIndexFilter.h" #include "RimCellRangeFilter.h" #include "RimPolygonFilter.h" +#include "RimProject.h" #include "RimUserDefinedFilter.h" #include "RimUserDefinedIndexFilter.h" #include "RimViewController.h" @@ -32,8 +33,21 @@ #include "cafPdmFieldReorderCapability.h" #include "cafPdmFieldScriptingCapability.h" #include "cafPdmObjectScriptingCapability.h" +#include "cafPdmUiLabelEditor.h" + #include "cvfStructGridGeometryGenerator.h" +namespace caf +{ +template <> +void caf::AppEnum::setUp() +{ + addItem( RimCellFilterCollection::AND, "AND", "AND" ); + addItem( RimCellFilterCollection::OR, "OR", "OR" ); + setDefault( RimCellFilterCollection::AND ); +} +} // namespace caf + CAF_PDM_SOURCE_INIT( RimCellFilterCollection, "CellFilterCollection", "RimCellFilterCollection", "CellRangeFilterCollection" ); //-------------------------------------------------------------------------------------------------- @@ -47,13 +61,17 @@ RimCellFilterCollection::RimCellFilterCollection() CAF_PDM_InitScriptableField( &m_isActive, "Active", true, "Active" ); m_isActive.uiCapability()->setUiHidden( true ); + CAF_PDM_InitFieldNoDefault( &m_combineFilterMode, "CombineFilterMode", "" ); + + CAF_PDM_InitField( &m_combineModeLabel, "CombineModeLabel", QString( "" ), "Combine Polygon and Range Filters Using Operation" ); + m_combineModeLabel.uiCapability()->setUiEditorTypeName( caf::PdmUiLabelEditor::uiEditorTypeName() ); + m_combineModeLabel.xmlCapability()->disableIO(); + CAF_PDM_InitFieldNoDefault( &m_cellFilters, "CellFilters", "Filters" ); - m_cellFilters.uiCapability()->setUiTreeHidden( true ); caf::PdmFieldReorderCapability::addToField( &m_cellFilters ); // for backwards project file compatibility with old CellRangeFilterCollection CAF_PDM_InitFieldNoDefault( &m_rangeFilters_OBSOLETE, "RangeFilters", "Range Filters" ); - m_rangeFilters_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_rangeFilters_OBSOLETE.xmlCapability()->setIOWritable( false ); } @@ -89,6 +107,14 @@ void RimCellFilterCollection::setActive( bool bActive ) updateIconState(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimCellFilterCollection::useAndOperation() const +{ + return m_combineFilterMode() == RimCellFilterCollection::AND; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -126,6 +152,12 @@ void RimCellFilterCollection::initAfterRead() m_cellFilters.push_back( filter ); } + // fallback to OR mode for older projects made without AND support + if ( RimProject::current()->isProjectFileVersionEqualOrOlderThan( "2023.12.0" ) ) + { + m_combineFilterMode = RimCellFilterCollection::OR; + } + // Copy by xml serialization does not give a RimCase parent the first time initAfterRead is called here when creating a new a contour // view from a 3d view. The second time we get called it is ok, so just skip setting up the filter connections if we have no case. auto rimCase = firstAncestorOrThisOfType(); @@ -147,6 +179,12 @@ void RimCellFilterCollection::fieldChangedByUi( const caf::PdmFieldHandle* chang uiCapability()->updateConnectedEditors(); onFilterUpdated( nullptr ); + + for ( const auto& filter : m_cellFilters ) + { + // Update the filters to make sure the 3D polygon targets are removed if the filter collection is disabled + filter->updateConnectedEditors(); + } } //-------------------------------------------------------------------------------------------------- @@ -157,6 +195,17 @@ caf::PdmFieldHandle* RimCellFilterCollection::objectToggleField() return &m_isActive; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimCellFilterCollection::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( &m_combineModeLabel ); + uiOrdering.add( &m_combineFilterMode ); + + uiOrdering.skipRemainingFields(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -178,6 +227,18 @@ void RimCellFilterCollection::defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTr updateIconState(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimCellFilterCollection::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + caf::PdmUiLabelEditorAttribute* myAttr = dynamic_cast( attribute ); + if ( myAttr ) + { + myAttr->m_useSingleWidgetInsteadOfLabelAndEditorWidget = true; + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -257,12 +318,22 @@ bool RimCellFilterCollection::hasActiveIncludeRangeFilters() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimPolygonFilter* RimCellFilterCollection::addNewPolygonFilter( RimCase* srcCase ) +RimPolygonFilter* RimCellFilterCollection::addNewPolygonFilter( RimCase* srcCase, RimPolygon* polygon ) { RimPolygonFilter* pFilter = new RimPolygonFilter(); pFilter->setCase( srcCase ); + pFilter->setPolygon( polygon ); addFilter( pFilter ); - pFilter->enablePicking( true ); + pFilter->configurePolygonEditor(); + if ( polygon ) + { + pFilter->enableFilter( true ); + } + else + { + pFilter->enablePicking( true ); + } + onFilterUpdated( pFilter ); return pFilter; } @@ -487,3 +558,23 @@ void RimCellFilterCollection::updateCellVisibilityByIndex( cvf::UByteArray* incl } } } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimCellFilterCollection::enabledCellFilterPolygons() const +{ + std::vector polyInView; + + for ( const auto& filter : m_cellFilters ) + { + if ( !filter->isActive() ) continue; + + if ( auto polygonFilter = dynamic_cast( filter.p() ) ) + { + polyInView.push_back( polygonFilter->polygonInView() ); + } + } + + return polyInView; +} diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.h b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.h index 87a7d808ba..45e23fc90b 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.h +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellFilterCollection.h @@ -32,6 +32,8 @@ class RimPolygonFilter; class RimUserDefinedFilter; class RimUserDefinedIndexFilter; class RimCase; +class RimPolygonInView; +class RimPolygon; namespace cvf { @@ -47,12 +49,18 @@ class RimCellFilterCollection : public caf::PdmObject CAF_PDM_HEADER_INIT; public: + enum CombineFilterModeType + { + OR, + AND + }; + RimCellFilterCollection(); ~RimCellFilterCollection() override; caf::Signal<> filtersChanged; - RimPolygonFilter* addNewPolygonFilter( RimCase* srcCase ); + RimPolygonFilter* addNewPolygonFilter( RimCase* srcCase, RimPolygon* polygon ); RimCellRangeFilter* addNewCellRangeFilter( RimCase* srcCase, int gridIndex, int sliceDirection = -1, int defaultSlice = -1 ); RimCellIndexFilter* addNewCellIndexFilter( RimCase* srcCase ); RimUserDefinedFilter* addNewUserDefinedFilter( RimCase* srcCase ); @@ -66,10 +74,13 @@ class RimCellFilterCollection : public caf::PdmObject bool isActive() const; void setActive( bool bActive ); + bool useAndOperation() const; + void compoundCellRangeFilter( cvf::CellRangeFilter* cellRangeFilter, size_t gridIndex ) const; void updateCellVisibilityByIndex( cvf::UByteArray* cellsIncluded, cvf::UByteArray* cellsExcluded, size_t gridIndex ) const; - std::vector filters() const; + std::vector enabledCellFilterPolygons() const; + std::vector filters() const; bool hasActiveFilters() const; bool hasActiveIncludeIndexFilters() const; @@ -84,7 +95,10 @@ class RimCellFilterCollection : public caf::PdmObject protected: void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; void defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, QString uiConfigName ) override; + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + caf::PdmFieldHandle* objectToggleField() override; void initAfterRead() override; @@ -94,8 +108,10 @@ class RimCellFilterCollection : public caf::PdmObject void setAutoName( RimCellFilter* pFilter ); void addFilter( RimCellFilter* pFilter ); - caf::PdmChildArrayField m_cellFilters; - caf::PdmField m_isActive; + caf::PdmChildArrayField m_cellFilters; + caf::PdmField m_isActive; + caf::PdmField m_combineModeLabel; + caf::PdmField> m_combineFilterMode; caf::PdmChildArrayField m_rangeFilters_OBSOLETE; }; diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellRangeFilter.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellRangeFilter.cpp index f9142e3954..079b5a33e6 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellRangeFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimCellRangeFilter.cpp @@ -184,8 +184,7 @@ void RimCellRangeFilter::setDefaultValues( int sliceDirection, int defaultSlice if ( grid == mainGrid && actCellInfo ) { - cvf::Vec3st min, max; - actCellInfo->IJKBoundingBox( min, max ); + auto [min, max] = actCellInfo->ijkBoundingBox(); // Adjust to Eclipse indexing min.x() = min.x() + 1; @@ -280,8 +279,7 @@ void RimCellRangeFilter::defineUiOrdering( QString uiConfigName, caf::PdmUiOrder if ( grid == mainGrid && actCellInfo ) { - cvf::Vec3st min, max; - actCellInfo->IJKBoundingBox( min, max ); + auto [min, max] = actCellInfo->ijkBoundingBox(); // Adjust to Eclipse indexing min.x() = min.x() + 1; diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilter.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilter.cpp index b9e3e5f318..81d2479bfe 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilter.cpp @@ -63,7 +63,6 @@ RimEclipsePropertyFilter::RimEclipsePropertyFilter() // Set to hidden to avoid this item to been displayed as a child item // Fields in this object are displayed using defineUiOrdering() - m_resultDefinition.uiCapability()->setUiTreeHidden( true ); m_resultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_rangeLabelText, "Dummy_keyword", QString( "Range Type" ), "Range Type" ); @@ -390,7 +389,7 @@ void RimEclipsePropertyFilter::defineObjectEditorAttribute( QString uiConfigName if ( treeItemAttribute ) { treeItemAttribute->tags.clear(); - auto tag = caf::PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = caf::PdmUiTreeViewItemAttribute::createTag(); tag->icon = caf::IconProvider( ":/chain.png" ); treeItemAttribute->tags.push_back( std::move( tag ) ); diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilterCollection.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilterCollection.cpp index 2ded2b8109..231d522db8 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilterCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimEclipsePropertyFilterCollection.cpp @@ -41,7 +41,6 @@ RimEclipsePropertyFilterCollection::RimEclipsePropertyFilterCollection() CAF_PDM_InitObject( "Property Filters", ":/CellFilter_Values.png" ); CAF_PDM_InitFieldNoDefault( &m_propertyFilters, "PropertyFilters", "Property Filters" ); - m_propertyFilters.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilter.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilter.cpp index 6ecc058b26..3d9b8cee90 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilter.cpp @@ -49,7 +49,6 @@ RimGeoMechPropertyFilter::RimGeoMechPropertyFilter() // Set to hidden to avoid this item to been displayed as a child item // Fields in this object are displayed using defineUiOrdering() - resultDefinition.uiCapability()->setUiTreeHidden( true ); resultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &lowerBound, "LowerBound", 0.0, "Min" ); diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilterCollection.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilterCollection.cpp index 81787855b0..432025ca8f 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilterCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimGeoMechPropertyFilterCollection.cpp @@ -37,7 +37,6 @@ RimGeoMechPropertyFilterCollection::RimGeoMechPropertyFilterCollection() CAF_PDM_InitObject( "Property Filters", ":/CellFilter_Values.png" ); CAF_PDM_InitFieldNoDefault( &propertyFilters, "PropertyFilters", "Property Filters" ); - propertyFilters.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.cpp b/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.cpp index 77e4599511..b8a28f811f 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.cpp @@ -20,39 +20,29 @@ #include "RigCellGeometryTools.h" #include "RigEclipseCaseData.h" -#include "RigFemPart.h" #include "RigFemPartCollection.h" #include "RigFemPartGrid.h" #include "RigGeoMechCaseData.h" #include "RigMainGrid.h" -#include "RigPolyLinesData.h" #include "RigReservoirGridTools.h" -#include "Rim3dView.h" -#include "RimCase.h" #include "RimCellFilterCollection.h" #include "RimEclipseCase.h" #include "RimGeoMechCase.h" #include "RimPolylineTarget.h" +#include "RimTools.h" -#include "WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.h" -#include "WellPathCommands/RicPolylineTargetsPickEventHandler.h" +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonCollection.h" +#include "Polygons/RimPolygonInView.h" +#include "Polygons/RimPolygonTools.h" -#include "RiuViewerCommands.h" +#include "Riu3DMainWindowTools.h" -#include "RiaStdStringTools.h" +#include "WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.h" +#include "WellPathCommands/RicPolylineTargetsPickEventHandler.h" -#include "cafCmdFeatureMenuBuilder.h" -#include "cafPdmUiLineEditor.h" #include "cafPdmUiPushButtonEditor.h" -#include "cafPdmUiTableViewEditor.h" -#include "cafPdmUiTreeOrdering.h" -#include - -#include "cvfBoundingBox.h" -#include "cvfStructGrid.h" - -#include #include @@ -75,43 +65,23 @@ void caf::AppEnum::setUp() setDefault( RimPolygonFilter::PolygonIncludeType::CENTER ); } -} // namespace caf - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -class ThicknessValidator : public QValidator +template <> +void caf::AppEnum::setUp() { -public: - State validate( QString& input, int& pos ) const override - { - if ( input.isEmpty() ) return State::Intermediate; - - int val = RiaStdStringTools::toInt( input.toStdString() ); - if ( val > 0 && val < 8 ) - return State::Acceptable; - else - return State::Invalid; - } -}; + addItem( RimPolygonFilter::GeometricalShape::AREA, "AREA", "Area Filter" ); + addItem( RimPolygonFilter::GeometricalShape::LINE, "LINE", "Line Filter" ); + setDefault( RimPolygonFilter::GeometricalShape::AREA ); +} -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -class RadiusValidator : public QValidator +template <> +void caf::AppEnum::setUp() { -public: - State validate( QString& input, int& pos ) const override - { - if ( input.isEmpty() ) return State::Intermediate; + addItem( RimPolygonFilter::PolygonDataSource::DEFINED_IN_FILTER, "DEFINED_IN_FILTER", "Defined in Filter" ); + addItem( RimPolygonFilter::PolygonDataSource::GLOBAL_POLYGON, "GLOBAL_POLYGON", "Polygon in Project" ); + setDefault( RimPolygonFilter::PolygonDataSource::DEFINED_IN_FILTER ); +} - double val = RiaStdStringTools::toDouble( input.toStdString() ); - if ( val > 0.001 && val <= 2.0 ) - return State::Acceptable; - else - return State::Invalid; - } -}; +} // namespace caf CAF_PDM_SOURCE_INIT( RimPolygonFilter, "PolygonFilter", "PolyLineFilter" ); @@ -128,85 +98,72 @@ RimPolygonFilter::RimPolygonFilter() CAF_PDM_InitFieldNoDefault( &m_polyFilterMode, "PolygonFilterType", "Vertical Filter" ); CAF_PDM_InitFieldNoDefault( &m_polyIncludeType, "PolyIncludeType", "Cells to include" ); + CAF_PDM_InitFieldNoDefault( &m_polygonDataSource, "PolygonDataSource", "Data Source" ); - CAF_PDM_InitField( &m_enablePicking, "EnablePicking", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_enablePicking ); - m_enablePicking.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); + CAF_PDM_InitFieldNoDefault( &m_geometricalShape, "GeometricalShape", "" ); + m_geometricalShape.registerGetMethod( this, &RimPolygonFilter::geometricalShape ); + m_geometricalShape.registerSetMethod( this, &RimPolygonFilter::setGeometricalShape ); - CAF_PDM_InitFieldNoDefault( &m_targets, "Targets", "Targets" ); - m_targets.uiCapability()->setUiEditorTypeName( caf::PdmUiTableViewEditor::uiEditorTypeName() ); - m_targets.uiCapability()->setUiTreeChildrenHidden( true ); - m_targets.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); - m_targets.uiCapability()->setCustomContextMenuEnabled( true ); + CAF_PDM_InitFieldNoDefault( &m_internalPolygon, "InternalPolygon", "Polygon For Filter" ); + m_internalPolygon = new RimPolygon; + m_internalPolygon->setName( "Polygon For Filter" ); + m_internalPolygon->uiCapability()->setUiTreeHidden( true ); - CAF_PDM_InitField( &m_showLines, "ShowLines", true, "Show Lines" ); - CAF_PDM_InitField( &m_showSpheres, "ShowSpheres", false, "Show Spheres" ); + CAF_PDM_InitFieldNoDefault( &m_cellFilterPolygon, "Polygon", "Polygon" ); - CAF_PDM_InitField( &m_lineThickness, "LineThickness", 3, "Line Thickness" ); - CAF_PDM_InitField( &m_sphereRadiusFactor, "SphereRadiusFactor", 0.15, "Sphere Radius Factor" ); - - CAF_PDM_InitField( &m_lineColor, "LineColor", cvf::Color3f( cvf::Color3f::WHITE ), "Line Color" ); - CAF_PDM_InitField( &m_sphereColor, "SphereColor", cvf::Color3f( cvf::Color3f::WHITE ), "Sphere Color" ); + CAF_PDM_InitFieldNoDefault( &m_polygonEditor, "PolygonEditor", "Polygon Editor" ); + m_polygonEditor = new RimPolygonInView; + m_polygonEditor->uiCapability()->setUiTreeHidden( true ); + m_polygonEditor.xmlCapability()->disableIO(); CAF_PDM_InitField( &m_enableFiltering, "EnableFiltering", false, "Enable Filter" ); CAF_PDM_InitField( &m_enableKFilter, "EnableKFilter", false, "Enable K Range Filter" ); CAF_PDM_InitFieldNoDefault( &m_kFilterStr, "KRangeFilter", "K Range Filter", "", "Example: 2,4-6,10-20:2", "" ); - CAF_PDM_InitField( &m_polygonPlaneDepth, "PolygonPlaneDepth", 0.0, "Polygon Plane Depth" ); - CAF_PDM_InitField( &m_lockPolygonToPlane, "LockPolygon", false, "Lock Polygon to Plane" ); - - m_polygonPlaneDepth.uiCapability()->setUiEditorTypeName( caf::PdmUiDoubleSliderEditor::uiEditorTypeName() ); - m_polygonPlaneDepth.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::TOP ); + CAF_PDM_InitField( &m_editPolygonButton, "EditPolygonButton", false, "Edit" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_editPolygonButton ); - setUi3dEditorTypeName( RicPolyline3dEditor::uiEditorTypeName() ); - uiCapability()->setUiTreeChildrenHidden( true ); + CAF_PDM_InitFieldNoDefault( &m_OBSOLETE_targets, "Targets", "Targets" ); + m_OBSOLETE_targets.uiCapability()->setUiTreeChildrenHidden( true ); + m_OBSOLETE_targets.uiCapability()->setUiTreeHidden( true ); + m_OBSOLETE_targets.uiCapability()->setUiHidden( true ); + m_OBSOLETE_targets.xmlCapability()->setIOWritable( false ); m_propagateToSubGrids = false; updateIconState(); setDeletable( true ); -} -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimPolygonFilter::~RimPolygonFilter() -{ -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::updateVisualization() -{ - updateCells(); - filterChanged.send(); + setUi3dEditorTypeName( RicPolyline3dEditor::uiEditorTypeName() ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::updateEditorsAndVisualization() +void RimPolygonFilter::enableFilter( bool bEnable ) { - updateConnectedEditors(); - updateVisualization(); + m_enableFiltering = bEnable; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::enableFilter( bool bEnable ) +void RimPolygonFilter::enableKFilter( bool bEnable ) { - m_enableFiltering = bEnable; + m_enableKFilter = bEnable; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::enableKFilter( bool bEnable ) +void RimPolygonFilter::setPolygon( RimPolygon* polygon ) { - m_enableKFilter = bEnable; + if ( polygon ) + { + m_polygonDataSource = PolygonDataSource::GLOBAL_POLYGON; + m_cellFilterPolygon = polygon; + } } //-------------------------------------------------------------------------------------------------- @@ -237,32 +194,23 @@ QString RimPolygonFilter::fullName() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RimPolygonFilter::activeTargets() const +void RimPolygonFilter::initAfterRead() { - return m_targets.childrenByType(); -} + RimCellFilter::initAfterRead(); -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::insertTarget( const RimPolylineTarget* targetToInsertBefore, RimPolylineTarget* targetToInsert ) -{ - size_t index = m_targets.indexOf( targetToInsertBefore ); - if ( index < m_targets.size() ) - m_targets.insert( index, targetToInsert ); - else - m_targets.push_back( targetToInsert ); + // Move existing polygons to global polygon + if ( !m_OBSOLETE_targets.empty() ) + { + std::vector points; + for ( const auto& target : m_OBSOLETE_targets ) + { + points.push_back( target->targetPointXYZ() ); + } - updateCells(); -} + m_internalPolygon->setPointsInDomainCoords( points ); + } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::deleteTarget( RimPolylineTarget* targetToDelete ) -{ - m_targets.removeChild( targetToDelete ); - delete targetToDelete; + configurePolygonEditor(); } //-------------------------------------------------------------------------------------------------- @@ -270,68 +218,17 @@ void RimPolygonFilter::deleteTarget( RimPolylineTarget* targetToDelete ) //-------------------------------------------------------------------------------------------------- void RimPolygonFilter::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) { - if ( field == &m_enablePicking ) + if ( auto attrib = dynamic_cast( attribute ) ) { - auto* pbAttribute = dynamic_cast( attribute ); - if ( pbAttribute ) - { - if ( !m_enablePicking ) - { - pbAttribute->m_buttonText = "Start Picking Points"; - } - else - { - pbAttribute->m_buttonText = "Stop Picking Points"; - } - } + attrib->pickEventHandler = m_pickTargetsEventHandler; + attrib->enablePicking = m_polygonEditor->pickingEnabled(); } - else if ( field == &m_targets ) - { - auto tvAttribute = dynamic_cast( attribute ); - if ( tvAttribute ) - { - tvAttribute->resizePolicy = caf::PdmUiTableViewEditorAttribute::RESIZE_TO_FIT_CONTENT; - if ( m_enablePicking ) - { - tvAttribute->baseColor.setRgb( 255, 220, 255 ); - tvAttribute->alwaysEnforceResizePolicy = true; - } - } - } - else if ( field == &m_lineThickness ) - { - auto myAttr = dynamic_cast( attribute ); - if ( myAttr ) - { - myAttr->validator = new ThicknessValidator(); - } - } - else if ( field == &m_lineThickness ) + if ( field == &m_editPolygonButton ) { - auto myAttr = dynamic_cast( attribute ); - if ( myAttr ) + if ( auto attrib = dynamic_cast( attribute ) ) { - myAttr->validator = new RadiusValidator(); - } - } - else if ( field == &m_polygonPlaneDepth ) - { - auto* attr = dynamic_cast( attribute ); - - if ( attr ) - { - if ( m_srcCase ) - { - auto bb = m_srcCase->allCellsBoundingBox(); - attr->m_minimum = -bb.max().z(); - attr->m_maximum = -bb.min().z(); - } - else - { - attr->m_minimum = 0; - attr->m_maximum = 10000; - } + attrib->m_buttonText = "Edit"; } } } @@ -339,14 +236,12 @@ void RimPolygonFilter::defineEditorAttribute( const caf::PdmFieldHandle* field, //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::defineCustomContextMenu( const caf::PdmFieldHandle* fieldNeedingMenu, QMenu* menu, QWidget* fieldEditorWidget ) +void RimPolygonFilter::childFieldChangedByUi( const caf::PdmFieldHandle* changedChildField ) { - caf::CmdFeatureMenuBuilder menuBuilder; - - menuBuilder << "RicDeletePolylineTargetFeature"; - menuBuilder << "RicAppendPointsToPolygonFilterFeature"; + // When interactive edit of polyline coordinates in enabled in RimPolygonInView::m_enablePicking, the editors to RimPolygonFilter must + // be updated to trigger calls to RimPolylinePickerInterface - menuBuilder.appendToMenu( menu ); + updateConnectedEditors(); } //-------------------------------------------------------------------------------------------------- @@ -358,32 +253,25 @@ void RimPolygonFilter::defineUiOrdering( QString uiConfigName, caf::PdmUiOrderin auto group = uiOrdering.addNewGroup( "General" ); group->add( &m_filterMode ); + group->add( &m_geometricalShape ); group->add( &m_enableFiltering ); - group->add( &m_showLines ); - group->add( &m_showSpheres ); + group->add( &m_polygonDataSource ); + if ( !isPolygonDefinedLocally() ) + { + group->add( &m_cellFilterPolygon ); + group->add( &m_editPolygonButton, { .newRow = false } ); + } auto group1 = uiOrdering.addNewGroup( "Polygon Selection" ); group1->add( &m_polyFilterMode ); - group1->add( &m_polyIncludeType ); - group1->add( &m_targets ); - group1->add( &m_enablePicking ); - - m_polyIncludeType.uiCapability()->setUiName( "Cells to " + modeString() ); - auto group2 = uiOrdering.addNewGroup( "Appearance" ); - if ( m_showLines ) - { - group2->add( &m_lineThickness ); - group2->add( &m_lineColor ); - } - if ( m_showSpheres ) + bool isPolygonClosed = m_cellFilterPolygon() ? m_cellFilterPolygon->isClosed() : false; + if ( isPolygonClosed ) { - group2->add( &m_sphereRadiusFactor ); - group2->add( &m_sphereColor ); + group1->add( &m_polyIncludeType ); } - group2->add( &m_lockPolygonToPlane ); - if ( m_lockPolygonToPlane ) group2->add( &m_polygonPlaneDepth ); - group2->setCollapsedByDefault(); + + m_polyIncludeType.uiCapability()->setUiName( "Cells to " + modeString() ); auto group3 = uiOrdering.addNewGroup( "Advanced Filter Settings" ); group3->add( &m_enableKFilter ); @@ -399,57 +287,94 @@ void RimPolygonFilter::defineUiOrdering( QString uiConfigName, caf::PdmUiOrderin { objField->uiCapability()->setUiReadOnly( readOnlyState ); } -} -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) -{ - if ( changedField == &m_enablePicking ) + if ( !isPolygonClosed ) { - updateConnectedEditors(); - - enableFilter( !m_enablePicking() ); - filterChanged.send(); + m_polyFilterMode = RimPolygonFilter::PolygonFilterModeType::INDEX_K; + m_polyFilterMode.uiCapability()->setUiReadOnly( true ); } - else if ( ( changedField == &m_showLines ) || ( changedField == &m_showSpheres ) || ( changedField == &m_sphereColor ) || - ( changedField == &m_sphereRadiusFactor ) || ( changedField == &m_lineThickness ) || ( changedField == &m_lineColor ) || - ( changedField == &m_lockPolygonToPlane ) || ( changedField == &m_polygonPlaneDepth ) ) + else { - filterChanged.send(); + m_polyFilterMode.uiCapability()->setUiReadOnly( readOnlyState ); } - else if ( changedField != &m_name ) + + if ( isPolygonDefinedLocally() ) { - updateCells(); - filterChanged.send(); - updateIconState(); + caf::PdmUiGroup* polyDefinitionGroup = uiOrdering.addNewGroup( "Polygon Definition" ); + m_polygonEditor()->uiOrderingForLocalPolygon( uiConfigName, *polyDefinitionGroup ); + + caf::PdmUiGroup* appearanceGroup = uiOrdering.addNewGroup( "Appearance" ); + appearanceGroup->setCollapsedByDefault(); + m_internalPolygon->uiOrderingForLocalPolygon( uiConfigName, *appearanceGroup ); } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimPolygonFilter::enablePicking( bool enable ) +QList RimPolygonFilter::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) { - m_enablePicking = enable; - updateConnectedEditors(); + QList options; + if ( fieldNeedingOptions == &m_cellFilterPolygon ) + { + RimTools::polygonOptionItems( &options ); + } + + return options; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimPolygonFilter::pickingEnabled() const +void RimPolygonFilter::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) { - return m_enablePicking(); + if ( changedField == &m_editPolygonButton ) + { + RimPolygonTools::activate3dEditOfPolygonInView( m_cellFilterPolygon(), this ); + + m_editPolygonButton = false; + + return; + } + + if ( changedField == &m_polygonDataSource ) + { + if ( !isPolygonDefinedLocally() ) + { + if ( m_cellFilterPolygon() == nullptr || m_cellFilterPolygon() == m_internalPolygon ) + { + auto polygonCollection = RimTools::polygonCollection(); + if ( polygonCollection && !polygonCollection->allPolygons().empty() ) + { + m_cellFilterPolygon = polygonCollection->allPolygons().front(); + } + } + } + configurePolygonEditor(); + updateAllRequiredEditors(); + } + + if ( changedField == &m_cellFilterPolygon ) + { + configurePolygonEditor(); + updateAllRequiredEditors(); + } + + if ( changedField != &m_name ) + { + updateCells(); + filterChanged.send(); + updateIconState(); + } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -caf::PickEventHandler* RimPolygonFilter::pickEventHandler() const +void RimPolygonFilter::enablePicking( bool enable ) { - return m_pickTargetsEventHandler.get(); + m_polygonEditor->enablePicking( enable ); + updateConnectedEditors(); } //-------------------------------------------------------------------------------------------------- @@ -527,6 +452,9 @@ bool RimPolygonFilter::cellInsidePolygon2D( cvf::Vec3d center, std::array& points, const RigGridBase* grid ) { // we should look in depth using Z coordinate @@ -568,15 +496,16 @@ void RimPolygonFilter::updateCellsKIndexEclipse( const std::vector& const int gIdx = static_cast( grid->gridIndex() ); std::list foundCells; + const bool closedPolygon = isPolygonClosed(); -#pragma omp parallel for // find all cells in the K layer that matches the polygon +#pragma omp parallel for for ( int i = 0; i < (int)grid->cellCountI(); i++ ) { for ( size_t j = 0; j < grid->cellCountJ(); j++ ) { - size_t cellIdx = grid->cellIndexFromIJK( i, j, K ); - RigCell cell = grid->cell( cellIdx ); + size_t cellIdx = grid->cellIndexFromIJK( i, j, K ); + const RigCell& cell = grid->cell( cellIdx ); // valid cell? if ( cell.isInvalid() ) continue; @@ -584,11 +513,23 @@ void RimPolygonFilter::updateCellsKIndexEclipse( const std::vector& std::array hexCorners; grid->cellCornerVertices( cellIdx, hexCorners.data() ); - // check if the polygon includes the cell - if ( cellInsidePolygon2D( cell.center(), hexCorners, points ) ) + if ( closedPolygon ) + { + // check if the polygon includes the cell + if ( cellInsidePolygon2D( cell.center(), hexCorners, points ) ) + { +#pragma omp critical + foundCells.push_back( cellIdx ); + } + } + else { + // check if the polyline touches the top face of the cell + if ( RigCellGeometryTools::polylineIntersectsCellNegK2D( points, hexCorners ) ) + { #pragma omp critical - foundCells.push_back( cellIdx ); + foundCells.push_back( cellIdx ); + } } } } @@ -606,7 +547,7 @@ void RimPolygonFilter::updateCellsKIndexEclipse( const std::vector& // get the cell index size_t newIdx = grid->cellIndexFromIJK( ci, cj, k ); // valid cell? - RigCell cell = grid->cell( newIdx ); + const RigCell& cell = grid->cell( newIdx ); if ( cell.isInvalid() ) continue; m_cells[gIdx].push_back( newIdx ); @@ -624,6 +565,8 @@ void RimPolygonFilter::updateCellsForEclipse( const std::vector& poi if ( m_polyFilterMode == PolygonFilterModeType::DEPTH_Z ) { + if ( !isPolygonClosed() ) return; + for ( size_t gridIndex = 0; gridIndex < data->gridCount(); gridIndex++ ) { auto grid = data->grid( gridIndex ); @@ -690,6 +633,8 @@ void RimPolygonFilter::updateCellsDepthGeoMech( const std::vector& p //-------------------------------------------------------------------------------------------------- void RimPolygonFilter::updateCellsKIndexGeoMech( const std::vector& points, const RigFemPartGrid* grid, int partId ) { + const bool closedPolygon = isPolygonClosed(); + // we need to find the K layer we hit with the first point size_t nk; // move the point a bit downwards to make sure it is inside something @@ -753,11 +698,23 @@ void RimPolygonFilter::updateCellsKIndexGeoMech( const std::vector& grid->cellCornerVertices( cellIdx, hexCorners.data() ); cvf::Vec3d center = grid->cellCentroid( cellIdx ); - // check if the polygon includes the cell - if ( cellInsidePolygon2D( center, hexCorners, points ) ) + if ( closedPolygon ) { + // check if the polygon includes the cell + if ( cellInsidePolygon2D( center, hexCorners, points ) ) + { #pragma omp critical - foundCells.push_back( cellIdx ); + foundCells.push_back( cellIdx ); + } + } + else + { + // check if the polyline touches the top face of the cell + if ( RigCellGeometryTools::polylineIntersectsCellNegK2D( points, hexCorners ) ) + { +#pragma omp critical + foundCells.push_back( cellIdx ); + } } } } @@ -795,7 +752,10 @@ void RimPolygonFilter::updateCellsForGeoMech( const std::vector& poi if ( m_polyFilterMode == PolygonFilterModeType::DEPTH_Z ) { - updateCellsDepthGeoMech( points, grid, i ); + if ( isPolygonClosed() ) + { + updateCellsDepthGeoMech( points, grid, i ); + } } else if ( m_polyFilterMode == PolygonFilterModeType::INDEX_K ) { @@ -818,16 +778,17 @@ void RimPolygonFilter::updateCells() // get polyline as vector std::vector points; - for ( auto& target : m_targets ) + + if ( m_polygonEditor && m_polygonEditor->polygon() ) { - if ( target->isEnabled() ) points.push_back( target->targetPointXYZ() ); + points = m_polygonEditor->polygon()->pointsInDomainCoords(); } - // We need at least three points to make a sensible polygon - if ( points.size() < 3 ) return; + // We need at least three points to make a closed polygon, or just 2 for a polyline + if ( ( !isPolygonClosed() && ( points.size() < 2 ) ) || ( isPolygonClosed() && ( points.size() < 3 ) ) ) return; - // make sure first and last point is the same (req. by polygon methods used later) - points.push_back( points.front() ); + // make sure first and last point is the same (req. by closed polygon methods used later) + if ( isPolygonClosed() ) points.push_back( points.front() ); RimEclipseCase* eCase = eclipseCase(); RimGeoMechCase* gCase = geoMechCase(); @@ -845,30 +806,120 @@ void RimPolygonFilter::updateCells() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -cvf::ref RimPolygonFilter::polyLinesData() const +void RimPolygonFilter::configurePolygonEditor() { - cvf::ref pld = new RigPolyLinesData; - std::vector line; - for ( const RimPolylineTarget* target : m_targets ) - { - if ( target->isEnabled() ) line.push_back( target->targetPointXYZ() ); - } - pld->setPolyLine( line ); + RimPolygon* polygon = nullptr; + if ( isPolygonDefinedLocally() ) + polygon = m_internalPolygon(); + else + polygon = m_cellFilterPolygon(); + + m_polygonEditor->setPolygon( polygon ); + + // Must connect the signals after polygon is assigned to the polygon editor + // When assigning an object to a ptr field, all signals are disconnected + connectObjectSignals( polygon ); +} - pld->setLineAppearance( m_lineThickness, m_lineColor, true ); - pld->setSphereAppearance( m_sphereRadiusFactor, m_sphereColor ); - pld->setZPlaneLock( m_lockPolygonToPlane, -m_polygonPlaneDepth ); +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonInView* RimPolygonFilter::polygonInView() const +{ + return m_polygonEditor(); +} - if ( isActive() ) +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::insertTarget( const RimPolylineTarget* targetToInsertBefore, RimPolylineTarget* targetToInsert ) +{ + m_polygonEditor->insertTarget( targetToInsertBefore, targetToInsert ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::deleteTarget( RimPolylineTarget* targetToDelete ) +{ + m_polygonEditor->deleteTarget( targetToDelete ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::updateEditorsAndVisualization() +{ + updateConnectedEditors(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::updateVisualization() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonFilter::activeTargets() const +{ + return m_polygonEditor->activeTargets(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonFilter::pickingEnabled() const +{ + return m_polygonEditor->pickingEnabled(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::PickEventHandler* RimPolygonFilter::pickEventHandler() const +{ + auto filterColl = firstAncestorOfType(); + if ( filterColl && !filterColl->isActive() ) return nullptr; + + if ( !isActive() ) return nullptr; + if ( !isPolygonDefinedLocally() && m_cellFilterPolygon && m_cellFilterPolygon()->isReadOnly() ) return nullptr; + + return m_pickTargetsEventHandler.get(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::AppEnum RimPolygonFilter::geometricalShape() const +{ + if ( isPolygonDefinedLocally() ) { - pld->setVisibility( m_showLines, m_showSpheres ); + if ( !m_internalPolygon->isClosed() ) return GeometricalShape::LINE; } else { - pld->setVisibility( false, false ); + if ( m_cellFilterPolygon && !m_cellFilterPolygon->isClosed() ) return GeometricalShape::LINE; } - return pld; + return GeometricalShape::AREA; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::setGeometricalShape( const caf::AppEnum& shape ) +{ + if ( isPolygonDefinedLocally() ) + { + m_internalPolygon->setIsClosed( shape == GeometricalShape::AREA ); + } + else if ( m_cellFilterPolygon() ) + { + m_cellFilterPolygon->setIsClosed( shape == GeometricalShape::AREA ); + } } //-------------------------------------------------------------------------------------------------- @@ -885,6 +936,53 @@ void RimPolygonFilter::initializeCellList() } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonFilter::isPolygonClosed() const +{ + if ( isPolygonDefinedLocally() ) return m_internalPolygon->isClosed(); + + if ( m_cellFilterPolygon() ) return m_cellFilterPolygon->isClosed(); + + return true; +} +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonFilter::isPolygonDefinedLocally() const +{ + return m_polygonDataSource() == PolygonDataSource::DEFINED_IN_FILTER; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::connectObjectSignals( RimPolygon* polygon ) +{ + if ( m_cellFilterPolygon() ) + { + m_cellFilterPolygon()->objectChanged.disconnect( this ); + } + + if ( polygon ) + { + m_cellFilterPolygon = polygon; + + polygon->objectChanged.connect( this, &RimPolygonFilter::onObjectChanged ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFilter::onObjectChanged( const caf::SignalEmitter* emitter ) +{ + updateCells(); + filterChanged.send(); + updateIconState(); +} + //-------------------------------------------------------------------------------------------------- /// Find which K layer we hit, in any of the grids, for any of the selected points //-------------------------------------------------------------------------------------------------- @@ -914,8 +1012,7 @@ int RimPolygonFilter::findEclipseKLayer( const std::vector& points, rayBBox.add( lowestPoint ); // Find the cells intersecting the ray - std::vector allCellIndices; - mainGrid->findIntersectingCells( rayBBox, &allCellIndices ); + std::vector allCellIndices = mainGrid->findIntersectingCells( rayBBox ); // Get the minimum K layer index int minK = std::numeric_limits::max(); diff --git a/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.h b/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.h index 4ff7ca0ec5..52e82a064f 100644 --- a/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.h +++ b/ApplicationLibCode/ProjectDataModel/CellFilters/RimPolygonFilter.h @@ -21,42 +21,42 @@ #include "RimCellFilter.h" #include "RimCellFilterIntervalTool.h" #include "RimPolylinePickerInterface.h" -#include "RimPolylinesDataInterface.h" #include "cafAppEnum.h" #include "cafPdmChildArrayField.h" -#include "cafPdmField.h" -#include "cafPdmFieldCvfColor.h" -#include "cafPdmFieldCvfVec3d.h" +#include "cafPdmChildField.h" #include "cafPdmObject.h" #include "cafPdmPtrField.h" -#include "cafPickEventHandler.h" -#include "cvfColor3.h" - -#include -#include - -class RicPolylineTargetsPickEventHandler; +class RimPolygon; class RimPolylineTarget; -class RimCase; -class RimEclipseCase; -class RimGeoMechCase; class RigGridBase; -class RigMainGrid; class RigFemPartGrid; -class RigPolylinesData; +class RimPolygonInView; class RigEclipseCaseData; +class RicPolylineTargetsPickEventHandler; //================================================================================================== /// /// //================================================================================================== -class RimPolygonFilter : public RimCellFilter, public RimPolylinePickerInterface, public RimPolylinesDataInterface +class RimPolygonFilter : public RimCellFilter, public RimPolylinePickerInterface { CAF_PDM_HEADER_INIT; public: + enum class PolygonDataSource + { + DEFINED_IN_FILTER, + GLOBAL_POLYGON + }; + + enum class GeometricalShape + { + AREA, + LINE + }; + enum class PolygonFilterModeType { DEPTH_Z, @@ -71,38 +71,32 @@ class RimPolygonFilter : public RimCellFilter, public RimPolylinePickerInterface }; RimPolygonFilter(); - ~RimPolygonFilter() override; void enableFilter( bool bEnable ); void enableKFilter( bool bEnable ); + void setPolygon( RimPolygon* polygon ); bool isFilterEnabled() const override; - void updateVisualization() override; - void updateEditorsAndVisualization() override; - void insertTarget( const RimPolylineTarget* targetToInsertBefore, RimPolylineTarget* targetToInsert ) override; - void deleteTarget( RimPolylineTarget* targetToDelete ) override; void enablePicking( bool enable ); - std::vector activeTargets() const override; - bool pickingEnabled() const override; - caf::PickEventHandler* pickEventHandler() const override; - void updateCellIndexFilter( cvf::UByteArray* includeVisibility, cvf::UByteArray* excludeVisibility, int gridIndex ) override; void onGridChanged() override; - cvf::ref polyLinesData() const override; + void configurePolygonEditor(); + RimPolygonInView* polygonInView() const; protected: void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; + QList calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) override; + void initAfterRead() override; + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + void childFieldChangedByUi( const caf::PdmFieldHandle* changedChildField ) override; QString fullName() const override; private: - void defineCustomContextMenu( const caf::PdmFieldHandle* fieldNeedingMenu, QMenu* menu, QWidget* fieldEditorWidget ) override; - void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; - void updateCells(); void updateCellsForEclipse( const std::vector& points, RimEclipseCase* eCase ); void updateCellsForGeoMech( const std::vector& points, RimGeoMechCase* gCase ); @@ -118,25 +112,45 @@ class RimPolygonFilter : public RimCellFilter, public RimPolylinePickerInterface void initializeCellList(); - caf::PdmField m_enablePicking; - caf::PdmChildArrayField m_targets; - caf::PdmField> m_polyFilterMode; - caf::PdmField> m_polyIncludeType; - caf::PdmField m_enableFiltering; - caf::PdmField m_showLines; - caf::PdmField m_showSpheres; - caf::PdmField m_lineThickness; - caf::PdmField m_sphereRadiusFactor; - caf::PdmField m_lineColor; - caf::PdmField m_sphereColor; - caf::PdmField m_polygonPlaneDepth; - caf::PdmField m_lockPolygonToPlane; - caf::PdmField m_enableKFilter; - caf::PdmField m_kFilterStr; + bool isPolygonClosed() const; + bool isPolygonDefinedLocally() const; - std::shared_ptr m_pickTargetsEventHandler; + void connectObjectSignals( RimPolygon* polygon ); + void onObjectChanged( const caf::SignalEmitter* emitter ); + + // RimPolylinePickerInterface used to forward events to m_polygonEditor + void insertTarget( const RimPolylineTarget* targetToInsertBefore, RimPolylineTarget* targetToInsert ) override; + void deleteTarget( RimPolylineTarget* targetToDelete ) override; + void updateEditorsAndVisualization() override; + void updateVisualization() override; + std::vector activeTargets() const override; + bool pickingEnabled() const override; + caf::PickEventHandler* pickEventHandler() const override; + + caf::AppEnum geometricalShape() const; + void setGeometricalShape( const caf::AppEnum& shape ); + +private: + caf::PdmField> m_polyFilterMode; + caf::PdmField> m_polyIncludeType; + caf::PdmField> m_polygonDataSource; + caf::PdmProxyValueField> m_geometricalShape; + + caf::PdmField m_enableFiltering; + caf::PdmField m_enableKFilter; + caf::PdmField m_kFilterStr; std::vector> m_cells; RimCellFilterIntervalTool m_intervalTool; + + // Local polygon and polygon editor + caf::PdmPtrField m_cellFilterPolygon; + caf::PdmChildField m_internalPolygon; + caf::PdmChildField m_polygonEditor; + caf::PdmField m_editPolygonButton; + + std::shared_ptr m_pickTargetsEventHandler; + + caf::PdmChildArrayField m_OBSOLETE_targets; }; diff --git a/ApplicationLibCode/ProjectDataModel/Completions/Rim3dWellLogCurveCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/Rim3dWellLogCurveCollection.cpp index b13d54323c..920664f8c8 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/Rim3dWellLogCurveCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/Rim3dWellLogCurveCollection.cpp @@ -42,7 +42,6 @@ Rim3dWellLogCurveCollection::Rim3dWellLogCurveCollection() CAF_PDM_InitField( &m_showGrid, "Show3dWellLogGrid", true, "Show Grid" ); CAF_PDM_InitField( &m_showBackground, "Show3dWellLogBackground", false, "Show Background" ); CAF_PDM_InitFieldNoDefault( &m_3dWellLogCurves, "ArrayOf3dWellLogCurves", "" ); - m_3dWellLogCurves.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimEnsembleFractureStatisticsCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimEnsembleFractureStatisticsCollection.cpp index 4682095520..747e75e967 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimEnsembleFractureStatisticsCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimEnsembleFractureStatisticsCollection.cpp @@ -30,7 +30,6 @@ RimEnsembleFractureStatisticsCollection::RimEnsembleFractureStatisticsCollection CAF_PDM_InitObject( "Ensemble Fracture Statistics", ":/FractureTemplates16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_fractureGroupStatistics, "FractureGroupStatistics", "" ); - m_fractureGroupStatistics.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimFishbones.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimFishbones.cpp index 085a6556be..2007363447 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimFishbones.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimFishbones.cpp @@ -109,7 +109,6 @@ RimFishbones::RimFishbones() CAF_PDM_InitFieldNoDefault( &m_valveLocations, "ValveLocations", "Valve Locations" ); m_valveLocations = new RimMultipleValveLocations(); m_valveLocations->findField( "RangeValveCount" )->uiCapability()->setUiName( "Number of Subs" ); - m_valveLocations.uiCapability()->setUiTreeHidden( true ); m_valveLocations.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_subsOrientationMode, @@ -123,7 +122,6 @@ RimFishbones::RimFishbones() CAF_PDM_InitField( &m_fixedInstallationRotationAngle, "FixedInstallationRotationAngle", 0.0, " Fixed Angle [deg]" ); CAF_PDM_InitFieldNoDefault( &m_pipeProperties, "PipeProperties", "Pipe Properties" ); - m_pipeProperties.uiCapability()->setUiTreeHidden( true ); m_pipeProperties.uiCapability()->setUiTreeChildrenHidden( true ); m_pipeProperties = new RimFishbonesPipeProperties; diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimFishbonesCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimFishbonesCollection.cpp index 0882d00464..790a00bf0c 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimFishbonesCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimFishbonesCollection.cpp @@ -46,7 +46,6 @@ RimFishbonesCollection::RimFishbonesCollection() setName( "Fishbones" ); CAF_PDM_InitFieldNoDefault( &m_fishbones, "FishbonesSubs", "fishbonesSubs" ); - m_fishbones.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_startMD, "StartMD", HUGE_VAL, "Start MD" ); CAF_PDM_InitField( &m_mainBoreDiameter, "MainBoreDiameter", 0.216, "Main Bore Diameter" ); diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimFracture.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimFracture.cpp index d1c7cb6227..bbc536d936 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimFracture.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimFracture.cpp @@ -203,14 +203,10 @@ void RimFracture::setStimPlanTimeIndexToPlot( int timeIndex ) //-------------------------------------------------------------------------------------------------- std::vector RimFracture::getPotentiallyFracturedCells( const RigMainGrid* mainGrid ) const { - std::vector cellindecies; - if ( !mainGrid ) return cellindecies; + if ( !mainGrid ) return {}; cvf::BoundingBox fractureBBox = boundingBoxInDomainCoords(); - - mainGrid->findIntersectingCells( fractureBBox, &cellindecies ); - - return cellindecies; + return mainGrid->findIntersectingCells( fractureBBox ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplate.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplate.cpp index b865fc627a..2083b5811e 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplate.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplate.cpp @@ -153,7 +153,6 @@ RimFractureTemplate::RimFractureTemplate() CAF_PDM_InitFieldNoDefault( &m_fractureContainment, "FractureContainmentField", "Fracture Containment" ); m_fractureContainment = new RimFractureContainment(); - m_fractureContainment.uiCapability()->setUiTreeHidden( true ); m_fractureContainment.uiCapability()->setUiTreeChildrenHidden( true ); // Non-Darcy Flow options @@ -211,9 +210,7 @@ RimFractureTemplate::RimFractureTemplate() "" ); CAF_PDM_InitField( &m_scaleApplyButton, "ScaleApplyButton", false, "Apply" ); - m_scaleApplyButton.xmlCapability()->disableIO(); - m_scaleApplyButton.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_scaleApplyButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_scaleApplyButton ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplateCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplateCollection.cpp index 61881ff479..70111e999a 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplateCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimFractureTemplateCollection.cpp @@ -49,7 +49,6 @@ RimFractureTemplateCollection::RimFractureTemplateCollection() "Default unit system for fracture templates" ); CAF_PDM_InitFieldNoDefault( &m_fractureDefinitions, "FractureDefinitions", "" ); - m_fractureDefinitions.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_nextValidFractureTemplateId, "NextValidFractureTemplateId", 0, "" ); m_nextValidFractureTemplateId.uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationCollection.cpp index b7952aae20..eb72cc800f 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationCollection.cpp @@ -49,11 +49,9 @@ RimPerforationCollection::RimPerforationCollection() setName( "Perforations" ); CAF_PDM_InitScriptableFieldNoDefault( &m_perforations, "Perforations", "Perforations" ); - m_perforations.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_nonDarcyParameters, "NonDarcyParameters", "Non-Darcy Parameters" ); m_nonDarcyParameters = new RimNonDarcyPerforationParameters(); - m_nonDarcyParameters.uiCapability()->setUiTreeHidden( true ); m_nonDarcyParameters.uiCapability()->setUiTreeChildrenHidden( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationInterval.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationInterval.cpp index ebc3efdaa3..b08a830bb3 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationInterval.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimPerforationInterval.cpp @@ -61,7 +61,6 @@ RimPerforationInterval::RimPerforationInterval() CAF_PDM_InitField( &m_endDate, "EndDate", QDateTime::currentDateTime(), "End Date" ); CAF_PDM_InitFieldNoDefault( &m_valves, "Valves", "Valves" ); - m_valves.uiCapability()->setUiTreeHidden( true ); nameField()->uiCapability()->setUiReadOnly( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimSimWellFractureCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimSimWellFractureCollection.cpp index e59d2ec2a4..627f50bfc8 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimSimWellFractureCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimSimWellFractureCollection.cpp @@ -31,7 +31,6 @@ RimSimWellFractureCollection::RimSimWellFractureCollection() CAF_PDM_InitObject( "Fractures", ":/FractureLayout16x16.png" ); CAF_PDM_InitFieldNoDefault( &simwellFractures, "Fractures", "" ); - simwellFractures.uiCapability()->setUiTreeHidden( true ); setDeletable( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplate.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplate.cpp index 22bb749ade..c765cff764 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplate.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplate.cpp @@ -51,7 +51,6 @@ RimValveTemplate::RimValveTemplate() CAF_PDM_InitFieldNoDefault( &m_aicdParameters, "AICDParameters", "AICD Parameters" ); m_aicdParameters = new RimWellPathAicdParameters; - m_aicdParameters.uiCapability()->setUiTreeHidden( true ); m_aicdParameters.uiCapability()->setUiTreeChildrenHidden( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplateCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplateCollection.cpp index 144863bbd0..226244cc63 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplateCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimValveTemplateCollection.cpp @@ -32,7 +32,6 @@ RimValveTemplateCollection::RimValveTemplateCollection() CAF_PDM_InitFieldNoDefault( &m_valveDefinitions, "ValveDefinitions", "" ); CAF_PDM_InitFieldNoDefault( &m_defaultUnitsForValveTemplates, "ValveUnits", "Default unit system for valve templates" ); m_defaultUnitsForValveTemplates = RiaDefines::EclipseUnitSystem::UNITS_METRIC; - m_valveDefinitions.uiCapability()->setUiTreeHidden( true ); addDefaultValveTemplates(); } diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletionSettings.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletionSettings.cpp index 29a73cd208..38e292d358 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletionSettings.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletionSettings.cpp @@ -27,7 +27,6 @@ #include "cafPdmFieldScriptingCapability.h" #include "cafPdmObjectScriptingCapability.h" #include "cafPdmUiLineEditor.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeOrdering.h" namespace caf @@ -98,7 +97,6 @@ RimWellPathCompletionSettings::RimWellPathCompletionSettings() CAF_PDM_InitFieldNoDefault( &m_mswParameters, "MswParameters", "Multi Segment Well Parameters" ); m_mswParameters = new RimMswCompletionParameters; - m_mswParameters.uiCapability()->setUiTreeHidden( true ); m_mswParameters.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitScriptableFieldNoDefault( &m_mswLinerDiameter, "MswLinerDiameter", "MSW Liner Diameter" ); diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletions.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletions.cpp index 27b6b5e0b4..d0adb6a1eb 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletions.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathCompletions.cpp @@ -55,19 +55,15 @@ RimWellPathCompletions::RimWellPathCompletions() CAF_PDM_InitScriptableFieldNoDefault( &m_perforationCollection, "Perforations", "Perforations" ); m_perforationCollection = new RimPerforationCollection; - m_perforationCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_fishbonesCollection, "Fishbones", "Fishbones" ); m_fishbonesCollection = new RimFishbonesCollection; - m_fishbonesCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_fractureCollection, "Fractures", "Fractures" ); m_fractureCollection = new RimWellPathFractureCollection; - m_fractureCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_stimPlanModelCollection, "StimPlanModels", "StimPlan Models" ); m_stimPlanModelCollection = new RimStimPlanModelCollection; - m_stimPlanModelCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_wellNameForExport_OBSOLETE, "WellNameForExport", QString(), "Well Name" ); m_wellNameForExport_OBSOLETE.xmlCapability()->setIOWritable( false ); diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathFractureCollection.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathFractureCollection.cpp index 642eacd2d7..0a006e22d6 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathFractureCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathFractureCollection.cpp @@ -33,7 +33,6 @@ RimWellPathFractureCollection::RimWellPathFractureCollection() CAF_PDM_InitObject( "Fractures", ":/FractureLayout16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_fractures, "Fractures", "" ); - m_fractures.uiCapability()->setUiTreeHidden( true ); setName( "Fractures" ); nameField()->uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathValve.cpp b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathValve.cpp index f209c73400..9e8af72834 100644 --- a/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathValve.cpp +++ b/ApplicationLibCode/ProjectDataModel/Completions/RimWellPathValve.cpp @@ -54,7 +54,6 @@ RimWellPathValve::RimWellPathValve() m_measuredDepth.uiCapability()->setUiEditorTypeName( caf::PdmUiDoubleSliderEditor::uiEditorTypeName() ); m_multipleValveLocations = new RimMultipleValveLocations; - m_multipleValveLocations.uiCapability()->setUiTreeHidden( true ); m_multipleValveLocations.uiCapability()->setUiTreeChildrenHidden( true ); m_editValveTemplate.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); m_editValveTemplate.uiCapability()->setUiEditorTypeName( caf::PdmUiToolButtonEditor::uiEditorTypeName() ); diff --git a/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimAbstractCorrelationPlot.cpp b/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimAbstractCorrelationPlot.cpp index 1a3013eb7a..fbea61f87b 100644 --- a/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimAbstractCorrelationPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimAbstractCorrelationPlot.cpp @@ -64,11 +64,9 @@ RimAbstractCorrelationPlot::RimAbstractCorrelationPlot() CAF_PDM_InitFieldNoDefault( &m_dataSources, "AnalysisPlotData", "" ); m_dataSources.uiCapability()->setUiTreeChildrenHidden( true ); - m_dataSources.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_pushButtonSelectSummaryAddress, "SelectAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_pushButtonSelectSummaryAddress ); - m_pushButtonSelectSummaryAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonSelectSummaryAddress ); m_pushButtonSelectSummaryAddress = false; CAF_PDM_InitFieldNoDefault( &m_timeStepFilter, "TimeStepFilter", "Available Time Steps" ); diff --git a/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationPlotCollection.cpp index 29621f76d9..6408faac80 100644 --- a/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationPlotCollection.cpp @@ -38,9 +38,6 @@ RimCorrelationPlotCollection::RimCorrelationPlotCollection() CAF_PDM_InitFieldNoDefault( &m_correlationPlots, "CorrelationPlots", "Correlation Plots" ); CAF_PDM_InitFieldNoDefault( &m_correlationReports, "CorrelationReports", "Correlation Reports" ); - - m_correlationPlots.uiCapability()->setUiTreeHidden( true ); - m_correlationReports.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationReportPlot.cpp b/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationReportPlot.cpp index b36cd65c62..e75eb7d66d 100644 --- a/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationReportPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/CorrelationPlots/RimCorrelationReportPlot.cpp @@ -33,7 +33,6 @@ #include "RiuQwtPlotWidget.h" #include "cafAssert.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeOrdering.h" #include diff --git a/ApplicationLibCode/ProjectDataModel/Faults/CMakeLists_files.cmake b/ApplicationLibCode/ProjectDataModel/Faults/CMakeLists_files.cmake index c904cfb827..58d388a898 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/CMakeLists_files.cmake +++ b/ApplicationLibCode/ProjectDataModel/Faults/CMakeLists_files.cmake @@ -11,6 +11,9 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorTemperature.h ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorGeoMech.h ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorStress.h + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorStressGeoMech.h + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorStressEclipse.h + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorWellLogExtraction.h ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationEnums.h ) @@ -27,6 +30,10 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorTemperature.cpp ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorGeoMech.cpp ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorStress.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorStressGeoMech.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorStressEclipse.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationDataAccessorWellLogExtraction.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimFaultReactivationEnums.cpp ) list(APPEND CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultInViewCollection.cpp index 0581e2e001..2f082dcf16 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultInViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultInViewCollection.cpp @@ -98,7 +98,6 @@ RimFaultInViewCollection::RimFaultInViewCollection() caf::PdmUiNativeCheckBoxEditor::configureFieldForEditor( &m_hideNNCsWhenNoResultIsAvailable ); CAF_PDM_InitFieldNoDefault( &m_faults, "Faults", "Faults" ); - m_faults.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_showFaultsOutsideFilters_obsolete, "ShowFaultsOutsideFilters", true, "Show Faults Outside Filters" ); m_showFaultsOutsideFilters_obsolete.xmlCapability()->setIOWritable( false ); diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.cpp index 20b961580f..46bdb8f00e 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.cpp @@ -35,23 +35,38 @@ #include "RimFaultReactivationDataAccessor.h" #include "RimFaultReactivationDataAccessorGeoMech.h" #include "RimFaultReactivationDataAccessorPorePressure.h" -#include "RimFaultReactivationDataAccessorStress.h" +#include "RimFaultReactivationDataAccessorStressEclipse.h" +#include "RimFaultReactivationDataAccessorStressGeoMech.h" #include "RimFaultReactivationDataAccessorTemperature.h" #include "RimFaultReactivationDataAccessorVoidRatio.h" #include "RimFaultReactivationEnums.h" +#include "RimFaultReactivationModel.h" +#include //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimFaultReactivationDataAccess::RimFaultReactivationDataAccess( RimEclipseCase* thecase, - RimGeoMechCase* geoMechCase, - const std::vector& timeSteps ) +RimFaultReactivationDataAccess::RimFaultReactivationDataAccess( const RimFaultReactivationModel& model, + RimEclipseCase* eCase, + RimGeoMechCase* geoMechCase, + const std::vector& timeSteps, + RimFaultReactivation::StressSource stressSource ) : m_timeSteps( timeSteps ) { - // TODO: correct default pore pressure gradient? - m_accessors.push_back( std::make_shared( thecase, 1.0 ) ); - m_accessors.push_back( std::make_shared( thecase, 0.0001 ) ); - m_accessors.push_back( std::make_shared( thecase ) ); + double porePressureGradient = 1.0; + double topTemperature = model.seabedTemperature(); + double seabedDepth = -model.seaBedDepth(); + m_accessors.push_back( std::make_shared( eCase, porePressureGradient, seabedDepth ) ); + m_accessors.push_back( std::make_shared( eCase, 0.0001 ) ); + m_accessors.push_back( std::make_shared( eCase, topTemperature, seabedDepth ) ); + + std::vector stressProperties = { RimFaultReactivation::Property::StressTop, + RimFaultReactivation::Property::DepthTop, + RimFaultReactivation::Property::StressBottom, + RimFaultReactivation::Property::DepthBottom, + RimFaultReactivation::Property::LateralStressComponentX, + RimFaultReactivation::Property::LateralStressComponentY }; + if ( geoMechCase ) { std::vector properties = { RimFaultReactivation::Property::YoungsModulus, @@ -62,16 +77,43 @@ RimFaultReactivationDataAccess::RimFaultReactivationDataAccess( RimEclipseCase* { m_accessors.push_back( std::make_shared( geoMechCase, property ) ); } + } - std::vector stressProperties = { RimFaultReactivation::Property::StressTop, - RimFaultReactivation::Property::DepthTop, - RimFaultReactivation::Property::StressBottom, - RimFaultReactivation::Property::DepthBottom, - RimFaultReactivation::Property::LateralStressComponentX, - RimFaultReactivation::Property::LateralStressComponentY }; + if ( ( stressSource == RimFaultReactivation::StressSource::StressFromGeoMech ) && ( geoMechCase ) ) + { for ( auto property : stressProperties ) { - m_accessors.push_back( std::make_shared( geoMechCase, property ) ); + m_accessors.push_back( + std::make_shared( geoMechCase, property, porePressureGradient, seabedDepth ) ); + } + } + else + { + auto extractDensities = []( const RimFaultReactivationModel& model ) + { + std::map densities; + std::vector elementSets = { RimFaultReactivation::ElementSets::OverBurden, + RimFaultReactivation::ElementSets::UnderBurden, + RimFaultReactivation::ElementSets::Reservoir, + RimFaultReactivation::ElementSets::IntraReservoir, + RimFaultReactivation::ElementSets::FaultZone }; + for ( auto e : elementSets ) + { + densities[e] = model.materialParameters( e )[2]; + } + return densities; + }; + + std::map densities = extractDensities( model ); + for ( auto property : stressProperties ) + { + m_accessors.push_back( std::make_shared( eCase, + property, + porePressureGradient, + seabedDepth, + model.waterDensity(), + model.lateralStressCoefficient(), + densities ) ); } } } @@ -126,39 +168,52 @@ std::vector RimFaultReactivationDataAccess::extractModelData( const RigF }; std::shared_ptr accessor = getAccessor( property ); + if ( accessor ) { - accessor->setTimeStep( timeStep ); + accessor->setModelAndTimeStep( model, timeStep ); auto grid = model.grid( gridPart ); - std::vector values; + const std::map>& borderSurfaceElements = grid->borderSurfaceElements(); + auto it = borderSurfaceElements.find( RimFaultReactivation::BorderSurface::Seabed ); + CAF_ASSERT( it != borderSurfaceElements.end() && "Sea bed border surface does not exist" ); + std::set seabedElements( it->second.begin(), it->second.end() ); if ( nodeProperties.contains( property ) ) { - for ( auto& node : grid->globalNodes() ) + int numNodes = static_cast( grid->dataNodes().size() ); + std::vector values( numNodes, std::numeric_limits::infinity() ); + + for ( int nodeIndex = 0; nodeIndex < numNodes; nodeIndex++ ) { - double value = accessor->valueAtPosition( node ); - values.push_back( value ); + double value = accessor->valueAtPosition( grid->dataNodes()[nodeIndex], model, gridPart ); + values[nodeIndex] = value; } + return values; } else { - size_t numElements = grid->elementIndices().size(); - for ( size_t elementIndex = 0; elementIndex < numElements; elementIndex++ ) + int numElements = static_cast( grid->elementIndices().size() ); + std::vector values( numElements, std::numeric_limits::infinity() ); + + for ( int elementIndex = 0; elementIndex < numElements; elementIndex++ ) { - std::vector corners = grid->elementCorners( elementIndex ); + std::vector corners = grid->elementDataCorners( elementIndex ); + + // Move top of sea bed element down to end up inside top element + bool isTopElement = seabedElements.contains( static_cast( elementIndex ) ); + double topDepthAdjust = isTopElement ? 0.1 : 0.0; - double topDepth = computeAverageDepth( corners, { 0, 1, 2, 3 } ); + double topDepth = computeAverageDepth( corners, { 0, 1, 2, 3 } ) - topDepthAdjust; double bottomDepth = computeAverageDepth( corners, { 4, 5, 6, 7 } ); - cvf::Vec3d position = RigCaseToCaseCellMapperTools::calculateCellCenter( corners.data() ); - double value = accessor->valueAtPosition( position, topDepth, bottomDepth ); - values.push_back( value ); + cvf::Vec3d position = RigCaseToCaseCellMapperTools::calculateCellCenter( corners.data() ); + double value = accessor->valueAtPosition( position, model, gridPart, topDepth, bottomDepth, elementIndex ); + values[elementIndex] = value; } + return values; } - - return values; } return {}; @@ -206,24 +261,3 @@ std::shared_ptr RimFaultReactivationDataAccess return nullptr; } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationDataAccess::elementHasValidData( std::vector elementCorners ) const -{ - auto accessor = getAccessor( RimFaultReactivation::Property::PorePressure ); - if ( !accessor ) return false; - - accessor->setTimeStep( 0 ); - - int nValid = 0; - - for ( auto& p : elementCorners ) - { - if ( accessor->hasValidDataAtPosition( p ) ) nValid++; - } - - // if more than half of the nodes have valid data, we're ok - return nValid > 4; -} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.h index 0410ade5a6..1b10f3ed51 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccess.h @@ -32,6 +32,7 @@ class RimEclipseCase; class RimGeoMechCase; class RimFaultReactivationDataAccessor; class RigFaultReactivationModel; +class RimFaultReactivationModel; //================================================================================================== /// @@ -40,7 +41,11 @@ class RigFaultReactivationModel; class RimFaultReactivationDataAccess { public: - RimFaultReactivationDataAccess( RimEclipseCase* eclipseCase, RimGeoMechCase* geoMechCase, const std::vector& timeSteps ); + RimFaultReactivationDataAccess( const RimFaultReactivationModel& model, + RimEclipseCase* eclipseCase, + RimGeoMechCase* geoMechCase, + const std::vector& timeSteps, + RimFaultReactivation::StressSource stressSource ); ~RimFaultReactivationDataAccess(); void extractModelData( const RigFaultReactivationModel& model ); @@ -50,8 +55,6 @@ class RimFaultReactivationDataAccess std::vector propertyValues( RimFaultReactivation::GridPart gridPart, RimFaultReactivation::Property property, size_t outputTimeStep ) const; - bool elementHasValidData( std::vector elementCorners ) const; - private: std::shared_ptr getAccessor( RimFaultReactivation::Property property ) const; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.cpp index c12f04b509..d708bd590d 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.cpp @@ -18,8 +18,10 @@ #include "RimFaultReactivationDataAccessor.h" +#include "RigFaultReactivationModel.h" #include "RigMainGrid.h" +#include "RimFaultReactivationEnums.h" #include "cafAssert.h" //-------------------------------------------------------------------------------------------------- @@ -28,6 +30,7 @@ RimFaultReactivationDataAccessor::RimFaultReactivationDataAccessor() { m_timeStep = -1; + m_model = nullptr; } //-------------------------------------------------------------------------------------------------- @@ -40,8 +43,27 @@ RimFaultReactivationDataAccessor::~RimFaultReactivationDataAccessor() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimFaultReactivationDataAccessor::setTimeStep( size_t timeStep ) +void RimFaultReactivationDataAccessor::setModelAndTimeStep( const RigFaultReactivationModel& model, size_t timeStep ) { + m_model = &model; m_timeStep = timeStep; updateResultAccessor(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessor::findElementSetForElementIndex( + const std::map>& elementSets, + int elementIndex ) +{ + for ( auto [s, indexes] : elementSets ) + { + if ( std::find( indexes.begin(), indexes.end(), elementIndex ) != indexes.end() ) + { + return std::pair( true, s ); + } + } + + return std::pair( false, RimFaultReactivation::ElementSets::OverBurden ); +} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.h index 2a125fb1b8..f01859bead 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessor.h @@ -24,8 +24,10 @@ #include #include +#include class RigMainGrid; +class RigFaultReactivationModel; //================================================================================================== /// @@ -37,18 +39,24 @@ class RimFaultReactivationDataAccessor RimFaultReactivationDataAccessor(); ~RimFaultReactivationDataAccessor(); - virtual void setTimeStep( size_t timeStep ); + virtual void setModelAndTimeStep( const RigFaultReactivationModel& model, size_t timeStep ); virtual bool isMatching( RimFaultReactivation::Property property ) const = 0; - virtual double valueAtPosition( const cvf::Vec3d& position, - double topDepth = std::numeric_limits::infinity(), - double bottomDepth = std::numeric_limits::infinity() ) const = 0; - - virtual bool hasValidDataAtPosition( const cvf::Vec3d& position ) const = 0; + virtual double valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth = std::numeric_limits::infinity(), + double bottomDepth = std::numeric_limits::infinity(), + size_t elementIndex = std::numeric_limits::max() ) const = 0; protected: virtual void updateResultAccessor() = 0; - size_t m_timeStep; + static std::pair + findElementSetForElementIndex( const std::map>& elementSets, + int elementIndex ); + + const RigFaultReactivationModel* m_model; + size_t m_timeStep; }; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.cpp index 5465fd67db..801a105866 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.cpp @@ -61,18 +61,14 @@ void RimFaultReactivationDataAccessorGeoMech::updateResultAccessor() { const int partIndex = 0; - auto loadFrameLambda = [&]( auto femParts, RigFemResultAddress addr ) -> RigFemScalarResultFrames* + auto loadFrameLambda = [&]( auto femParts, RigFemResultAddress addr ) -> std::vector { auto result = femParts->findOrLoadScalarResult( partIndex, addr ); - if ( result->frameData( 0, 0 ).empty() ) - { - return nullptr; - } - return result; + return result->frameData( 0, 0 ); }; - auto femParts = m_geoMechCaseData->femPartResults(); - m_resultFrames = loadFrameLambda( femParts, getResultAddress( m_property ) ); + auto femParts = m_geoMechCaseData->femPartResults(); + m_data = loadFrameLambda( femParts, getResultAddress( m_property ) ); } //-------------------------------------------------------------------------------------------------- @@ -97,36 +93,27 @@ bool RimFaultReactivationDataAccessorGeoMech::isMatching( RimFaultReactivation:: //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorGeoMech::valueAtPosition( const cvf::Vec3d& position, double topDepth, double bottomDepth ) const - +double RimFaultReactivationDataAccessorGeoMech::valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth, + double bottomDepth, + size_t elementIndex ) const { - if ( !m_resultFrames ) return std::numeric_limits::infinity(); + if ( !m_data.empty() ) return std::numeric_limits::infinity(); RimWellIADataAccess iaDataAccess( m_geoMechCase ); int elementIdx = iaDataAccess.elementIndex( position ); if ( elementIdx != -1 ) { - int timeStepIndex = 0; - int frameIndex = 0; - - const std::vector& data = m_resultFrames->frameData( timeStepIndex, frameIndex ); - if ( elementIdx >= static_cast( data.size() ) ) return std::numeric_limits::infinity(); + if ( elementIdx >= static_cast( m_data.size() ) ) return std::numeric_limits::infinity(); if ( m_property == RimFaultReactivation::Property::YoungsModulus ) { - return RiaEclipseUnitTools::gigaPascalToPascal( data[elementIdx] ); + return RiaEclipseUnitTools::gigaPascalToPascal( m_data[elementIdx] ); } - return data[elementIdx]; + return m_data[elementIdx]; } return std::numeric_limits::infinity(); } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationDataAccessorGeoMech::hasValidDataAtPosition( const cvf::Vec3d& position ) const -{ - double value = valueAtPosition( position ); - return !std::isinf( value ); -} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.h index 99efa722f2..5041db2467 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorGeoMech.h @@ -40,11 +40,12 @@ class RimFaultReactivationDataAccessorGeoMech : public RimFaultReactivationDataA bool isMatching( RimFaultReactivation::Property property ) const override; - double valueAtPosition( const cvf::Vec3d& position, - double topDepth = std::numeric_limits::infinity(), - double bottomDepth = std::numeric_limits::infinity() ) const override; - - bool hasValidDataAtPosition( const cvf::Vec3d& position ) const override; + double valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth = std::numeric_limits::infinity(), + double bottomDepth = std::numeric_limits::infinity(), + size_t elementIndex = std::numeric_limits::max() ) const override; private: void updateResultAccessor() override; @@ -54,5 +55,5 @@ class RimFaultReactivationDataAccessorGeoMech : public RimFaultReactivationDataA RimGeoMechCase* m_geoMechCase; RimFaultReactivation::Property m_property; RigGeoMechCaseData* m_geoMechCaseData; - RigFemScalarResultFrames* m_resultFrames; + std::vector m_data; }; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.cpp index 67a137a8ce..c63b8c9607 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.cpp @@ -17,29 +17,36 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RimFaultReactivationDataAccessorPorePressure.h" +#include "RimEclipseCase.h" #include "RimFaciesProperties.h" +#include "RimFaultReactivationDataAccessorWellLogExtraction.h" #include "RimFaultReactivationEnums.h" #include "RiaDefines.h" +#include "RiaEclipseUnitTools.h" #include "RiaPorosityModel.h" #include "RigCaseCellResultsData.h" #include "RigEclipseCaseData.h" #include "RigEclipseResultAddress.h" +#include "RigEclipseWellLogExtractor.h" +#include "RigFaultReactivationModel.h" #include "RigMainGrid.h" #include "RigResultAccessorFactory.h" - -#include "RimEclipseCase.h" +#include "RigWellPath.h" #include +#include //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- RimFaultReactivationDataAccessorPorePressure::RimFaultReactivationDataAccessorPorePressure( RimEclipseCase* eclipseCase, - double porePressureGradient ) + double porePressureGradient, + double seabedDepth ) : m_eclipseCase( eclipseCase ) , m_defaultPorePressureGradient( porePressureGradient ) + , m_seabedDepth( seabedDepth ) , m_caseData( nullptr ) , m_mainGrid( nullptr ) { @@ -62,17 +69,18 @@ RimFaultReactivationDataAccessorPorePressure::~RimFaultReactivationDataAccessorP //-------------------------------------------------------------------------------------------------- void RimFaultReactivationDataAccessorPorePressure::updateResultAccessor() { - if ( m_caseData ) - { - RigEclipseResultAddress resVarAddress( RiaDefines::ResultCatType::DYNAMIC_NATIVE, "PRESSURE" ); - m_eclipseCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->ensureKnownResultLoaded( resVarAddress ); - - m_resultAccessor = RigResultAccessorFactory::createFromResultAddress( m_caseData, - 0, - RiaDefines::PorosityModelType::MATRIX_MODEL, - m_timeStep, - resVarAddress ); - } + if ( !m_caseData ) return; + + RigEclipseResultAddress resVarAddress( RiaDefines::ResultCatType::DYNAMIC_NATIVE, "PRESSURE" ); + m_eclipseCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->ensureKnownResultLoaded( resVarAddress ); + + m_resultAccessor = + RigResultAccessorFactory::createFromResultAddress( m_caseData, 0, RiaDefines::PorosityModelType::MATRIX_MODEL, m_timeStep, resVarAddress ); + + auto [wellPaths, extractors] = + RimFaultReactivationDataAccessorWellLogExtraction::createEclipseWellPathExtractors( *m_model, *m_caseData, m_seabedDepth ); + m_wellPaths = wellPaths; + m_extractors = extractors; } //-------------------------------------------------------------------------------------------------- @@ -86,40 +94,42 @@ bool RimFaultReactivationDataAccessorPorePressure::isMatching( RimFaultReactivat //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorPorePressure::valueAtPosition( const cvf::Vec3d& position, double topDepth, double bottomDepth ) const +double RimFaultReactivationDataAccessorPorePressure::valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth, + double bottomDepth, + size_t elementIndex ) const { if ( ( m_mainGrid != nullptr ) && m_resultAccessor.notNull() ) { + CAF_ASSERT( m_extractors.find( gridPart ) != m_extractors.end() ); + auto extractor = m_extractors.find( gridPart )->second; + + CAF_ASSERT( m_wellPaths.find( gridPart ) != m_wellPaths.end() ); + auto wellPath = m_wellPaths.find( gridPart )->second; + auto cellIdx = m_mainGrid->findReservoirCellIndexFromPoint( position ); if ( cellIdx != cvf::UNDEFINED_SIZE_T ) { - double value = m_resultAccessor->cellScalar( cellIdx ); - if ( !std::isinf( value ) ) - { - return 100000.0 * value; // return in pascal, not bar - } + double valueFromEclipse = m_resultAccessor->cellScalar( cellIdx ); + if ( !std::isinf( valueFromEclipse ) ) return RiaEclipseUnitTools::barToPascal( valueFromEclipse ); } - } - return calculatePorePressure( std::abs( position.z() ), m_defaultPorePressureGradient ); -} + auto [values, intersections] = + RimFaultReactivationDataAccessorWellLogExtraction::extractValuesAndIntersections( *m_resultAccessor.p(), *extractor.p(), *wellPath ); -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorPorePressure::calculatePorePressure( double depth, double gradient ) -{ - return gradient * 9.81 * depth * 1000.0; -} + RimFaultReactivation::ElementSets elementSet = RimFaultReactivation::ElementSets::UnderBurden; + auto [value, pos] = RimFaultReactivationDataAccessorWellLogExtraction::calculatePorBar( model, + gridPart, + intersections, + values, + position, + elementSet, + m_defaultPorePressureGradient ); -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationDataAccessorPorePressure::hasValidDataAtPosition( const cvf::Vec3d& position ) const -{ - auto cellIdx = m_mainGrid->findReservoirCellIndexFromPoint( position ); - if ( cellIdx == cvf::UNDEFINED_SIZE_T ) return false; + return RiaEclipseUnitTools::barToPascal( value ); + } - double value = m_resultAccessor->cellScalar( cellIdx ); - return !std::isinf( value ); + return std::numeric_limits::infinity(); } diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.h index bd80a0e34d..e8e759bbe7 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorPorePressure.h @@ -18,16 +18,17 @@ #pragma once +#include "RimFaultReactivationDataAccessor.h" + #include "cvfObject.h" #include "cvfVector3.h" -#include "RimFaultReactivationDataAccessor.h" -#include "RimFaultReactivationEnums.h" - class RimEclipseCase; class RigEclipseCaseData; class RigMainGrid; class RigResultAccessor; +class RigEclipseWellLogExtractor; +class RigWellPath; //================================================================================================== /// @@ -36,16 +37,17 @@ class RigResultAccessor; class RimFaultReactivationDataAccessorPorePressure : public RimFaultReactivationDataAccessor { public: - RimFaultReactivationDataAccessorPorePressure( RimEclipseCase* eclipseCase, double porePressureGradient ); + RimFaultReactivationDataAccessorPorePressure( RimEclipseCase* eclipseCase, double porePressureGradient, double seabedDepth ); ~RimFaultReactivationDataAccessorPorePressure(); bool isMatching( RimFaultReactivation::Property property ) const override; - double valueAtPosition( const cvf::Vec3d& position, - double topDepth = std::numeric_limits::infinity(), - double bottomDepth = std::numeric_limits::infinity() ) const override; - - bool hasValidDataAtPosition( const cvf::Vec3d& position ) const override; + double valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth = std::numeric_limits::infinity(), + double bottomDepth = std::numeric_limits::infinity(), + size_t elementIndex = std::numeric_limits::max() ) const override; private: void updateResultAccessor() override; @@ -56,5 +58,9 @@ class RimFaultReactivationDataAccessorPorePressure : public RimFaultReactivation RigEclipseCaseData* m_caseData; const RigMainGrid* m_mainGrid; double m_defaultPorePressureGradient; + double m_seabedDepth; cvf::ref m_resultAccessor; + + std::map> m_wellPaths; + std::map> m_extractors; }; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.cpp index c6596816e5..4a899e1357 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.cpp @@ -19,31 +19,39 @@ #include "RimFaultReactivationDataAccessorStress.h" #include "RiaEclipseUnitTools.h" +#include "RiaLogging.h" +#include "RigFaultReactivationModel.h" #include "RigFemAddressDefines.h" #include "RigFemPartCollection.h" #include "RigFemPartResultsCollection.h" #include "RigFemResultAddress.h" #include "RigFemScalarResultFrames.h" #include "RigGeoMechCaseData.h" -#include "RigResultAccessorFactory.h" +#include "RigGeoMechWellLogExtractor.h" +#include "RigGriddedPart3d.h" +#include "RigWellPath.h" +#include "RimFaultReactivationDataAccessorWellLogExtraction.h" #include "RimFaultReactivationEnums.h" #include "RimGeoMechCase.h" #include "RimWellIADataAccess.h" +#include "cvfVector3.h" + #include #include //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimFaultReactivationDataAccessorStress::RimFaultReactivationDataAccessorStress( RimGeoMechCase* geoMechCase, - RimFaultReactivation::Property property ) - : m_geoMechCase( geoMechCase ) - , m_property( property ) +RimFaultReactivationDataAccessorStress::RimFaultReactivationDataAccessorStress( RimFaultReactivation::Property property, + double gradient, + double seabedDepth ) + : m_property( property ) + , m_gradient( gradient ) + , m_seabedDepth( seabedDepth ) { - m_geoMechCaseData = geoMechCase->geoMechData(); } //-------------------------------------------------------------------------------------------------- @@ -53,39 +61,6 @@ RimFaultReactivationDataAccessorStress::~RimFaultReactivationDataAccessorStress( { } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimFaultReactivationDataAccessorStress::updateResultAccessor() -{ - const int partIndex = 0; - - auto loadFrameLambda = [&]( auto femParts, RigFemResultAddress addr ) -> RigFemScalarResultFrames* - { - auto result = femParts->findOrLoadScalarResult( partIndex, addr ); - if ( result->frameData( 0, 0 ).empty() ) - { - return nullptr; - } - return result; - }; - - auto femParts = m_geoMechCaseData->femPartResults(); - m_femPart = femParts->parts()->part( partIndex ); - m_s33Frames = loadFrameLambda( femParts, getResultAddress( "ST", "S33" ) ); - m_s11Frames = loadFrameLambda( femParts, getResultAddress( "ST", "S11" ) ); - m_s22Frames = loadFrameLambda( femParts, getResultAddress( "ST", "S22" ) ); - m_porFrames = loadFrameLambda( femParts, RigFemAddressDefines::elementNodalPorBarAddress() ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RigFemResultAddress RimFaultReactivationDataAccessorStress::getResultAddress( const std::string& fieldName, const std::string& componentName ) -{ - return RigFemResultAddress( RIG_ELEMENT_NODAL, fieldName, componentName ); -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -97,39 +72,36 @@ bool RimFaultReactivationDataAccessorStress::isMatching( RimFaultReactivation::P //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorStress::valueAtPosition( const cvf::Vec3d& position, double topDepth, double bottomDepth ) const +double RimFaultReactivationDataAccessorStress::valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth, + double bottomDepth, + size_t elementIndex ) const { - if ( !m_porFrames || !m_s11Frames || !m_s22Frames || !m_s33Frames || !m_femPart ) return std::numeric_limits::infinity(); - - RimWellIADataAccess iaDataAccess( m_geoMechCase ); - int centerElementIdx = iaDataAccess.elementIndex( position ); + if ( !isDataAvailable() ) return std::numeric_limits::infinity(); cvf::Vec3d topPosition( position.x(), position.y(), topDepth ); - int topElementIdx = iaDataAccess.elementIndex( topPosition ); - cvf::Vec3d bottomPosition( position.x(), position.y(), bottomDepth ); - int bottomElementIdx = iaDataAccess.elementIndex( bottomPosition ); - if ( centerElementIdx != -1 && topElementIdx != -1 && bottomElementIdx != -1 ) - { - int timeStepIndex = 0; - int frameIndex = 0; + auto part = model.grid( gridPart ); - const std::vector& s11Data = m_s11Frames->frameData( timeStepIndex, frameIndex ); - const std::vector& s22Data = m_s22Frames->frameData( timeStepIndex, frameIndex ); - const std::vector& s33Data = m_s33Frames->frameData( timeStepIndex, frameIndex ); - const std::vector& porData = m_porFrames->frameData( timeStepIndex, frameIndex ); + auto [isOk, elementSet] = findElementSetForElementIndex( part->elementSets(), static_cast( elementIndex ) ); + if ( isPositionValid( position, topPosition, bottomPosition, gridPart ) ) + { if ( m_property == RimFaultReactivation::Property::StressTop ) { - double s33 = interpolatedResultValue( iaDataAccess, m_femPart, topPosition, s33Data ); - double porBar = interpolatedResultValue( iaDataAccess, m_femPart, topPosition, porData ); - return RiaEclipseUnitTools::barToPascal( s33 - porBar ); + auto [porBar, extractionPos] = calculatePorBar( topPosition, elementSet, m_gradient, gridPart ); + if ( std::isinf( porBar ) ) return porBar; + double s33 = extractStressValue( StressType::S33, extractionPos, gridPart ); + return -RiaEclipseUnitTools::barToPascal( s33 - porBar ); } else if ( m_property == RimFaultReactivation::Property::StressBottom ) { - double s33 = interpolatedResultValue( iaDataAccess, m_femPart, bottomPosition, s33Data ); - double porBar = interpolatedResultValue( iaDataAccess, m_femPart, bottomPosition, porData ); - return RiaEclipseUnitTools::barToPascal( s33 - porBar ); + auto [porBar, extractionPos] = calculatePorBar( bottomPosition, elementSet, m_gradient, gridPart ); + if ( std::isinf( porBar ) ) return porBar; + double s33 = extractStressValue( StressType::S33, extractionPos, gridPart ); + return -RiaEclipseUnitTools::barToPascal( s33 - porBar ); } else if ( m_property == RimFaultReactivation::Property::DepthTop ) { @@ -141,17 +113,11 @@ double RimFaultReactivationDataAccessorStress::valueAtPosition( const cvf::Vec3d } else if ( m_property == RimFaultReactivation::Property::LateralStressComponentX ) { - double s11 = interpolatedResultValue( iaDataAccess, m_femPart, position, s11Data ); - double s33 = interpolatedResultValue( iaDataAccess, m_femPart, position, s33Data ); - double porBar = interpolatedResultValue( iaDataAccess, m_femPart, position, porData ); - return ( s11 - porBar ) / ( s33 - porBar ); + return lateralStressComponentX( position, elementSet, gridPart ); } else if ( m_property == RimFaultReactivation::Property::LateralStressComponentY ) { - double s22 = interpolatedResultValue( iaDataAccess, m_femPart, position, s22Data ); - double s33 = interpolatedResultValue( iaDataAccess, m_femPart, position, s33Data ); - double porBar = interpolatedResultValue( iaDataAccess, m_femPart, position, porData ); - return ( s22 - porBar ) / ( s33 - porBar ); + return lateralStressComponentY( position, elementSet, gridPart ); } } @@ -161,19 +127,27 @@ double RimFaultReactivationDataAccessorStress::valueAtPosition( const cvf::Vec3d //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationDataAccessorStress::hasValidDataAtPosition( const cvf::Vec3d& position ) const +double RimFaultReactivationDataAccessorStress::lateralStressComponentX( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const { - double value = valueAtPosition( position ); - return !std::isinf( value ); + auto [porBar, extractionPos] = calculatePorBar( position, elementSet, m_gradient, gridPart ); + if ( std::isinf( porBar ) ) return porBar; + double s11 = extractStressValue( StressType::S11, extractionPos, gridPart ); + double s33 = extractStressValue( StressType::S33, extractionPos, gridPart ); + return ( s11 - porBar ) / ( s33 - porBar ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorStress::interpolatedResultValue( RimWellIADataAccess& iaDataAccess, - const RigFemPart* femPart, - const cvf::Vec3d& position, - const std::vector& scalarResults ) const +double RimFaultReactivationDataAccessorStress::lateralStressComponentY( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const { - return iaDataAccess.interpolatedResultValue( femPart, scalarResults, RIG_ELEMENT_NODAL, position ); + auto [porBar, extractionPos] = calculatePorBar( position, elementSet, m_gradient, gridPart ); + if ( std::isinf( porBar ) ) return porBar; + double s22 = extractStressValue( StressType::S22, extractionPos, gridPart ); + double s33 = extractStressValue( StressType::S33, extractionPos, gridPart ); + return ( s22 - porBar ) / ( s33 - porBar ); } diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.h index 53a87f1bb4..a03a475fe4 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStress.h @@ -21,16 +21,16 @@ #include "RimFaultReactivationDataAccessor.h" #include "RimFaultReactivationEnums.h" -#include "RigFemResultAddress.h" - #include -class RigFemPartResultsCollection; -class RimGeoMechCase; -class RigGeoMechCaseData; -class RigFemScalarResultFrames; -class RigFemPart; -class RimWellIADataAccess; +#include "cafPdmField.h" +#include "cafPdmPtrField.h" + +#include "cvfObject.h" + +class RigGriddedPart3d; +class RimModeledWellPath; +class RigWellPath; //================================================================================================== /// @@ -39,33 +39,48 @@ class RimWellIADataAccess; class RimFaultReactivationDataAccessorStress : public RimFaultReactivationDataAccessor { public: - RimFaultReactivationDataAccessorStress( RimGeoMechCase* geoMechCase, RimFaultReactivation::Property property ); - ~RimFaultReactivationDataAccessorStress(); + enum class StressType + { + S11, + S22, + S33 + }; + + RimFaultReactivationDataAccessorStress( RimFaultReactivation::Property property, double gradient, double seabedDepth ); + virtual ~RimFaultReactivationDataAccessorStress(); bool isMatching( RimFaultReactivation::Property property ) const override; - double valueAtPosition( const cvf::Vec3d& position, - double topDepth = std::numeric_limits::infinity(), - double bottomDepth = std::numeric_limits::infinity() ) const override; + double valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth = std::numeric_limits::infinity(), + double bottomDepth = std::numeric_limits::infinity(), + size_t elementIndex = std::numeric_limits::max() ) const override; + +protected: + virtual bool isDataAvailable() const = 0; - bool hasValidDataAtPosition( const cvf::Vec3d& position ) const override; + virtual double extractStressValue( StressType stressType, const cvf::Vec3d& position, RimFaultReactivation::GridPart gridPart ) const = 0; -private: - void updateResultAccessor() override; + virtual std::pair calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart ) const = 0; - static RigFemResultAddress getResultAddress( const std::string& fieldName, const std::string& componentName ); + virtual bool isPositionValid( const cvf::Vec3d& position, + const cvf::Vec3d& topPosition, + const cvf::Vec3d& bottomPosition, + RimFaultReactivation::GridPart gridPart ) const = 0; - double interpolatedResultValue( RimWellIADataAccess& iaDataAccess, - const RigFemPart* femPart, - const cvf::Vec3d& position, - const std::vector& scalarResults ) const; + virtual double lateralStressComponentX( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const; + virtual double lateralStressComponentY( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const; - RimGeoMechCase* m_geoMechCase; RimFaultReactivation::Property m_property; - RigGeoMechCaseData* m_geoMechCaseData; - RigFemScalarResultFrames* m_s11Frames; - RigFemScalarResultFrames* m_s22Frames; - RigFemScalarResultFrames* m_s33Frames; - RigFemScalarResultFrames* m_porFrames; - const RigFemPart* m_femPart; + double m_gradient; + double m_seabedDepth; }; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressEclipse.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressEclipse.cpp new file mode 100644 index 0000000000..f7b3f2d026 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressEclipse.cpp @@ -0,0 +1,294 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimFaultReactivationDataAccessorStressEclipse.h" + +#include "RiaEclipseUnitTools.h" +#include "RiaInterpolationTools.h" +#include "RiaLogging.h" +#include "RiaWellLogUnitTools.h" + +#include "RigCaseCellResultsData.h" +#include "RigEclipseResultAddress.h" +#include "RigEclipseWellLogExtractor.h" +#include "RigFaultReactivationModel.h" +#include "RigGriddedPart3d.h" +#include "RigMainGrid.h" +#include "RigResultAccessorFactory.h" +#include "RigWellPath.h" + +#include "RimEclipseCase.h" +#include "RimFaultReactivationDataAccessorStress.h" +#include "RimFaultReactivationDataAccessorWellLogExtraction.h" +#include "RimFaultReactivationEnums.h" + +#include "cvfObject.h" +#include "cvfVector3.h" + +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivationDataAccessorStressEclipse::RimFaultReactivationDataAccessorStressEclipse( + RimEclipseCase* eclipseCase, + RimFaultReactivation::Property property, + double gradient, + double seabedDepth, + double waterDensity, + double lateralStressComponent, + const std::map& densities ) + : RimFaultReactivationDataAccessorStress( property, gradient, seabedDepth ) + , m_eclipseCase( eclipseCase ) + , m_caseData( nullptr ) + , m_mainGrid( nullptr ) + , m_waterDensity( waterDensity ) + , m_lateralStressComponent( lateralStressComponent ) + , m_densities( densities ) +{ + if ( m_eclipseCase ) + { + m_caseData = m_eclipseCase->eclipseCaseData(); + m_mainGrid = m_eclipseCase->mainGrid(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivationDataAccessorStressEclipse::~RimFaultReactivationDataAccessorStressEclipse() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorStressEclipse::updateResultAccessor() +{ + if ( !m_caseData ) return; + + RigEclipseResultAddress resVarAddress( RiaDefines::ResultCatType::DYNAMIC_NATIVE, "PRESSURE" ); + m_eclipseCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->ensureKnownResultLoaded( resVarAddress ); + + m_resultAccessor = + RigResultAccessorFactory::createFromResultAddress( m_caseData, 0, RiaDefines::PorosityModelType::MATRIX_MODEL, m_timeStep, resVarAddress ); + + auto [wellPaths, extractors] = + RimFaultReactivationDataAccessorWellLogExtraction::createEclipseWellPathExtractors( *m_model, *m_caseData, m_seabedDepth ); + m_wellPaths = wellPaths; + m_extractors = extractors; + + for ( auto [gridPart, wellPath] : m_wellPaths ) + { + auto extractor = m_extractors[gridPart]; + std::vector intersections = extractor->intersections(); + + addOverburdenAndUnderburdenPoints( intersections, wellPath->wellPathPoints() ); + + m_stressValues[gridPart] = + integrateVerticalStress( *wellPath.p(), intersections, *m_model, gridPart, m_seabedDepth, m_waterDensity, m_densities ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorStressEclipse::addOverburdenAndUnderburdenPoints( std::vector& intersections, + const std::vector& wellPathPoints ) +{ + // Insert points at top of overburden and under underburden + intersections.insert( intersections.begin(), wellPathPoints.front() ); + intersections.push_back( wellPathPoints.back() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimFaultReactivationDataAccessorStressEclipse::isDataAvailable() const +{ + return m_mainGrid != nullptr && m_resultAccessor.notNull(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorStressEclipse::extractStressValue( StressType stressType, + const cvf::Vec3d& position, + RimFaultReactivation::GridPart gridPart ) const +{ + CAF_ASSERT( m_extractors.find( gridPart ) != m_extractors.end() ); + auto extractor = m_extractors.find( gridPart )->second; + + CAF_ASSERT( m_stressValues.find( gridPart ) != m_stressValues.end() ); + auto stressValues = m_stressValues.find( gridPart )->second; + + CAF_ASSERT( m_wellPaths.find( gridPart ) != m_wellPaths.end() ); + auto wellPath = m_wellPaths.find( gridPart )->second; + + auto intersections = extractor->intersections(); + addOverburdenAndUnderburdenPoints( intersections, wellPath->wellPathPoints() ); + + CAF_ASSERT( stressValues.size() == intersections.size() ); + + auto [topIdx, bottomIdx] = RimFaultReactivationDataAccessorWellLogExtraction::findIntersectionsForTvd( intersections, position.z() ); + if ( topIdx != -1 && bottomIdx != -1 ) + { + double topValue = stressValues[topIdx]; + double bottomValue = stressValues[bottomIdx]; + + if ( !std::isinf( topValue ) && !std::isinf( bottomValue ) ) + { + // Interpolate value from the two closest points. + std::vector xs = { intersections[bottomIdx].z(), intersections[topIdx].z() }; + std::vector ys = { stressValues[bottomIdx], stressValues[topIdx] }; + return RiaEclipseUnitTools::pascalToBar( RiaInterpolationTools::linear( xs, ys, position.z() ) ); + } + } + else if ( position.z() <= intersections.back().z() ) + { + return RiaEclipseUnitTools::pascalToBar( stressValues.back() ); + } + + return std::numeric_limits::infinity(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimFaultReactivationDataAccessorStressEclipse::isPositionValid( const cvf::Vec3d& position, + const cvf::Vec3d& topPosition, + const cvf::Vec3d& bottomPosition, + RimFaultReactivation::GridPart gridPart ) const +{ + // auto [porBar, extractionPosition] = calculatePorBar( position, m_gradient, gridPart ); + // return !std::isinf( porBar ); + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorStressEclipse::calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart ) const +{ + if ( ( m_mainGrid != nullptr ) && m_resultAccessor.notNull() ) + { + CAF_ASSERT( m_extractors.find( gridPart ) != m_extractors.end() ); + auto extractor = m_extractors.find( gridPart )->second; + + CAF_ASSERT( m_wellPaths.find( gridPart ) != m_wellPaths.end() ); + auto wellPath = m_wellPaths.find( gridPart )->second; + + auto [values, intersections] = + RimFaultReactivationDataAccessorWellLogExtraction::extractValuesAndIntersections( *m_resultAccessor.p(), *extractor.p(), *wellPath ); + + auto [value, extractionPos] = RimFaultReactivationDataAccessorWellLogExtraction::calculatePorBar( *m_model, + gridPart, + intersections, + values, + position, + elementSet, + m_gradient ); + if ( extractionPos.isUndefined() ) + { + auto cellIdx = m_mainGrid->findReservoirCellIndexFromPoint( position ); + if ( cellIdx != cvf::UNDEFINED_SIZE_T ) + { + double valueFromEclipse = m_resultAccessor->cellScalar( cellIdx ); + if ( !std::isinf( valueFromEclipse ) ) return { valueFromEclipse, position }; + } + return { value, position }; + } + + return { value, extractionPos }; + } + + return { std::numeric_limits::infinity(), cvf::Vec3d::UNDEFINED }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector + RimFaultReactivationDataAccessorStressEclipse::integrateVerticalStress( const RigWellPath& wellPath, + const std::vector& intersections, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double seabedDepth, + double waterDensity, + const std::map& densities ) +{ + double gravity = RiaWellLogUnitTools::gravityAcceleration(); + double seaWaterLoad = gravity * std::abs( seabedDepth ) * waterDensity; + std::vector values = { seaWaterLoad }; + + auto part = model.grid( gridPart ); + CAF_ASSERT( part ); + auto elementSets = part->elementSets(); + + double previousDensity = densities.find( RimFaultReactivation::ElementSets::OverBurden )->second; + + for ( size_t i = 1; i < intersections.size(); i++ ) + { + double previousValue = values[i - 1]; + double previousDepth = intersections[i - 1].z(); + double currentDepth = intersections[i].z(); + + double deltaDepth = previousDepth - currentDepth; + double density = previousDensity; + + auto [isOk, elementSet] = + RimFaultReactivationDataAccessorWellLogExtraction::findElementSetForPoint( *part, intersections[i], elementSets ); + if ( isOk ) + { + // Unit: kg/m^3 + CAF_ASSERT( densities.find( elementSet ) != densities.end() ); + density = densities.find( elementSet )->second; + } + + double value = previousValue + density * gravity * deltaDepth; + values.push_back( value ); + + previousDensity = density; + } + + return values; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorStressEclipse::lateralStressComponentX( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const +{ + return m_lateralStressComponent; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorStressEclipse::lateralStressComponentY( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const +{ + return m_lateralStressComponent; +} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressEclipse.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressEclipse.h new file mode 100644 index 0000000000..678db36e70 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressEclipse.h @@ -0,0 +1,100 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 - Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RimFaultReactivationDataAccessorStress.h" +#include "RimFaultReactivationEnums.h" + +#include "cafPdmField.h" +#include "cafPdmPtrField.h" + +#include "cvfObject.h" + +#include + +class RigGriddedPart3d; +class RimModeledWellPath; +class RigWellPath; +class RimEclipseCase; +class RigEclipseCaseData; +class RigResultAccessor; +class RigEclipseWellLogExtractor; + +//================================================================================================== +/// +/// +//================================================================================================== +class RimFaultReactivationDataAccessorStressEclipse : public RimFaultReactivationDataAccessorStress +{ +public: + RimFaultReactivationDataAccessorStressEclipse( RimEclipseCase* geoMechCase, + RimFaultReactivation::Property property, + double gradient, + double seabedDepth, + double waterDensity, + double lateralStressComponent, + const std::map& densities ); + ~RimFaultReactivationDataAccessorStressEclipse() override; + +private: + void updateResultAccessor() override; + + bool isDataAvailable() const override; + + double extractStressValue( StressType stressType, const cvf::Vec3d& position, RimFaultReactivation::GridPart gridPart ) const override; + + std::pair calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart ) const override; + + bool isPositionValid( const cvf::Vec3d& position, + const cvf::Vec3d& topPosition, + const cvf::Vec3d& bottomPosition, + RimFaultReactivation::GridPart gridPart ) const override; + + double lateralStressComponentX( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const override; + double lateralStressComponentY( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + RimFaultReactivation::GridPart gridPart ) const override; + + static std::vector integrateVerticalStress( const RigWellPath& wellPath, + const std::vector& intersections, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double seabedDepth, + double waterDensity, + const std::map& densities ); + + static void addOverburdenAndUnderburdenPoints( std::vector& intersections, const std::vector& wellPathPoints ); + + RimEclipseCase* m_eclipseCase; + RigEclipseCaseData* m_caseData; + const RigMainGrid* m_mainGrid; + cvf::ref m_resultAccessor; + double m_waterDensity; + double m_lateralStressComponent; + + std::map> m_wellPaths; + std::map> m_extractors; + std::map> m_stressValues; + std::map m_densities; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressGeoMech.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressGeoMech.cpp new file mode 100644 index 0000000000..b804c7fce2 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressGeoMech.cpp @@ -0,0 +1,263 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimFaultReactivationDataAccessorStressGeoMech.h" + +#include "RiaEclipseUnitTools.h" +#include "RiaLogging.h" + +#include "RigFaultReactivationModel.h" +#include "RigFemAddressDefines.h" +#include "RigFemPartCollection.h" +#include "RigFemPartResultsCollection.h" +#include "RigFemResultAddress.h" +#include "RigFemScalarResultFrames.h" +#include "RigGeoMechCaseData.h" +#include "RigGeoMechWellLogExtractor.h" +#include "RigGriddedPart3d.h" +#include "RigResultAccessorFactory.h" +#include "RigWellPath.h" + +#include "RimFaultReactivationDataAccessorStress.h" +#include "RimFaultReactivationDataAccessorWellLogExtraction.h" +#include "RimFaultReactivationEnums.h" +#include "RimGeoMechCase.h" +#include "RimWellIADataAccess.h" + +#include "cvfVector3.h" + +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivationDataAccessorStressGeoMech::RimFaultReactivationDataAccessorStressGeoMech( RimGeoMechCase* geoMechCase, + RimFaultReactivation::Property property, + double gradient, + double seabedDepth ) + : RimFaultReactivationDataAccessorStress( property, gradient, seabedDepth ) + , m_geoMechCase( geoMechCase ) +{ + m_geoMechCaseData = geoMechCase->geoMechData(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivationDataAccessorStressGeoMech::~RimFaultReactivationDataAccessorStressGeoMech() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorStressGeoMech::updateResultAccessor() +{ + const int partIndex = 0; + + auto loadFrameLambda = [&]( auto femParts, RigFemResultAddress addr, int timeStepIndex ) -> RigFemScalarResultFrames* + { + auto result = femParts->findOrLoadScalarResult( partIndex, addr ); + int frameIndex = result->frameCount( timeStepIndex ) - 1; + if ( result->frameData( timeStepIndex, frameIndex ).empty() ) + { + return nullptr; + } + return result; + }; + + auto femParts = m_geoMechCaseData->femPartResults(); + m_femPart = femParts->parts()->part( partIndex ); + int timeStepIndex = 0; + m_s33Frames = loadFrameLambda( femParts, getResultAddress( "ST", "S33" ), timeStepIndex ); + m_s11Frames = loadFrameLambda( femParts, getResultAddress( "ST", "S11" ), timeStepIndex ); + m_s22Frames = loadFrameLambda( femParts, getResultAddress( "ST", "S22" ), timeStepIndex ); + m_porBarFrames = loadFrameLambda( femParts, RigFemAddressDefines::nodalPorBarAddress(), timeStepIndex ); + + auto [faultTopPosition, faultBottomPosition] = m_model->faultTopBottom(); + auto faultNormal = m_model->modelNormal() ^ cvf::Vec3d::Z_AXIS; + faultNormal.normalize(); + + double distanceFromFault = 1.0; + auto [topDepth, bottomDepth] = m_model->depthTopBottom(); + + for ( auto gridPart : m_model->allGridParts() ) + { + double sign = m_model->normalPointsAt() == gridPart ? -1.0 : 1.0; + std::vector wellPoints = + RimFaultReactivationDataAccessorWellLogExtraction::generateWellPoints( faultTopPosition, + faultBottomPosition, + m_seabedDepth, + bottomDepth, + sign * faultNormal * distanceFromFault ); + + cvf::ref wellPath = + new RigWellPath( wellPoints, RimFaultReactivationDataAccessorWellLogExtraction::generateMds( wellPoints ) ); + m_wellPaths[gridPart] = wellPath; + + std::string errorName = "fault reactivation data access"; + cvf::ref extractor = + new RigGeoMechWellLogExtractor( m_geoMechCaseData, partIndex, wellPath.p(), errorName ); + + m_extractors[gridPart] = extractor; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigFemResultAddress RimFaultReactivationDataAccessorStressGeoMech::getResultAddress( const std::string& fieldName, + const std::string& componentName ) +{ + return RigFemResultAddress( RIG_ELEMENT_NODAL, fieldName, componentName ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimFaultReactivationDataAccessorStressGeoMech::isDataAvailable() const +{ + return m_s11Frames && m_s22Frames && m_s33Frames && m_porBarFrames && m_femPart; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorStressGeoMech::extractStressValue( StressType stressType, + const cvf::Vec3d& position, + RimFaultReactivation::GridPart gridPart ) const +{ + RimWellIADataAccess iaDataAccess( m_geoMechCase ); + + int timeStepIndex = 0; + + RigFemScalarResultFrames* frames = dataFrames( stressType ); + int frameIndex = frames->frameCount( timeStepIndex ) - 1; + const std::vector& s11Data = frames->frameData( timeStepIndex, frameIndex ); + return interpolatedResultValue( iaDataAccess, m_femPart, position, s11Data ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigFemScalarResultFrames* RimFaultReactivationDataAccessorStressGeoMech::dataFrames( StressType stressType ) const +{ + if ( stressType == StressType::S11 ) + return m_s11Frames; + else if ( stressType == StressType::S22 ) + return m_s22Frames; + else + { + CAF_ASSERT( stressType == StressType::S33 ); + return m_s33Frames; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorStressGeoMech::calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart ) const +{ + int timeStepIndex = 0; + int frameIndex = m_s33Frames->frameCount( timeStepIndex ) - 1; + return calculatePorBar( position, elementSet, m_gradient, gridPart, timeStepIndex, frameIndex ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimFaultReactivationDataAccessorStressGeoMech::isPositionValid( const cvf::Vec3d& position, + const cvf::Vec3d& topPosition, + const cvf::Vec3d& bottomPosition, + RimFaultReactivation::GridPart gridPart ) const +{ + RimWellIADataAccess iaDataAccess( m_geoMechCase ); + int centerElementIdx = iaDataAccess.elementIndex( position ); + int bottomElementIdx = iaDataAccess.elementIndex( bottomPosition ); + int topElementIdx = iaDataAccess.elementIndex( topPosition ); + return ( centerElementIdx != -1 && topElementIdx != -1 && bottomElementIdx != -1 ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorStressGeoMech::interpolatedResultValue( RimWellIADataAccess& iaDataAccess, + const RigFemPart* femPart, + const cvf::Vec3d& position, + const std::vector& scalarResults ) const +{ + return iaDataAccess.interpolatedResultValue( femPart, scalarResults, RIG_ELEMENT_NODAL, position ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorStressGeoMech::calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart, + int timeStepIndex, + int frameIndex ) const +{ + CAF_ASSERT( m_extractors.find( gridPart ) != m_extractors.end() ); + auto extractor = m_extractors.find( gridPart )->second; + + if ( !extractor->valid() ) + { + RiaLogging::error( "Invalid extractor when extracting PorBar" ); + return { std::numeric_limits::infinity(), cvf::Vec3d::UNDEFINED }; + } + + RigFemResultAddress resAddr = RigFemAddressDefines::nodalPorBarAddress(); + std::vector values; + extractor->curveData( resAddr, timeStepIndex, frameIndex, &values ); + + auto [value, extractionPos] = RimFaultReactivationDataAccessorWellLogExtraction::calculatePorBar( *m_model, + gridPart, + extractor->intersections(), + values, + position, + elementSet, + gradient ); + + if ( extractionPos.isUndefined() ) + { + // If extraction position is not defined the position is not close to the border between the two parts. + // This means it should be safe to use POR-BAR from the model. + const std::vector& frameData = m_porBarFrames->frameData( timeStepIndex, frameIndex ); + + // Use data from geo mech grid if defined (only position is reservoir). + RimWellIADataAccess iaDataAccess( m_geoMechCase ); + double gridValue = iaDataAccess.interpolatedResultValue( m_femPart, frameData, RIG_NODAL, position ); + if ( !std::isinf( gridValue ) && !std::isnan( gridValue ) ) + { + return { gridValue, position }; + } + + // Use calculated value when POR-BAR is inf (outside of reservoir). + return { value, position }; + } + else + { + return { value, extractionPos }; + } +} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressGeoMech.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressGeoMech.h new file mode 100644 index 0000000000..4e292ecba4 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorStressGeoMech.h @@ -0,0 +1,101 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 - Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RimFaultReactivationDataAccessorStress.h" +#include "RimFaultReactivationEnums.h" + +#include "RigFemResultAddress.h" + +#include + +#include "cafPdmField.h" +#include "cafPdmPtrField.h" + +#include "cvfObject.h" + +class RigFemPart; +class RigFemPartResultsCollection; +class RigFemScalarResultFrames; +class RigGeoMechCaseData; +class RigGriddedPart3d; +class RimGeoMechCase; +class RimWellIADataAccess; +class RimModeledWellPath; +class RigWellPath; +class RigFemPartCollection; +class RigGeoMechWellLogExtractor; + +//================================================================================================== +/// +/// +//================================================================================================== +class RimFaultReactivationDataAccessorStressGeoMech : public RimFaultReactivationDataAccessorStress +{ +public: + RimFaultReactivationDataAccessorStressGeoMech( RimGeoMechCase* geoMechCase, + RimFaultReactivation::Property property, + double gradient, + double seabedDepth ); + ~RimFaultReactivationDataAccessorStressGeoMech() override; + +private: + void updateResultAccessor() override; + + bool isDataAvailable() const override; + + double extractStressValue( StressType stressType, const cvf::Vec3d& position, RimFaultReactivation::GridPart gridPart ) const override; + + std::pair calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart ) const override; + + bool isPositionValid( const cvf::Vec3d& position, + const cvf::Vec3d& topPosition, + const cvf::Vec3d& bottomPosition, + RimFaultReactivation::GridPart gridPart ) const override; + + static RigFemResultAddress getResultAddress( const std::string& fieldName, const std::string& componentName ); + + double interpolatedResultValue( RimWellIADataAccess& iaDataAccess, + const RigFemPart* femPart, + const cvf::Vec3d& position, + const std::vector& scalarResults ) const; + + std::pair calculatePorBar( const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient, + RimFaultReactivation::GridPart gridPart, + int timeStepIndex, + int frameIndex ) const; + + RigFemScalarResultFrames* dataFrames( StressType stressType ) const; + + RimGeoMechCase* m_geoMechCase; + RigGeoMechCaseData* m_geoMechCaseData; + RigFemScalarResultFrames* m_s11Frames; + RigFemScalarResultFrames* m_s22Frames; + RigFemScalarResultFrames* m_s33Frames; + const RigFemScalarResultFrames* m_porBarFrames; + const RigFemPart* m_femPart; + + std::map> m_wellPaths; + std::map> m_extractors; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.cpp index 49364a25d8..be16499b68 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.cpp @@ -17,6 +17,7 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RimFaultReactivationDataAccessorTemperature.h" +#include "RigFaultReactivationModel.h" #include "RimFaultReactivationEnums.h" #include "RiaDefines.h" @@ -25,10 +26,13 @@ #include "RigCaseCellResultsData.h" #include "RigEclipseCaseData.h" #include "RigEclipseResultAddress.h" +#include "RigEclipseWellLogExtractor.h" #include "RigMainGrid.h" #include "RigResultAccessorFactory.h" +#include "RigWellPath.h" #include "RimEclipseCase.h" +#include "RimFaultReactivationDataAccessorWellLogExtraction.h" #include #include @@ -36,10 +40,14 @@ //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimFaultReactivationDataAccessorTemperature::RimFaultReactivationDataAccessorTemperature( RimEclipseCase* eclipseCase ) +RimFaultReactivationDataAccessorTemperature::RimFaultReactivationDataAccessorTemperature( RimEclipseCase* eclipseCase, + double seabedTemperature, + double seabedDepth ) : m_eclipseCase( eclipseCase ) , m_caseData( nullptr ) , m_mainGrid( nullptr ) + , m_seabedTemperature( seabedTemperature ) + , m_seabedDepth( seabedDepth ) { if ( m_eclipseCase ) { @@ -60,18 +68,64 @@ RimFaultReactivationDataAccessorTemperature::~RimFaultReactivationDataAccessorTe //-------------------------------------------------------------------------------------------------- void RimFaultReactivationDataAccessorTemperature::updateResultAccessor() { - if ( m_caseData ) + if ( !m_caseData ) return; + + RigEclipseResultAddress resVarAddress( RiaDefines::ResultCatType::DYNAMIC_NATIVE, "TEMP" ); + m_eclipseCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->ensureKnownResultLoaded( resVarAddress ); + m_resultAccessor = + RigResultAccessorFactory::createFromResultAddress( m_caseData, 0, RiaDefines::PorosityModelType::MATRIX_MODEL, m_timeStep, resVarAddress ); + + if ( m_resultAccessor.notNull() ) { - RigEclipseResultAddress resVarAddress( RiaDefines::ResultCatType::DYNAMIC_NATIVE, "TEMP" ); - m_eclipseCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->ensureKnownResultLoaded( resVarAddress ); - m_resultAccessor = RigResultAccessorFactory::createFromResultAddress( m_caseData, - 0, - RiaDefines::PorosityModelType::MATRIX_MODEL, - m_timeStep, - resVarAddress ); + auto [wellPaths, extractors] = + RimFaultReactivationDataAccessorWellLogExtraction::createEclipseWellPathExtractors( *m_model, *m_caseData, m_seabedDepth ); + m_wellPaths = wellPaths; + m_extractors = extractors; + + m_gradient = computeGradient(); } } +//-------------------------------------------------------------------------------------------------- +/// Find the top encounter with reservoir (of the two well paths), and create gradient from that point +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorTemperature::computeGradient() const +{ + double gradient = std::numeric_limits::infinity(); + double minDepth = -std::numeric_limits::max(); + for ( auto gridPart : m_model->allGridParts() ) + { + auto extractor = m_extractors.find( gridPart )->second; + auto wellPath = m_wellPaths.find( gridPart )->second; + + auto [values, intersections] = + RimFaultReactivationDataAccessorWellLogExtraction::extractValuesAndIntersections( *m_resultAccessor.p(), *extractor.p(), *wellPath ); + + int lastOverburdenIndex = RimFaultReactivationDataAccessorWellLogExtraction::findLastOverburdenIndex( values ); + if ( lastOverburdenIndex != -1 ) + { + double depth = intersections[lastOverburdenIndex].z(); + double value = values[lastOverburdenIndex]; + + if ( !std::isinf( value ) ) + { + double currentGradient = + RimFaultReactivationDataAccessorWellLogExtraction::computeGradient( intersections[0].z(), + m_seabedTemperature, + intersections[lastOverburdenIndex].z(), + values[lastOverburdenIndex] ); + if ( !std::isinf( value ) && !std::isnan( currentGradient ) && depth > minDepth ) + { + gradient = currentGradient; + minDepth = depth; + } + } + } + } + + return gradient; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -83,25 +137,36 @@ bool RimFaultReactivationDataAccessorTemperature::isMatching( RimFaultReactivati //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorTemperature::valueAtPosition( const cvf::Vec3d& position, double topDepth, double bottomDepth ) const +double RimFaultReactivationDataAccessorTemperature::valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth, + double bottomDepth, + size_t elementIndex ) const { if ( ( m_mainGrid != nullptr ) && m_resultAccessor.notNull() ) { auto cellIdx = m_mainGrid->findReservoirCellIndexFromPoint( position ); if ( cellIdx != cvf::UNDEFINED_SIZE_T ) { - return m_resultAccessor->cellScalar( cellIdx ); + double tempFromEclipse = m_resultAccessor->cellScalar( cellIdx ); + if ( !std::isinf( tempFromEclipse ) ) return tempFromEclipse; } + + CAF_ASSERT( m_extractors.find( gridPart ) != m_extractors.end() ); + auto extractor = m_extractors.find( gridPart )->second; + + CAF_ASSERT( m_wellPaths.find( gridPart ) != m_wellPaths.end() ); + auto wellPath = m_wellPaths.find( gridPart )->second; + + auto [values, intersections] = + RimFaultReactivationDataAccessorWellLogExtraction::extractValuesAndIntersections( *m_resultAccessor.p(), *extractor.p(), *wellPath ); + + auto [value, pos] = + RimFaultReactivationDataAccessorWellLogExtraction::calculateTemperature( intersections, position, m_seabedTemperature, m_gradient ); + + return value; } return std::numeric_limits::infinity(); } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationDataAccessorTemperature::hasValidDataAtPosition( const cvf::Vec3d& position ) const -{ - auto cellIdx = m_mainGrid->findReservoirCellIndexFromPoint( position ); - return ( cellIdx != cvf::UNDEFINED_SIZE_T ); -} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.h index 25c828b067..d8b5b1fce0 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorTemperature.h @@ -28,6 +28,8 @@ class RimEclipseCase; class RigEclipseCaseData; class RigMainGrid; class RigResultAccessor; +class RigWellPath; +class RigEclipseWellLogExtractor; //================================================================================================== /// @@ -36,22 +38,31 @@ class RigResultAccessor; class RimFaultReactivationDataAccessorTemperature : public RimFaultReactivationDataAccessor { public: - RimFaultReactivationDataAccessorTemperature( RimEclipseCase* eclipseCase ); + RimFaultReactivationDataAccessorTemperature( RimEclipseCase* eclipseCase, double seabedTemperature, double seabedDepth ); ~RimFaultReactivationDataAccessorTemperature(); bool isMatching( RimFaultReactivation::Property property ) const override; - double valueAtPosition( const cvf::Vec3d& position, - double topDepth = std::numeric_limits::infinity(), - double bottomDepth = std::numeric_limits::infinity() ) const override; - - bool hasValidDataAtPosition( const cvf::Vec3d& position ) const override; + double valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth = std::numeric_limits::infinity(), + double bottomDepth = std::numeric_limits::infinity(), + size_t elementIndex = std::numeric_limits::max() ) const override; private: - void updateResultAccessor() override; + void updateResultAccessor() override; + double computeGradient() const; + + RimEclipseCase* m_eclipseCase; + RigEclipseCaseData* m_caseData; + const RigMainGrid* m_mainGrid; + double m_seabedTemperature; + double m_seabedDepth; + double m_gradient; - RimEclipseCase* m_eclipseCase; - RigEclipseCaseData* m_caseData; - const RigMainGrid* m_mainGrid; cvf::ref m_resultAccessor; + + std::map> m_wellPaths; + std::map> m_extractors; }; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.cpp index f0c7e91e5a..96fe0c6f3b 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.cpp @@ -84,7 +84,12 @@ bool RimFaultReactivationDataAccessorVoidRatio::isMatching( RimFaultReactivation //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -double RimFaultReactivationDataAccessorVoidRatio::valueAtPosition( const cvf::Vec3d& position, double topDepth, double bottomDepth ) const +double RimFaultReactivationDataAccessorVoidRatio::valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth, + double bottomDepth, + size_t elementIndex ) const { if ( ( m_mainGrid != nullptr ) && m_resultAccessor.notNull() ) { @@ -101,15 +106,3 @@ double RimFaultReactivationDataAccessorVoidRatio::valueAtPosition( const cvf::Ve return m_missingValue; } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationDataAccessorVoidRatio::hasValidDataAtPosition( const cvf::Vec3d& position ) const -{ - auto cellIdx = m_mainGrid->findReservoirCellIndexFromPoint( position ); - if ( cellIdx == cvf::UNDEFINED_SIZE_T ) return false; - - double value = m_resultAccessor->cellScalar( cellIdx ); - return !std::isinf( value ); -} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.h index 0b8eafca88..519a5727da 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorVoidRatio.h @@ -41,11 +41,12 @@ class RimFaultReactivationDataAccessorVoidRatio : public RimFaultReactivationDat bool isMatching( RimFaultReactivation::Property property ) const override; - double valueAtPosition( const cvf::Vec3d& position, - double topDepth = std::numeric_limits::infinity(), - double bottomDepth = std::numeric_limits::infinity() ) const override; - - bool hasValidDataAtPosition( const cvf::Vec3d& position ) const override; + double valueAtPosition( const cvf::Vec3d& position, + const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + double topDepth = std::numeric_limits::infinity(), + double bottomDepth = std::numeric_limits::infinity(), + size_t elementIndex = std::numeric_limits::max() ) const override; private: void updateResultAccessor() override; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorWellLogExtraction.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorWellLogExtraction.cpp new file mode 100644 index 0000000000..a126f1087b --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorWellLogExtraction.cpp @@ -0,0 +1,483 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimFaultReactivationDataAccessorWellLogExtraction.h" + +#include "RiaEclipseUnitTools.h" +#include "RiaInterpolationTools.h" +#include "RiaLogging.h" + +#include "RigEclipseWellLogExtractor.h" +#include "RigFaultReactivationModel.h" +#include "RigFemAddressDefines.h" +#include "RigFemPartCollection.h" +#include "RigFemPartResultsCollection.h" +#include "RigFemResultAddress.h" +#include "RigFemScalarResultFrames.h" +#include "RigGeoMechCaseData.h" +#include "RigGeoMechWellLogExtractor.h" +#include "RigGriddedPart3d.h" +#include "RigResultAccessorFactory.h" +#include "RigWellPath.h" + +#include "RimFaultReactivationEnums.h" +#include "RimFracture.h" +#include "RimGeoMechCase.h" +#include "RimWellIADataAccess.h" + +#include "cvfGeometryTools.h" +#include "cvfVector3.h" + +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivationDataAccessorWellLogExtraction::RimFaultReactivationDataAccessorWellLogExtraction() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivationDataAccessorWellLogExtraction::~RimFaultReactivationDataAccessorWellLogExtraction() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorWellLogExtraction::calculatePorBar( const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + const std::vector& intersections, + std::vector& values, + const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient ) +{ + if ( elementSet == RimFaultReactivation::ElementSets::OverBurden || elementSet == RimFaultReactivation::ElementSets::UnderBurden ) + { + return { calculatePorePressure( std::abs( position.z() ), gradient ), position }; + } + + // Fill in missing values + fillInMissingValuesWithGradient( intersections, values, gradient ); + auto [value, extractionPosition] = findValueAndPosition( intersections, values, position ); + + double minDistance = computeMinimumDistance( position, intersections ); + if ( minDistance < 1.0 ) + { + return { value, extractionPosition }; + } + else + { + return { value, cvf::Vec3d::UNDEFINED }; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair + RimFaultReactivationDataAccessorWellLogExtraction::calculateTemperature( const std::vector& intersections, + const cvf::Vec3d& position, + double seabedTemperature, + double gradient ) +{ + return { calculateTemperature( seabedTemperature, intersections[0].z(), std::abs( position.z() ), gradient ), position }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair + RimFaultReactivationDataAccessorWellLogExtraction::findValueAndPosition( const std::vector& intersections, + const std::vector& values, + const cvf::Vec3d& position ) +{ + // Linear interpolation between two points + auto lerp = []( const cvf::Vec3d& start, const cvf::Vec3d& end, double t ) { return start + t * ( end - start ); }; + + auto [topIdx, bottomIdx] = findIntersectionsForTvd( intersections, position.z() ); + if ( topIdx != -1 && bottomIdx != -1 ) + { + double topValue = values[topIdx]; + double bottomValue = values[bottomIdx]; + if ( !std::isinf( topValue ) && !std::isinf( bottomValue ) ) + { + // Interpolate value from the two closest points. + std::vector xs = { intersections[bottomIdx].z(), intersections[topIdx].z() }; + std::vector ys = { values[bottomIdx], values[topIdx] }; + double porBar = RiaInterpolationTools::linear( xs, ys, position.z() ); + + // Interpolate position from depth + double fraction = RiaInterpolationTools::linear( xs, { 0.0, 1.0 }, position.z() ); + cvf::Vec3d extractionPosition = lerp( intersections[bottomIdx], intersections[topIdx], fraction ); + return { porBar, extractionPosition }; + } + } + else if ( position.z() <= intersections.back().z() ) + { + return { values.back(), intersections.back() }; + } + + return { std::numeric_limits::infinity(), cvf::Vec3d::UNDEFINED }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorWellLogExtraction::findIntersectionsForTvd( const std::vector& intersections, + double tvd ) +{ + int topIdx = -1; + int bottomIdx = -1; + if ( intersections.size() >= 2 ) + { + for ( size_t i = 1; i < intersections.size(); i++ ) + { + auto top = intersections[i - 1]; + auto bottom = intersections[i]; + if ( top.z() >= tvd && bottom.z() < tvd ) + { + topIdx = static_cast( i ) - 1; + bottomIdx = static_cast( i ); + break; + } + } + } + return std::make_pair( topIdx, bottomIdx ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorWellLogExtraction::findOverburdenAndUnderburdenIndex( const std::vector& values ) +{ + auto findFirstUnderburdenIndex = []( const std::vector& values ) + { + for ( size_t i = values.size() - 1; i > 0; i-- ) + { + if ( !std::isinf( values[i] ) ) return static_cast( i ); + } + + return -1; + }; + + int lastOverburdenIndex = findLastOverburdenIndex( values ); + int firstUnderburdenIndex = findFirstUnderburdenIndex( values ); + return { lastOverburdenIndex, firstUnderburdenIndex }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RimFaultReactivationDataAccessorWellLogExtraction::findLastOverburdenIndex( const std::vector& values ) +{ + for ( size_t i = 0; i < values.size(); i++ ) + { + if ( !std::isinf( values[i] ) ) return static_cast( i ); + } + + return -1; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorWellLogExtraction::computeValueWithGradient( const std::vector& intersections, + const std::vector& values, + int i1, + int i2, + double gradient ) +{ + double tvdDiff = intersections[i2].z() - intersections[i1].z(); + return tvdDiff * gradient + values[i2]; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorWellLogExtraction::fillInMissingValuesWithGradient( const std::vector& intersections, + std::vector& values, + double gradient ) +{ + CAF_ASSERT( intersections.size() == values.size() ); + + auto [lastOverburdenIndex, firstUnderburdenIndex] = findOverburdenAndUnderburdenIndex( values ); + + // Fill in overburden values using gradient + double topPorePressure = calculatePorePressure( std::abs( intersections[0].z() ), gradient ); + insertOverburdenValues( intersections, values, lastOverburdenIndex, topPorePressure ); + + // Fill in underburden values using gradient + int lastElementIndex = static_cast( values.size() ) - 1; + double bottomPorePressure = calculatePorePressure( std::abs( intersections[lastElementIndex].z() ), gradient ); + insertUnderburdenValues( intersections, values, firstUnderburdenIndex, bottomPorePressure ); + + // Interpolate the missing values (should only be intra-reservoir by now) + std::vector intersectionsZ = extractDepthValues( intersections ); + RiaInterpolationTools::interpolateMissingValues( intersectionsZ, values ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorWellLogExtraction::fillInMissingValuesWithTopValue( const std::vector& intersections, + std::vector& values, + double topValue ) +{ + CAF_ASSERT( intersections.size() == values.size() ); + + auto [lastOverburdenIndex, firstUnderburdenIndex] = findOverburdenAndUnderburdenIndex( values ); + + // Fill in overburden values using gradient + insertOverburdenValues( intersections, values, lastOverburdenIndex, topValue ); + + // Fill in underburden values + double bottomValue = values[firstUnderburdenIndex - 1]; + insertUnderburdenValues( intersections, values, firstUnderburdenIndex, bottomValue ); + + // Interpolate the missing values (should only be intra-reservoir by now) + std::vector intersectionsZ = extractDepthValues( intersections ); + RiaInterpolationTools::interpolateMissingValues( intersectionsZ, values ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimFaultReactivationDataAccessorWellLogExtraction::generateWellPoints( const cvf::Vec3d& faultTopPosition, + const cvf::Vec3d& faultBottomPosition, + double seabedDepth, + double bottomDepth, + const cvf::Vec3d& offset ) +{ + cvf::Vec3d faultTop = faultTopPosition + offset; + cvf::Vec3d seabed( faultTop.x(), faultTop.y(), seabedDepth ); + cvf::Vec3d faultBottom = faultBottomPosition + offset; + cvf::Vec3d underburdenBottom( faultBottom.x(), faultBottom.y(), bottomDepth ); + return { seabed, faultTop, faultBottom, underburdenBottom }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimFaultReactivationDataAccessorWellLogExtraction::generateMds( const std::vector& points ) +{ + CAF_ASSERT( points.size() >= 2 ); + + // Assume first at zero, all other points relative to that. + std::vector mds = { 0.0 }; + double sum = 0.0; + for ( size_t i = 1; i < points.size(); i++ ) + { + sum += points[i - 1].pointDistance( points[i] ); + mds.push_back( sum ); + } + return mds; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair>, std::map>> + RimFaultReactivationDataAccessorWellLogExtraction::createEclipseWellPathExtractors( const RigFaultReactivationModel& model, + RigEclipseCaseData& eclipseCaseData, + double seabedDepth ) +{ + auto [faultTopPosition, faultBottomPosition] = model.faultTopBottom(); + auto faultNormal = model.modelNormal() ^ cvf::Vec3d::Z_AXIS; + faultNormal.normalize(); + + double distanceFromFault = 1.0; + auto [topDepth, bottomDepth] = model.depthTopBottom(); + + std::map> wellPaths; + std::map> extractors; + + for ( auto gridPart : model.allGridParts() ) + { + double sign = model.normalPointsAt() == gridPart ? -1.0 : 1.0; + std::vector wellPoints = + RimFaultReactivationDataAccessorWellLogExtraction::generateWellPoints( faultTopPosition, + faultBottomPosition, + seabedDepth, + bottomDepth, + sign * faultNormal * distanceFromFault ); + cvf::ref wellPath = + new RigWellPath( wellPoints, RimFaultReactivationDataAccessorWellLogExtraction::generateMds( wellPoints ) ); + wellPaths[gridPart] = wellPath; + + std::string errorName = "fault reactivation data access"; + cvf::ref extractor = new RigEclipseWellLogExtractor( &eclipseCaseData, wellPath.p(), errorName ); + extractors[gridPart] = extractor; + } + + return { wellPaths, extractors }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair, std::vector> + RimFaultReactivationDataAccessorWellLogExtraction::extractValuesAndIntersections( const RigResultAccessor& resultAccessor, + RigEclipseWellLogExtractor& extractor, + const RigWellPath& wellPath ) +{ + // Extract values along well path + std::vector values; + extractor.curveData( &resultAccessor, &values ); + + auto intersections = extractor.intersections(); + + // Insert top of overburden point + intersections.insert( intersections.begin(), wellPath.wellPathPoints().front() ); + values.insert( values.begin(), std::numeric_limits::infinity() ); + + // Insert bottom of underburden point + intersections.push_back( wellPath.wellPathPoints().back() ); + values.push_back( std::numeric_limits::infinity() ); + + return { values, intersections }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorWellLogExtraction::computeGradient( double depth1, double value1, double depth2, double value2 ) +{ + return ( value2 - value1 ) / ( depth2 - depth1 ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimFaultReactivationDataAccessorWellLogExtraction::extractDepthValues( const std::vector& intersections ) +{ + std::vector intersectionsZ; + for ( auto i : intersections ) + { + intersectionsZ.push_back( -i.z() ); + } + return intersectionsZ; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorWellLogExtraction::insertUnderburdenValues( const std::vector& intersections, + std::vector& values, + int firstUnderburdenIndex, + double bottomValue ) +{ + int lastElementIndex = static_cast( values.size() ) - 1; + double underburdenGradient = computeGradient( intersections[firstUnderburdenIndex].z(), + values[firstUnderburdenIndex], + intersections[lastElementIndex].z(), + bottomValue ); + + for ( int i = lastElementIndex; i >= firstUnderburdenIndex; i-- ) + { + values[i] = computeValueWithGradient( intersections, values, i, firstUnderburdenIndex, -underburdenGradient ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimFaultReactivationDataAccessorWellLogExtraction::insertOverburdenValues( const std::vector& intersections, + std::vector& values, + int lastOverburdenIndex, + double topValue ) +{ + double overburdenGradient = + computeGradient( intersections[0].z(), topValue, intersections[lastOverburdenIndex].z(), values[lastOverburdenIndex] ); + + for ( int i = 0; i < lastOverburdenIndex; i++ ) + { + values[i] = computeValueWithGradient( intersections, values, i, lastOverburdenIndex, -overburdenGradient ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorWellLogExtraction::computeMinimumDistance( const cvf::Vec3d& position, + const std::vector& positions ) +{ + double minDistance = std::numeric_limits::max(); + for ( size_t i = 1; i < positions.size(); i++ ) + { + cvf::Vec3d point1 = positions[i - 1]; + cvf::Vec3d point2 = positions[i - 0]; + + double candidateDistance = cvf::GeometryTools::linePointSquareDist( point1, point2, position ); + minDistance = std::min( candidateDistance, minDistance ); + } + + return std::sqrt( minDistance ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RimFaultReactivationDataAccessorWellLogExtraction::findElementSetForPoint( + const RigGriddedPart3d& part, + const cvf::Vec3d& point, + const std::map>& elementSets ) +{ + for ( auto [elementSet, elements] : elementSets ) + { + for ( unsigned int elementIndex : elements ) + { + // Find nodes from element + auto positions = part.elementCorners( elementIndex ); + + std::array coordinates; + for ( size_t i = 0; i < positions.size(); ++i ) + { + coordinates[i] = positions[i]; + } + + if ( RigHexIntersectionTools::isPointInCell( point, coordinates.data() ) ) + { + return { true, elementSet }; + } + } + } + + return { false, RimFaultReactivation::ElementSets::OverBurden }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorWellLogExtraction::calculatePorePressure( double depth, double gradient ) +{ + return RiaEclipseUnitTools::pascalToBar( gradient * 9.81 * depth * 1000.0 ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationDataAccessorWellLogExtraction::calculateTemperature( double topValue, double topDepth, double depth, double gradient ) +{ + double tvdDiff = topDepth - depth; + return tvdDiff * gradient + topValue; +} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorWellLogExtraction.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorWellLogExtraction.h new file mode 100644 index 0000000000..489309cb68 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationDataAccessorWellLogExtraction.h @@ -0,0 +1,110 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023 - Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RigGriddedPart3d.h" +#include "RimFaultReactivationDataAccessor.h" +#include "RimFaultReactivationEnums.h" + +#include "cvfObject.h" + +#include + +class RigWellPath; +class RigEclipseWellLogExtractor; +class RigEclipseCaseData; +class RigResultAccessor; +class RigGriddedPart3d; + +//================================================================================================== +/// +/// +//================================================================================================== +class RimFaultReactivationDataAccessorWellLogExtraction +{ +public: + RimFaultReactivationDataAccessorWellLogExtraction(); + ~RimFaultReactivationDataAccessorWellLogExtraction(); + + static std::pair calculatePorBar( const RigFaultReactivationModel& model, + RimFaultReactivation::GridPart gridPart, + const std::vector& intersections, + std::vector& values, + const cvf::Vec3d& position, + RimFaultReactivation::ElementSets elementSet, + double gradient ); + + static std::pair calculateTemperature( const std::vector& intersections, + const cvf::Vec3d& position, + double seabedTemperature, + double gradient ); + static std::pair>, + std::map>> + createEclipseWellPathExtractors( const RigFaultReactivationModel& model, RigEclipseCaseData& eclipseCaseData, double seabedDepth ); + + static std::vector generateWellPoints( const cvf::Vec3d& faultTopPosition, + const cvf::Vec3d& faultBottomPosition, + double seabedDepth, + double bottomDepth, + const cvf::Vec3d& offset ); + + static std::vector generateMds( const std::vector& points ); + + static std::pair, std::vector> extractValuesAndIntersections( const RigResultAccessor& resultAccessor, + RigEclipseWellLogExtractor& extractor, + const RigWellPath& wellPath ); + static std::pair findIntersectionsForTvd( const std::vector& intersections, double tvd ); + + static std::pair + findElementSetForPoint( const RigGriddedPart3d& part, + const cvf::Vec3d& point, + const std::map>& elementSets ); + + static int findLastOverburdenIndex( const std::vector& values ); + + static double computeGradient( double depth1, double value1, double depth2, double value2 ); + +protected: + static std::pair findOverburdenAndUnderburdenIndex( const std::vector& values ); + static double computeValueWithGradient( const std::vector& intersections, + const std::vector& values, + int i1, + int i2, + double gradient ); + static void fillInMissingValuesWithGradient( const std::vector& intersections, std::vector& values, double gradient ); + static void fillInMissingValuesWithTopValue( const std::vector& intersections, std::vector& values, double topValue ); + + static std::pair + findValueAndPosition( const std::vector& intersections, const std::vector& values, const cvf::Vec3d& position ); + + static std::vector extractDepthValues( const std::vector& intersections ); + + static void insertUnderburdenValues( const std::vector& intersections, + std::vector& values, + int firstUnderburdenIndex, + double bottomValue ); + static void insertOverburdenValues( const std::vector& intersections, + std::vector& values, + int lastOverburdenIndex, + double topValue ); + static double computeMinimumDistance( const cvf::Vec3d& position, const std::vector& positions ); + + static double calculatePorePressure( double depth, double gradient ); + static double calculateTemperature( double topValue, double topDepth, double depth, double gradient ); +}; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.cpp new file mode 100644 index 0000000000..b32c5b7fb4 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.cpp @@ -0,0 +1,33 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimFaultReactivationEnums.h" + +#include "cafAppEnum.h" + +namespace caf +{ +template <> +void caf::AppEnum::setUp() +{ + addItem( RimFaultReactivation::StressSource::StressFromEclipse, "StressFromEclipse", "Eclipse Model" ); + addItem( RimFaultReactivation::StressSource::StressFromGeoMech, "StressFromGeoMech", "Geo-Mech Model" ); + setDefault( RimFaultReactivation::StressSource::StressFromEclipse ); +} + +} // namespace caf diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.h index e9504aab6c..6bc81eef46 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationEnums.h @@ -38,7 +38,9 @@ enum class BorderSurface enum class Boundary { FarSide, - Bottom + Bottom, + Fault, + Reservoir }; enum class ElementSets @@ -46,7 +48,14 @@ enum class ElementSets OverBurden, UnderBurden, Reservoir, - IntraReservoir + IntraReservoir, + FaultZone +}; + +enum class StressSource +{ + StressFromEclipse, + StressFromGeoMech }; enum class Property diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.cpp index 0ded3a19f1..91c42fec25 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.cpp @@ -19,6 +19,7 @@ #include "RimFaultReactivationModel.h" #include "RiaApplication.h" +#include "RiaFilePathTools.h" #include "RiaPreferences.h" #include "RiaPreferencesGeoMech.h" #include "RiaQDateTimeTools.h" @@ -46,7 +47,6 @@ #include "RimEclipseView.h" #include "RimFaultInView.h" #include "RimFaultInViewCollection.h" -#include "RimFaultReactivationDataAccess.h" #include "RimFaultReactivationEnums.h" #include "RimFaultReactivationTools.h" #include "RimGeoMechCase.h" @@ -82,7 +82,7 @@ RimFaultReactivationModel::RimFaultReactivationModel() CAF_PDM_InitFieldNoDefault( &m_baseDir, "BaseDirectory", "Working Folder" ); CAF_PDM_InitField( &m_modelThickness, "ModelThickness", 100.0, "Model Cell Thickness" ); - CAF_PDM_InitField( &m_modelExtentFromAnchor, "ModelExtentFromAnchor", 3000.0, "Horz. Extent from Anchor" ); + CAF_PDM_InitField( &m_modelExtentFromAnchor, "ModelExtentFromAnchor", 1000.0, "Horz. Extent from Anchor" ); CAF_PDM_InitField( &m_modelMinZ, "ModelMinZ", 0.0, "Seabed Depth" ); CAF_PDM_InitField( &m_modelBelowSize, "ModelBelowSize", 500.0, "Depth Below Fault" ); @@ -96,6 +96,8 @@ RimFaultReactivationModel::RimFaultReactivationModel() CAF_PDM_InitField( &m_faultExtendDownwards, "FaultExtendDownwards", 0.0, "Below Reservoir" ); m_faultExtendDownwards.uiCapability()->setUiEditorTypeName( caf::PdmUiDoubleSliderEditor::uiEditorTypeName() ); + CAF_PDM_InitField( &m_faultZoneCells, "FaultZoneCells", 0, "Fault Zone Width [cells]" ); + CAF_PDM_InitField( &m_showModelPlane, "ShowModelPlane", true, "Show 2D Model" ); CAF_PDM_InitFieldNoDefault( &m_fault, "Fault", "Fault" ); @@ -104,13 +106,14 @@ RimFaultReactivationModel::RimFaultReactivationModel() CAF_PDM_InitField( &m_modelPart1Color, "ModelPart1Color", cvf::Color3f( cvf::Color3f::GREEN ), "Part 1 Color" ); CAF_PDM_InitField( &m_modelPart2Color, "ModelPart2Color", cvf::Color3f( cvf::Color3f::BLUE ), "Part 2 Color" ); - CAF_PDM_InitField( &m_maxReservoirCellHeight, "MaxReservoirCellHeight", 20.0, "Max. Reservoir Cell Height" ); - CAF_PDM_InitField( &m_cellHeightGrowFactor, "CellHeightGrowFactor", 1.05, "Cell Height Grow Factor" ); + CAF_PDM_InitField( &m_maxReservoirCellHeight, "MaxReservoirCellHeight", 5.0, "Max. Reservoir Cell Height" ); + CAF_PDM_InitField( &m_minReservoirCellHeight, "MinReservoirCellHeight", 0.5, "Min. Reservoir Cell Height" ); + CAF_PDM_InitField( &m_cellHeightGrowFactor, "CellHeightGrowFactor", 1.15, "Cell Height Grow Factor" ); - CAF_PDM_InitField( &m_minReservoirCellWidth, "MinReservoirCellWidth", 20.0, "Reservoir Cell Width" ); - CAF_PDM_InitField( &m_cellWidthGrowFactor, "CellWidthGrowFactor", 1.05, "Cell Width Grow Factor" ); + CAF_PDM_InitField( &m_minReservoirCellWidth, "MinReservoirCellWidth", 5.0, "Reservoir Cell Width" ); + CAF_PDM_InitField( &m_cellWidthGrowFactor, "CellWidthGrowFactor", 1.15, "Cell Width Grow Factor" ); - CAF_PDM_InitField( &m_useLocalCoordinates, "UseLocalCoordinates", false, "Export Using Local Coordinates" ); + CAF_PDM_InitField( &m_useLocalCoordinates, "UseLocalCoordinates", true, "Use Local Coordinates" ); // Time Step Selection CAF_PDM_InitFieldNoDefault( &m_timeStepFilter, "TimeStepFilter", "Available Time Steps" ); @@ -123,14 +126,17 @@ RimFaultReactivationModel::RimFaultReactivationModel() CAF_PDM_InitField( &m_useGridTemperature, "UseGridTemperature", true, "Output Grid Temperature" ); CAF_PDM_InitField( &m_useGridDensity, "UseGridDensity", false, "Output Grid Density" ); CAF_PDM_InitField( &m_useGridElasticProperties, "UseGridElasticProperties", false, "Output Grid Elastic Properties" ); - CAF_PDM_InitField( &m_useGridStress, "UseGridStress", false, "Output Grid Stress" ); CAF_PDM_InitField( &m_waterDensity, "WaterDensity", 1030.0, "Water Density [kg/m3]" ); + CAF_PDM_InitField( &m_frictionAngleDeg, "FrictionAngle", 20.0, "Fault Friction Angle [degree]" ); + CAF_PDM_InitField( &m_seabedTemperature, "SeabedTemperature", 5.0, "Seabed Temperature [C]" ); + CAF_PDM_InitField( &m_lateralStressCoefficient, "LateralStressCoefficient", 0.5, "Lateral Stress Coefficient" ); + + CAF_PDM_InitFieldNoDefault( &m_stressSource, "StressSource", "Use Stress from" ); CAF_PDM_InitFieldNoDefault( &m_targets, "Targets", "Targets" ); m_targets.uiCapability()->setUiEditorTypeName( caf::PdmUiTableViewEditor::uiEditorTypeName() ); m_targets.uiCapability()->setUiTreeChildrenHidden( true ); - m_targets.uiCapability()->setUiTreeHidden( true ); m_targets.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); m_targets.uiCapability()->setCustomContextMenuEnabled( false ); @@ -194,21 +200,28 @@ caf::PdmFieldHandle* RimFaultReactivationModel::userDescriptionField() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::pair RimFaultReactivationModel::validateBeforeRun() const +std::pair RimFaultReactivationModel::validateModel() const { + const std::string postStr = ". Please check your model settings."; + if ( fault() == nullptr ) { - return std::make_pair( false, "A fault has not been selected. Please check your model settings." ); + return std::make_pair( false, "A fault has not been selected" + postStr ); } if ( selectedTimeSteps().size() < 2 ) { - return std::make_pair( false, "You need at least 2 selected timesteps. Please check your model settings." ); + return std::make_pair( false, "You need at least 2 selected timesteps" + postStr ); } if ( selectedTimeSteps()[0] != m_availableTimeSteps[0] ) { - return std::make_pair( false, "The first available timestep must always be selected. Please check your model settings." ); + return std::make_pair( false, "The first available timestep must always be selected" + postStr ); + } + + if ( ( m_frictionAngleDeg() <= 0.0 ) || ( m_frictionAngleDeg() >= 90.0 ) ) + { + return std::make_pair( false, "Fault Friction Angle must be between 0 and 90 degrees" + postStr ); } return std::make_pair( true, "" ); @@ -308,22 +321,27 @@ void RimFaultReactivationModel::updateVisualization() if ( !normal.normalize() ) return; auto modelNormal = normal ^ cvf::Vec3d::Z_AXIS; - modelNormal.normalize(); + if ( !modelNormal.normalize() ) return; - auto generator = std::make_shared( m_targets[0]->targetPointXYZ(), modelNormal ); + auto generator = std::make_shared( m_targets[0]->targetPointXYZ(), modelNormal, normal ); generator->setFault( m_fault()->faultGeometry() ); generator->setGrid( eclipseCase()->mainGrid() ); generator->setActiveCellInfo( eclipseCase()->eclipseCaseData()->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL ) ); generator->setModelSize( m_modelMinZ, m_modelBelowSize, m_modelExtentFromAnchor ); - generator->setFaultBufferDepth( m_faultExtendUpwards, m_faultExtendDownwards ); + generator->setFaultBufferDepth( m_faultExtendUpwards, m_faultExtendDownwards, m_faultZoneCells ); generator->setModelThickness( m_modelThickness ); - generator->setModelGriddingOptions( m_maxReservoirCellHeight, m_cellHeightGrowFactor, m_minReservoirCellWidth, m_cellWidthGrowFactor ); + generator->setModelGriddingOptions( m_minReservoirCellHeight, + m_maxReservoirCellHeight, + m_cellHeightGrowFactor, + m_minReservoirCellWidth, + m_cellWidthGrowFactor ); generator->setupLocalCoordinateTransform(); generator->setUseLocalCoordinates( m_useLocalCoordinates ); m_2Dmodel->setPartColors( m_modelPart1Color, m_modelPart2Color ); m_2Dmodel->setGenerator( generator ); m_2Dmodel->updateGeometry( m_startCellIndex, (cvf::StructGridInterface::FaceType)m_startCellFace() ); + m_2Dmodel->postProcessElementSets( eclipseCase() ); view->scheduleCreateDisplayModelAndRedraw(); } @@ -376,6 +394,7 @@ QList RimFaultReactivationModel::calculateValueOptions( else if ( fieldNeedingOptions == &m_geomechCase ) { RimTools::geoMechCaseOptionItems( &options ); + options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); } return options; @@ -425,8 +444,11 @@ void RimFaultReactivationModel::defineUiOrdering( QString uiConfigName, caf::Pdm sizeModelGrp->add( &m_modelExtentFromAnchor ); sizeModelGrp->add( &m_modelMinZ ); sizeModelGrp->add( &m_modelBelowSize ); + sizeModelGrp->add( &m_faultZoneCells ); - if ( m_geomechCase() != nullptr ) + const bool hasGeoMechCase = ( m_geomechCase() != nullptr ); + + if ( hasGeoMechCase ) { m_modelMinZ.setValue( std::abs( m_geomechCase->allCellsBoundingBox().max().z() ) ); m_modelMinZ.uiCapability()->setUiReadOnly( true ); @@ -441,6 +463,7 @@ void RimFaultReactivationModel::defineUiOrdering( QString uiConfigName, caf::Pdm faultGrp->add( &m_faultExtendDownwards ); auto gridModelGrp = modelGrp->addNewGroup( "Grid Definition" ); + gridModelGrp->add( &m_minReservoirCellHeight ); gridModelGrp->add( &m_maxReservoirCellHeight ); gridModelGrp->add( &m_cellHeightGrowFactor ); @@ -463,14 +486,40 @@ void RimFaultReactivationModel::defineUiOrdering( QString uiConfigName, caf::Pdm propertiesGrp->add( &m_useGridPorePressure ); propertiesGrp->add( &m_useGridVoidRatio ); propertiesGrp->add( &m_useGridTemperature ); - propertiesGrp->add( &m_useGridDensity ); - propertiesGrp->add( &m_useGridElasticProperties ); - propertiesGrp->add( &m_useGridStress ); - propertiesGrp->add( &m_waterDensity ); - auto trgGroup = uiOrdering.addNewGroup( "Debug" ); - trgGroup->setCollapsedByDefault(); - trgGroup->add( &m_targets ); + if ( hasGeoMechCase ) + { + propertiesGrp->add( &m_useGridDensity ); + propertiesGrp->add( &m_useGridElasticProperties ); + + bool useTemperatureFromGrid = m_useGridTemperature(); + m_seabedTemperature.uiCapability()->setUiReadOnly( !useTemperatureFromGrid ); + } + + propertiesGrp->add( &m_stressSource ); + if ( hasGeoMechCase ) + { + m_stressSource.uiCapability()->setUiReadOnly( false ); + } + else + { + m_stressSource = RimFaultReactivation::StressSource::StressFromEclipse; + m_stressSource.uiCapability()->setUiReadOnly( true ); + } + + auto parmGrp = propertiesGrp->addNewGroup( "Parameters" ); + + parmGrp->add( &m_frictionAngleDeg ); + if ( m_stressSource() == RimFaultReactivation::StressSource::StressFromEclipse ) + { + parmGrp->add( &m_lateralStressCoefficient ); + } + + if ( hasGeoMechCase ) + { + parmGrp->add( &m_waterDensity ); + parmGrp->add( &m_seabedTemperature ); + } uiOrdering.skipRemainingFields(); } @@ -480,8 +529,9 @@ void RimFaultReactivationModel::defineUiOrdering( QString uiConfigName, caf::Pdm //-------------------------------------------------------------------------------------------------- void RimFaultReactivationModel::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) { - if ( ( changedField == &m_useGridPorePressure ) || ( changedField == &m_useGridVoidRatio ) || ( changedField == &m_useGridTemperature ) || - ( changedField == &m_useGridDensity ) || ( changedField == &m_useGridElasticProperties ) ) + if ( ( changedField == &m_useGridPorePressure ) || ( changedField == &m_useGridVoidRatio ) || + ( changedField == &m_useGridTemperature ) || ( changedField == &m_useGridDensity ) || + ( changedField == &m_useGridElasticProperties ) || ( changedField == &m_waterDensity ) || ( changedField == &m_frictionAngleDeg ) ) { return; // do nothing } @@ -542,22 +592,20 @@ void RimFaultReactivationModel::defineEditorAttribute( const caf::PdmFieldHandle //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimEclipseCase* RimFaultReactivationModel::eclipseCase() +RimEclipseCase* RimFaultReactivationModel::eclipseCase() const { auto eCase = firstAncestorOrThisOfType(); - if ( eCase == nullptr ) - { - eCase = dynamic_cast( RiaApplication::instance()->activeGridView()->ownerCase() ); - } - - return eCase; + if ( eCase != nullptr ) + return eCase; + else + return dynamic_cast( RiaApplication::instance()->activeGridView()->ownerCase() ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimGeoMechCase* RimFaultReactivationModel::geoMechCase() +RimGeoMechCase* RimFaultReactivationModel::geoMechCase() const { return m_geomechCase(); } @@ -586,6 +634,17 @@ void RimFaultReactivationModel::updateTimeSteps() m_availableTimeSteps.clear(); const auto eCase = eclipseCase(); if ( eCase != nullptr ) m_availableTimeSteps = eCase->timeStepDates(); + + int nAvailSteps = (int)m_availableTimeSteps.size(); + + if ( m_selectedTimeSteps().empty() ) + { + std::vector newVal; + if ( nAvailSteps > 0 ) newVal.push_back( m_availableTimeSteps.front() ); + if ( nAvailSteps > 1 ) newVal.push_back( m_availableTimeSteps.back() ); + + m_selectedTimeSteps.setValue( newVal ); + } } //-------------------------------------------------------------------------------------------------- @@ -605,124 +664,85 @@ std::vector RimFaultReactivationModel::selectedTimeSteps() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QStringList RimFaultReactivationModel::commandParameters() const +std::vector RimFaultReactivationModel::selectedTimeStepIndexes() const { - QStringList retlist; - - retlist << baseDir(); - retlist << inputFilename(); - retlist << outputOdbFilename(); + std::vector selectedTimeStepIndexes; + for ( auto& timeStep : selectedTimeSteps() ) + { + auto idx = std::find( m_availableTimeSteps.begin(), m_availableTimeSteps.end(), timeStep ); + if ( idx == m_availableTimeSteps.end() ) return {}; - return retlist; + selectedTimeStepIndexes.push_back( idx - m_availableTimeSteps.begin() ); + } + return selectedTimeStepIndexes; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QString RimFaultReactivationModel::outputOdbFilename() const +QStringList RimFaultReactivationModel::commandParameters() const { - QDir directory( baseDir() ); - return directory.absoluteFilePath( baseFilename() + ".odb" ); + QStringList retlist; + + retlist << baseDir(); + retlist << QString::fromStdString( inputFilename() ); + retlist << QString::fromStdString( outputOdbFilename() ); + + return retlist; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QString RimFaultReactivationModel::inputFilename() const +std::string RimFaultReactivationModel::outputOdbFilename() const { - QDir directory( baseDir() ); - return directory.absoluteFilePath( baseFilename() + ".inp" ); + return baseFilePath() + ".odb"; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QString RimFaultReactivationModel::settingsFilename() const +std::string RimFaultReactivationModel::inputFilename() const { - QDir directory( baseDir() ); - return directory.absoluteFilePath( baseFilename() + ".settings.json" ); + return baseFilePath() + ".inp"; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QString RimFaultReactivationModel::baseFilename() const +std::string RimFaultReactivationModel::settingsFilename() const { - QString tmp = m_userDescription(); - - if ( tmp.isEmpty() ) return "faultReactivation"; - - tmp.replace( ' ', '_' ); - tmp.replace( '/', '_' ); - tmp.replace( '\\', '_' ); - tmp.replace( ':', '_' ); - - return tmp; + return baseFilePath() + ".settings.json"; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationModel::exportModelSettings() +std::string RimFaultReactivationModel::baseFilename() const { - if ( m_2Dmodel.isNull() ) return false; - if ( !m_2Dmodel->isValid() ) return false; - - QMap settings; - - auto [topPosition, bottomPosition] = m_2Dmodel->faultTopBottom(); - auto faultNormal = m_2Dmodel->faultNormal(); - - // make sure we move horizontally, and along the 2D model - faultNormal.z() = 0.0; - faultNormal.normalize(); - faultNormal = faultNormal ^ cvf::Vec3d::Z_AXIS; - - RimFaultReactivationTools::addSettingsToMap( settings, faultNormal, topPosition, bottomPosition ); - - QDir directory( baseDir() ); - return ResInsightInternalJson::JsonWriter::encodeFile( settingsFilename(), settings ); + return RiaFilePathTools::makeSuitableAsFileName( m_userDescription().toStdString() ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationModel::extractAndExportModelData() +std::string RimFaultReactivationModel::baseFilePath() const { - if ( m_dataAccess ) m_dataAccess->clearModelData(); - - if ( !exportModelSettings() ) return false; - - auto eCase = eclipseCase(); - if ( eCase == nullptr ) return false; - - // get the selected time step indexes - std::vector selectedTimeStepIndexes; - for ( auto& timeStep : selectedTimeSteps() ) - { - auto idx = std::find( m_availableTimeSteps.begin(), m_availableTimeSteps.end(), timeStep ); - if ( idx == m_availableTimeSteps.end() ) return false; - - selectedTimeStepIndexes.push_back( idx - m_availableTimeSteps.begin() ); - } - - // extract data for each timestep - m_dataAccess = std::make_shared( eCase, geoMechCase(), selectedTimeStepIndexes ); - m_dataAccess->extractModelData( *model() ); - - return true; + QDir directory( baseDir() ); + return directory.absoluteFilePath( QString::fromStdString( baseFilename() ) ).toStdString(); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::array RimFaultReactivationModel::materialParameters( ElementSets elementSet ) const +std::array RimFaultReactivationModel::materialParameters( ElementSets elementSet ) const { - std::array retVal = { 0.0, 0.0, 0.0 }; + std::array retVal = { 0.0, 0.0, 0.0, 0.0 }; static std::map groupMap = { { ElementSets::OverBurden, "material_overburden" }, { ElementSets::Reservoir, "material_reservoir" }, { ElementSets::IntraReservoir, "material_intrareservoir" }, - { ElementSets::UnderBurden, "material_underburden" } }; + { ElementSets::UnderBurden, "material_underburden" }, + { ElementSets::FaultZone, "material_faultzone" } }; auto keyName = QString::fromStdString( groupMap[elementSet] ); @@ -733,6 +753,7 @@ std::array RimFaultReactivationModel::materialParameters( ElementSets retVal[0] = grp->parameterDoubleValue( "youngs_modulus", 0.0 ); retVal[1] = grp->parameterDoubleValue( "poissons_number", 0.0 ); retVal[2] = grp->parameterDoubleValue( "density", 0.0 ); + retVal[3] = grp->parameterDoubleValue( "expansion", 0.0 ); break; } @@ -743,9 +764,9 @@ std::array RimFaultReactivationModel::materialParameters( ElementSets //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::shared_ptr RimFaultReactivationModel::dataAccess() const +bool RimFaultReactivationModel::useLocalCoordinates() const { - return m_dataAccess; + return m_useLocalCoordinates(); } //-------------------------------------------------------------------------------------------------- @@ -791,9 +812,9 @@ bool RimFaultReactivationModel::useGridElasticProperties() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimFaultReactivationModel::useGridStress() const +RimFaultReactivation::StressSource RimFaultReactivationModel::stressSource() const { - return m_useGridStress(); + return m_stressSource(); } //-------------------------------------------------------------------------------------------------- @@ -804,6 +825,14 @@ double RimFaultReactivationModel::seaBedDepth() const return m_modelMinZ; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationModel::frictionAngleDeg() const +{ + return m_frictionAngleDeg; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -811,3 +840,19 @@ double RimFaultReactivationModel::waterDensity() const { return m_waterDensity; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationModel::seabedTemperature() const +{ + return m_seabedTemperature; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimFaultReactivationModel::lateralStressCoefficient() const +{ + return m_lateralStressCoefficient; +} diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.h b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.h index e3c741b5eb..00de04def1 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.h +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModel.h @@ -18,7 +18,6 @@ #pragma once #include "RimCheckableNamedObject.h" -#include "RimFaultReactivationDataAccess.h" #include "RimFaultReactivationEnums.h" #include "RimPolylinePickerInterface.h" #include "RimPolylinesDataInterface.h" @@ -53,7 +52,6 @@ class RimTimeStepFilter; class RivFaultReactivationModelPartMgr; class RigBasicPlane; class RigFaultReactivationModel; -class RimFaultReactivationDataAccess; namespace cvf { @@ -67,6 +65,7 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly using TimeStepFilterEnum = caf::AppEnum; using ElementSets = RimFaultReactivation::ElementSets; + using StressSourceEnum = caf::AppEnum; public: RimFaultReactivationModel(); @@ -77,7 +76,7 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly QString userDescription(); void setUserDescription( QString description ); - std::pair validateBeforeRun() const; + std::pair validateModel() const; void setFaultInformation( RimFaultInView* fault, size_t cellIndex, cvf::StructGridInterface::FaceType face ); RimFaultInView* fault() const; @@ -102,34 +101,40 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly cvf::ref model() const; bool showModel() const; - bool extractAndExportModelData(); - QString baseDir() const; void setBaseDir( QString path ); std::vector selectedTimeSteps() const; + std::vector selectedTimeStepIndexes() const; - std::array materialParameters( ElementSets elementSet ) const; + std::array materialParameters( ElementSets elementSet ) const; QStringList commandParameters() const; - QString outputOdbFilename() const; - QString inputFilename() const; - QString settingsFilename() const; + std::string outputOdbFilename() const; + std::string inputFilename() const; + std::string settingsFilename() const; + std::string baseFilePath() const; void updateTimeSteps(); - std::shared_ptr dataAccess() const; - bool useGridVoidRatio() const; bool useGridPorePressure() const; bool useGridTemperature() const; bool useGridDensity() const; bool useGridElasticProperties() const; - bool useGridStress() const; + bool useLocalCoordinates() const; double seaBedDepth() const; double waterDensity() const; + double frictionAngleDeg() const; + double seabedTemperature() const; + double lateralStressCoefficient() const; + + RimFaultReactivation::StressSource stressSource() const; + + RimEclipseCase* eclipseCase() const; + RimGeoMechCase* geoMechCase() const; protected: caf::PdmFieldHandle* userDescriptionField() override; @@ -139,12 +144,7 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; - RimEclipseCase* eclipseCase(); - RimGeoMechCase* geoMechCase(); - - QString baseFilename() const; - - bool exportModelSettings(); + std::string baseFilename() const; private: std::shared_ptr m_pickTargetsEventHandler; @@ -169,8 +169,10 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly caf::PdmField m_faultExtendUpwards; caf::PdmField m_faultExtendDownwards; + caf::PdmField m_faultZoneCells; caf::PdmField m_maxReservoirCellHeight; + caf::PdmField m_minReservoirCellHeight; caf::PdmField m_cellHeightGrowFactor; caf::PdmField m_minReservoirCellWidth; caf::PdmField m_cellWidthGrowFactor; @@ -182,9 +184,13 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly caf::PdmField m_useGridTemperature; caf::PdmField m_useGridDensity; caf::PdmField m_useGridElasticProperties; - caf::PdmField m_useGridStress; + + caf::PdmField m_stressSource; caf::PdmField m_waterDensity; + caf::PdmField m_frictionAngleDeg; + caf::PdmField m_seabedTemperature; + caf::PdmField m_lateralStressCoefficient; caf::PdmField m_startCellIndex; caf::PdmField m_startCellFace; @@ -197,6 +203,4 @@ class RimFaultReactivationModel : public RimCheckableNamedObject, public RimPoly caf::PdmChildArrayField m_materialParameters; std::vector m_availableTimeSteps; - - std::shared_ptr m_dataAccess; }; diff --git a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModelCollection.cpp b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModelCollection.cpp index 2659903554..08439b4e05 100644 --- a/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModelCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Faults/RimFaultReactivationModelCollection.cpp @@ -45,7 +45,6 @@ RimFaultReactivationModelCollection::RimFaultReactivationModelCollection() CAF_PDM_InitField( &m_userDescription, "UserDescription", QString( "Fault Reactivation Models" ), "Name" ); CAF_PDM_InitFieldNoDefault( &m_models, "FaultReactivationModels", "Models" ); - m_models.uiCapability()->setUiTreeHidden( true ); m_models.uiCapability()->setUiHidden( true ); setName( "Fault Reactivation Models" ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimFlowCharacteristicsPlot.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimFlowCharacteristicsPlot.cpp index 0313cd03a2..805a5dde6e 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimFlowCharacteristicsPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimFlowCharacteristicsPlot.cpp @@ -78,7 +78,7 @@ RimFlowCharacteristicsPlot::RimFlowCharacteristicsPlot() m_selectedTimeSteps.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_selectedTimeStepsUi, "SelectedTimeStepsUi", "" ); CAF_PDM_InitFieldNoDefault( &m_applyTimeSteps, "ApplyTimeSteps", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_applyTimeSteps ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_applyTimeSteps ); CAF_PDM_InitField( &m_maxPvFraction, "CellPVThreshold", @@ -97,7 +97,7 @@ RimFlowCharacteristicsPlot::RimFlowCharacteristicsPlot() CAF_PDM_InitField( &m_tracerFilter, "TracerFilter", QString(), "Tracer Filter" ); CAF_PDM_InitFieldNoDefault( &m_selectedTracerNames, "SelectedTracerNames", " " ); CAF_PDM_InitFieldNoDefault( &m_showRegion, "ShowRegion", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_showRegion ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_showRegion ); CAF_PDM_InitField( &m_minCommunication, "MinCommunication", 0.0, "Min Communication" ); CAF_PDM_InitField( &m_maxTof, "MaxTof", 146000, "Max Time of Flight [days]" ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimFlowPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimFlowPlotCollection.cpp index 648fef1571..6c11e5468d 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimFlowPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimFlowPlotCollection.cpp @@ -38,19 +38,14 @@ RimFlowPlotCollection::RimFlowPlotCollection() CAF_PDM_InitObject( "Flow Diagnostics Plots", ":/WellAllocPlots16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_flowCharacteristicsPlot, "FlowCharacteristicsPlot", "" ); - m_flowCharacteristicsPlot.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_defaultWellConnectivityTable, "DefaultWellConnectivityTable", "" ); - m_defaultWellConnectivityTable.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_defaultWellAllocOverTimePlot, "DefaultWellAllocationOverTimePlot", "" ); - m_defaultWellAllocOverTimePlot.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_defaultWellAllocPlot, "DefaultWellAllocationPlot", "" ); - m_defaultWellAllocPlot.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wellDistributionPlotCollection, "WellDistributionPlotCollection", "" ); - m_wellDistributionPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_storedWellAllocPlots, "StoredWellAllocationPlots", "Stored Well Allocation Plots" ); CAF_PDM_InitFieldNoDefault( &m_storedFlowCharacteristicsPlots, "StoredFlowCharacteristicsPlots", "Stored Flow Characteristics Plots" ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationOverTimePlot.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationOverTimePlot.cpp index 39d18ae5d4..9d2669b88a 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationOverTimePlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationOverTimePlot.cpp @@ -116,7 +116,7 @@ RimWellAllocationOverTimePlot::RimWellAllocationOverTimePlot() CAF_PDM_InitFieldNoDefault( &m_excludeTimeSteps, "ExcludeTimeSteps", "" ); m_excludeTimeSteps.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_applyTimeStepSelections, "ApplyTimeStepSelections", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_applyTimeStepSelections ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_applyTimeStepSelections ); CAF_PDM_InitFieldNoDefault( &m_flowDiagSolution, "FlowDiagSolution", "Plot Type" ); CAF_PDM_InitFieldNoDefault( &m_flowValueType, "FlowValueType", "Value Type" ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.cpp index 9c72a90eea..b81e7766e6 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.cpp @@ -19,10 +19,12 @@ #include "RimWellAllocationPlot.h" #include "RiaNumericalTools.h" +#include "RiaPlotDefines.h" #include "RiaPreferences.h" #include "RigAccWellFlowCalculator.h" #include "RigEclipseCaseData.h" +#include "RigEclipseCaseDataTools.h" #include "RigFlowDiagResultAddress.h" #include "RigFlowDiagResults.h" #include "RigSimWellData.h" @@ -47,6 +49,7 @@ #include "RimWellLogCurveCommonDataSource.h" #include "RimWellLogLasFile.h" #include "RimWellLogPlot.h" +#include "RimWellLogPlotNameConfig.h" #include "RimWellLogTrack.h" #include "RimWellPlotTools.h" @@ -95,13 +98,12 @@ RimWellAllocationPlot::RimWellAllocationPlot() m_case.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_timeStep, "PlotTimeStep", 0, "Time Step" ); - CAF_PDM_InitField( &m_wellName, "WellName", QString( "None" ), "Well" ); + CAF_PDM_InitField( &m_wellName, "WellName", RiaDefines::selectionTextNone(), "Well" ); CAF_PDM_InitFieldNoDefault( &m_flowDiagSolution, "FlowDiagSolution", "Plot Type" ); CAF_PDM_InitFieldNoDefault( &m_flowType, "FlowType", "Flow Type" ); CAF_PDM_InitField( &m_groupSmallContributions, "GroupSmallContributions", true, "Group Small Contributions" ); CAF_PDM_InitField( &m_smallContributionsThreshold, "SmallContributionsThreshold", 0.005, "Threshold" ); CAF_PDM_InitFieldNoDefault( &m_accumulatedWellFlowPlot, "AccumulatedWellFlowPlot", "Accumulated Well Flow" ); - m_accumulatedWellFlowPlot.uiCapability()->setUiTreeHidden( true ); m_accumulatedWellFlowPlot = new RimWellLogPlot; m_accumulatedWellFlowPlot->setDepthUnit( RiaDefines::DepthUnitType::UNIT_NONE ); m_accumulatedWellFlowPlot->setDepthType( RiaDefines::DepthTypeEnum::CONNECTION_NUMBER ); @@ -109,15 +111,12 @@ RimWellAllocationPlot::RimWellAllocationPlot() m_accumulatedWellFlowPlot->uiCapability()->setUiIconFromResourceString( ":/WellFlowPlot16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_totalWellAllocationPlot, "TotalWellFlowPlot", "Total Well Flow" ); - m_totalWellAllocationPlot.uiCapability()->setUiTreeHidden( true ); m_totalWellAllocationPlot = new RimTotalWellAllocationPlot; CAF_PDM_InitFieldNoDefault( &m_wellAllocationPlotLegend, "WellAllocLegend", "Legend" ); - m_wellAllocationPlotLegend.uiCapability()->setUiTreeHidden( true ); m_wellAllocationPlotLegend = new RimWellAllocationPlotLegend; CAF_PDM_InitFieldNoDefault( &m_tofAccumulatedPhaseFractionsPlot, "TofAccumulatedPhaseFractionsPlot", "TOF Accumulated Phase Fractions" ); - m_tofAccumulatedPhaseFractionsPlot.uiCapability()->setUiTreeHidden( true ); m_tofAccumulatedPhaseFractionsPlot = new RimTofAccumulatedPhaseFractionsPlot; setAsPlotMdiWindow(); @@ -128,6 +127,9 @@ RimWellAllocationPlot::RimWellAllocationPlot() RiaDefines::DepthTypeEnum::PSEUDO_LENGTH } ); m_accumulatedWellFlowPlot->setCommonDataSourceEnabled( false ); + m_accumulatedWellFlowPlot->nameConfig()->setCustomName( "Accumulated Flow Chart" ); + m_accumulatedWellFlowPlot->setNamingMethod( RiaDefines::ObjectNamingMethod::CUSTOM ); + m_accumulatedWellFlowPlot->updateAutoName(); m_showWindow = false; setDeletable( true ); @@ -219,6 +221,52 @@ void RimWellAllocationPlot::deleteViewWidget() } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimWellAllocationPlot::setCase( RimEclipseResultCase* eclipseCase ) +{ + bool emptyPreviousCase = !m_case; + + m_case = eclipseCase; + + if ( m_case ) + { + m_flowDiagSolution = m_case->defaultFlowDiagSolution(); + + if ( emptyPreviousCase ) + { + m_timeStep = (int)( m_case->timeStepDates().size() - 1 ); + } + + m_timeStep = std::min( m_timeStep(), ( (int)m_case->timeStepDates().size() ) - 1 ); + } + else + { + m_flowDiagSolution = nullptr; + m_timeStep = 0; + } + + if ( m_wellName().isEmpty() || m_wellName() == RiaDefines::selectionTextNone() ) + { + auto firstProducer = RigEclipseCaseDataTools::firstProducer( m_case->eclipseCaseData() ); + if ( !firstProducer.isEmpty() ) + { + m_wellName = firstProducer; + } + else + { + std::set sortedWellNames = findSortedWellNames(); + if ( sortedWellNames.empty() ) + m_wellName = RiaDefines::selectionTextNone(); + else if ( sortedWellNames.count( m_wellName() ) == 0 ) + { + m_wellName = *sortedWellNames.begin(); + } + } + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -732,36 +780,26 @@ void RimWellAllocationPlot::fieldChangedByUi( const caf::PdmFieldHandle* changed { RimViewWindow::fieldChangedByUi( changedField, oldValue, newValue ); + if ( changedField == &m_showWindow ) + { + if ( !m_case ) + { + auto resultCases = RimEclipseCaseTools::eclipseResultCases(); + if ( !resultCases.empty() ) + { + setCase( resultCases.front() ); + onLoadDataAndUpdate(); + } + } + } + if ( changedField == &m_userName || changedField == &m_showPlotTitle ) { updateWidgetTitleWindowTitle(); } else if ( changedField == &m_case ) { - if ( m_flowDiagSolution && m_case ) - { - m_flowDiagSolution = m_case->defaultFlowDiagSolution(); - } - else - { - m_flowDiagSolution = nullptr; - } - - if ( !m_case ) - m_timeStep = 0; - else if ( m_timeStep >= static_cast( m_case->timeStepDates().size() ) ) - { - m_timeStep = std::max( 0, ( (int)m_case->timeStepDates().size() ) - 1 ); - } - - std::set sortedWellNames = findSortedWellNames(); - if ( sortedWellNames.empty() ) - m_wellName = ""; - else if ( sortedWellNames.count( m_wellName() ) == 0 ) - { - m_wellName = *sortedWellNames.begin(); - } - + setCase( m_case ); onLoadDataAndUpdate(); } else if ( changedField == &m_wellName || changedField == &m_timeStep || changedField == &m_flowDiagSolution || @@ -849,7 +887,11 @@ void RimWellAllocationPlot::onLoadDataAndUpdate() { updateMdiWindowVisibility(); - if ( !m_case ) return; + if ( !m_case ) + { + m_flowDiagSolution = nullptr; + return; + } // If no 3D view is open, we have to make sure the case is opened if ( !m_case->ensureReservoirCaseIsOpen() ) diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.h b/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.h index 410be11526..f1305f2352 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.h +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellAllocationPlot.h @@ -109,6 +109,7 @@ class RimWellAllocationPlot : public RimViewWindow void onLoadDataAndUpdate() override; private: + void setCase( RimEclipseResultCase* eclipseCase ); void updateFromWell(); void updateWellFlowPlotXAxisTitle( RimWellLogTrack* plotTrack ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellConnectivityTable.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellConnectivityTable.cpp index b5041f26c0..2788a18535 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellConnectivityTable.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellConnectivityTable.cpp @@ -157,7 +157,7 @@ RimWellConnectivityTable::RimWellConnectivityTable() CAF_PDM_InitFieldNoDefault( &m_excludeTimeSteps, "ExcludeTimeSteps", "" ); m_excludeTimeSteps.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_applyTimeStepSelections, "ApplyTimeStepSelections", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_applyTimeStepSelections ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_applyTimeStepSelections ); // Producer/Injector tracer configuration CAF_PDM_InitFieldNoDefault( &m_selectedProducerTracersUiField, "SelectedProducerTracers", "Producer Tracers" ); @@ -169,7 +169,7 @@ RimWellConnectivityTable::RimWellConnectivityTable() CAF_PDM_InitField( &m_syncSelectedProducersFromInjectorSelection, "SyncSelectedInjProd", false, "<- Synch Communicators" ); m_syncSelectedProducersFromInjectorSelection.uiCapability()->setUiEditorTypeName( caf::PdmUiToolButtonEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_applySelectedInectorProducerTracers, "ApplySelectedInectorProducerTracers", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_applySelectedInectorProducerTracers ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_applySelectedInectorProducerTracers ); // Table settings CAF_PDM_InitField( &m_showValueLabels, "ShowValueLabels", false, "Show Value Labels" ); @@ -1291,6 +1291,8 @@ std::vector RimWellConnectivityTable::getViewFilteredWellNamesFromFilte const auto productionWellResultFrame = wellResult->staticWellResultFrame(); for ( const auto& resultPoint : productionWellResultFrame->allResultPoints() ) { + if ( !resultPoint.isCell() ) continue; + if ( cellIdxCalc.isCellVisible( resultPoint.gridIndex(), resultPoint.cellIndex() ) ) { productionWells.push_back( wellResult->m_wellName ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellDistributionPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellDistributionPlotCollection.cpp index ffda3a2717..365c13fc44 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellDistributionPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellDistributionPlotCollection.cpp @@ -70,7 +70,6 @@ RimWellDistributionPlotCollection::RimWellDistributionPlotCollection() CAF_PDM_InitField( &m_maximumTof, "MaximumTOF", 20.0, "Maximum Time of Flight [0, 200]" ); CAF_PDM_InitFieldNoDefault( &m_plots, "Plots", "" ); - m_plots.uiCapability()->setUiTreeHidden( true ); m_plots.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_showOil, "ShowOil", true, "Show Oil" ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.cpp index ae50f33846..66bf0a75ea 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.cpp @@ -78,7 +78,7 @@ class StaticFieldsInitializer //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimWellPlotTools::hasPressureData( const RimWellLogLasFile* wellLogFile ) +bool RimWellPlotTools::hasPressureData( const RimWellLogFile* wellLogFile ) { for ( RimWellLogFileChannel* const wellLogChannel : wellLogFile->wellLogChannels() ) { @@ -92,7 +92,7 @@ bool RimWellPlotTools::hasPressureData( const RimWellLogLasFile* wellLogFile ) //-------------------------------------------------------------------------------------------------- bool RimWellPlotTools::hasPressureData( RimWellPath* wellPath ) { - for ( RimWellLogLasFile* const wellLogFile : wellPath->wellLogFiles() ) + for ( RimWellLogFile* const wellLogFile : wellPath->wellLogFiles() ) { if ( hasPressureData( wellLogFile ) ) { @@ -144,7 +144,7 @@ bool RimWellPlotTools::hasPressureData( RimEclipseResultCase* gridCase ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimWellPlotTools::hasFlowData( const RimWellLogLasFile* wellLogFile ) +bool RimWellPlotTools::hasFlowData( const RimWellLogFile* wellLogFile ) { for ( RimWellLogFileChannel* const wellLogChannel : wellLogFile->wellLogChannels() ) { @@ -158,7 +158,7 @@ bool RimWellPlotTools::hasFlowData( const RimWellLogLasFile* wellLogFile ) //-------------------------------------------------------------------------------------------------- bool RimWellPlotTools::hasFlowData( const RimWellPath* wellPath ) { - for ( RimWellLogLasFile* const wellLogFile : wellPath->wellLogFiles() ) + for ( RimWellLogFile* const wellLogFile : wellPath->wellLogFiles() ) { if ( hasFlowData( wellLogFile ) ) { @@ -268,20 +268,20 @@ void RimWellPlotTools::addTimeStepsToMap( std::map RimWellPlotTools::wellLogFilesContainingPressure( const QString& wellPathNameOrSimWellName ) +std::vector RimWellPlotTools::wellLogFilesContainingPressure( const QString& wellPathNameOrSimWellName ) { - std::vector wellLogFiles; - const RimProject* const project = RimProject::current(); - std::vector wellPaths = project->allWellPaths(); + std::vector wellLogFiles; + const RimProject* const project = RimProject::current(); + std::vector wellPaths = project->allWellPaths(); for ( auto wellPath : wellPaths ) { if ( !wellPathNameOrSimWellName.isEmpty() && ( wellPathNameOrSimWellName == wellPath->associatedSimulationWellName() || wellPathNameOrSimWellName == wellPath->name() ) ) { - const std::vector files = wellPath->wellLogFiles(); + const std::vector files = wellPath->wellLogFiles(); - for ( RimWellLogLasFile* file : files ) + for ( RimWellLogFile* file : files ) { if ( hasPressureData( file ) ) { @@ -297,7 +297,7 @@ std::vector RimWellPlotTools::wellLogFilesContainingPressure //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimWellLogFileChannel* RimWellPlotTools::getPressureChannelFromWellFile( const RimWellLogLasFile* wellLogFile ) +RimWellLogFileChannel* RimWellPlotTools::getPressureChannelFromWellFile( const RimWellLogFile* wellLogFile ) { if ( wellLogFile != nullptr ) { @@ -315,19 +315,19 @@ RimWellLogFileChannel* RimWellPlotTools::getPressureChannelFromWellFile( const R //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RimWellPlotTools::wellLogFilesContainingFlow( const QString& wellPathName ) +std::vector RimWellPlotTools::wellLogFilesContainingFlow( const QString& wellPathName ) { - std::vector wellLogFiles; - const RimProject* const project = RimProject::current(); - std::vector wellPaths = project->allWellPaths(); + std::vector wellLogFiles; + const RimProject* const project = RimProject::current(); + std::vector wellPaths = project->allWellPaths(); for ( auto wellPath : wellPaths ) { if ( wellPath->name() == wellPathName ) { - std::vector files = wellPath->wellLogFiles(); + std::vector files = wellPath->wellLogFiles(); - for ( RimWellLogLasFile* file : files ) + for ( RimWellLogFile* file : files ) { if ( hasFlowData( file ) ) { @@ -342,14 +342,14 @@ std::vector RimWellPlotTools::wellLogFilesContainingFlow( co //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimWellPath* RimWellPlotTools::wellPathFromWellLogFile( const RimWellLogLasFile* wellLogFile ) +RimWellPath* RimWellPlotTools::wellPathFromWellLogFile( const RimWellLogFile* wellLogFile ) { RimProject* const project = RimProject::current(); for ( const auto& oilField : project->oilFields ) { for ( const auto& wellPath : oilField->wellPathCollection()->allWellPaths() ) { - for ( RimWellLogLasFile* const file : wellPath->wellLogFiles() ) + for ( RimWellLogFile* const file : wellPath->wellLogFiles() ) { if ( file == wellLogFile ) { @@ -676,7 +676,7 @@ RiaRftPltCurveDefinition RimWellPlotTools::curveDefFromCurve( const RimWellLogCu } else if ( wellLogFileCurve != nullptr ) { - RimWellLogLasFile* const wellLogFile = wellLogFileCurve->wellLogFile(); + RimWellLogFile* const wellLogFile = wellLogFileCurve->wellLogFile(); if ( wellLogFile != nullptr ) { @@ -684,7 +684,10 @@ RiaRftPltCurveDefinition RimWellPlotTools::curveDefFromCurve( const RimWellLogCu if ( date.isValid() ) { - return RiaRftPltCurveDefinition( RifDataSourceForRftPlt( wellLogFile ), wellLogFile->wellName(), date ); + if ( auto wellLogLasFile = dynamic_cast( wellLogFile ) ) + { + return RiaRftPltCurveDefinition( RifDataSourceForRftPlt( wellLogLasFile ), wellLogFile->wellName(), date ); + } } } } diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.h b/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.h index db83992e72..8ff2ccbb8a 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.h +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellPlotTools.h @@ -75,24 +75,24 @@ class RimWellPlotTools static bool isTotalFlowChannel( const QString& channelName ); static FlowPhase flowPhaseFromChannelName( const QString& channelName ); - static std::vector wellLogFilesContainingFlow( const QString& wellName ); - static RimWellPath* wellPathByWellPathNameOrSimWellName( const QString& wellPathNameOrSimwellName ); + static std::vector wellLogFilesContainingFlow( const QString& wellName ); + static RimWellPath* wellPathByWellPathNameOrSimWellName( const QString& wellPathNameOrSimwellName ); // RFT Only private: static std::pair pressureResultDataInfo( const RigEclipseCaseData* eclipseCaseData ); public: - static void addTimeStepsToMap( std::map>& destMap, - const std::map>& timeStepsToAdd ); - static std::vector wellLogFilesContainingPressure( const QString& wellPathNameOrSimWellName ); - static RimWellLogFileChannel* getPressureChannelFromWellFile( const RimWellLogLasFile* wellLogFile ); - static RimWellPath* wellPathFromWellLogFile( const RimWellLogLasFile* wellLogFile ); + static void addTimeStepsToMap( std::map>& destMap, + const std::map>& timeStepsToAdd ); + static std::vector wellLogFilesContainingPressure( const QString& wellPathNameOrSimWellName ); + static RimWellLogFileChannel* getPressureChannelFromWellFile( const RimWellLogFile* wellLogFile ); + static RimWellPath* wellPathFromWellLogFile( const RimWellLogFile* wellLogFile ); static std::map> timeStepsMapFromGridCase( RimEclipseCase* gridCase ); static RiaRftPltCurveDefinition curveDefFromCurve( const RimWellLogCurve* curve ); // others - static bool hasFlowData( const RimWellLogLasFile* wellLogFile ); + static bool hasFlowData( const RimWellLogFile* wellLogFile ); static bool hasAssociatedWellPath( const QString& wellName ); // Both @@ -145,7 +145,7 @@ class RimWellPlotTools static std::set FLOW_DATA_NAMES; - static bool hasPressureData( const RimWellLogLasFile* wellLogFile ); + static bool hasPressureData( const RimWellLogFile* wellLogFile ); static bool isPressureChannel( RimWellLogFileChannel* channel ); static bool hasPressureData( RimEclipseResultCase* gridCase ); static bool hasPressureData( RimWellPath* wellPath ); diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellPltPlot.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellPltPlot.cpp index 43c06c9bb8..f3bc1ec6a2 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellPltPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellPltPlot.cpp @@ -48,6 +48,7 @@ #include "RimSummaryCurveAppearanceCalculator.h" #include "RimWellFlowRateCurve.h" #include "RimWellLogExtractionCurve.h" +#include "RimWellLogFile.h" #include "RimWellLogFileChannel.h" #include "RimWellLogLasFile.h" #include "RimWellLogLasFileCurve.h" @@ -104,7 +105,6 @@ RimWellPltPlot::RimWellPltPlot() CAF_PDM_InitObject( "Well Allocation Plot", ":/WellFlowPlot16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_wellLogPlot_OBSOLETE, "WellLog", "WellLog" ); - m_wellLogPlot_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_wellLogPlot_OBSOLETE.xmlCapability()->setIOWritable( false ); CAF_PDM_InitFieldNoDefault( &m_wellPathName, "WellName", "Well Name" ); @@ -116,7 +116,6 @@ RimWellPltPlot::RimWellPltPlot() m_selectedSources.xmlCapability()->disableIO(); CAF_PDM_InitFieldNoDefault( &m_selectedSourcesForIo, "Sources", "Sources" ); - m_selectedSourcesForIo.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_selectedTimeSteps, "TimeSteps", "Time Steps" ); m_selectedTimeSteps.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); @@ -780,10 +779,13 @@ QList RimWellPltPlot::calculateValueOptions( const caf:: for ( const auto& wellLogFile : wellLogFiles ) { - auto addr = RifDataSourceForRftPlt( wellLogFile ); - auto item = caf::PdmOptionItemInfo( wellLogFile->name(), QVariant::fromValue( addr ) ); - item.setLevel( 1 ); - options.push_back( item ); + if ( auto wellLogLasFile = dynamic_cast( wellLogFile ) ) + { + auto addr = RifDataSourceForRftPlt( wellLogLasFile ); + auto item = caf::PdmOptionItemInfo( wellLogFile->name(), QVariant::fromValue( addr ) ); + item.setLevel( 1 ); + options.push_back( item ); + } } } } @@ -994,8 +996,11 @@ void RimWellPltPlot::initAfterLoad() { for ( const auto& wellLogFile : wellLogFiles ) { - auto addr = RifDataSourceForRftPlt( wellLogFile ); - selectedSources.push_back( addr ); + if ( auto wellLogLasFile = dynamic_cast( wellLogFile ) ) + { + auto addr = RifDataSourceForRftPlt( wellLogLasFile ); + selectedSources.push_back( addr ); + } } } diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.cpp index 55a431292a..1c368d3566 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.cpp @@ -31,7 +31,6 @@ #include "RiuQwtPlotWidget.h" #include "cafPdmUiObjectHandle.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeOrdering.h" #include "cafPdmUiTreeSelectionEditor.h" @@ -167,7 +166,7 @@ std::vector RimWellRftEnsembleCurveSet::parametersWithVariation() const //-------------------------------------------------------------------------------------------------- void RimWellRftEnsembleCurveSet::clearEnsembleStatistics() { - m_statisticsEclipseRftReader = new RifReaderEnsembleStatisticsRft( m_ensemble(), m_eclipseCase() ); + m_statisticsEclipseRftReader = std::make_unique( m_ensemble(), m_eclipseCase() ); } //-------------------------------------------------------------------------------------------------- @@ -227,7 +226,7 @@ RimEclipseCase* RimWellRftEnsembleCurveSet::eclipseCase() const //-------------------------------------------------------------------------------------------------- RifReaderRftInterface* RimWellRftEnsembleCurveSet::statisticsEclipseRftReader() { - return m_statisticsEclipseRftReader.p(); + return m_statisticsEclipseRftReader.get(); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.h b/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.h index 9ee889010e..ceabd9ac59 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.h +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftEnsembleCurveSet.h @@ -87,7 +87,7 @@ class RimWellRftEnsembleCurveSet : public caf::PdmObject caf::PdmField m_ensembleParameter; caf::PdmChildField m_ensembleLegendConfig; - cvf::ref m_statisticsEclipseRftReader; + std::unique_ptr m_statisticsEclipseRftReader; protected: void initAfterRead() override; diff --git a/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftPlot.cpp b/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftPlot.cpp index 86882e2e1f..03f64193e9 100644 --- a/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Flow/RimWellRftPlot.cpp @@ -25,8 +25,6 @@ #include "RiaSimWellBranchTools.h" #include "RiaSummaryTools.h" -#include "RicImportGridModelFromSummaryCaseFeature.h" - #include "RifReaderEclipseRft.h" #include "RigCaseCellResultsData.h" @@ -44,6 +42,7 @@ #include "RimPressureDepthData.h" #include "RimProject.h" #include "RimRegularLegendConfig.h" +#include "RimReloadCaseTools.h" #include "RimSummaryCase.h" #include "RimSummaryCaseCollection.h" #include "RimTools.h" @@ -96,7 +95,6 @@ RimWellRftPlot::RimWellRftPlot() CAF_PDM_InitField( &m_showErrorInObservedData, "ShowErrorObserved", true, "Show Observed Data Error" ); CAF_PDM_InitFieldNoDefault( &m_wellLogPlot_OBSOLETE, "WellLog", "Well Log" ); - m_wellLogPlot_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_wellLogPlot_OBSOLETE.xmlCapability()->setIOWritable( false ); m_depthType = RiaDefines::DepthTypeEnum::TRUE_VERTICAL_DEPTH; @@ -295,12 +293,15 @@ void RimWellRftPlot::applyInitialSelections( std::variant wellLogFiles = RimWellPlotTools::wellLogFilesContainingPressure( m_wellPathNameOrSimWellName ); + std::vector wellLogFiles = RimWellPlotTools::wellLogFilesContainingPressure( m_wellPathNameOrSimWellName ); if ( !wellLogFiles.empty() ) { - for ( RimWellLogLasFile* const wellLogFile : wellLogFiles ) + for ( RimWellLogFile* const wellLogFile : wellLogFiles ) { - sourcesToSelect.push_back( RifDataSourceForRftPlt( wellLogFile ) ); + if ( auto wellLogLasFile = dynamic_cast( wellLogFile ) ) + { + sourcesToSelect.push_back( RifDataSourceForRftPlt( wellLogLasFile ) ); + } } } @@ -722,9 +723,12 @@ std::vector RimWellRftPlot::selectedSourcesExpanded() co { if ( addr.sourceType() == RifDataSourceForRftPlt::SourceType::OBSERVED_LAS_FILE ) { - for ( RimWellLogLasFile* const wellLogFile : RimWellPlotTools::wellLogFilesContainingPressure( m_wellPathNameOrSimWellName ) ) + for ( RimWellLogFile* const wellLogFile : RimWellPlotTools::wellLogFilesContainingPressure( m_wellPathNameOrSimWellName ) ) { - sources.push_back( RifDataSourceForRftPlt( wellLogFile ) ); + if ( auto wellLogLasFile = dynamic_cast( wellLogFile ) ) + { + sources.push_back( RifDataSourceForRftPlt( wellLogLasFile ) ); + } } } else @@ -896,7 +900,7 @@ QList RimWellRftPlot::calculateValueOptionsForSources() { if ( summaryCase->rftReader() && summaryCase->rftReader()->wellNames().contains( m_wellPathNameOrSimWellName ) ) { - auto eclipeGridModel = RicImportGridModelFromSummaryCaseFeature::gridModelFromSummaryCase( summaryCase ); + auto eclipeGridModel = RimReloadCaseTools::gridModelFromSummaryCase( summaryCase ); auto parentEnsemble = summaryCase->firstAncestorOrThisOfType(); auto addr = RifDataSourceForRftPlt( summaryCase, parentEnsemble, eclipeGridModel ); @@ -932,10 +936,13 @@ QList RimWellRftPlot::calculateValueOptionsForSources() for ( const auto& wellLogFile : wellLogFiles ) { - auto addr = RifDataSourceForRftPlt( wellLogFile ); - auto item = caf::PdmOptionItemInfo( "Observed Data", QVariant::fromValue( addr ) ); - item.setLevel( 1 ); - options.push_back( item ); + if ( auto wellLogLasFile = dynamic_cast( wellLogFile ) ) + { + auto addr = RifDataSourceForRftPlt( wellLogLasFile ); + auto item = caf::PdmOptionItemInfo( "Observed Data", QVariant::fromValue( addr ) ); + item.setLevel( 1 ); + options.push_back( item ); + } } } const std::vector observedFmuRftCases = RimWellPlotTools::observedFmuRftDataForWell( m_wellPathNameOrSimWellName ); diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCase.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCase.cpp index e1c5879a14..ee72f023b1 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCase.cpp @@ -63,6 +63,7 @@ #include "cvfVector3.h" +#include #include #include @@ -106,7 +107,6 @@ RimGeoMechCase::RimGeoMechCase() "The Abaqus Based GeoMech Case" ); CAF_PDM_InitScriptableFieldWithScriptKeywordNoDefault( &geoMechViews, "GeoMechViews", "Views", "", "", "", "All GeoMech Views in the Case" ); - geoMechViews.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_cohesion, "CaseCohesion", 10.0, "Cohesion", "", "Used to calculate the SE:SFI result", "" ); CAF_PDM_InitField( &m_frictionAngleDeg, "FrctionAngleDeg", 30.0, "Friction Angle [Deg]", "", "Used to calculate the SE:SFI result", "" ); @@ -117,13 +117,13 @@ RimGeoMechCase::RimGeoMechCase() m_elementPropertyFileNameIndexUiSelection.xmlCapability()->disableIO(); CAF_PDM_InitField( &m_importElementPropertyFileCommand, "importElementPropertyFileCommad", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_importElementPropertyFileCommand ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_importElementPropertyFileCommand ); CAF_PDM_InitField( &m_closeElementPropertyFileCommand, "closeElementPropertyFileCommad", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_closeElementPropertyFileCommand ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_closeElementPropertyFileCommand ); CAF_PDM_InitField( &m_reloadElementPropertyFileCommand, "reloadElementPropertyFileCommand", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_reloadElementPropertyFileCommand ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_reloadElementPropertyFileCommand ); caf::AppEnum defaultBiotCoefficientType = RimGeoMechCase::BiotCoefficientType::BIOT_NONE; CAF_PDM_InitField( &m_biotCoefficientType, "BiotCoefficientType", defaultBiotCoefficientType, "Biot Coefficient" ); @@ -147,11 +147,9 @@ RimGeoMechCase::RimGeoMechCase() CAF_PDM_InitFieldNoDefault( &m_contourMapCollection, "ContourMaps", "2d Contour Maps" ); m_contourMapCollection = new RimGeoMechContourMapViewCollection; - m_contourMapCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_mudWeightWindowParameters, "MudWeightWindowParameters", "Mud Weight Window Parameters" ); m_mudWeightWindowParameters = new RimMudWeightWindowParameters; - m_mudWeightWindowParameters.uiCapability()->setUiTreeHidden( true ); m_displayNameOption = RimCaseDisplayNameTools::DisplayName::CUSTOM; m_displayNameOption.uiCapability()->setUiHidden( true ); @@ -1067,7 +1065,7 @@ void RimGeoMechCase::reloadSelectedElementPropertyFiles() //-------------------------------------------------------------------------------------------------- void RimGeoMechCase::importElementPropertyFile() { - RicImportElementPropertyFeature::importElementProperties(); + RicImportElementPropertyFeature::importElementProperties( this ); } //-------------------------------------------------------------------------------------------------- @@ -1125,15 +1123,15 @@ void RimGeoMechCase::defineEditorAttribute( const caf::PdmFieldHandle* field, QS { if ( field == &m_importElementPropertyFileCommand ) { - dynamic_cast( attribute )->m_buttonText = "Import Element Property"; + dynamic_cast( attribute )->m_buttonText = "Import New Element Property"; } if ( field == &m_reloadElementPropertyFileCommand ) { - dynamic_cast( attribute )->m_buttonText = "Reload Element Property"; + dynamic_cast( attribute )->m_buttonText = "Reload Selected Properties"; } if ( field == &m_closeElementPropertyFileCommand ) { - dynamic_cast( attribute )->m_buttonText = "Close Element Property"; + dynamic_cast( attribute )->m_buttonText = "Close Selected Properties"; } if ( field == &m_biotFixedCoefficient ) @@ -1160,7 +1158,7 @@ QList RimGeoMechCase::calculateValueOptions( const caf:: { for ( size_t i = 0; i < m_elementPropertyFileNames.v().size(); i++ ) { - options.push_back( caf::PdmOptionItemInfo( m_elementPropertyFileNames.v().at( i ).path(), (int)i, true ) ); + options.push_back( caf::PdmOptionItemInfo( m_elementPropertyFileNames.v().at( i ).path(), (int)i, false ) ); } } else if ( fieldNeedingOptions == &m_biotResultAddress || fieldNeedingOptions == &m_initialPermeabilityResultAddress ) diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCellColors.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCellColors.cpp index 7ca434b2f9..4219273eea 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCellColors.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechCellColors.cpp @@ -34,7 +34,6 @@ RimGeoMechCellColors::RimGeoMechCellColors() { CAF_PDM_InitFieldNoDefault( &legendConfig, "LegendDefinition", "Color Legend" ); legendConfig = new RimRegularLegendConfig(); - legendConfig.uiCapability()->setUiTreeHidden( true ); legendConfig->changed.connect( this, &RimGeoMechCellColors::onLegendConfigChanged ); } diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapProjection.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapProjection.cpp index 3fad4a4409..5e8d3946b8 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapProjection.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapProjection.cpp @@ -161,7 +161,8 @@ cvf::ref RimGeoMechContourMapProjection::getCellVisibility() co cellRangeFilter, &indexIncludeVis, &indexExcludeVis, - view()->cellFilterCollection()->hasActiveIncludeIndexFilters() ); + view()->cellFilterCollection()->hasActiveIncludeIndexFilters(), + view()->cellFilterCollection()->useAndOperation() ); } if ( view()->propertyFilterCollection()->isActive() ) { @@ -451,9 +452,7 @@ RimGridView* RimGeoMechContourMapProjection::baseView() const //-------------------------------------------------------------------------------------------------- std::vector RimGeoMechContourMapProjection::findIntersectingCells( const cvf::BoundingBox& bbox ) const { - std::vector allCellIndices; - m_femPart->findIntersectingElementsWithExistingSearchTree( bbox, &allCellIndices ); - return allCellIndices; + return m_femPart->findIntersectingElementsWithExistingSearchTree( bbox ); } //-------------------------------------------------------------------------------------------------- @@ -542,7 +541,7 @@ std::vector RimGeoMechContourMapProjection::gridCellValues( RigFemResult for ( size_t globalCellIdx = 0; globalCellIdx < static_cast( m_femPart->elementCount() ); ++globalCellIdx ) { RigElementType elmType = m_femPart->elementType( globalCellIdx ); - if ( elmType != HEX8 && elmType != HEX8P ) continue; + if ( !RigFemTypes::is8NodeElement( elmType ) ) continue; if ( resAddr.resultPosType == RIG_ELEMENT ) { diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapViewCollection.cpp index 90cb7b6de1..1041d6b6a7 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechContourMapViewCollection.cpp @@ -13,7 +13,6 @@ RimGeoMechContourMapViewCollection::RimGeoMechContourMapViewCollection() CAF_PDM_InitObject( "GeoMech Contour Maps", ":/2DMaps16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_contourMapViews, "GeoMechViews", "Contour Maps", ":/CrossSection16x16.png" ); - m_contourMapViews.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.cpp index 7097456810..511c115e5c 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.cpp @@ -29,7 +29,6 @@ #include "RigFemPartCollection.h" #include "RigGeoMechCaseData.h" -#include "RigHexIntersectionTools.h" #include "RigReservoirGridTools.h" #include "RimFaultReactivationTools.h" @@ -75,7 +74,7 @@ RimGeoMechFaultReactivationResult::RimGeoMechFaultReactivationResult() CAF_PDM_InitField( &m_distanceFromFault, "DistanceFromFault", 5.0, "Distance From Fault" ); CAF_PDM_InitFieldNoDefault( &m_createFaultReactivationPlot, "CreateReactivationPlot", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_createFaultReactivationPlot ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_createFaultReactivationPlot ); CAF_PDM_InitFieldNoDefault( &m_faultNormal, "FaultNormal", "" ); CAF_PDM_InitFieldNoDefault( &m_faultTopPosition, "FaultTopPosition", "" ); @@ -253,8 +252,8 @@ void RimGeoMechFaultReactivationResult::createWellGeometry() m_faceBWellPath->createWellPathGeometry(); // Detect which part well path centers are in - m_faceAWellPathPartIndex = getPartIndexFromPoint( geoMechPartCollection, partATop ); - m_faceBWellPathPartIndex = getPartIndexFromPoint( geoMechPartCollection, partBTop ); + m_faceAWellPathPartIndex = geoMechPartCollection->getPartIndexFromPoint( partATop ); + m_faceBWellPathPartIndex = geoMechPartCollection->getPartIndexFromPoint( partBTop ); // Update UI wellPathCollection->uiCapability()->updateConnectedEditors(); @@ -325,39 +324,6 @@ void RimGeoMechFaultReactivationResult::createWellLogCurves() m_faceBWellPathPartIndex() ); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int RimGeoMechFaultReactivationResult::getPartIndexFromPoint( const RigFemPartCollection* const partCollection, const cvf::Vec3d& point ) const -{ - const int idx = 0; - if ( !partCollection ) return idx; - - // Find candidates for intersected global elements - const cvf::BoundingBox intersectingBb( point, point ); - std::vector intersectedGlobalElementIndexCandidates; - partCollection->findIntersectingGlobalElementIndices( intersectingBb, &intersectedGlobalElementIndexCandidates ); - - if ( intersectedGlobalElementIndexCandidates.empty() ) return idx; - - // Iterate through global element candidates and check if point is in hexCorners - for ( const auto& globalElementIndex : intersectedGlobalElementIndexCandidates ) - { - const auto [part, elementIndex] = partCollection->partAndElementIndex( globalElementIndex ); - - // Find nodes from element - std::array coordinates; - const bool isSuccess = part->fillElementCoordinates( elementIndex, coordinates ); - if ( !isSuccess ) continue; - - const bool isPointInCell = RigHexIntersectionTools::isPointInCell( point, coordinates.data() ); - if ( isPointInCell ) return part->elementPartId(); - } - - // Utilize first part to have an id - return idx; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.h b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.h index 13fa6b1555..f3f01845d3 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.h +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechFaultReactivationResult.h @@ -58,8 +58,6 @@ class RimGeoMechFaultReactivationResult : public caf::PdmObject void createWellGeometry(); void createWellLogCurves(); - int getPartIndexFromPoint( const RigFemPartCollection* const partCollection, const cvf::Vec3d& point ) const; - RimWellLogExtractionCurve* createWellLogExtractionCurveAndAddToTrack( RimWellLogTrack* track, const RigFemResultAddress& resultAddress, RimModeledWellPath* wellPath, diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechModels.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechModels.cpp index 559e572cef..fa89d0162b 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechModels.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechModels.cpp @@ -37,7 +37,6 @@ RimGeoMechModels::RimGeoMechModels() CAF_PDM_InitObject( "Geomechanical Models", ":/GeoMechCases48x48.png" ); CAF_PDM_InitFieldNoDefault( &m_cases, "Cases", "" ); - m_cases.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechPartCollection.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechPartCollection.cpp index bdf0646c2e..b820c7bc6d 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechPartCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechPartCollection.cpp @@ -44,7 +44,6 @@ RimGeoMechPartCollection::RimGeoMechPartCollection() CAF_PDM_InitScriptableObject( "Parts", ":/GeoMechCase24x24.png" ); CAF_PDM_InitScriptableFieldNoDefault( &m_parts, "Parts", "Parts" ); - m_parts.uiCapability()->setUiTreeHidden( true ); setDeletable( false ); } diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechResultDefinition.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechResultDefinition.cpp index 169715bb35..f3c91c25ca 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechResultDefinition.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechResultDefinition.cpp @@ -271,7 +271,7 @@ QList RimGeoMechResultDefinition::calculateValueOptions( { if ( m_geomCase->geoMechData() ) { - size_t kCount = m_geomCase->geoMechData()->femParts()->part( 0 )->getOrCreateStructGrid()->gridPointCountK() - 1; + size_t kCount = m_geomCase->geoMechData()->femParts()->part( 0 )->getOrCreateStructGrid()->cellCountK(); for ( size_t layerIdx = 0; layerIdx < kCount; ++layerIdx ) { options.push_back( caf::PdmOptionItemInfo( QString::number( layerIdx + 1 ), (int)layerIdx ) ); diff --git a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechView.cpp b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechView.cpp index 74fb3adce7..293eea1334 100644 --- a/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechView.cpp +++ b/ApplicationLibCode/ProjectDataModel/GeoMech/RimGeoMechView.cpp @@ -19,6 +19,7 @@ #include "RimGeoMechView.h" +#include "RiaApplication.h" #include "RiaLogging.h" #include "RiaPreferences.h" #include "RiaRegressionTestRunner.h" @@ -31,6 +32,7 @@ #include "RigFormationNames.h" #include "RigGeoMechCaseData.h" +#include "Polygons/RimPolygonInViewCollection.h" #include "Rim3dOverlayInfoConfig.h" #include "RimCellFilterCollection.h" #include "RimEclipseResultDefinition.h" @@ -93,22 +95,18 @@ RimGeoMechView::RimGeoMechView() CAF_PDM_InitFieldNoDefault( &cellResult, "GridCellResult", "Color Result", ":/CellResult.png" ); cellResult = new RimGeoMechCellColors(); - cellResult.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_tensorResults, "TensorResults", "Tensor Results" ); m_tensorResults = new RimTensorResults(); - m_tensorResults.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_faultReactivationResult, "FaultReactivationResult", "Fault Reactivation Result" ); m_faultReactivationResult = new RimGeoMechFaultReactivationResult(); CAF_PDM_InitFieldNoDefault( &m_propertyFilterCollection, "PropertyFilters", "Property Filters" ); m_propertyFilterCollection = new RimGeoMechPropertyFilterCollection(); - m_propertyFilterCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_partsCollection, "Parts", "Parts" ); m_partsCollection = new RimGeoMechPartCollection(); - m_partsCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_showDisplacement, "ShowDisplacement", false, "Show Displacement" ); CAF_PDM_InitField( &m_displacementScaling, "DisplacementScaling", 1.0, "Scaling Factor" ); @@ -157,7 +155,7 @@ void RimGeoMechView::onLoadDataAndUpdate() onUpdateScaleTransform(); - updateSurfacesInViewTreeItems(); + updateViewTreeItems( RiaDefines::ItemIn3dView::ALL ); if ( m_geomechCase ) { @@ -323,6 +321,9 @@ void RimGeoMechView::onCreateDisplayModel() m_seismicSectionCollection->appendPartsToModel( this, m_seismicVizModel.p(), transform.p(), femBBox ); nativeOrOverrideViewer()->addStaticModelOnce( m_seismicVizModel.p(), isUsingOverrideViewer() ); + // Polygons + appendPolygonPartsToModel( transform.p(), ownerCase()->allCellsBoundingBox() ); + // Surfaces m_surfaceVizModel->removeAllParts(); @@ -1047,6 +1048,8 @@ void RimGeoMechView::defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrderin if ( surfaceInViewCollection() ) uiTreeOrdering.add( surfaceInViewCollection() ); if ( seismicSectionCollection()->shouldBeVisibleInTree() ) uiTreeOrdering.add( seismicSectionCollection() ); + uiTreeOrdering.add( m_polygonInViewCollection ); + uiTreeOrdering.skipRemainingChildren( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellFilterCollection.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellFilterCollection.cpp index 6b4285c69e..fe4ce06393 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellFilterCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellFilterCollection.cpp @@ -31,7 +31,6 @@ RimPlotCellFilterCollection::RimPlotCellFilterCollection() CAF_PDM_InitObject( "Plot Cell Filters" ); CAF_PDM_InitFieldNoDefault( &m_cellFilters, "CellFilters", "Cell Filters" ); - m_cellFilters.uiCapability()->setUiTreeHidden( true ); setName( "Filter Collection" ); } diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellPropertyFilter.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellPropertyFilter.cpp index 7ebb04711f..91c23b0ef4 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellPropertyFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/CellFilters/RimPlotCellPropertyFilter.cpp @@ -47,7 +47,6 @@ RimPlotCellPropertyFilter::RimPlotCellPropertyFilter() // Set to hidden to avoid this item to been displayed as a child item // Fields in this object are displayed using defineUiOrdering() - m_resultDefinition.uiCapability()->setUiTreeHidden( true ); m_resultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_lowerBound, "LowerBound", 0.0, "Min" ); diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlot.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlot.cpp index 826ce4dde6..7154c02f8a 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlot.cpp @@ -58,18 +58,15 @@ RimGridCrossPlot::RimGridCrossPlot() CAF_PDM_InitField( &m_showInfoBox, "ShowInfoBox", true, "Show Info Box" ); CAF_PDM_InitFieldNoDefault( &m_nameConfig, "NameConfig", "Name Config" ); - m_nameConfig.uiCapability()->setUiTreeHidden( true ); m_nameConfig.uiCapability()->setUiTreeChildrenHidden( true ); m_nameConfig = new RimGridCrossPlotNameConfig(); CAF_PDM_InitFieldNoDefault( &m_xAxisProperties, "xAxisProperties", "X Axis" ); - m_xAxisProperties.uiCapability()->setUiTreeHidden( true ); m_xAxisProperties = new RimPlotAxisProperties; m_xAxisProperties->setNameAndAxis( "X-Axis", "X-Axis", RiaDefines::PlotAxis::PLOT_AXIS_BOTTOM ); m_xAxisProperties->setEnableTitleTextSettings( false ); CAF_PDM_InitFieldNoDefault( &m_yAxisProperties, "yAxisProperties", "Y Axis" ); - m_yAxisProperties.uiCapability()->setUiTreeHidden( true ); m_yAxisProperties = new RimPlotAxisProperties; m_yAxisProperties->setNameAndAxis( "Y-Axis", "Y-Axis", RiaDefines::PlotAxis::PLOT_AXIS_LEFT ); m_yAxisProperties->setEnableTitleTextSettings( false ); @@ -78,7 +75,6 @@ RimGridCrossPlot::RimGridCrossPlot() connectAxisSignals( m_yAxisProperties() ); CAF_PDM_InitFieldNoDefault( &m_crossPlotDataSets, "CrossPlotCurve", "Cross Plot Data Set" ); - m_crossPlotDataSets.uiCapability()->setUiTreeHidden( true ); setDeletable( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotCollection.cpp index 37177b830b..e60eca9681 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotCollection.cpp @@ -30,7 +30,6 @@ RimGridCrossPlotCollection::RimGridCrossPlotCollection() CAF_PDM_InitObject( "Grid Cross Plots", ":/SummaryXPlotsLight16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_gridCrossPlots, "GridCrossPlots", "Grid Cross Plots" ); - m_gridCrossPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotDataSet.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotDataSet.cpp index 8d52f7d19a..977fd86dac 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotDataSet.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotDataSet.cpp @@ -100,13 +100,11 @@ RimGridCrossPlotDataSet::RimGridCrossPlotDataSet() CAF_PDM_InitFieldNoDefault( &m_xAxisProperty, "XAxisProperty", "X-Axis Property" ); m_xAxisProperty = new RimEclipseResultDefinition( caf::PdmUiItemInfo::TOP ); - m_xAxisProperty.uiCapability()->setUiTreeHidden( true ); m_xAxisProperty.uiCapability()->setUiTreeChildrenHidden( true ); m_xAxisProperty->setTernaryEnabled( false ); CAF_PDM_InitFieldNoDefault( &m_yAxisProperty, "YAxisProperty", "Y-Axis Property" ); m_yAxisProperty = new RimEclipseResultDefinition( caf::PdmUiItemInfo::TOP ); - m_yAxisProperty.uiCapability()->setUiTreeHidden( true ); m_yAxisProperty.uiCapability()->setUiTreeChildrenHidden( true ); m_yAxisProperty->setTernaryEnabled( false ); @@ -114,18 +112,15 @@ RimGridCrossPlotDataSet::RimGridCrossPlotDataSet() CAF_PDM_InitFieldNoDefault( &m_groupingProperty, "GroupingProperty", "Data Grouping Property" ); m_groupingProperty = new RimEclipseCellColors; m_groupingProperty->useDiscreteLogLevels( true ); - m_groupingProperty.uiCapability()->setUiTreeHidden( true ); CVF_ASSERT( m_groupingProperty->legendConfig() ); m_groupingProperty->legendConfig()->setMappingMode( RimRegularLegendConfig::MappingType::CATEGORY_INTEGER ); m_groupingProperty->setTernaryEnabled( false ); CAF_PDM_InitFieldNoDefault( &m_nameConfig, "NameConfig", "Name" ); m_nameConfig = new RimGridCrossPlotDataSetNameConfig(); - m_nameConfig.uiCapability()->setUiTreeHidden( true ); m_nameConfig.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_crossPlotCurves, "CrossPlotCurves", "Curves" ); - m_crossPlotCurves.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_crossPlotRegressionCurves, "CrossPlotRegressionCurves", "Regression Curves", ":/regression-curve.svg" ); @@ -133,7 +128,6 @@ RimGridCrossPlotDataSet::RimGridCrossPlotDataSet() CAF_PDM_InitField( &m_customColor, "CustomColor", cvf::Color3f( cvf::Color3f::BLACK ), "Custom Color" ); CAF_PDM_InitFieldNoDefault( &m_plotCellFilterCollection, "PlotCellFilterCollection", "Cell Filters" ); - m_plotCellFilterCollection.uiCapability()->setUiTreeHidden( true ); m_plotCellFilterCollection.uiCapability()->setUiTreeChildrenHidden( true ); m_plotCellFilterCollection = new RimPlotCellFilterCollection; diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotRegressionCurve.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotRegressionCurve.cpp index 2d6d73e0fb..a1197a59a9 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotRegressionCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimGridCrossPlotRegressionCurve.cpp @@ -108,7 +108,6 @@ RimGridCrossPlotRegressionCurve::RimGridCrossPlotRegressionCurve() auto rectAnnotation = new RimPlotRectAnnotation; rectAnnotation->setName( "Data Selection" ); m_rectAnnotations.push_back( rectAnnotation ); - m_rectAnnotations.uiCapability()->setUiTreeHidden( true ); m_rectAnnotations.uiCapability()->setUiTreeChildrenHidden( true ); setCheckState( false ); diff --git a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimSaturationPressurePlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimSaturationPressurePlotCollection.cpp index a725e6f5b8..d22ed8db8a 100644 --- a/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimSaturationPressurePlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/GridCrossPlots/RimSaturationPressurePlotCollection.cpp @@ -37,7 +37,6 @@ RimSaturationPressurePlotCollection::RimSaturationPressurePlotCollection() CAF_PDM_InitObject( "Saturation Pressure Plots", ":/SummaryXPlotsLight16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_saturationPressurePlots, "SaturationPressurePlots", "Saturation Pressure Plots" ); - m_saturationPressurePlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimBoxIntersection.cpp b/ApplicationLibCode/ProjectDataModel/Intersections/RimBoxIntersection.cpp index 6cc32f71c3..3633f6a7f1 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimBoxIntersection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimBoxIntersection.cpp @@ -91,7 +91,7 @@ RimBoxIntersection::RimBoxIntersection() CAF_PDM_InitField( &m_depthSliderStepSize, "DepthSliderStepSize", 0.5, "Depth Slider Step Size" ); CAF_PDM_InitFieldNoDefault( &m_show3DManipulator, "show3DManipulator", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_show3DManipulator ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_show3DManipulator ); m_show3DManipulator = false; setDeletable( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.cpp b/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.cpp index 01a3d57286..b8cbb0d76f 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.cpp @@ -21,22 +21,20 @@ #include "RiaVec3Tools.h" -#include "RigEclipseCaseData.h" #include "RigMainGrid.h" +#include "RigPolyLinesData.h" +#include "RigSimulationWellCenterLineCalculator.h" #include "RigWellPath.h" +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonCollection.h" +#include "Polygons/RimPolygonTools.h" + #include "Rim2dIntersectionView.h" #include "Rim3dView.h" #include "RimCase.h" -#include "RimEclipseCase.h" #include "RimEclipseView.h" -#include "RimEnsembleSurface.h" #include "RimGeoMechView.h" -#include "RimGridView.h" -#include "RimIntersectionResultDefinition.h" -#include "RimIntersectionResultsDefinitionCollection.h" -#include "RimOilField.h" -#include "RimProject.h" #include "RimSimWellInView.h" #include "RimSimWellInViewCollection.h" #include "RimSurface.h" @@ -47,12 +45,8 @@ #include "RimTools.h" #include "RimWellPath.h" -#include "RiuViewer.h" - #include "RivExtrudedCurveIntersectionPartMgr.h" -#include "cafCmdFeature.h" -#include "cafCmdFeatureManager.h" #include "cafPdmFieldScriptingCapability.h" #include "cafPdmFieldScriptingCapabilityCvfVec3d.h" #include "cafPdmObjectScriptingCapability.h" @@ -60,12 +54,9 @@ #include "cafPdmUiDoubleSliderEditor.h" #include "cafPdmUiListEditor.h" #include "cafPdmUiPushButtonEditor.h" -#include "cafPdmUiSliderEditor.h" #include "cafPdmUiTreeOrdering.h" -#include "cafPdmUiTreeSelectionEditor.h" #include "cvfBoundingBox.h" #include "cvfGeometryTools.h" -#include "cvfPlane.h" namespace caf { @@ -76,6 +67,7 @@ void caf::AppEnum::setUp() addItem( RimExtrudedCurveIntersection::CrossSectionEnum::CS_SIMULATION_WELL, "CS_SIMULATION_WELL", "Simulation Well" ); addItem( RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYLINE, "CS_POLYLINE", "Polyline" ); addItem( RimExtrudedCurveIntersection::CrossSectionEnum::CS_AZIMUTHLINE, "CS_AZIMUTHLINE", "Azimuth and Dip" ); + addItem( RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYGON, "CS_POLYGON", "Project Polygon" ); setDefault( RimExtrudedCurveIntersection::CrossSectionEnum::CS_POLYLINE ); } @@ -185,6 +177,17 @@ void RimExtrudedCurveIntersection::configureForPolyLine() m_inputPolylineFromViewerEnabled = true; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimExtrudedCurveIntersection::configureForProjectPolyLine( RimPolygon* polygon ) +{ + m_type = CrossSectionEnum::CS_POLYGON; + m_projectPolygon = polygon; + + updateName(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -206,6 +209,11 @@ RimExtrudedCurveIntersection::RimExtrudedCurveIntersection() CAF_PDM_InitFieldNoDefault( &m_direction, "Direction", "Direction" ); CAF_PDM_InitScriptableFieldNoDefault( &m_wellPath, "WellPath", "Well Path " ); CAF_PDM_InitScriptableFieldNoDefault( &m_simulationWell, "SimulationWell", "Simulation Well" ); + + CAF_PDM_InitFieldNoDefault( &m_projectPolygon, "ProjectPolygon", "Project Polygon" ); + CAF_PDM_InitField( &m_editPolygonButton, "EditPolygonButton", false, "Edit" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_editPolygonButton ); + CAF_PDM_InitScriptableFieldNoDefault( &m_userPolylineXyz, "Points", "Points", "", "Use Ctrl-C for copy and Ctrl-V for paste", "" ); CAF_PDM_InitFieldNoDefault( &m_userPolylineXydForUi, "PointsUi", "Points", "", "Use Ctrl-C for copy and Ctrl-V for paste", "" ); @@ -232,15 +240,15 @@ RimExtrudedCurveIntersection::RimExtrudedCurveIntersection() CAF_PDM_InitField( &m_lengthDown, "lengthDown", 1000.0, "Length Down" ); CAF_PDM_InitFieldNoDefault( &m_inputPolylineFromViewerEnabled, "m_activateUiAppendPointsCommand", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_inputPolylineFromViewerEnabled ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_inputPolylineFromViewerEnabled ); m_inputPolylineFromViewerEnabled = false; CAF_PDM_InitFieldNoDefault( &m_inputExtrusionPointsFromViewerEnabled, "inputExtrusionPointsFromViewerEnabled", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_inputExtrusionPointsFromViewerEnabled ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_inputExtrusionPointsFromViewerEnabled ); m_inputExtrusionPointsFromViewerEnabled = false; CAF_PDM_InitFieldNoDefault( &m_inputTwoAzimuthPointsFromViewerEnabled, "inputTwoAzimuthPointsFromViewerEnabled", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_inputTwoAzimuthPointsFromViewerEnabled ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_inputTwoAzimuthPointsFromViewerEnabled ); m_inputTwoAzimuthPointsFromViewerEnabled = false; CAF_PDM_InitFieldNoDefault( &m_surfaceIntersections, "SurfaceIntersections", "Surface Intersections" ); @@ -438,21 +446,22 @@ void RimExtrudedCurveIntersection::setKFilterOverride( bool collectionOverride, void RimExtrudedCurveIntersection::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) { if ( changedField == &m_isActive || changedField == &m_type || changedField == &m_direction || changedField == &m_wellPath || - changedField == &m_simulationWell || changedField == &m_branchIndex || changedField == &m_extentLength || - changedField == &m_lengthUp || changedField == &m_lengthDown || changedField == &m_showInactiveCells || - changedField == &m_useSeparateDataSource || changedField == &m_separateDataSource || changedField == &m_depthUpperThreshold || - changedField == &m_depthLowerThreshold || changedField == &m_depthThresholdOverridden || changedField == &m_depthFilterType || - changedField == &m_enableKFilter || changedField == &m_kFilterText || changedField == &m_kFilterCollectionOverride ) + changedField == &m_simulationWell || changedField == &m_branchIndex || changedField == &m_extentLength || changedField == &m_lengthUp || + changedField == &m_lengthDown || changedField == &m_showInactiveCells || changedField == &m_useSeparateDataSource || + changedField == &m_separateDataSource || changedField == &m_depthUpperThreshold || changedField == &m_depthLowerThreshold || + changedField == &m_depthThresholdOverridden || changedField == &m_depthFilterType || changedField == &m_enableKFilter || + changedField == &m_kFilterText || changedField == &m_kFilterCollectionOverride || changedField == &m_projectPolygon ) { rebuildGeometryAndScheduleCreateDisplayModel(); } if ( changedField == &m_simulationWell || changedField == &m_isActive || changedField == &m_type ) { - recomputeSimulationWellBranchData(); + rebuildGeometryAndScheduleCreateDisplayModel(); } - if ( changedField == &m_simulationWell || changedField == &m_wellPath || changedField == &m_branchIndex ) + if ( changedField == &m_simulationWell || changedField == &m_wellPath || changedField == &m_branchIndex || + changedField == &m_projectPolygon || changedField == &m_type ) { updateName(); } @@ -510,6 +519,15 @@ void RimExtrudedCurveIntersection::fieldChangedByUi( const caf::PdmFieldHandle* { rebuildGeometryAndScheduleCreateDisplayModel(); } + + if ( changedField == &m_editPolygonButton ) + { + RimPolygonTools::activate3dEditOfPolygonInView( m_projectPolygon(), this ); + + m_editPolygonButton = false; + + return; + } } //-------------------------------------------------------------------------------------------------- @@ -528,10 +546,14 @@ void RimExtrudedCurveIntersection::defineUiOrdering( QString uiConfigName, caf:: else if ( type() == CrossSectionEnum::CS_SIMULATION_WELL ) { geometryGroup->add( &m_simulationWell ); - updateSimulationWellCenterline(); - if ( m_simulationWell() && m_simulationWellBranchCenterlines.size() > 1 ) + + if ( m_simulationWell() ) { - geometryGroup->add( &m_branchIndex ); + auto branchCenterLines = simulationWellBranchCenterlines(); + if ( branchCenterLines.size() > 1 ) + { + geometryGroup->add( &m_branchIndex ); + } } } else if ( type() == CrossSectionEnum::CS_POLYLINE ) @@ -539,6 +561,11 @@ void RimExtrudedCurveIntersection::defineUiOrdering( QString uiConfigName, caf:: geometryGroup->add( &m_userPolylineXydForUi ); geometryGroup->add( &m_inputPolylineFromViewerEnabled ); } + else if ( type() == CrossSectionEnum::CS_POLYGON ) + { + geometryGroup->add( &m_projectPolygon ); + geometryGroup->add( &m_editPolygonButton, { .newRow = false } ); + } else if ( type() == CrossSectionEnum::CS_AZIMUTHLINE ) { geometryGroup->add( &m_twoAzimuthPoints ); @@ -667,11 +694,23 @@ QList RimExtrudedCurveIntersection::calculateValueOption options.push_front( caf::PdmOptionItemInfo( "None", nullptr ) ); } } - else if ( fieldNeedingOptions == &m_branchIndex ) + else if ( fieldNeedingOptions == &m_projectPolygon ) { - updateSimulationWellCenterline(); + options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); - size_t branchCount = m_simulationWellBranchCenterlines.size(); + RimTools::polygonOptionItems( &options ); + + if ( m_projectPolygon() == nullptr ) + { + auto polygonCollection = RimTools::polygonCollection(); + auto polygons = polygonCollection->allPolygons(); + if ( !polygons.empty() ) m_projectPolygon = polygons.front(); + } + } + else if ( fieldNeedingOptions == &m_branchIndex ) + { + auto branchCenterLines = simulationWellBranchCenterlines(); + size_t branchCount = branchCenterLines.size(); options.push_back( caf::PdmOptionItemInfo( "All", -1 ) ); @@ -774,18 +813,18 @@ std::vector> RimExtrudedCurveIntersection::polyLines( cv { if ( m_simulationWell() ) { - updateSimulationWellCenterline(); - int branchIndexToUse = branchIndex(); - if ( 0 <= branchIndexToUse && branchIndexToUse < static_cast( m_simulationWellBranchCenterlines.size() ) ) + auto branchCenterLines = simulationWellBranchCenterlines(); + + if ( 0 <= branchIndexToUse && branchIndexToUse < static_cast( branchCenterLines.size() ) ) { - lines.push_back( m_simulationWellBranchCenterlines[branchIndexToUse] ); + lines.push_back( branchCenterLines[branchIndexToUse] ); } if ( branchIndexToUse == -1 ) { - lines = m_simulationWellBranchCenterlines; + lines = branchCenterLines; } } } @@ -793,6 +832,13 @@ std::vector> RimExtrudedCurveIntersection::polyLines( cv { lines.push_back( m_userPolylineXyz ); } + else if ( type() == CrossSectionEnum::CS_POLYGON ) + { + if ( m_projectPolygon ) + { + lines = m_projectPolygon->polyLinesData()->completePolyLines(); + } + } else if ( type() == CrossSectionEnum::CS_AZIMUTHLINE ) { lines.push_back( m_twoAzimuthPoints ); @@ -859,28 +905,6 @@ std::vector RimExtrudedCurveIntersection::polyLinesForExtrusionDirec return m_customExtrusionPoints; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimExtrudedCurveIntersection::updateSimulationWellCenterline() const -{ - if ( m_isActive() && type() == CrossSectionEnum::CS_SIMULATION_WELL && m_simulationWell() ) - { - if ( m_simulationWellBranchCenterlines.empty() ) - { - auto branches = m_simulationWell->wellPipeBranches(); - for ( const auto& branch : branches ) - { - m_simulationWellBranchCenterlines.push_back( branch->wellPathPoints() ); - } - } - } - else - { - m_simulationWellBranchCenterlines.clear(); - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -954,6 +978,10 @@ void RimExtrudedCurveIntersection::updateName() { m_name = m_wellPath()->name(); } + else if ( m_type() == CrossSectionEnum::CS_POLYGON && m_projectPolygon() ) + { + m_name = m_projectPolygon->name(); + } Rim2dIntersectionView* iView = correspondingIntersectionView(); if ( iView ) @@ -975,7 +1003,8 @@ int RimExtrudedCurveIntersection::branchIndex() const return -1; } - if ( m_branchIndex >= static_cast( m_simulationWellBranchCenterlines.size() ) ) + auto branchCenterLines = simulationWellBranchCenterlines(); + if ( m_branchIndex >= static_cast( branchCenterLines.size() ) ) { return -1; } @@ -1081,6 +1110,14 @@ void RimExtrudedCurveIntersection::defineEditorAttribute( const caf::PdmFieldHan { setBaseColor( m_inputExtrusionPointsFromViewerEnabled, dynamic_cast( attribute ) ); } + + if ( field == &m_editPolygonButton ) + { + if ( auto attrib = dynamic_cast( attribute ) ) + { + attrib->m_buttonText = "Edit"; + } + } } //-------------------------------------------------------------------------------------------------- @@ -1227,20 +1264,6 @@ double RimExtrudedCurveIntersection::extentLength() return m_extentLength(); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimExtrudedCurveIntersection::recomputeSimulationWellBranchData() -{ - if ( m_type() == CrossSectionEnum::CS_SIMULATION_WELL ) - { - m_simulationWellBranchCenterlines.clear(); - updateSimulationWellCenterline(); - - m_crossSectionPartMgr = nullptr; - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -1374,3 +1397,16 @@ RimEclipseView* RimExtrudedCurveIntersection::eclipseView() const { return firstAncestorOrThisOfType(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector> RimExtrudedCurveIntersection::simulationWellBranchCenterlines() const +{ + if ( !m_simulationWell() ) return {}; + + const auto simWells = m_simulationWell()->wellBranchesForVisualization(); + const auto& [branchCenterLines, wellCells] = RigSimulationWellCenterLineCalculator::extractBranchData( simWells ); + + return branchCenterLines; +} diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.h b/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.h index f4de75e8ae..5e0388b90a 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.h +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimExtrudedCurveIntersection.h @@ -24,9 +24,10 @@ #include "RimIntersectionEnums.h" #include "cafPdmChildField.h" +#include "cafPdmFieldCvfVec3d.h" #include "cafPdmProxyValueField.h" -#include +#include "cvfVector3.h" class RimWellPath; class RivExtrudedCurveIntersectionPartMgr; @@ -40,6 +41,7 @@ class RimSurfaceCollection; class RimSurfaceIntersectionCollection; class RimSurfaceIntersectionCurve; class RimSurfaceIntersectionBand; +class RimPolygon; namespace caf { @@ -62,7 +64,8 @@ class RimExtrudedCurveIntersection : public RimIntersection CS_WELL_PATH, CS_SIMULATION_WELL, CS_POLYLINE, - CS_AZIMUTHLINE + CS_AZIMUTHLINE, + CS_POLYGON, }; enum class CrossSectionDirEnum @@ -102,6 +105,7 @@ class RimExtrudedCurveIntersection : public RimIntersection void configureForSimulationWell( RimSimWellInView* simWell ); void configureForWellPath( RimWellPath* wellPath ); void configureForPolyLine(); + void configureForProjectPolyLine( RimPolygon* polygon ); void configureForAzimuthLine(); std::vector> polyLines( cvf::Vec3d* flattenedPolylineStartPoint = nullptr ) const; @@ -123,7 +127,6 @@ class RimExtrudedCurveIntersection : public RimIntersection void setLengthUp( double heightUp ); void setLengthDown( double heightDown ); double extentLength(); - void recomputeSimulationWellBranchData(); bool hasDefiningPoints() const; std::vector surfaceIntersectionCurves() const; @@ -134,7 +137,7 @@ class RimExtrudedCurveIntersection : public RimIntersection int branchIndex() const; void rebuildGeometryAndScheduleCreateDisplayModel(); -protected: +private: caf::PdmFieldHandle* userDescriptionField() final; void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; @@ -143,13 +146,11 @@ class RimExtrudedCurveIntersection : public RimIntersection void defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, QString uiConfigName = "" ) override; -private: static void setPushButtonText( bool buttonEnable, caf::PdmUiPushButtonEditorAttribute* attribute ); static void setBaseColor( bool enable, caf::PdmUiListEditorAttribute* attribute ); RimSimWellInViewCollection* simulationWellCollection() const; void updateAzimuthLine(); - void updateSimulationWellCenterline() const; void addExtents( std::vector& polyLine ) const; void updateName(); static double azimuthInRadians( cvf::Vec3d vec ); @@ -163,6 +164,8 @@ class RimExtrudedCurveIntersection : public RimIntersection RimEclipseView* eclipseView() const; + std::vector> simulationWellBranchCenterlines() const; + private: caf::PdmField m_name; @@ -181,6 +184,9 @@ class RimExtrudedCurveIntersection : public RimIntersection caf::PdmPtrField m_wellPath; caf::PdmPtrField m_simulationWell; + caf::PdmPtrField m_projectPolygon; + caf::PdmField m_editPolygonButton; + caf::PdmField m_inputPolylineFromViewerEnabled; caf::PdmField m_inputExtrusionPointsFromViewerEnabled; caf::PdmField m_inputTwoAzimuthPointsFromViewerEnabled; @@ -202,7 +208,7 @@ class RimExtrudedCurveIntersection : public RimIntersection cvf::ref m_crossSectionPartMgr; - mutable std::vector> m_simulationWellBranchCenterlines; + std::vector> m_simulationWellBranchCenterlines; caf::PdmField m_enableKFilter; caf::PdmField m_kFilterText; diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.cpp b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.cpp index a5226cf1a5..5eabceaf88 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.cpp @@ -19,7 +19,6 @@ #include "RimIntersection.h" #include "RigEclipseCaseData.h" -#include "RigFemPartCollection.h" #include "RigGeoMechCaseData.h" #include "RimEclipseCase.h" #include "RimEclipseResultDefinition.h" diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.h b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.h index e94d2ff776..df8b70d7ba 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.h +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersection.h @@ -18,7 +18,6 @@ #pragma once #include "cafPdmField.h" -#include "cafPdmFieldCvfVec3d.h" #include "cafPdmObject.h" #include "cafPdmPtrField.h" diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.cpp b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.cpp index 0d9e0847d6..3157f32f49 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.cpp @@ -56,10 +56,8 @@ RimIntersectionCollection::RimIntersectionCollection() CAF_PDM_InitScriptableObject( "Intersections", ":/CrossSections16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_intersections, "CrossSections", "Intersections" ); - m_intersections.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_intersectionBoxes, "IntersectionBoxes", "IntersectionBoxes" ); - m_intersectionBoxes.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_isActive, "Active", true, "Active" ); m_isActive.uiCapability()->setUiHidden( true ); @@ -297,17 +295,6 @@ std::vector RimIntersectionCollection::intersectionBoxes() return m_intersectionBoxes.childrenByType(); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimIntersectionCollection::recomputeSimWellBranchData() -{ - for ( const auto& intersection : intersections() ) - { - intersection->recomputeSimulationWellBranchData(); - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.h b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.h index a634f2e2d9..47e67d35e9 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.h +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionCollection.h @@ -68,7 +68,6 @@ class RimIntersectionCollection : public caf::PdmObject void syncronize2dIntersectionViews(); void scheduleCreateDisplayModelAndRedraw2dIntersectionViews(); - void recomputeSimWellBranchData(); bool shouldApplyCellFiltersToIntersections() const; diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultDefinition.cpp b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultDefinition.cpp index a0c19daddf..1aded30af6 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultDefinition.cpp +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultDefinition.cpp @@ -60,22 +60,18 @@ RimIntersectionResultDefinition::RimIntersectionResultDefinition() m_autoName.xmlCapability()->setIOWritable( false ); CAF_PDM_InitFieldNoDefault( &m_eclipseResultDefinition, "EclipseResultDef", "EclipseResultDef" ); - m_eclipseResultDefinition.uiCapability()->setUiTreeHidden( true ); m_eclipseResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_eclipseResultDefinition = new RimEclipseResultDefinition; CAF_PDM_InitFieldNoDefault( &m_geomResultDefinition, "GeoMechResultDef", "GeoMechResultDef" ); - m_geomResultDefinition.uiCapability()->setUiTreeHidden( true ); m_geomResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_geomResultDefinition = new RimGeoMechResultDefinition; CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendConfig", "Legend" ); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); m_legendConfig.uiCapability()->setUiTreeChildrenHidden( false ); m_legendConfig = new RimRegularLegendConfig; CAF_PDM_InitFieldNoDefault( &m_ternaryLegendConfig, "TernaryLegendConfig", "Legend" ); - m_ternaryLegendConfig.uiCapability()->setUiTreeHidden( true ); m_ternaryLegendConfig.uiCapability()->setUiTreeChildrenHidden( false ); m_ternaryLegendConfig = new RimTernaryLegendConfig; diff --git a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultsDefinitionCollection.cpp b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultsDefinitionCollection.cpp index 360db3bc0d..adaa8a426c 100644 --- a/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultsDefinitionCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Intersections/RimIntersectionResultsDefinitionCollection.cpp @@ -36,7 +36,6 @@ RimIntersectionResultsDefinitionCollection::RimIntersectionResultsDefinitionColl m_isActive.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_intersectionResultsDefs, "IntersectionResultDefinitions", "Data Sources" ); - m_intersectionResultsDefs.uiCapability()->setUiTreeHidden( true ); m_intersectionResultsDefs.push_back( new RimIntersectionResultDefinition ); // Add the default result definition } diff --git a/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterGroup.cpp b/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterGroup.cpp index 376b89d331..b9621e763a 100644 --- a/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterGroup.cpp +++ b/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterGroup.cpp @@ -72,7 +72,6 @@ RimParameterGroup::RimParameterGroup() CAF_PDM_InitFieldNoDefault( &m_lists, "ParameterLists", "Parameter Lists" ); m_lists.uiCapability()->setUiHidden( true ); - m_lists.uiCapability()->setUiTreeHidden( true ); m_lists.uiCapability()->setUiTreeChildrenHidden( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterList.cpp b/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterList.cpp index 174b6012cd..1a2af30762 100644 --- a/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterList.cpp +++ b/ApplicationLibCode/ProjectDataModel/Parameters/RimParameterList.cpp @@ -34,7 +34,6 @@ RimParameterList::RimParameterList() CAF_PDM_InitFieldNoDefault( &m_parameterNames, "ParameterNames", "Parameters" ); m_parameterNames.uiCapability()->setUiHidden( true ); - m_parameterNames.uiCapability()->setUiTreeHidden( true ); m_parameterNames.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_name, "Name", QString(), "Name" ); diff --git a/ApplicationLibCode/ProjectDataModel/PlotTemplates/RimPlotTemplateFolderItem.cpp b/ApplicationLibCode/ProjectDataModel/PlotTemplates/RimPlotTemplateFolderItem.cpp index fd63167e95..252b3da043 100644 --- a/ApplicationLibCode/ProjectDataModel/PlotTemplates/RimPlotTemplateFolderItem.cpp +++ b/ApplicationLibCode/ProjectDataModel/PlotTemplates/RimPlotTemplateFolderItem.cpp @@ -40,9 +40,7 @@ RimPlotTemplateFolderItem::RimPlotTemplateFolderItem() CAF_PDM_InitFieldNoDefault( &m_folderName, "FolderName", "Folder" ); m_folderName.uiCapability()->setUiReadOnly( true ); CAF_PDM_InitFieldNoDefault( &m_fileNames, "FileNames", "" ); - m_fileNames.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_subFolders, "SubFolders", "" ); - m_subFolders.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/CMakeLists_files.cmake b/ApplicationLibCode/ProjectDataModel/Polygons/CMakeLists_files.cmake new file mode 100644 index 0000000000..ace8580f7d --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/CMakeLists_files.cmake @@ -0,0 +1,29 @@ +set(SOURCE_GROUP_HEADER_FILES + ${CMAKE_CURRENT_LIST_DIR}/RimPolygon.h + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonFile.h + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonCollection.h + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonInView.h + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonInViewCollection.h + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonAppearance.h + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonTools.h +) + +set(SOURCE_GROUP_SOURCE_FILES + ${CMAKE_CURRENT_LIST_DIR}/RimPolygon.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonFile.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonCollection.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonInView.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonInViewCollection.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonAppearance.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimPolygonTools.cpp +) + +list(APPEND CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) + +list(APPEND CODE_SOURCE_FILES ${SOURCE_GROUP_SOURCE_FILES}) + +source_group( + "ProjectDataModel\\Polygons" + FILES ${SOURCE_GROUP_HEADER_FILES} ${SOURCE_GROUP_SOURCE_FILES} + ${CMAKE_CURRENT_LIST_DIR}/CMakeLists_files.cmake +) diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygon.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygon.cpp new file mode 100644 index 0000000000..3865b86be9 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygon.cpp @@ -0,0 +1,282 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygon.h" + +#include "RiaApplication.h" +#include "RiaColorTools.h" + +#include "RigPolyLinesData.h" + +#include "Rim3dView.h" +#include "RimPolygonAppearance.h" +#include "RimPolygonTools.h" + +#include "RiuGuiTheme.h" + +#include "cafCmdFeatureMenuBuilder.h" +#include "cafPdmUiColorEditor.h" +#include "cafPdmUiPushButtonEditor.h" +#include "cafPdmUiTreeAttributes.h" + +CAF_PDM_SOURCE_INIT( RimPolygon, "RimPolygon" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygon::RimPolygon() + : objectChanged( this ) + , coordinatesChanged( this ) +{ + CAF_PDM_InitObject( "Polygon", ":/PolylinesFromFile16x16.png" ); + + CAF_PDM_InitField( &m_isReadOnly, "IsReadOnly", false, "Read Only" ); + CAF_PDM_InitFieldNoDefault( &m_pointsInDomainCoords, "PointsInDomainCoords", "Points" ); + + CAF_PDM_InitField( &m_editPolygonButton, "EditPolygonButton", false, "Edit" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_editPolygonButton ); + + CAF_PDM_InitFieldNoDefault( &m_appearance, "Appearance", "Appearance" ); + m_appearance = new RimPolygonAppearance; + m_appearance.uiCapability()->setUiTreeChildrenHidden( true ); + + setDeletable( true ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref RimPolygon::polyLinesData() const +{ + cvf::ref pld = new RigPolyLinesData; + + pld->setPolyLine( m_pointsInDomainCoords() ); + m_appearance->applyAppearanceSettings( pld.p() ); + + return pld; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::uiOrderingForLocalPolygon( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + m_appearance->uiOrdering( uiConfigName, uiOrdering ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const +{ + RimPolygon::appendPolygonMenuItems( menuBuilder ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::setPointsInDomainCoords( const std::vector& points ) +{ + m_pointsInDomainCoords = points; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygon::pointsInDomainCoords() const +{ + return m_pointsInDomainCoords(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::setIsClosed( bool isClosed ) +{ + m_appearance->setIsClosed( isClosed ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygon::isClosed() const +{ + return m_appearance->isClosed(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::setReadOnly( bool isReadOnly ) +{ + m_isReadOnly = isReadOnly; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygon::isReadOnly() const +{ + return m_isReadOnly(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::disableStorageOfPolygonPoints() +{ + m_pointsInDomainCoords.xmlCapability()->setIOWritable( false ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Color3f RimPolygon::color() const +{ + return m_appearance->lineColor(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::setColor( const cvf::Color3f& color ) +{ + m_appearance->setLineColor( color ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( nameField() ); + uiOrdering.add( &m_isReadOnly ); + uiOrdering.add( &m_editPolygonButton ); + + auto groupPoints = uiOrdering.addNewGroup( "Points" ); + groupPoints->setCollapsedByDefault(); + groupPoints->add( &m_pointsInDomainCoords ); + + m_pointsInDomainCoords.uiCapability()->setUiReadOnly( m_isReadOnly() ); + + auto group = uiOrdering.addNewGroup( "Appearance" ); + m_appearance->uiOrdering( uiConfigName, *group ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + if ( changedField == &m_pointsInDomainCoords ) + { + coordinatesChanged.send(); + objectChanged.send(); + } + + if ( changedField == &m_editPolygonButton ) + { + auto activeView = RiaApplication::instance()->activeReservoirView(); + RimPolygonTools::activate3dEditOfPolygonInView( this, activeView ); + + m_editPolygonButton = false; + + return; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::childFieldChangedByUi( const caf::PdmFieldHandle* changedChildField ) +{ + objectChanged.send(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( field == &m_editPolygonButton ) + { + if ( auto attrib = dynamic_cast( attribute ) ) + { + if ( m_isReadOnly() ) + { + attrib->m_buttonText = "Select in Active View"; + } + else + { + attrib->m_buttonText = "Edit in Active View"; + } + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::onColorTagClicked( const SignalEmitter* emitter, size_t index ) +{ + QColor sourceColor = RiaColorTools::toQColor( color() ); + QColor newColor = caf::PdmUiColorEditor::getColor( sourceColor ); + + if ( newColor.isValid() && newColor != sourceColor ) + { + setColor( RiaColorTools::fromQColorTo3f( newColor ) ); + objectChanged.send(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::appendPolygonMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) +{ + menuBuilder << "RicNewPolygonIntersectionFeature"; + menuBuilder << "RicNewPolygonFilterFeature"; + menuBuilder << "Separator"; + menuBuilder << "RicDuplicatePolygonFeature"; + menuBuilder << "RicSimplifyPolygonFeature"; + menuBuilder << "Separator"; + menuBuilder << "RicExportPolygonCsvFeature"; + menuBuilder << "RicExportPolygonPolFeature"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygon::defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( auto* treeItemAttribute = dynamic_cast( attribute ) ) + { + auto tag = caf::PdmUiTreeViewItemAttribute::createTag( RiaColorTools::toQColor( color() ), + RiuGuiTheme::getColorByVariableName( "backgroundColor1" ), + "---" ); + + tag->clicked.connect( this, &RimPolygon::onColorTagClicked ); + + treeItemAttribute->tags.push_back( std::move( tag ) ); + } + + if ( m_isReadOnly ) + { + caf::PdmUiTreeViewItemAttribute::appendTagToTreeViewItemAttribute( attribute, ":/padlock.svg" ); + } +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygon.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygon.h new file mode 100644 index 0000000000..0d607c7424 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygon.h @@ -0,0 +1,81 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include "RimNamedObject.h" + +#include "RimPolylinesDataInterface.h" + +#include "cafPdmChildField.h" +#include "cafPdmFieldCvfVec3d.h" + +#include "cvfColor3.h" +#include "cvfVector3.h" + +class RimPolygonAppearance; + +namespace caf +{ +class CmdFeatureMenuBuilder; +} + +class RimPolygon : public RimNamedObject, public RimPolylinesDataInterface +{ + CAF_PDM_HEADER_INIT; + +public: + caf::Signal<> objectChanged; + caf::Signal<> coordinatesChanged; + +public: + RimPolygon(); + + void setPointsInDomainCoords( const std::vector& points ); + std::vector pointsInDomainCoords() const; + void setIsClosed( bool isClosed ); + bool isClosed() const; + + void setReadOnly( bool isReadOnly ); + bool isReadOnly() const; + + void disableStorageOfPolygonPoints(); + + cvf::Color3f color() const; + void setColor( const cvf::Color3f& color ); + + cvf::ref polyLinesData() const override; + + void uiOrderingForLocalPolygon( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ); + void onColorTagClicked( const SignalEmitter* emitter, size_t index ); + + static void appendPolygonMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ); + +private: + void appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const override; + void defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void childFieldChangedByUi( const caf::PdmFieldHandle* changedChildField ) override; + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + +private: + caf::PdmField m_isReadOnly; + caf::PdmField m_editPolygonButton; + caf::PdmField> m_pointsInDomainCoords; + caf::PdmChildField m_appearance; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonAppearance.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonAppearance.cpp new file mode 100644 index 0000000000..ea8446151c --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonAppearance.cpp @@ -0,0 +1,230 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygonAppearance.h" + +#include "RimCase.h" +#include "RimProject.h" + +#include "RigPolyLinesData.h" + +#include "RiaNumericalTools.h" +#include "RiaStdStringTools.h" + +#include "cafPdmUiDoubleSliderEditor.h" +#include "cafPdmUiLineEditor.h" + +#include "cvfBoundingBox.h" + +CAF_PDM_SOURCE_INIT( RimPolygonAppearance, "RimPolygonAppearance" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +class ThicknessValidator : public QValidator +{ +public: + State validate( QString& input, int& pos ) const override + { + if ( input.isEmpty() ) return State::Intermediate; + + int val = RiaStdStringTools::toInt( input.toStdString() ); + if ( val > 0 && val < 8 ) + return State::Acceptable; + else + return State::Invalid; + } +}; + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +class RadiusValidator : public QValidator +{ +public: + State validate( QString& input, int& pos ) const override + { + if ( input.isEmpty() ) return State::Intermediate; + + double val = RiaStdStringTools::toDouble( input.toStdString() ); + if ( val > 0.001 && val <= 2.0 ) + return State::Acceptable; + else + return State::Invalid; + } +}; + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonAppearance::RimPolygonAppearance() + : objectChanged( this ) + +{ + CAF_PDM_InitObject( "Polygon", ":/PolylinesFromFile16x16.png" ); + + CAF_PDM_InitField( &m_isClosed, "IsClosed", true, "Closed Polygon" ); + CAF_PDM_InitField( &m_showLines, "ShowLines", true, "Show Lines" ); + CAF_PDM_InitField( &m_showSpheres, "ShowSpheres", false, "Show Spheres" ); + + CAF_PDM_InitField( &m_lineThickness, "LineThickness", 3, "Line Thickness" ); + CAF_PDM_InitField( &m_sphereRadiusFactor, "SphereRadiusFactor", 0.15, "Sphere Radius Factor" ); + + CAF_PDM_InitField( &m_lineColor, "LineColor", cvf::Color3f( cvf::Color3f::ORANGE ), "Line Color" ); + CAF_PDM_InitField( &m_sphereColor, "SphereColor", cvf::Color3f( cvf::Color3f::ORANGE ), "Sphere Color" ); + + CAF_PDM_InitField( &m_polygonPlaneDepth, "PolygonPlaneDepth", 0.0, "Polygon Plane Depth" ); + CAF_PDM_InitField( &m_lockPolygonToPlane, "LockPolygon", false, "Lock Polygon to Plane" ); + + m_polygonPlaneDepth.uiCapability()->setUiEditorTypeName( caf::PdmUiDoubleSliderEditor::uiEditorTypeName() ); + m_polygonPlaneDepth.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::TOP ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonAppearance::applyAppearanceSettings( RigPolyLinesData* polyLinesData ) +{ + polyLinesData->setLineAppearance( m_lineThickness, m_lineColor, m_isClosed ); + polyLinesData->setSphereAppearance( m_sphereRadiusFactor, m_sphereColor ); + polyLinesData->setZPlaneLock( m_lockPolygonToPlane, -m_polygonPlaneDepth ); + polyLinesData->setVisibility( m_showLines, m_showSpheres ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonAppearance::setIsClosed( bool isClosed ) +{ + m_isClosed = isClosed; + objectChanged.send(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonAppearance::isClosed() const +{ + return m_isClosed(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Color3f RimPolygonAppearance::lineColor() const +{ + return m_lineColor(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonAppearance::setLineColor( const cvf::Color3f& color ) +{ + m_lineColor = color; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonAppearance::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( &m_showLines ); + if ( m_showLines ) + { + uiOrdering.add( &m_lineThickness ); + uiOrdering.add( &m_lineColor ); + } + + uiOrdering.add( &m_showSpheres ); + if ( m_showSpheres ) + { + uiOrdering.add( &m_sphereRadiusFactor ); + uiOrdering.add( &m_sphereColor ); + } + + uiOrdering.add( &m_lockPolygonToPlane ); + if ( m_lockPolygonToPlane ) + { + uiOrdering.add( &m_polygonPlaneDepth ); + } + + uiOrdering.add( &m_isClosed ); + + uiOrdering.skipRemainingFields(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonAppearance::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + objectChanged.send(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonAppearance::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( field == &m_lineThickness ) + { + if ( auto myAttr = dynamic_cast( attribute ) ) + { + myAttr->validator = new ThicknessValidator(); + } + } + else if ( field == &m_lineThickness ) + { + if ( auto myAttr = dynamic_cast( attribute ) ) + { + myAttr->validator = new RadiusValidator(); + } + } + else if ( field == &m_polygonPlaneDepth ) + { + if ( auto attr = dynamic_cast( attribute ) ) + { + auto allCases = RimProject::current()->allGridCases(); + if ( allCases.empty() ) + { + attr->m_minimum = 0; + attr->m_maximum = 10000.0; + } + else + { + double min = std::numeric_limits::max(); + double max = -std::numeric_limits::max(); + + for ( auto gridCase : allCases ) + { + auto bb = gridCase->allCellsBoundingBox(); + + min = std::min( min, bb.min().z() ); + max = std::max( max, bb.max().z() ); + } + + auto adjustedMin = RiaNumericalTools::roundToNumSignificantDigitsFloor( -min, 2 ); + auto adjustedMax = RiaNumericalTools::roundToNumSignificantDigitsCeil( -max, 2 ); + + attr->m_minimum = adjustedMax; + attr->m_maximum = adjustedMin; + } + } + } +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonAppearance.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonAppearance.h new file mode 100644 index 0000000000..0f6fd767d0 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonAppearance.h @@ -0,0 +1,63 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include "cafPdmField.h" +#include "cafPdmObject.h" + +#include "cafPdmFieldCvfColor.h" +#include "cvfVector3.h" + +class RigPolyLinesData; + +class RimPolygonAppearance : public caf::PdmObject +{ + CAF_PDM_HEADER_INIT; + +public: + caf::Signal<> objectChanged; + + void applyAppearanceSettings( RigPolyLinesData* polyLinesData ); + + void setIsClosed( bool isClosed ); + bool isClosed() const; + + cvf::Color3f lineColor() const; + void setLineColor( const cvf::Color3f& color ); + +public: + RimPolygonAppearance(); + +protected: + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + +private: + caf::PdmField m_isClosed; + caf::PdmField m_showLines; + caf::PdmField m_lineThickness; + caf::PdmField m_lineColor; + + caf::PdmField m_showSpheres; + caf::PdmField m_sphereRadiusFactor; + caf::PdmField m_sphereColor; + + caf::PdmField m_lockPolygonToPlane; + caf::PdmField m_polygonPlaneDepth; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonCollection.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonCollection.cpp new file mode 100644 index 0000000000..ee52064c39 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonCollection.cpp @@ -0,0 +1,262 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygonCollection.h" + +#include "Rim3dView.h" +#include "RimPolygon.h" +#include "RimPolygonFile.h" +#include "RimProject.h" + +#include "cafCmdFeatureMenuBuilder.h" + +CAF_PDM_SOURCE_INIT( RimPolygonCollection, "RimPolygonCollection" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonCollection::RimPolygonCollection() +{ + CAF_PDM_InitObject( "Polygons", ":/PolylinesFromFile16x16.png" ); + + CAF_PDM_InitFieldNoDefault( &m_polygons, "Polygons", "Polygons" ); + CAF_PDM_InitFieldNoDefault( &m_polygonFiles, "PolygonFiles", "Polygon Files" ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::loadData() +{ + for ( auto& p : m_polygonFiles() ) + { + p->loadData(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygon* RimPolygonCollection::createUserDefinedPolygon() +{ + auto newPolygon = new RimPolygon(); + newPolygon->setName( "Polygon " + QString::number( userDefinedPolygons().size() + 1 ) ); + + return newPolygon; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygon* RimPolygonCollection::appendUserDefinedPolygon() +{ + auto newPolygon = createUserDefinedPolygon(); + addUserDefinedPolygon( newPolygon ); + + return newPolygon; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::addUserDefinedPolygon( RimPolygon* polygon ) +{ + m_polygons().push_back( polygon ); + + connectPolygonSignals( polygon ); + + updateViewTreeItems(); + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::deleteUserDefinedPolygons() +{ + m_polygons().deleteChildren(); + + updateViewTreeItems(); + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::addPolygonFile( RimPolygonFile* polygonFile ) +{ + m_polygonFiles().push_back( polygonFile ); + + connectPolygonFileSignals( polygonFile ); + + updateViewTreeItems(); + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonCollection::userDefinedPolygons() const +{ + return m_polygons.childrenByType(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonCollection::polygonFiles() const +{ + return m_polygonFiles.childrenByType(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonCollection::allPolygons() const +{ + std::vector allPolygons; + + for ( auto& p : m_polygonFiles() ) + { + for ( auto& polygon : p->polygons() ) + { + allPolygons.push_back( polygon ); + } + } + + for ( auto& polygon : m_polygons.childrenByType() ) + { + allPolygons.push_back( polygon ); + } + + return allPolygons; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::appendPolygonMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) +{ + menuBuilder << "RicCreatePolygonFeature"; + menuBuilder << "RicImportPolygonFileFeature"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::onChildDeleted( caf::PdmChildArrayFieldHandle* childArray, std::vector& referringObjects ) +{ + updateViewTreeItems(); + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::childFieldChangedByUi( const caf::PdmFieldHandle* changedChildField ) +{ + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const +{ + RimPolygonCollection::appendPolygonMenuItems( menuBuilder ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::updateViewTreeItems() +{ + RimProject* proj = RimProject::current(); + + // Make sure the tree items are synchronized + std::vector views; + proj->allViews( views ); + for ( auto view : views ) + { + view->updateViewTreeItems( RiaDefines::ItemIn3dView::POLYGON ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::scheduleRedrawViews() +{ + RimProject* proj = RimProject::current(); + proj->scheduleCreateDisplayModelAndRedrawAllViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::connectPolygonSignals( RimPolygon* polygon ) +{ + if ( polygon ) + { + polygon->objectChanged.connect( this, &RimPolygonCollection::onPolygonChanged ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::connectPolygonFileSignals( RimPolygonFile* polygonFile ) +{ + if ( polygonFile ) + { + polygonFile->objectChanged.connect( this, &RimPolygonCollection::onPolygonFileChanged ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::onPolygonChanged( const caf::SignalEmitter* emitter ) +{ + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::onPolygonFileChanged( const caf::SignalEmitter* emitter ) +{ + updateViewTreeItems(); + scheduleRedrawViews(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonCollection::initAfterRead() +{ + for ( auto& p : m_polygons() ) + { + connectPolygonSignals( p ); + } + + for ( auto& pf : m_polygonFiles() ) + { + connectPolygonFileSignals( pf ); + } +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonCollection.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonCollection.h new file mode 100644 index 0000000000..3c0b163582 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonCollection.h @@ -0,0 +1,71 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cafPdmChildArrayField.h" +#include "cafPdmObject.h" + +class RimPolygon; +class RimPolygonFile; + +//================================================================================================== +/// +/// +//================================================================================================== +class RimPolygonCollection : public caf::PdmObject +{ + CAF_PDM_HEADER_INIT; + +public: + RimPolygonCollection(); + + void loadData(); + RimPolygon* createUserDefinedPolygon(); + RimPolygon* appendUserDefinedPolygon(); + void addUserDefinedPolygon( RimPolygon* polygon ); + void deleteUserDefinedPolygons(); + + void addPolygonFile( RimPolygonFile* polygonFile ); + + std::vector userDefinedPolygons() const; + std::vector polygonFiles() const; + std::vector allPolygons() const; + + static void appendPolygonMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ); + +private: + void onChildDeleted( caf::PdmChildArrayFieldHandle* childArray, std::vector& referringObjects ) override; + void childFieldChangedByUi( const caf::PdmFieldHandle* changedChildField ) override; + void appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const override; + + void updateViewTreeItems(); + void scheduleRedrawViews(); + + void connectPolygonSignals( RimPolygon* polygon ); + void connectPolygonFileSignals( RimPolygonFile* polygonFile ); + void onPolygonChanged( const caf::SignalEmitter* emitter ); + void onPolygonFileChanged( const caf::SignalEmitter* emitter ); + +private: + caf::PdmChildArrayField m_polygons; + caf::PdmChildArrayField m_polygonFiles; + +protected: + void initAfterRead() override; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonFile.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonFile.cpp new file mode 100644 index 0000000000..d09e29af02 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonFile.cpp @@ -0,0 +1,206 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygonFile.h" + +#include "RiaLogging.h" + +#include "RifPolygonReader.h" + +#include "RimPolygon.h" + +#include "cafCmdFeatureMenuBuilder.h" +#include "cafPdmUiTreeAttributes.h" + +#include + +CAF_PDM_SOURCE_INIT( RimPolygonFile, "RimPolygonFileFile" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonFile::RimPolygonFile() + : objectChanged( this ) +{ + CAF_PDM_InitObject( "PolygonFile", ":/PolylinesFromFile16x16.png" ); + + CAF_PDM_InitFieldNoDefault( &m_fileName, "StimPlanFileName", "File Name" ); + CAF_PDM_InitFieldNoDefault( &m_polygons, "Polygons", "Polygons" ); + + setDeletable( true ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::setFileName( const QString& fileName ) +{ + m_fileName = fileName; + + updateName(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::loadData() +{ + auto polygonsFromFile = importDataFromFile( m_fileName().path() ); + + if ( m_polygons.size() == polygonsFromFile.size() ) + { + for ( size_t i = 0; i < m_polygons.size(); i++ ) + { + auto projectPoly = m_polygons()[i]; + auto filePoly = polygonsFromFile[i]; + projectPoly->setPointsInDomainCoords( filePoly->pointsInDomainCoords() ); + projectPoly->coordinatesChanged.send(); // updates editors + projectPoly->objectChanged.send(); // updates filters + delete filePoly; + } + } + else + { + m_polygons.deleteChildren(); + + m_polygons.setValue( polygonsFromFile ); + } + + if ( polygonsFromFile.empty() ) + { + RiaLogging::warning( "No polygons found in file: " + m_fileName().path() ); + } + else + { + RiaLogging::info( QString( "Imported %1 polygons from file: " ).arg( polygonsFromFile.size() ) + m_fileName().path() ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonFile::polygons() const +{ + return m_polygons.childrenByType(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimPolygonFile::name() const +{ + QString nameCandidate = RimNamedObject::name(); + + if ( !nameCandidate.isEmpty() ) + { + return nameCandidate; + } + + auto fileName = m_fileName().path(); + if ( fileName.isEmpty() ) + { + return "Polygon File"; + } + + QFileInfo fileInfo( fileName ); + return fileInfo.fileName(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( nameField() ); + uiOrdering.add( &m_fileName ); + uiOrdering.skipRemainingFields(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + if ( changedField == &m_fileName ) + { + updateName(); + + m_polygons.deleteChildren(); + loadData(); + } + + objectChanged.send(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonFile::importDataFromFile( const QString& fileName ) +{ + QString errorMessages; + auto filePolygons = RifPolygonReader::parsePolygonFile( fileName, &errorMessages ); + + std::vector polygons; + + for ( const auto& [polygonId, filePolygon] : filePolygons ) + { + auto polygon = new RimPolygon(); + polygon->disableStorageOfPolygonPoints(); + polygon->setReadOnly( true ); + + int id = ( polygonId != -1 ) ? polygonId : static_cast( polygons.size() + 1 ); + polygon->setName( QString( "Polygon %1" ).arg( id ) ); + polygon->setPointsInDomainCoords( filePolygon ); + polygons.push_back( polygon ); + } + + if ( !errorMessages.isEmpty() ) + { + RiaLogging::error( errorMessages ); + } + + return polygons; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::updateName() +{ + QFileInfo fileInfo( m_fileName().path() ); + setName( fileInfo.fileName() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const +{ + menuBuilder << "RicReloadPolygonFileFeature"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonFile::defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( m_polygons.empty() ) + { + caf::PdmUiTreeViewItemAttribute::appendTagToTreeViewItemAttribute( attribute, ":/warning.svg" ); + } +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonFile.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonFile.h new file mode 100644 index 0000000000..d90442097e --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonFile.h @@ -0,0 +1,59 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include "RimNamedObject.h" + +#include "cafFilePath.h" +#include "cafPdmChildArrayField.h" + +class RimPolygon; + +class RimPolygonFile : public RimNamedObject +{ + CAF_PDM_HEADER_INIT; + +public: + caf::Signal<> objectChanged; + +public: + RimPolygonFile(); + + void setFileName( const QString& fileName ); + + void loadData(); + + std::vector polygons() const; + + QString name() const override; + +protected: + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const override; + void defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + +private: + static std::vector importDataFromFile( const QString& fileName ); + void updateName(); + +private: + caf::PdmField m_fileName; + + caf::PdmChildArrayField m_polygons; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInView.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInView.cpp new file mode 100644 index 0000000000..e3f4776779 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInView.cpp @@ -0,0 +1,504 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygonInView.h" + +#include "RiaColorTools.h" + +#include "RigPolyLinesData.h" + +#include "Rim3dView.h" +#include "RimPolygon.h" +#include "RimPolygonInViewCollection.h" +#include "RimPolylineTarget.h" +#include "RimTools.h" + +#include "WellPathCommands/PointTangentManipulator/RicPolyline3dEditor.h" +#include "WellPathCommands/RicPolylineTargetsPickEventHandler.h" + +#include "Riu3DMainWindowTools.h" +#include "RiuGuiTheme.h" + +#include "RivPolylinePartMgr.h" + +#include "cafCmdFeatureMenuBuilder.h" +#include "cafDisplayCoordTransform.h" +#include "cafPdmUiPushButtonEditor.h" +#include "cafPdmUiTableViewEditor.h" +#include "cafPdmUiTreeAttributes.h" + +#include "cvfModelBasicList.h" + +CAF_PDM_SOURCE_INIT( RimPolygonInView, "RimPolygonInView" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonInView::RimPolygonInView() + : m_pickTargetsEventHandler( new RicPolylineTargetsPickEventHandler( this ) ) +{ + CAF_PDM_InitObject( "Polygon", ":/PolylinesFromFile16x16.png" ); + + CAF_PDM_InitFieldNoDefault( &m_polygon, "Polygon", "Polygon" ); + m_polygon.uiCapability()->setUiReadOnly( true ); + + nameField()->uiCapability()->setUiReadOnly( true ); + + CAF_PDM_InitField( &m_enablePicking, "EnablePicking", false, "" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_enablePicking ); + + CAF_PDM_InitField( &m_selectPolygon, "SelectPolygon", false, "" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_selectPolygon ); + + CAF_PDM_InitField( &m_handleScalingFactor, "HandleScalingFactor", 1.0, "Handle Scaling Factor" ); + + CAF_PDM_InitFieldNoDefault( &m_targets, "Targets", "Targets" ); + m_targets.uiCapability()->setUiEditorTypeName( caf::PdmUiTableViewEditor::uiEditorTypeName() ); + m_targets.uiCapability()->setUiTreeChildrenHidden( true ); + m_targets.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); + m_targets.uiCapability()->setCustomContextMenuEnabled( true ); + m_targets.xmlCapability()->disableIO(); + + setUi3dEditorTypeName( RicPolyline3dEditor::uiEditorTypeName() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygon* RimPolygonInView::polygon() const +{ + return m_polygon(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::setPolygon( RimPolygon* polygon ) +{ + m_polygon = polygon; + + connectSignals(); + + updateTargetsFromPolygon(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::appendPartsToModel( cvf::ModelBasicList* model, + const caf::DisplayCoordTransform* scaleTransform, + const cvf::BoundingBox& boundingBox ) +{ + auto view = firstAncestorOfType(); + + if ( m_polylinePartMgr.isNull() ) m_polylinePartMgr = new RivPolylinePartMgr( view, this, this ); + + m_polylinePartMgr->appendDynamicGeometryPartsToModel( model, scaleTransform, boundingBox ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::enablePicking( bool enable ) +{ + m_enablePicking = enable; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::insertTarget( const RimPolylineTarget* targetToInsertBefore, RimPolylineTarget* targetToInsert ) +{ + size_t index = m_targets.indexOf( targetToInsertBefore ); + if ( index < m_targets.size() ) + m_targets.insert( index, targetToInsert ); + else + m_targets.push_back( targetToInsert ); + + updatePolygonFromTargets(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::deleteTarget( RimPolylineTarget* targetToDelete ) +{ + m_targets.removeChild( targetToDelete ); + delete targetToDelete; + + updatePolygonFromTargets(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::updateEditorsAndVisualization() +{ + updateConnectedEditors(); + updateVisualization(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::updateVisualization() +{ + auto view = firstAncestorOfType(); + if ( view ) + { + view->scheduleCreateDisplayModelAndRedraw(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonInView::activeTargets() const +{ + return m_targets.childrenByType(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonInView::pickingEnabled() const +{ + return m_enablePicking(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::PickEventHandler* RimPolygonInView::pickEventHandler() const +{ + auto filterColl = firstAncestorOfType(); + if ( filterColl && !filterColl->isChecked() ) return nullptr; + + if ( !isChecked() ) return nullptr; + + if ( m_polygon() && polygon()->isReadOnly() ) return nullptr; + + return m_pickTargetsEventHandler.get(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::onChildrenUpdated( caf::PdmChildArrayFieldHandle* childArray, std::vector& updatedObjects ) +{ + if ( childArray == &m_targets ) + { + updatePolygonFromTargets(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref RimPolygonInView::polyLinesData() const +{ + if ( m_polygon ) + { + return m_polygon->polyLinesData(); + } + + return nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::updatePolygonFromTargets() +{ + if ( m_polygon ) + { + std::vector points; + for ( const RimPolylineTarget* target : m_targets ) + { + points.push_back( target->targetPointXYZ() ); + } + m_polygon->setPointsInDomainCoords( points ); + + // update other pick editors, make sure we don't update ourselves + m_polygon->coordinatesChanged.block( this ); + m_polygon->coordinatesChanged.send(); + m_polygon->coordinatesChanged.unblock( this ); + + m_polygon->objectChanged.send(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::connectSignals() +{ + if ( m_polygon ) + { + m_polygon->objectChanged.connect( this, &RimPolygonInView::onObjectChanged ); + m_polygon->coordinatesChanged.connect( this, &RimPolygonInView::onCoordinatesChanged ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::updateTargetsFromPolygon() +{ + if ( m_polygon ) + { + m_targets.deleteChildren(); + + for ( const auto& p : m_polygon->pointsInDomainCoords() ) + { + auto target = new RimPolylineTarget(); + target->setAsPointXYZ( p ); + + m_targets.push_back( target ); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + updateNameField(); + + bool enableEdit = true; + if ( m_polygon() && m_polygon->isReadOnly() ) enableEdit = false; + + uiOrdering.add( m_polygon ); + + if ( enableEdit ) + { + uiOrdering.add( &m_enablePicking ); + uiOrdering.add( &m_targets ); + uiOrdering.add( &m_handleScalingFactor ); + } + + if ( m_polygon() ) + { + uiOrdering.add( &m_selectPolygon ); + } + + uiOrdering.skipRemainingFields(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + if ( changedField == &m_enablePicking ) + { + updateConnectedEditors(); + } + + if ( changedField == &m_selectPolygon && m_polygon() ) + { + Riu3DMainWindowTools::selectAsCurrentItem( m_polygon() ); + } + + updateVisualization(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QList RimPolygonInView::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) +{ + QList options; + if ( fieldNeedingOptions == &m_polygon ) + { + options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); + + RimTools::polygonOptionItems( &options ); + } + + return options; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( auto attrib = dynamic_cast( attribute ) ) + { + attrib->pickEventHandler = m_pickTargetsEventHandler; + attrib->enablePicking = m_enablePicking; + } + + if ( m_polygon() ) + { + if ( auto* treeItemAttribute = dynamic_cast( attribute ) ) + { + auto tag = caf::PdmUiTreeViewItemAttribute::createTag( RiaColorTools::toQColor( m_polygon->color() ), + RiuGuiTheme::getColorByVariableName( "backgroundColor1" ), + "---" ); + + tag->clicked.connect( m_polygon(), &RimPolygon::onColorTagClicked ); + + treeItemAttribute->tags.push_back( std::move( tag ) ); + } + + if ( m_polygon->isReadOnly() ) + { + caf::PdmUiTreeViewItemAttribute::appendTagToTreeViewItemAttribute( attribute, ":/padlock.svg" ); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::uiOrderingForLocalPolygon( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( &m_enablePicking ); + uiOrdering.add( &m_targets ); + uiOrdering.add( &m_handleScalingFactor ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const +{ + RimPolygon::appendPolygonMenuItems( menuBuilder ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::onObjectChanged( const caf::SignalEmitter* emitter ) +{ + updateVisualization(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::onCoordinatesChanged( const caf::SignalEmitter* emitter ) +{ + updateTargetsFromPolygon(); + + updateConnectedEditors(); + updateVisualization(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::initAfterRead() +{ + connectSignals(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimPolygonInView::scalingFactorForTarget() const +{ + return m_handleScalingFactor(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( field == &m_enablePicking ) + { + auto* pbAttribute = dynamic_cast( attribute ); + if ( pbAttribute ) + { + if ( !m_enablePicking ) + { + pbAttribute->m_buttonText = "Start Picking Points"; + } + else + { + pbAttribute->m_buttonText = "Stop Picking Points"; + } + } + } + + if ( field == &m_selectPolygon ) + { + auto* pbAttribute = dynamic_cast( attribute ); + if ( pbAttribute ) + { + pbAttribute->m_buttonText = "Go to Polygon"; + } + } + + if ( field == &m_targets ) + { + if ( auto tvAttribute = dynamic_cast( attribute ) ) + { + tvAttribute->resizePolicy = caf::PdmUiTableViewEditorAttribute::RESIZE_TO_FIT_CONTENT; + + if ( m_enablePicking ) + { + tvAttribute->baseColor = RiuGuiTheme::getColorByVariableName( "externalInputColor" ); + } + tvAttribute->alwaysEnforceResizePolicy = true; + tvAttribute->heightHint = 1000; + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::defineCustomContextMenu( const caf::PdmFieldHandle* fieldNeedingMenu, QMenu* menu, QWidget* fieldEditorWidget ) +{ + if ( m_polygon() && m_polygon->isReadOnly() ) return; + + caf::CmdFeatureMenuBuilder menuBuilder; + + menuBuilder << "RicNewPolylineTargetFeature"; + menuBuilder << "Separator"; + menuBuilder << "RicDeletePolylineTargetFeature"; + + menuBuilder.appendToMenu( menu ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::updateNameField() +{ + QString name = "Undefined"; + if ( m_polygon() ) + { + name = m_polygon->name(); + } + + setName( name ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInView::defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, QString uiConfigName /*= "" */ ) +{ + updateNameField(); +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInView.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInView.h new file mode 100644 index 0000000000..dbe5d07a96 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInView.h @@ -0,0 +1,103 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// +#pragma once + +#include "RimCheckableNamedObject.h" +#include "RimPolylinePickerInterface.h" +#include "RimPolylinesDataInterface.h" + +#include "RivPolylinePartMgr.h" + +#include "cafPdmChildArrayField.h" +#include "cafPdmPtrField.h" + +class RimPolygon; +class RivPolylinePartMgr; +class RicPolylineTargetsPickEventHandler; +class RimPolylineTarget; + +namespace cvf +{ +class ModelBasicList; +class BoundingBox; +} // namespace cvf + +namespace caf +{ +class DisplayCoordTransform; +} // namespace caf + +class RimPolygonInView : public RimCheckableNamedObject, public RimPolylinesDataInterface, public RimPolylinePickerInterface +{ + CAF_PDM_HEADER_INIT; + +public: + RimPolygonInView(); + + RimPolygon* polygon() const; + void setPolygon( RimPolygon* polygon ); + void updateTargetsFromPolygon(); + + void appendPartsToModel( cvf::ModelBasicList* model, const caf::DisplayCoordTransform* scaleTransform, const cvf::BoundingBox& boundingBox ); + void enablePicking( bool enable ); + + void insertTarget( const RimPolylineTarget* targetToInsertBefore, RimPolylineTarget* targetToInsert ) override; + void deleteTarget( RimPolylineTarget* targetToDelete ) override; + void updateEditorsAndVisualization() override; + void updateVisualization() override; + std::vector activeTargets() const override; + bool pickingEnabled() const override; + caf::PickEventHandler* pickEventHandler() const override; + double scalingFactorForTarget() const override; + + cvf::ref polyLinesData() const override; + + void onChildrenUpdated( caf::PdmChildArrayFieldHandle* childArray, std::vector& updatedObjects ) override; + void defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + + void uiOrderingForLocalPolygon( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ); + +protected: + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, QString uiConfigName = "" ) override; + QList calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) override; + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + void defineCustomContextMenu( const caf::PdmFieldHandle* fieldNeedingMenu, QMenu* menu, QWidget* fieldEditorWidget ) override; + void appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const override; + void onObjectChanged( const caf::SignalEmitter* emitter ); + void onCoordinatesChanged( const caf::SignalEmitter* emitter ); + void initAfterRead() override; + +private: + void updateNameField(); + + void updatePolygonFromTargets(); + void connectSignals(); + +private: + caf::PdmPtrField m_polygon; + + caf::PdmField m_selectPolygon; + caf::PdmField m_enablePicking; + caf::PdmField m_handleScalingFactor; + caf::PdmChildArrayField m_targets; + + cvf::ref m_polylinePartMgr; + std::shared_ptr m_pickTargetsEventHandler; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInViewCollection.cpp new file mode 100644 index 0000000000..15ba10d72c --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInViewCollection.cpp @@ -0,0 +1,281 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygonInViewCollection.h" + +#include "Rim3dView.h" +#include "RimPolygon.h" +#include "RimPolygonCollection.h" +#include "RimPolygonFile.h" +#include "RimPolygonInView.h" +#include "RimTools.h" + +CAF_PDM_SOURCE_INIT( RimPolygonInViewCollection, "RimPolygonInViewCollection" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonInViewCollection::RimPolygonInViewCollection() +{ + CAF_PDM_InitObject( "Polygons", ":/PolylinesFromFile16x16.png" ); + + CAF_PDM_InitFieldNoDefault( &m_polygonsInView, "Polygons", "Polygons" ); + CAF_PDM_InitFieldNoDefault( &m_collectionsInView, "Collections", "Collections" ); + + nameField()->uiCapability()->setUiHidden( true ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::updateFromPolygonCollection() +{ + updateAllViewItems(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonInViewCollection::visiblePolygonsInView() const +{ + if ( !m_isChecked ) return {}; + + std::vector polys = m_polygonsInView.childrenByType(); + + for ( auto coll : m_collectionsInView ) + { + if ( !coll->isChecked() ) continue; + + auto other = coll->visiblePolygonsInView(); + polys.insert( polys.end(), other.begin(), other.end() ); + } + + return polys; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimPolygonInViewCollection::allPolygonsInView() const +{ + std::vector polys = m_polygonsInView.childrenByType(); + + for ( auto coll : m_collectionsInView ) + { + auto other = coll->visiblePolygonsInView(); + polys.insert( polys.end(), other.begin(), other.end() ); + } + + return polys; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::setPolygonFile( RimPolygonFile* polygonFile ) +{ + m_polygonFile = polygonFile; + + updateName(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonFile* RimPolygonInViewCollection::polygonFile() const +{ + return m_polygonFile; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + RimCheckableNamedObject::fieldChangedByUi( changedField, oldValue, newValue ); + + if ( changedField == &m_isChecked ) + { + for ( auto poly : visiblePolygonsInView() ) + { + poly->updateConnectedEditors(); + } + + if ( auto view = firstAncestorOfType() ) + { + view->scheduleCreateDisplayModelAndRedraw(); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const +{ + RimPolygonCollection::appendPolygonMenuItems( menuBuilder ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::updateAllViewItems() +{ + // Based on the same concept as RimSurfaceInViewCollection + + syncCollectionsWithView(); + syncPolygonsWithView(); + updateConnectedEditors(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::syncCollectionsWithView() +{ + // Based on the same concept as RimSurfaceInViewCollection + + auto colls = m_collectionsInView.childrenByType(); + + for ( auto coll : colls ) + { + if ( !coll->polygonFile() ) + { + m_collectionsInView.removeChild( coll ); + delete coll; + } + } + + if ( !m_polygonFile ) + { + std::vector orderedColls; + + if ( auto polygonCollection = RimTools::polygonCollection() ) + { + std::vector newPolygonsInView; + + for ( auto polygonFile : polygonCollection->polygonFiles() ) + { + if ( polygonFile->polygons().empty() ) continue; + + auto viewPolygonFile = getCollectionInViewForPolygonFile( polygonFile ); + if ( viewPolygonFile == nullptr ) + { + auto newColl = new RimPolygonInViewCollection(); + newColl->setPolygonFile( polygonFile ); + orderedColls.push_back( newColl ); + } + else + { + viewPolygonFile->updateName(); + orderedColls.push_back( viewPolygonFile ); + } + } + } + + m_collectionsInView.clearWithoutDelete(); + for ( auto viewColl : orderedColls ) + { + m_collectionsInView.push_back( viewColl ); + viewColl->updateAllViewItems(); + } + } + + updateName(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::syncPolygonsWithView() +{ + std::vector existingPolygonsInView = m_polygonsInView.childrenByType(); + m_polygonsInView.clearWithoutDelete(); + + std::vector polygons; + + if ( m_polygonFile ) + { + polygons = m_polygonFile->polygons(); + } + else + { + auto polygonCollection = RimTools::polygonCollection(); + polygons = polygonCollection->userDefinedPolygons(); + } + + std::vector newPolygonsInView; + + for ( auto polygon : polygons ) + { + auto it = std::find_if( existingPolygonsInView.begin(), + existingPolygonsInView.end(), + [polygon]( auto* polygonInView ) { return polygonInView->polygon() == polygon; } ); + + if ( it != existingPolygonsInView.end() ) + { + newPolygonsInView.push_back( *it ); + ( *it )->updateTargetsFromPolygon(); + existingPolygonsInView.erase( it ); + } + else + { + auto polygonInView = new RimPolygonInView(); + polygonInView->setPolygon( polygon ); + newPolygonsInView.push_back( polygonInView ); + } + } + + m_polygonsInView.setValue( newPolygonsInView ); + + for ( auto polyInView : existingPolygonsInView ) + { + delete polyInView; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonInViewCollection::updateName() +{ + QString name = "Polygons"; + + if ( m_polygonFile ) + { + name = m_polygonFile->name(); + } + + setName( name ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonInViewCollection* RimPolygonInViewCollection::getCollectionInViewForPolygonFile( const RimPolygonFile* polygonFile ) const +{ + for ( auto collInView : m_collectionsInView ) + { + if ( collInView->polygonFile() == polygonFile ) + { + return collInView; + } + } + + return nullptr; +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInViewCollection.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInViewCollection.h new file mode 100644 index 0000000000..a320ef3a63 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonInViewCollection.h @@ -0,0 +1,65 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RimCheckableNamedObject.h" + +#include "cafPdmChildArrayField.h" +#include "cafPdmPointer.h" + +class RimPolygonInView; +class RimPolygonFile; +class RimPolygon; + +//================================================================================================== +/// +/// +//================================================================================================== +class RimPolygonInViewCollection : public RimCheckableNamedObject +{ + CAF_PDM_HEADER_INIT; + +public: + RimPolygonInViewCollection(); + + void updateFromPolygonCollection(); + + std::vector visiblePolygonsInView() const; + std::vector allPolygonsInView() const; + +private: + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const override; + + void setPolygonFile( RimPolygonFile* polygonFile ); + RimPolygonFile* polygonFile() const; + + void updateAllViewItems(); + void syncCollectionsWithView(); + void syncPolygonsWithView(); + void updateName(); + + RimPolygonInViewCollection* getCollectionInViewForPolygonFile( const RimPolygonFile* polygonFile ) const; + +private: + caf::PdmChildArrayField m_polygonsInView; + caf::PdmChildArrayField m_collectionsInView; + + caf::PdmPointer m_polygonFile; +}; diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonTools.cpp b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonTools.cpp new file mode 100644 index 0000000000..11d2d49425 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonTools.cpp @@ -0,0 +1,178 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolygonTools.h" + +#include "RiaPreferences.h" + +#include "RifCsvDataTableFormatter.h" + +#include "RimGridView.h" +#include "RimOilField.h" +#include "RimPolygon.h" +#include "RimPolygonCollection.h" +#include "RimPolygonInView.h" +#include "RimPolygonInViewCollection.h" +#include "RimProject.h" + +#include "Riu3DMainWindowTools.h" + +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonTools::activate3dEditOfPolygonInView( RimPolygon* polygon, caf::PdmObject* sourceObject ) +{ + auto polygonInView = findPolygonInView( polygon, sourceObject ); + if ( polygonInView ) + { + polygonInView->enablePicking( true ); + Riu3DMainWindowTools::selectAsCurrentItem( polygonInView ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimPolygonTools::selectPolygonInView( RimPolygon* polygon, caf::PdmObject* sourceObject ) +{ + auto polygonInView = findPolygonInView( polygon, sourceObject ); + if ( polygonInView ) + { + Riu3DMainWindowTools::selectAsCurrentItem( polygonInView ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonTools::exportPolygonCsv( const RimPolygon* polygon, const QString& filePath ) +{ + if ( !polygon ) return false; + + QFile file( filePath ); + if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) + { + return false; + } + + QTextStream out( &file ); + + QString fieldSeparator = RiaPreferences::current()->csvTextExportFieldSeparator; + RifCsvDataTableFormatter formatter( out, fieldSeparator ); + const int precision = 2; + + std::vector header; + header.emplace_back( "X", RifTextDataTableDoubleFormatting( RIF_FLOAT, precision ) ); + header.emplace_back( "Y", RifTextDataTableDoubleFormatting( RIF_FLOAT, precision ) ); + header.emplace_back( "Z", RifTextDataTableDoubleFormatting( RIF_FLOAT, precision ) ); + formatter.header( header ); + + for ( const auto& point : polygon->pointsInDomainCoords() ) + { + formatter.add( point.x() ); + formatter.add( point.y() ); + formatter.add( -point.z() ); + formatter.rowCompleted(); + } + + formatter.tableCompleted(); + + file.close(); + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimPolygonTools::exportPolygonPol( const RimPolygon* polygon, const QString& filePath ) +{ + if ( !polygon ) return false; + + QFile file( filePath ); + if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) ) return false; + + QTextStream out( &file ); + + QString fieldSeparator = " "; + RifCsvDataTableFormatter formatter( out, fieldSeparator ); + const int precision = 2; + + std::vector header; + header.emplace_back( " ", RifTextDataTableDoubleFormatting( RIF_FLOAT, precision ) ); + header.emplace_back( " ", RifTextDataTableDoubleFormatting( RIF_FLOAT, precision ) ); + header.emplace_back( " ", RifTextDataTableDoubleFormatting( RIF_FLOAT, precision ) ); + formatter.header( header ); + + for ( const auto& point : polygon->pointsInDomainCoords() ) + { + formatter.add( point.x() ); + formatter.add( point.y() ); + formatter.add( -point.z() ); + formatter.rowCompleted(); + } + + const double endOfPolygon = 999.0; + formatter.add( endOfPolygon ); + formatter.add( endOfPolygon ); + formatter.add( endOfPolygon ); + formatter.rowCompleted(); + + formatter.tableCompleted(); + + file.close(); + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimPolygonTools::polygonCacheName() +{ + return "POLYGON"; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonInView* RimPolygonTools::findPolygonInView( RimPolygon* polygon, caf::PdmObject* sourceObject ) +{ + if ( !polygon || !sourceObject ) + { + return nullptr; + } + + if ( auto gridView = sourceObject->firstAncestorOrThisOfType() ) + { + auto polyCollection = gridView->polygonInViewCollection(); + + for ( auto polygonInView : polyCollection->allPolygonsInView() ) + { + if ( polygonInView && polygonInView->polygon() == polygon ) + { + return polygonInView; + } + } + } + + return nullptr; +} diff --git a/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonTools.h b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonTools.h new file mode 100644 index 0000000000..29fb32b401 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/Polygons/RimPolygonTools.h @@ -0,0 +1,43 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +class RimPolygon; +class RimPolygonInView; + +class QString; + +namespace caf +{ +class PdmObject; +} + +class RimPolygonTools +{ +public: + static void activate3dEditOfPolygonInView( RimPolygon* polygon, caf::PdmObject* sourceObject ); + static void selectPolygonInView( RimPolygon* polygon, caf::PdmObject* sourceObject ); + static bool exportPolygonCsv( const RimPolygon* polygon, const QString& filePath ); + static bool exportPolygonPol( const RimPolygon* polygon, const QString& filePath ); + + static QString polygonCacheName(); + +private: + static RimPolygonInView* findPolygonInView( RimPolygon* polygon, caf::PdmObject* sourceObject ); +}; diff --git a/ApplicationLibCode/ProjectDataModel/ProcessControl/RimProcess.cpp b/ApplicationLibCode/ProjectDataModel/ProcessControl/RimProcess.cpp index 5fe493acef..770b6f3684 100644 --- a/ApplicationLibCode/ProjectDataModel/ProcessControl/RimProcess.cpp +++ b/ApplicationLibCode/ProjectDataModel/ProcessControl/RimProcess.cpp @@ -23,6 +23,7 @@ #include "cafPdmFieldCapability.h" +#include #include #include diff --git a/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionView.cpp b/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionView.cpp index 63e67d833c..4fc6d0bd04 100644 --- a/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionView.cpp +++ b/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionView.cpp @@ -70,13 +70,11 @@ Rim2dIntersectionView::Rim2dIntersectionView() m_intersection.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendDefinition", "Color Legend" ); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); m_legendConfig.uiCapability()->setUiTreeChildrenHidden( true ); m_legendConfig.xmlCapability()->disableIO(); m_legendConfig = new RimRegularLegendConfig(); CAF_PDM_InitFieldNoDefault( &m_ternaryLegendConfig, "TernaryLegendDefinition", "Ternary Color Legend" ); - m_ternaryLegendConfig.uiCapability()->setUiTreeHidden( true ); m_ternaryLegendConfig.uiCapability()->setUiTreeChildrenHidden( true ); m_ternaryLegendConfig.xmlCapability()->disableIO(); m_ternaryLegendConfig = new RimTernaryLegendConfig(); diff --git a/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionViewCollection.cpp index 6a0c0ab1ff..7502d72fb7 100644 --- a/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Rim2dIntersectionViewCollection.cpp @@ -32,7 +32,6 @@ Rim2dIntersectionViewCollection::Rim2dIntersectionViewCollection() CAF_PDM_InitObject( "2D Intersection Views", ":/CrossSection16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_intersectionViews, "IntersectionViews", "Intersection Views", ":/CrossSection16x16.png" ); - m_intersectionViews.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Rim3dView.cpp b/ApplicationLibCode/ProjectDataModel/Rim3dView.cpp index 19f00ad9df..8d98b5067c 100644 --- a/ApplicationLibCode/ProjectDataModel/Rim3dView.cpp +++ b/ApplicationLibCode/ProjectDataModel/Rim3dView.cpp @@ -51,7 +51,6 @@ #include "RimWellPathCollection.h" #include "RivAnnotationsPartMgr.h" -#include "RivCellFilterPartMgr.h" #include "RivMeasurementPartMgr.h" #include "RivWellPathsPartMgr.h" @@ -174,7 +173,6 @@ Rim3dView::Rim3dView() m_wellPathsPartManager = new RivWellPathsPartMgr( this ); m_annotationsPartManager = new RivAnnotationsPartMgr( this ); - m_cellfilterPartManager = new RivCellFilterPartMgr( this ); m_measurementPartManager = new RivMeasurementPartMgr( this ); this->setAs3DViewMdiWindow(); @@ -358,14 +356,11 @@ cvf::Color3f Rim3dView::backgroundColor() const //-------------------------------------------------------------------------------------------------- QWidget* Rim3dView::createViewWidget( QWidget* mainWindowParent ) { - QGLFormat glFormat; - glFormat.setDirectRendering( RiaGuiApplication::instance()->useShaders() ); - // If parent widget is a live widget, the application will get OpenGL window issues if started on a non-primary // screen. Using nullptr as parent solves the issue. // https://github.com/OPM/ResInsight/issues/8192 // - m_viewer = new RiuViewer( glFormat, nullptr ); + m_viewer = new RiuViewer( nullptr ); m_viewer->setOwnerReservoirView( this ); cvf::String xLabel; @@ -537,11 +532,6 @@ QImage Rim3dView::snapshotWindowContent() { if ( m_viewer ) { - // Force update of scheduled display models before snapshotting - RiaViewRedrawScheduler::instance()->updateAndRedrawScheduledViews(); - - m_viewer->repaint(); - return m_viewer->snapshotImage(); } @@ -709,14 +699,12 @@ void Rim3dView::updateDisplayModelForCurrentTimeStepAndRedraw() this->onUpdateDisplayModelForCurrentTimeStep(); appendAnnotationsToModel(); appendMeasurementToModel(); - appendCellFiltersToModel(); if ( Rim3dView* depView = prepareComparisonView() ) { depView->onUpdateDisplayModelForCurrentTimeStep(); depView->appendAnnotationsToModel(); depView->appendMeasurementToModel(); - depView->appendCellFiltersToModel(); restoreComparisonView(); } @@ -1141,19 +1129,6 @@ void Rim3dView::addAnnotationsToModel( cvf::ModelBasicList* annotationsModel ) annotationsModel->updateBoundingBoxesRecursive(); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void Rim3dView::addCellFiltersToModel( cvf::ModelBasicList* cellFilterModel ) -{ - if ( !this->ownerCase() ) return; - - cvf::ref transForm = displayCoordTransform(); - m_cellfilterPartManager->appendGeometryPartsToModel( cellFilterModel, transForm.p(), ownerCase()->allCellsBoundingBox() ); - - cellFilterModel->updateBoundingBoxesRecursive(); -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -1724,28 +1699,6 @@ void Rim3dView::updateScreenSpaceModel() nativeOrOverrideViewer()->addStaticModelOnce( m_screenSpaceModel.p(), isUsingOverrideViewer() ); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void Rim3dView::appendCellFiltersToModel() -{ - if ( !nativeOrOverrideViewer() ) return; - - cvf::Scene* frameScene = nativeOrOverrideViewer()->frame( m_currentTimeStep, isUsingOverrideViewer() ); - if ( frameScene ) - { - cvf::String name = "CellFilters"; - this->removeModelByName( frameScene, name ); - - cvf::ref model = new cvf::ModelBasicList; - model->setName( name ); - - addCellFiltersToModel( model.p() ); - - frameScene->addModel( model.p() ); - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -1753,18 +1706,19 @@ void Rim3dView::appendMeasurementToModel() { if ( !nativeOrOverrideViewer() ) return; - cvf::Scene* frameScene = nativeOrOverrideViewer()->frame( m_currentTimeStep, isUsingOverrideViewer() ); - if ( frameScene ) + const cvf::String name = "Measurement"; + + cvf::Scene* scene = nativeOrOverrideViewer()->currentScene( isUsingOverrideViewer() ); + if ( scene ) { - cvf::String name = "Measurement"; - this->removeModelByName( frameScene, name ); + Rim3dView::removeModelByName( scene, name ); cvf::ref model = new cvf::ModelBasicList; model->setName( name ); addMeasurementToModel( model.p() ); - frameScene->addModel( model.p() ); + scene->addModel( model.p() ); } } @@ -1868,7 +1822,7 @@ void Rim3dView::onUpdateScaleTransform() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void Rim3dView::updateSurfacesInViewTreeItems() +void Rim3dView::updateViewTreeItems( RiaDefines::ItemIn3dView itemType ) { // default is to do nothing } diff --git a/ApplicationLibCode/ProjectDataModel/Rim3dView.h b/ApplicationLibCode/ProjectDataModel/Rim3dView.h index c58b5daedd..a193617c6a 100644 --- a/ApplicationLibCode/ProjectDataModel/Rim3dView.h +++ b/ApplicationLibCode/ProjectDataModel/Rim3dView.h @@ -52,7 +52,6 @@ class RiuViewer; class RivAnnotationsPartMgr; class RivMeasurementPartMgr; class RivWellPathsPartMgr; -class RivCellFilterPartMgr; class RimViewNameConfig; namespace cvf @@ -193,7 +192,7 @@ class Rim3dView : public RimViewWindow, public RiuViewerToViewInterface, public RimViewLinker* assosiatedViewLinker() const override; RimViewController* viewController() const override; - virtual void updateSurfacesInViewTreeItems(); + virtual void updateViewTreeItems( RiaDefines::ItemIn3dView itemType ); RimAnnotationInViewCollection* annotationCollection() const; void syncronizeLocalAnnotationsFromGlobal(); @@ -222,7 +221,6 @@ class Rim3dView : public RimViewWindow, public RiuViewerToViewInterface, public double characteristicCellSize ); void addAnnotationsToModel( cvf::ModelBasicList* annotationsModel ); void addMeasurementToModel( cvf::ModelBasicList* measureModel ); - void addCellFiltersToModel( cvf::ModelBasicList* cellFilterModel ); // Override viewer @@ -311,7 +309,6 @@ class Rim3dView : public RimViewWindow, public RiuViewerToViewInterface, public void createHighlightAndGridBoxDisplayModel(); void appendMeasurementToModel(); - void appendCellFiltersToModel(); void appendAnnotationsToModel(); void updateScreenSpaceModel(); @@ -349,7 +346,6 @@ class Rim3dView : public RimViewWindow, public RiuViewerToViewInterface, public // 3D display model data cvf::ref m_annotationsPartManager; cvf::ref m_measurementPartManager; - cvf::ref m_cellfilterPartManager; // Timer for animations std::unique_ptr m_animationTimer; diff --git a/ApplicationLibCode/ProjectDataModel/RimAdvancedSnapshotExportDefinition.cpp b/ApplicationLibCode/ProjectDataModel/RimAdvancedSnapshotExportDefinition.cpp index 1efc9e70cf..046c5e7b7d 100644 --- a/ApplicationLibCode/ProjectDataModel/RimAdvancedSnapshotExportDefinition.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimAdvancedSnapshotExportDefinition.cpp @@ -197,8 +197,7 @@ void RimAdvancedSnapshotExportDefinition::fieldChangedByUi( const caf::PdmFieldH if ( mainGrid && actCellInfo ) { - cvf::Vec3st min, max; - actCellInfo->IJKBoundingBox( min, max ); + auto [min, max] = actCellInfo->ijkBoundingBox(); // Adjust to Eclipse indexing min.x() = min.x() + 1; diff --git a/ApplicationLibCode/ProjectDataModel/RimCase.cpp b/ApplicationLibCode/ProjectDataModel/RimCase.cpp index a84defae7e..14250fb879 100644 --- a/ApplicationLibCode/ProjectDataModel/RimCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimCase.cpp @@ -67,12 +67,10 @@ RimCase::RimCase() CAF_PDM_InitFieldNoDefault( &m_activeFormationNames, "DefaultFormationNames", "Formation Names File" ); CAF_PDM_InitFieldNoDefault( &m_timeStepFilter, "TimeStepFilter", "Time Step Filter" ); - m_timeStepFilter.uiCapability()->setUiTreeHidden( true ); m_timeStepFilter.uiCapability()->setUiTreeChildrenHidden( true ); m_timeStepFilter = new RimTimeStepFilter; CAF_PDM_InitFieldNoDefault( &m_2dIntersectionViewCollection, "IntersectionViewCollection", "2D Intersection Views", ":/CrossSections16x16.png" ); - m_2dIntersectionViewCollection.uiCapability()->setUiTreeHidden( true ); m_2dIntersectionViewCollection = new Rim2dIntersectionViewCollection(); } diff --git a/ApplicationLibCode/ProjectDataModel/RimCaseCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimCaseCollection.cpp index 5899a7e874..73d94d2748 100644 --- a/ApplicationLibCode/ProjectDataModel/RimCaseCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimCaseCollection.cpp @@ -33,7 +33,6 @@ RimCaseCollection::RimCaseCollection() CAF_PDM_InitObject( "Derived Statistics" ); CAF_PDM_InitFieldNoDefault( &reservoirs, "Reservoirs", "Reservoirs ChildArrayField" ); - reservoirs.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimColorLegend.cpp b/ApplicationLibCode/ProjectDataModel/RimColorLegend.cpp index fa06f0c9db..637ccf11d2 100644 --- a/ApplicationLibCode/ProjectDataModel/RimColorLegend.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimColorLegend.cpp @@ -40,7 +40,6 @@ RimColorLegend::RimColorLegend() CAF_PDM_InitField( &m_colorLegendName, "ColorLegendName", QString( "" ), "Color Legend Name" ); CAF_PDM_InitFieldNoDefault( &m_colorLegendItems, "ColorLegendItems", "" ); - m_colorLegendItems.uiCapability()->setUiTreeHidden( true ); setDeletable( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/RimCommandObject.cpp b/ApplicationLibCode/ProjectDataModel/RimCommandObject.cpp index 4b51937e9e..d6fc849771 100644 --- a/ApplicationLibCode/ProjectDataModel/RimCommandObject.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimCommandObject.cpp @@ -63,9 +63,7 @@ RimCommandExecuteScript::RimCommandExecuteScript() CAF_PDM_InitField( &isEnabled, "IsEnabled", true, "Enabled " ); CAF_PDM_InitField( &execute, "Execute", true, "Execute" ); - execute.xmlCapability()->disableIO(); - execute.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - execute.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &execute ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimContextCommandBuilder.cpp b/ApplicationLibCode/ProjectDataModel/RimContextCommandBuilder.cpp index 8745c6db91..71841548ff 100644 --- a/ApplicationLibCode/ProjectDataModel/RimContextCommandBuilder.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimContextCommandBuilder.cpp @@ -389,9 +389,11 @@ caf::CmdFeatureMenuBuilder RimContextCommandBuilder::commandsFromSelection() { menuBuilder << "RicNewEditableWellPathFeature"; menuBuilder << "RicNewWellPathLateralFeature"; - menuBuilder << "RicLinkWellPathFeature"; menuBuilder << "RicDuplicateWellPathFeature"; + menuBuilder.addSeparator(); + menuBuilder << "RicSetParentWellPathFeature"; + menuBuilder.addSeparator(); menuBuilder << "RicNewWellPathIntersectionFeature"; @@ -421,6 +423,7 @@ caf::CmdFeatureMenuBuilder RimContextCommandBuilder::commandsFromSelection() menuBuilder.subMenuEnd(); menuBuilder.addSeparator(); + menuBuilder << "RicLinkWellPathFeature"; menuBuilder << "RicDeleteWellPathFeature"; menuBuilder.addSeparator(); @@ -1151,6 +1154,11 @@ caf::CmdFeatureMenuBuilder RimContextCommandBuilder::commandsFromSelection() if ( firstUiItem ) { + if ( auto pdmObject = dynamic_cast( firstUiItem ) ) + { + pdmObject->appendMenuItems( menuBuilder ); + } + // Work in progress -- Start // All commands should be aware of selection of multiple objects // Based on the selection, the command feature can decide if the command @@ -1492,6 +1500,7 @@ int RimContextCommandBuilder::appendImportMenu( caf::CmdFeatureMenuBuilder& menu candidates << "RicWellPathsImportFileFeature"; candidates << "RicWellPathFormationsImportFileFeature"; candidates << "RicWellLogsImportFileFeature"; + candidates << "RicImportWellLogCsvFileFeature"; candidates << "RicReloadWellPathFormationNamesFeature"; return appendSubMenuWithCommands( menuBuilder, candidates, "Import", QIcon(), addSeparatorBeforeMenu ); diff --git a/ApplicationLibCode/ProjectDataModel/RimCustomObjectiveFunctionWeight.cpp b/ApplicationLibCode/ProjectDataModel/RimCustomObjectiveFunctionWeight.cpp index f459d88122..977d8c2903 100644 --- a/ApplicationLibCode/ProjectDataModel/RimCustomObjectiveFunctionWeight.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimCustomObjectiveFunctionWeight.cpp @@ -49,12 +49,10 @@ RimCustomObjectiveFunctionWeight::RimCustomObjectiveFunctionWeight() m_objectiveValuesSummaryAddressesUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_objectiveValuesSummaryAddresses, "ObjectiveSummaryAddress", "Summary Address" ); - m_objectiveValuesSummaryAddresses.uiCapability()->setUiTreeHidden( true ); m_objectiveValuesSummaryAddresses.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_objectiveValuesSelectSummaryAddressPushButton, "SelectObjectiveSummaryAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_objectiveValuesSelectSummaryAddressPushButton ); - m_objectiveValuesSelectSummaryAddressPushButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_objectiveValuesSelectSummaryAddressPushButton ); m_objectiveValuesSelectSummaryAddressPushButton = false; CAF_PDM_InitField( &m_weightValue, "WeightValue", 1.0, "Weight" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimDataSourceSteppingTools.cpp b/ApplicationLibCode/ProjectDataModel/RimDataSourceSteppingTools.cpp index 404f0388f3..fb61df4c9b 100644 --- a/ApplicationLibCode/ProjectDataModel/RimDataSourceSteppingTools.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimDataSourceSteppingTools.cpp @@ -18,12 +18,10 @@ #include "RimDataSourceSteppingTools.h" -#include "RiaSummaryAddressAnalyzer.h" +#include "RimProject.h" +#include "RimSummaryCalculationCollection.h" #include "RifEclipseSummaryAddress.h" -#include "cafPdmUiFieldHandle.h" - -#include "cvfAssert.h" //-------------------------------------------------------------------------------------------------- /// @@ -184,12 +182,34 @@ bool RimDataSourceSteppingTools::updateAddressIfMatching( const QVariant& //-------------------------------------------------------------------------------------------------- bool RimDataSourceSteppingTools::updateQuantityIfMatching( const QVariant& oldValue, const QVariant& newValue, RifEclipseSummaryAddress& adr ) { - std::string oldString = oldValue.toString().toStdString(); - std::string newString = newValue.toString().toStdString(); + std::string oldString = oldValue.toString().toStdString(); + auto newQString = newValue.toString(); + std::string newString = newQString.toStdString(); + + // Calculation ID < 0 means native summary vector + int calculationId = -1; + + RimSummaryCalculationCollection* calculationColl = RimProject::current()->calculationCollection(); + if ( calculationColl ) + { + // Parse the calculations and find ID if text is matching. This can cause issues if a calculation has the same name as a native + // summary vector imported from file. + + auto calculations = calculationColl->calculations(); + for ( auto c : calculations ) + { + if ( c->shortName() == newQString ) + { + calculationId = c->id(); + break; + } + } + } if ( adr.vectorName() == oldString ) { adr.setVectorName( newString ); + adr.setId( calculationId ); return true; } diff --git a/ApplicationLibCode/ProjectDataModel/RimDepthTrackPlot.cpp b/ApplicationLibCode/ProjectDataModel/RimDepthTrackPlot.cpp index 11fd2fe36b..d65dca2134 100644 --- a/ApplicationLibCode/ProjectDataModel/RimDepthTrackPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimDepthTrackPlot.cpp @@ -103,7 +103,6 @@ RimDepthTrackPlot::RimDepthTrackPlot() CAF_PDM_InitObject( "Depth Track Plot", "", "", "A Plot With a shared Depth Axis and Multiple Tracks" ); CAF_PDM_InitFieldNoDefault( &m_commonDataSource, "CommonDataSource", "Data Source", "", "Change the Data Source of All Curves in the Plot", "" ); - m_commonDataSource.uiCapability()->setUiTreeHidden( true ); m_commonDataSource.uiCapability()->setUiTreeChildrenHidden( true ); m_commonDataSource.xmlCapability()->disableIO(); m_commonDataSource = new RimWellLogCurveCommonDataSource; @@ -139,7 +138,6 @@ RimDepthTrackPlot::RimDepthTrackPlot() CAF_PDM_InitScriptableField( &m_autoZoomMaxDepthFactor, "AutoZoomMaxDepthFactor", 0.0, "Auto Zoom Maximum Factor" ); CAF_PDM_InitFieldNoDefault( &m_depthAnnotations, "DepthAnnotations", "Depth Annotations" ); - m_depthAnnotations.uiCapability()->setUiTreeHidden( true ); m_depthAnnotations.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitScriptableFieldNoDefault( &m_subTitleFontSize, "SubTitleFontSize", "Track Title Font Size" ); @@ -147,7 +145,6 @@ RimDepthTrackPlot::RimDepthTrackPlot() CAF_PDM_InitScriptableFieldNoDefault( &m_axisValueFontSize, "AxisValueFontSize", "Axis Value Font Size" ); CAF_PDM_InitFieldNoDefault( &m_nameConfig, "NameConfig", "" ); - m_nameConfig.uiCapability()->setUiTreeHidden( true ); m_nameConfig.uiCapability()->setUiTreeChildrenHidden( true ); m_nameConfig = new RimWellLogPlotNameConfig(); @@ -155,7 +152,6 @@ RimDepthTrackPlot::RimDepthTrackPlot() CAF_PDM_InitFieldNoDefault( &m_depthEqualization, "DepthEqualization", "Depth Equalization" ); CAF_PDM_InitFieldNoDefault( &m_plots, "Tracks", "Tracks" ); - m_plots.uiCapability()->setUiTreeHidden( true ); auto reorderability = caf::PdmFieldReorderCapability::addToField( &m_plots ); reorderability->orderChanged.connect( this, &RimDepthTrackPlot::onPlotsReordered ); diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseCase.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseCase.cpp index 9b97a53668..17c2c98d8a 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseCase.cpp @@ -92,23 +92,21 @@ RimEclipseCase::RimEclipseCase() CAF_PDM_InitScriptableObjectWithNameAndComment( "EclipseCase", ":/Case48x48.png", "", "", "Reservoir", "Abstract base class for Eclipse Cases" ); CAF_PDM_InitScriptableFieldWithScriptKeywordNoDefault( &reservoirViews, "ReservoirViews", "Views", "", "", "", "All Eclipse Views in the case" ); - reservoirViews.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_matrixModelResults, "MatrixModelResults", "" ); - m_matrixModelResults.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_fractureModelResults, "FractureModelResults", "" ); - m_fractureModelResults.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_flipXAxis, "FlipXAxis", false, "Flip X Axis" ); CAF_PDM_InitField( &m_flipYAxis, "FlipYAxis", false, "Flip Y Axis" ); - CAF_PDM_InitFieldNoDefault( &m_filesContainingFaults_OBSOLETE, "CachedFileNamesContainingFaults", "" ); - m_filesContainingFaults_OBSOLETE.uiCapability()->setUiHidden( true ); - m_filesContainingFaults_OBSOLETE.xmlCapability()->disableIO(); + CAF_PDM_InitFieldNoDefault( &m_filesContainingFaults, "CachedFileNamesContainingFaults", "" ); + m_filesContainingFaults.uiCapability()->setUiHidden( true ); + // Caching of file names causes issues when using the project file as template, do not save to disk + // https://github.com/OPM/ResInsight/issues/7308 + m_filesContainingFaults.xmlCapability()->disableIO(); CAF_PDM_InitFieldNoDefault( &m_contourMapCollection, "ContourMaps", "2d Contour Maps" ); m_contourMapCollection = new RimEclipseContourMapViewCollection; - m_contourMapCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_inputPropertyCollection, "InputPropertyCollection", "" ); m_inputPropertyCollection = new RimEclipseInputPropertyCollection; @@ -116,17 +114,14 @@ RimEclipseCase::RimEclipseCase() CAF_PDM_InitFieldNoDefault( &m_resultAddressCollections, "ResultAddressCollections", "Result Addresses" ); m_resultAddressCollections.uiCapability()->setUiHidden( true ); - m_resultAddressCollections.uiCapability()->setUiTreeHidden( true ); m_resultAddressCollections.xmlCapability()->disableIO(); // Init m_matrixModelResults = new RimReservoirCellResultsStorage; - m_matrixModelResults.uiCapability()->setUiTreeHidden( true ); m_matrixModelResults.uiCapability()->setUiTreeChildrenHidden( true ); m_fractureModelResults = new RimReservoirCellResultsStorage; - m_fractureModelResults.uiCapability()->setUiTreeHidden( true ); m_fractureModelResults.uiCapability()->setUiTreeChildrenHidden( true ); setReservoirData( nullptr ); @@ -460,7 +455,7 @@ void RimEclipseCase::fieldChangedByUi( const caf::PdmFieldHandle* changedField, RimCase::fieldChangedByUi( changedField, oldValue, newValue ); if ( changedField == &m_releaseResultMemory ) { - RimReloadCaseTools::reloadAllEclipseGridData( this ); + RimReloadCaseTools::reloadEclipseGrid( this ); m_releaseResultMemory = oldValue.toBool(); } @@ -625,11 +620,9 @@ void RimEclipseCase::computeCachedData() caf::ProgressInfo pInf( 30, "" ); { - auto task = pInf.task( "", 1 ); - rigEclipseCase->computeActiveCellBoundingBoxes(); - } + // NB! Call computeCachedData() first, as this function also computes the bounding box used in other functions, specifically + // computeActiveCellsBoundingBox() - { auto task = pInf.task( "Calculating Cell Search Tree", 10 ); std::string aabbTreeInfo; @@ -639,6 +632,11 @@ void RimEclipseCase::computeCachedData() // RiaLogging::debug( QString::fromStdString( aabbTreeInfo ) ); } + { + auto task = pInf.task( "", 1 ); + computeActiveCellsBoundingBox(); + } + { auto task = pInf.task( "Calculating faults", 17 ); @@ -708,7 +706,7 @@ void RimEclipseCase::loadAndSynchronizeInputProperties( bool importGridOrFaultDa // Make sure we actually have reservoir data CVF_ASSERT( eclipseCaseData() ); - CVF_ASSERT( eclipseCaseData()->mainGrid()->gridPointDimensions() != cvf::Vec3st( 0, 0, 0 ) ); + CVF_ASSERT( eclipseCaseData()->mainGrid()->cellCount() != 0 ); // Then read the properties from all the files referenced by the InputReservoir @@ -771,6 +769,26 @@ void RimEclipseCase::createDisplayModelAndUpdateAllViews() } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseCase::computeActiveCellsBoundingBox() +{ + if ( !eclipseCaseData() ) return; + + bool useOptimizedVersion = true; + + if ( auto proj = RimProject::current() ) + { + if ( proj->isProjectFileVersionEqualOrOlderThan( "2023.12.0" ) ) + { + useOptimizedVersion = false; + } + } + + eclipseCaseData()->computeActiveCellBoundingBoxes( useOptimizedVersion ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -911,7 +929,7 @@ std::vector RimEclipseCase::filesContainingFaults() const { std::vector stdPathList; - for ( auto& filePath : m_filesContainingFaults_OBSOLETE() ) + for ( auto& filePath : m_filesContainingFaults() ) { stdPathList.push_back( filePath.path() ); } @@ -930,7 +948,7 @@ void RimEclipseCase::setFilesContainingFaults( const std::vector& pathS filePaths.push_back( pathString ); } - m_filesContainingFaults_OBSOLETE = filePaths; + m_filesContainingFaults = filePaths; } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseCase.h b/ApplicationLibCode/ProjectDataModel/RimEclipseCase.h index e0ed0596be..dad144c78d 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseCase.h +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseCase.h @@ -122,6 +122,7 @@ class RimEclipseCase : public RimCase void ensureFaultDataIsComputed(); bool ensureNncDataIsComputed(); void createDisplayModelAndUpdateAllViews(); + void computeActiveCellsBoundingBox(); void setReaderSettings( std::shared_ptr readerSettings ); @@ -166,7 +167,5 @@ class RimEclipseCase : public RimCase caf::PdmChildField m_matrixModelResults; caf::PdmChildField m_fractureModelResults; - // To be removed as the caching of file names causes issues when using the project file as template - // https://github.com/OPM/ResInsight/issues/7308 - caf::PdmField> m_filesContainingFaults_OBSOLETE; + caf::PdmField> m_filesContainingFaults; }; diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseCaseCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseCaseCollection.cpp index 1e5de1a137..7d770d090f 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseCaseCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseCaseCollection.cpp @@ -44,10 +44,8 @@ RimEclipseCaseCollection::RimEclipseCaseCollection() CAF_PDM_InitObject( "Grid Models", ":/Cases16x16.png" ); CAF_PDM_InitFieldNoDefault( &cases, "Reservoirs", "" ); - cases.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &caseGroups, "CaseGroups", "" ); - caseGroups.uiCapability()->setUiTreeHidden( true ); m_gridCollection = new RigGridManager; } diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapProjection.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapProjection.cpp index 207adb36e3..bda217ec3c 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapProjection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapProjection.cpp @@ -66,7 +66,6 @@ RimEclipseContourMapProjection::RimEclipseContourMapProjection() CAF_PDM_InitField( &m_weightByParameter, "WeightByParameter", false, "Weight by Result Parameter" ); CAF_PDM_InitFieldNoDefault( &m_weightingResult, "WeightingResult", "" ); - m_weightingResult.uiCapability()->setUiTreeHidden( true ); m_weightingResult.uiCapability()->setUiTreeChildrenHidden( true ); m_weightingResult = new RimEclipseResultDefinition; m_weightingResult->findField( "MResultType" )->uiCapability()->setUiName( "Result Type" ); @@ -402,9 +401,7 @@ RimGridView* RimEclipseContourMapProjection::baseView() const //-------------------------------------------------------------------------------------------------- std::vector RimEclipseContourMapProjection::findIntersectingCells( const cvf::BoundingBox& bbox ) const { - std::vector allCellIndices; - m_mainGrid->findIntersectingCells( bbox, &allCellIndices ); - return allCellIndices; + return m_mainGrid->findIntersectingCells( bbox ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapViewCollection.cpp index 64c3540048..317765fca5 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseContourMapViewCollection.cpp @@ -13,7 +13,6 @@ RimEclipseContourMapViewCollection::RimEclipseContourMapViewCollection() CAF_PDM_InitObject( "Contour Maps", ":/2DMaps16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_contourMapViews, "EclipseViews", "Contour Maps", ":/CrossSection16x16.png" ); - m_contourMapViews.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseFaultColors.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseFaultColors.cpp index 6fdfc2c668..6990605095 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseFaultColors.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseFaultColors.cpp @@ -42,7 +42,6 @@ RimEclipseFaultColors::RimEclipseFaultColors() CAF_PDM_InitFieldNoDefault( &m_customFaultResultColors, "CustomResultSlot", "Custom Fault Result", ":/CellResult.png" ); m_customFaultResultColors = new RimEclipseCellColors(); - m_customFaultResultColors.uiCapability()->setUiTreeHidden( true ); m_customFaultResultColors->enableDeltaResults( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseInputCase.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseInputCase.cpp index b9319f1c0f..345485560e 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseInputCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseInputCase.cpp @@ -114,7 +114,7 @@ bool RimEclipseInputCase::openDataFileSet( const QStringList& fileNames ) QString gridFileName; // First find and read the grid data - if ( eclipseCaseData()->mainGrid()->gridPointDimensions() == cvf::Vec3st( 0, 0, 0 ) ) + if ( eclipseCaseData()->mainGrid()->cellCount() == 0 ) { for ( int i = 0; i < fileNames.size(); i++ ) { @@ -142,7 +142,7 @@ bool RimEclipseInputCase::openDataFileSet( const QStringList& fileNames ) } } - if ( eclipseCaseData()->mainGrid()->gridPointDimensions() == cvf::Vec3st( 0, 0, 0 ) ) + if ( eclipseCaseData()->mainGrid()->cellCount() == 0 ) { for ( QString errorMessages : allErrorMessages ) { diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseInputPropertyCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseInputPropertyCollection.cpp index 4bb0144d65..b261ec1166 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseInputPropertyCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseInputPropertyCollection.cpp @@ -34,7 +34,6 @@ RimEclipseInputPropertyCollection::RimEclipseInputPropertyCollection() CAF_PDM_InitObject( "Input Properties", ":/EclipseInput48x48.png" ); CAF_PDM_InitFieldNoDefault( &inputProperties, "InputProperties", "" ); - inputProperties.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseResultAddressCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseResultAddressCollection.cpp index 8cdf5d4d80..286adc35ce 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseResultAddressCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseResultAddressCollection.cpp @@ -32,7 +32,6 @@ RimEclipseResultAddressCollection::RimEclipseResultAddressCollection() CAF_PDM_InitObject( "Folder", ":/Folder.png", "", "" ); CAF_PDM_InitFieldNoDefault( &m_adresses, "Addresses", "Addresses" ); - m_adresses.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_resultType, "ResultType", "Type" ); m_resultType.uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.cpp index b08c30af91..5cb28a8360 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.cpp @@ -55,14 +55,17 @@ #include "RimTimeStepFilter.h" #include "RimTools.h" +#include "cafPdmUiCheckBoxAndTextEditor.h" #include "cafPdmUiFilePathEditor.h" #include "cafPdmUiPropertyViewDialog.h" #include "cafProgressInfo.h" #include "cafUtils.h" +#include #include #include #include + #include #include @@ -91,7 +94,6 @@ RimEclipseResultCase::RimEclipseResultCase() m_unitSystem.uiCapability()->setUiReadOnly( true ); CAF_PDM_InitFieldNoDefault( &m_flowDiagSolutions, "FlowDiagSolutions", "Flow Diagnostics Solutions" ); - m_flowDiagSolutions.uiCapability()->setUiTreeHidden( true ); m_flowDiagSolutions.uiCapability()->setUiTreeChildrenHidden( true ); m_flipXAxis.xmlCapability()->setIOWritable( true ); @@ -102,6 +104,9 @@ RimEclipseResultCase::RimEclipseResultCase() #ifndef USE_HDF5 m_sourSimFileName.uiCapability()->setUiHidden( true ); #endif + + CAF_PDM_InitField( &m_mswMergeThreshold, "MswMergeThreshold", std::make_pair( false, 3 ), "MSW Short Well Merge Threshold" ); + m_mswMergeThreshold.uiCapability()->setUiEditorTypeName( caf::PdmUiCheckBoxAndTextEditor::uiEditorTypeName() ); } //-------------------------------------------------------------------------------------------------- @@ -313,7 +318,7 @@ bool RimEclipseResultCase::openAndReadActiveCellData( RigEclipseCaseData* mainEc CVF_ASSERT( eclipseCaseData() ); CVF_ASSERT( readerInterface.notNull() ); - eclipseCaseData()->computeActiveCellBoundingBoxes(); + computeActiveCellsBoundingBox(); m_activeCellInfoIsReadFromFile = true; @@ -493,6 +498,13 @@ cvf::ref RimEclipseResultCase::createMockModel( QString mode //-------------------------------------------------------------------------------------------------- RimEclipseResultCase::~RimEclipseResultCase() { + // Disconnect all comparison views. In debug build on Windows, a crash occurs. The comparison view is also set to zero in the destructor + // of Rim3dView() + for ( auto v : reservoirViews ) + { + if ( v ) v->setComparisonView( nullptr ); + } + reservoirViews.deleteChildren(); m_flowDiagSolutions.deleteChildren(); } @@ -561,6 +573,21 @@ RifReaderRftInterface* RimEclipseResultCase::rftReader() return m_readerEclipseRft.p(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RimEclipseResultCase::mswMergeThreshold() const +{ + // This value is used in RigMswCenterLineCalculator::calculateMswWellPipeGeometry + + if ( m_mswMergeThreshold().first ) + { + return m_mswMergeThreshold().second; + } + + return 4; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -607,6 +634,7 @@ void RimEclipseResultCase::defineUiOrdering( QString uiConfigName, caf::PdmUiOrd group->add( &m_activeFormationNames ); group->add( &m_flipXAxis ); group->add( &m_flipYAxis ); + group->add( &m_mswMergeThreshold ); if ( eclipseCaseData() && eclipseCaseData()->results( RiaDefines::PorosityModelType::MATRIX_MODEL ) && eclipseCaseData()->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->maxTimeStepCount() > 0 ) @@ -627,6 +655,15 @@ void RimEclipseResultCase::fieldChangedByUi( const caf::PdmFieldHandle* changedF loadAndUpdateSourSimData(); } + if ( changedField == &m_mswMergeThreshold ) + { + for ( auto resView : reservoirViews() ) + { + resView->scheduleSimWellGeometryRegen(); + resView->scheduleCreateDisplayModelAndRedraw(); + } + } + return RimEclipseCase::fieldChangedByUi( changedField, oldValue, newValue ); } diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.h b/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.h index 9edbd91b7d..a208056f70 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.h +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseResultCase.h @@ -73,6 +73,10 @@ class RimEclipseResultCase : public RimEclipseCase RifReaderRftInterface* rftReader(); + // A multi segment well can have multiple well paths. Valves can be modeled using short branches. This threshold defines the limit for + // merging branches into the upstream branch. + int mswMergeThreshold() const; + protected: void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; @@ -95,6 +99,8 @@ class RimEclipseResultCase : public RimEclipseCase caf::PdmChildArrayField m_flowDiagSolutions; caf::PdmField m_sourSimFileName; + caf::PdmField> m_mswMergeThreshold; + bool m_gridAndWellDataIsReadFromFile; bool m_activeCellInfoIsReadFromFile; bool m_useOpmRftReader; diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseResultDefinition.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseResultDefinition.cpp index ea63ec6231..ee64dffbd6 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseResultDefinition.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseResultDefinition.cpp @@ -1,1893 +1,1893 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// Copyright (C) 2011- Statoil ASA -// Copyright (C) 2013- Ceetron Solutions AS -// Copyright (C) 2011-2012 Ceetron AS -// -// ResInsight 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 3 of the License, or -// (at your option) any later version. -// -// ResInsight 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 at -// for more details. -// -///////////////////////////////////////////////////////////////////////////////// - -#include "RimEclipseResultDefinition.h" - -#include "RiaLogging.h" -#include "RiaQDateTimeTools.h" - -#include "RicfCommandObject.h" - -#include "RigActiveCellInfo.h" -#include "RigCaseCellResultsData.h" -#include "RigEclipseCaseData.h" -#include "RigEclipseResultInfo.h" -#include "RigFlowDiagResultAddress.h" -#include "RigFlowDiagResults.h" -#include "RigFormationNames.h" - -#include "Rim3dView.h" -#include "Rim3dWellLogCurve.h" -#include "RimCellEdgeColors.h" -#include "RimContourMapProjection.h" -#include "RimEclipseCase.h" -#include "RimEclipseCellColors.h" -#include "RimEclipseContourMapProjection.h" -#include "RimEclipseContourMapView.h" -#include "RimEclipseFaultColors.h" -#include "RimEclipsePropertyFilter.h" -#include "RimEclipseResultCase.h" -#include "RimEclipseResultDefinitionTools.h" -#include "RimEclipseView.h" -#include "RimFlowDiagSolution.h" -#include "RimFlowDiagnosticsTools.h" -#include "RimGridCrossPlot.h" -#include "RimGridCrossPlotDataSet.h" -#include "RimGridTimeHistoryCurve.h" -#include "RimIntersectionCollection.h" -#include "RimIntersectionResultDefinition.h" -#include "RimPlotCurve.h" -#include "RimProject.h" -#include "RimRegularLegendConfig.h" -#include "RimReservoirCellResultsStorage.h" -#include "RimViewLinker.h" -#include "RimWellLogExtractionCurve.h" -#include "RimWellLogTrack.h" - -#ifdef USE_QTCHARTS -#include "RimGridStatisticsPlot.h" -#endif - -#include "cafPdmFieldScriptingCapability.h" -#include "cafPdmUiToolButtonEditor.h" -#include "cafPdmUiTreeSelectionEditor.h" -#include "cafUtils.h" - -#include - -namespace caf -{ -template <> -void RimEclipseResultDefinition::FlowTracerSelectionEnum::setUp() -{ - addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD, "FLOW_TR_INJ_AND_PROD", "All Injectors and Producers" ); - addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_PRODUCERS, "FLOW_TR_PRODUCERS", "All Producers" ); - addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_INJECTORS, "FLOW_TR_INJECTORS", "All Injectors" ); - addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_BY_SELECTION, "FLOW_TR_BY_SELECTION", "By Selection" ); - - setDefault( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD ); -} -} // namespace caf - -CAF_PDM_SOURCE_INIT( RimEclipseResultDefinition, "ResultDefinition" ); - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimEclipseResultDefinition::RimEclipseResultDefinition( caf::PdmUiItemInfo::LabelPosType labelPosition ) - : m_isDeltaResultEnabled( false ) - , m_labelPosition( labelPosition ) - , m_ternaryEnabled( true ) -{ - CAF_PDM_InitScriptableObjectWithNameAndComment( "Result Definition", "", "", "", "EclipseResult", "An eclipse result definition" ); - - CAF_PDM_InitScriptableFieldNoDefault( &m_resultType, "ResultType", "Type" ); - m_resultType.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitScriptableFieldNoDefault( &m_porosityModel, "PorosityModelType", "Porosity" ); - m_porosityModel.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitScriptableField( &m_resultVariable, "ResultVariable", RiaResultNames::undefinedResultName(), "Variable" ); - m_resultVariable.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitFieldNoDefault( &m_flowSolution, "FlowDiagSolution", "Solution" ); - m_flowSolution.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitField( &m_timeLapseBaseTimestep, "TimeLapseBaseTimeStep", RigEclipseResultAddress::noTimeLapseValue(), "Base Time Step" ); - - CAF_PDM_InitFieldNoDefault( &m_differenceCase, "DifferenceCase", "Difference Case" ); - - CAF_PDM_InitField( &m_divideByCellFaceArea, "DivideByCellFaceArea", false, "Divide By Area" ); - - CAF_PDM_InitScriptableFieldNoDefault( &m_selectedInjectorTracers, "SelectedInjectorTracers", "Injector Tracers" ); - m_selectedInjectorTracers.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitScriptableFieldNoDefault( &m_selectedProducerTracers, "SelectedProducerTracers", "Producer Tracers" ); - m_selectedProducerTracers.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitScriptableFieldNoDefault( &m_selectedSouringTracers, "SelectedSouringTracers", "Tracers" ); - m_selectedSouringTracers.uiCapability()->setUiHidden( true ); - - CAF_PDM_InitScriptableFieldNoDefault( &m_flowTracerSelectionMode, "FlowTracerSelectionMode", "Tracers" ); - CAF_PDM_InitScriptableFieldNoDefault( &m_phaseSelection, "PhaseSelection", "Phases" ); - m_phaseSelection.uiCapability()->setUiLabelPosition( m_labelPosition ); - - CAF_PDM_InitScriptableField( &m_showOnlyVisibleCategoriesInLegend, - "ShowOnlyVisibleCategoriesInLegend", - true, - "Show Only Visible Categories In Legend" ); - - // Ui only fields - - CAF_PDM_InitFieldNoDefault( &m_resultTypeUiField, "MResultType", "Type" ); - m_resultTypeUiField.xmlCapability()->disableIO(); - m_resultTypeUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); - - CAF_PDM_InitFieldNoDefault( &m_porosityModelUiField, "MPorosityModelType", "Porosity" ); - m_porosityModelUiField.xmlCapability()->disableIO(); - m_porosityModelUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); - - CAF_PDM_InitField( &m_resultVariableUiField, "MResultVariable", RiaResultNames::undefinedResultName(), "Result Property" ); - m_resultVariableUiField.xmlCapability()->disableIO(); - m_resultVariableUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); - m_resultVariableUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); - - CAF_PDM_InitFieldNoDefault( &m_inputPropertyFileName, "InputPropertyFileName", "File Name" ); - m_inputPropertyFileName.xmlCapability()->disableIO(); - m_inputPropertyFileName.uiCapability()->setUiReadOnly( true ); - - CAF_PDM_InitFieldNoDefault( &m_flowSolutionUiField, "MFlowDiagSolution", "Solution" ); - m_flowSolutionUiField.xmlCapability()->disableIO(); - m_flowSolutionUiField.uiCapability()->setUiHidden( true ); // For now since there are only one to choose from - - CAF_PDM_InitField( &m_syncInjectorToProducerSelection, "MSyncSelectedInjProd", false, "Add Communicators ->" ); - m_syncInjectorToProducerSelection.uiCapability()->setUiEditorTypeName( caf::PdmUiToolButtonEditor::uiEditorTypeName() ); - - CAF_PDM_InitField( &m_syncProducerToInjectorSelection, "MSyncSelectedProdInj", false, "<- Add Communicators" ); - m_syncProducerToInjectorSelection.uiCapability()->setUiEditorTypeName( caf::PdmUiToolButtonEditor::uiEditorTypeName() ); - - CAF_PDM_InitFieldNoDefault( &m_selectedInjectorTracersUiField, "MSelectedInjectorTracers", "Injector Tracers" ); - m_selectedInjectorTracersUiField.xmlCapability()->disableIO(); - m_selectedInjectorTracersUiField.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); - - CAF_PDM_InitFieldNoDefault( &m_selectedProducerTracersUiField, "MSelectedProducerTracers", "Producer Tracers" ); - m_selectedProducerTracersUiField.xmlCapability()->disableIO(); - m_selectedProducerTracersUiField.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); - - CAF_PDM_InitFieldNoDefault( &m_selectedSouringTracersUiField, "MSelectedSouringTracers", "Tracers" ); - m_selectedSouringTracersUiField.xmlCapability()->disableIO(); - m_selectedSouringTracersUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimEclipseResultDefinition::~RimEclipseResultDefinition() -{ -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::simpleCopy( const RimEclipseResultDefinition* other ) -{ - setResultVariable( other->resultVariable() ); - setPorosityModel( other->porosityModel() ); - setResultType( other->resultType() ); - setFlowSolution( other->m_flowSolution() ); - setSelectedInjectorTracers( other->m_selectedInjectorTracers() ); - setSelectedProducerTracers( other->m_selectedProducerTracers() ); - setSelectedSouringTracers( other->m_selectedSouringTracers() ); - m_flowTracerSelectionMode = other->m_flowTracerSelectionMode(); - m_phaseSelection = other->m_phaseSelection; - - m_differenceCase = other->m_differenceCase(); - m_timeLapseBaseTimestep = other->m_timeLapseBaseTimestep(); - m_divideByCellFaceArea = other->m_divideByCellFaceArea(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setEclipseCase( RimEclipseCase* eclipseCase ) -{ - m_eclipseCase = eclipseCase; - - assignFlowSolutionFromCase(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimEclipseCase* RimEclipseResultDefinition::eclipseCase() const -{ - return m_eclipseCase; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RiaDefines::ResultCatType RimEclipseResultDefinition::resultType() const -{ - return m_resultType(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RigCaseCellResultsData* RimEclipseResultDefinition::currentGridCellResults() const -{ - if ( !m_eclipseCase ) return nullptr; - - return m_eclipseCase->results( m_porosityModel() ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) -{ - if ( &m_flowSolutionUiField == changedField || &m_resultTypeUiField == changedField || &m_porosityModelUiField == changedField ) - { - // If the user are seeing the list with the actually selected result, - // select that result in the list. Otherwise select nothing. - - QStringList varList = RimEclipseResultDefinitionTools::getResultNamesForResultType( m_resultTypeUiField(), currentGridCellResults() ); - - bool isFlowDiagFieldsRelevant = ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ); - - if ( ( m_flowSolutionUiField() == m_flowSolution() || !isFlowDiagFieldsRelevant ) && m_resultTypeUiField() == m_resultType() && - m_porosityModelUiField() == m_porosityModel() ) - { - if ( varList.contains( resultVariable() ) ) - { - m_resultVariableUiField = resultVariable(); - } - - if ( isFlowDiagFieldsRelevant ) - { - m_selectedInjectorTracersUiField = m_selectedInjectorTracers(); - m_selectedProducerTracersUiField = m_selectedProducerTracers(); - } - else - { - m_selectedInjectorTracersUiField = std::vector(); - m_selectedProducerTracersUiField = std::vector(); - } - } - else - { - m_resultVariableUiField = ""; - m_selectedInjectorTracersUiField = std::vector(); - m_selectedProducerTracersUiField = std::vector(); - } - } - - if ( &m_resultVariableUiField == changedField ) - { - m_porosityModel = m_porosityModelUiField; - m_resultType = m_resultTypeUiField; - m_resultVariable = m_resultVariableUiField; - - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - m_flowSolution = m_flowSolutionUiField(); - m_selectedInjectorTracers = m_selectedInjectorTracersUiField(); - m_selectedProducerTracers = m_selectedProducerTracersUiField(); - } - else if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INJECTION_FLOODING ) - { - m_selectedSouringTracers = m_selectedSouringTracersUiField(); - } - else if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INPUT_PROPERTY ) - { - m_inputPropertyFileName = RimEclipseResultDefinitionTools::getInputPropertyFileName( eclipseCase(), newValue.toString() ); - } - loadDataAndUpdate(); - } - - if ( &m_porosityModelUiField == changedField ) - { - m_porosityModel = m_porosityModelUiField; - m_resultVariableUiField = resultVariable(); - - auto eclipseView = firstAncestorOrThisOfType(); - if ( eclipseView ) - { - // Active cells can be different between matrix and fracture, make sure all geometry is recreated - eclipseView->scheduleReservoirGridGeometryRegen(); - } - - loadDataAndUpdate(); - } - - auto contourMapView = firstAncestorOrThisOfType(); - - if ( &m_differenceCase == changedField ) - { - m_timeLapseBaseTimestep = RigEclipseResultAddress::noTimeLapseValue(); - - if ( contourMapView ) - { - contourMapView->contourMapProjection()->clearGridMappingAndRedraw(); - } - - loadDataAndUpdate(); - } - - if ( &m_timeLapseBaseTimestep == changedField ) - { - if ( contourMapView ) - { - contourMapView->contourMapProjection()->clearGridMappingAndRedraw(); - } - - loadDataAndUpdate(); - } - - if ( &m_divideByCellFaceArea == changedField ) - { - loadDataAndUpdate(); - } - - if ( &m_flowTracerSelectionMode == changedField ) - { - loadDataAndUpdate(); - } - - if ( &m_selectedInjectorTracersUiField == changedField ) - { - changedTracerSelectionField( true ); - } - - if ( &m_selectedProducerTracersUiField == changedField ) - { - changedTracerSelectionField( false ); - } - - if ( &m_syncInjectorToProducerSelection == changedField ) - { - syncInjectorToProducerSelection(); - m_syncInjectorToProducerSelection = false; - } - - if ( &m_syncProducerToInjectorSelection == changedField ) - { - syncProducerToInjectorSelection(); - m_syncProducerToInjectorSelection = false; - } - - if ( &m_selectedSouringTracersUiField == changedField ) - { - if ( !m_resultVariable().isEmpty() ) - { - m_selectedSouringTracers = m_selectedSouringTracersUiField(); - loadDataAndUpdate(); - } - } - - if ( &m_phaseSelection == changedField ) - { - if ( m_phaseSelection() != RigFlowDiagResultAddress::PHASE_ALL ) - { - m_resultType = m_resultTypeUiField; - m_resultVariable = RIG_FLD_TOF_RESNAME; - m_resultVariableUiField = RIG_FLD_TOF_RESNAME; - } - loadDataAndUpdate(); - } - - if ( &m_showOnlyVisibleCategoriesInLegend == changedField ) - { - loadDataAndUpdate(); - } - - updateAnyFieldHasChanged(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::changedTracerSelectionField( bool injector ) -{ - m_flowSolution = m_flowSolutionUiField(); - - std::vector& selectedTracers = injector ? m_selectedInjectorTracers.v() : m_selectedProducerTracers.v(); - const std::vector& selectedTracersUi = injector ? m_selectedInjectorTracersUiField.v() : m_selectedProducerTracersUiField.v(); - - selectedTracers = selectedTracersUi; - - loadDataAndUpdate(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::updateAnyFieldHasChanged() -{ - RimEclipsePropertyFilter* propFilter = firstAncestorOrThisOfType(); - if ( propFilter ) - { - propFilter->updateConnectedEditors(); - } - - RimEclipseFaultColors* faultColors = firstAncestorOrThisOfType(); - if ( faultColors ) - { - faultColors->updateConnectedEditors(); - } - - RimCellEdgeColors* cellEdgeColors = firstAncestorOrThisOfType(); - if ( cellEdgeColors ) - { - cellEdgeColors->updateConnectedEditors(); - } - - RimEclipseCellColors* cellColors = firstAncestorOrThisOfType(); - if ( cellColors ) - { - cellColors->updateConnectedEditors(); - } - - RimIntersectionResultDefinition* intersectResDef = firstAncestorOrThisOfType(); - if ( intersectResDef ) - { - intersectResDef->setDefaultEclipseLegendConfig(); - intersectResDef->updateConnectedEditors(); - } - - RimGridCrossPlotDataSet* crossPlotCurveSet = firstAncestorOrThisOfType(); - if ( crossPlotCurveSet ) - { - crossPlotCurveSet->updateConnectedEditors(); - } - - RimPlotCurve* curve = firstAncestorOrThisOfType(); - if ( curve ) - { - curve->updateConnectedEditors(); - } - - Rim3dWellLogCurve* rim3dWellLogCurve = firstAncestorOrThisOfType(); - if ( rim3dWellLogCurve ) - { - rim3dWellLogCurve->resetMinMaxValues(); - } - - RimEclipseContourMapProjection* contourMap = firstAncestorOrThisOfType(); - if ( contourMap ) - { - contourMap->clearGridMappingAndRedraw(); - } - - RimWellLogTrack* wellLogTrack = firstAncestorOrThisOfType(); - if ( wellLogTrack ) - { - wellLogTrack->loadDataAndUpdate(); - wellLogTrack->updateEditors(); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setTofAndSelectTracer( const QString& tracerName ) -{ - setResultType( RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ); - setResultVariable( "TOF" ); - setFlowDiagTracerSelectionType( FlowTracerSelectionType::FLOW_TR_BY_SELECTION ); - - if ( m_flowSolution() == nullptr ) - { - assignFlowSolutionFromCase(); - } - - if ( m_flowSolution() ) - { - RimFlowDiagSolution::TracerStatusType tracerStatus = m_flowSolution()->tracerStatusOverall( tracerName ); - - std::vector tracers; - tracers.push_back( tracerName ); - if ( ( tracerStatus == RimFlowDiagSolution::TracerStatusType::INJECTOR ) || - ( tracerStatus == RimFlowDiagSolution::TracerStatusType::VARYING ) ) - { - setSelectedInjectorTracers( tracers ); - } - - if ( ( tracerStatus == RimFlowDiagSolution::TracerStatusType::PRODUCER ) || - ( tracerStatus == RimFlowDiagSolution::TracerStatusType::VARYING ) ) - { - setSelectedProducerTracers( tracers ); - } - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::loadDataAndUpdate() -{ - auto view = firstAncestorOrThisOfType(); - - loadResult(); - - RimEclipsePropertyFilter* propFilter = firstAncestorOrThisOfType(); - if ( propFilter ) - { - propFilter->setToDefaultValues(); - propFilter->updateFilterName(); - - if ( view ) - { - view->scheduleGeometryRegen( PROPERTY_FILTERED ); - view->scheduleCreateDisplayModelAndRedraw(); - } - } - - RimEclipseCellColors* cellColors = firstAncestorOrThisOfType(); - if ( cellColors ) - { - updateLegendCategorySettings(); - - if ( view ) - { - RimViewLinker* viewLinker = view->assosiatedViewLinker(); - if ( viewLinker ) - { - viewLinker->updateCellResult(); - } - RimGridView* eclView = dynamic_cast( view ); - if ( eclView ) eclView->intersectionCollection()->scheduleCreateDisplayModelAndRedraw2dIntersectionViews(); - } - } - - RimIntersectionResultDefinition* sepIntersectionResDef = firstAncestorOrThisOfType(); - if ( sepIntersectionResDef && sepIntersectionResDef->isInAction() ) - { - if ( view ) view->scheduleCreateDisplayModelAndRedraw(); - RimGridView* gridView = dynamic_cast( view ); - if ( gridView ) gridView->intersectionCollection()->scheduleCreateDisplayModelAndRedraw2dIntersectionViews(); - } - - RimCellEdgeColors* cellEdgeColors = firstAncestorOrThisOfType(); - if ( cellEdgeColors ) - { - cellEdgeColors->loadResult(); - - if ( view ) - { - view->scheduleCreateDisplayModelAndRedraw(); - } - } - - RimGridCrossPlotDataSet* crossPlotCurveSet = firstAncestorOrThisOfType(); - if ( crossPlotCurveSet ) - { - crossPlotCurveSet->destroyCurves(); - crossPlotCurveSet->loadDataAndUpdate( true ); - } - - RimPlotCurve* curve = firstAncestorOrThisOfType(); - if ( curve ) - { - curve->loadDataAndUpdate( true ); - } - - Rim3dWellLogCurve* rim3dWellLogCurve = firstAncestorOrThisOfType(); - if ( rim3dWellLogCurve ) - { - rim3dWellLogCurve->updateCurveIn3dView(); - } - -#ifdef USE_QTCHARTS - RimGridStatisticsPlot* gridStatisticsPlot = firstAncestorOrThisOfType(); - if ( gridStatisticsPlot ) - { - gridStatisticsPlot->loadDataAndUpdate(); - } -#endif -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QList RimEclipseResultDefinition::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) -{ - QList options; - - if ( fieldNeedingOptions == &m_resultTypeUiField ) - { - bool hasSourSimRLFile = false; - RimEclipseResultCase* eclResCase = dynamic_cast( m_eclipseCase.p() ); - if ( eclResCase && eclResCase->eclipseCaseData() ) - { - hasSourSimRLFile = eclResCase->hasSourSimFile(); - } - -#ifndef USE_HDF5 - // If using ResInsight without HDF5 support, ignore SourSim files and - // do not show it as a result category. - hasSourSimRLFile = false; -#endif - - bool enableSouring = false; - -#ifdef USE_HDF5 - if ( m_eclipseCase.notNull() ) - { - RigCaseCellResultsData* cellResultsData = m_eclipseCase->results( porosityModel() ); - - if ( cellResultsData && cellResultsData->hasFlowDiagUsableFluxes() ) - { - enableSouring = true; - } - } -#endif /* USE_HDF5 */ - - RimGridTimeHistoryCurve* timeHistoryCurve = firstAncestorOrThisOfType(); - - bool isSeparateFaultResult = false; - { - RimEclipseFaultColors* sepFaultResult = firstAncestorOrThisOfType(); - if ( sepFaultResult ) isSeparateFaultResult = true; - } - - using ResCatEnum = caf::AppEnum; - for ( size_t i = 0; i < ResCatEnum::size(); ++i ) - { - RiaDefines::ResultCatType resType = ResCatEnum::fromIndex( i ); - - // Do not include flow diagnostics results if it is a time history curve - - if ( resType == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && ( timeHistoryCurve ) ) - { - continue; - } - - if ( resType == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && m_eclipseCase && m_eclipseCase->eclipseCaseData() && - m_eclipseCase->eclipseCaseData()->hasFractureResults() ) - { - // Flow diagnostics is not supported for dual porosity models - continue; - } - - // Do not include SourSimRL if no SourSim file is loaded - - if ( resType == RiaDefines::ResultCatType::SOURSIMRL && ( !hasSourSimRLFile ) ) - { - continue; - } - - if ( resType == RiaDefines::ResultCatType::INJECTION_FLOODING && !enableSouring ) - { - continue; - } - - if ( resType == RiaDefines::ResultCatType::ALLAN_DIAGRAMS && !isSeparateFaultResult ) - { - continue; - } - - QString uiString = ResCatEnum::uiTextFromIndex( i ); - options.push_back( caf::PdmOptionItemInfo( uiString, resType ) ); - } - } - - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - if ( fieldNeedingOptions == &m_resultVariableUiField ) - { - options.push_back( caf::PdmOptionItemInfo( RimEclipseResultDefinitionTools::timeOfFlightString( injectorSelectionState(), - producerSelectionState(), - false ), - RIG_FLD_TOF_RESNAME ) ); - if ( m_phaseSelection() == RigFlowDiagResultAddress::PHASE_ALL ) - { - options.push_back( caf::PdmOptionItemInfo( "Tracer Cell Fraction (Sum)", RIG_FLD_CELL_FRACTION_RESNAME ) ); - options.push_back( caf::PdmOptionItemInfo( RimEclipseResultDefinitionTools::maxFractionTracerString( injectorSelectionState(), - producerSelectionState(), - false ), - RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) ); - options.push_back( caf::PdmOptionItemInfo( "Injector Producer Communication", RIG_FLD_COMMUNICATION_RESNAME ) ); - } - } - else if ( fieldNeedingOptions == &m_flowSolutionUiField ) - { - RimEclipseResultCase* eclCase = dynamic_cast( m_eclipseCase.p() ); - if ( eclCase ) - { - std::vector flowSols = eclCase->flowDiagSolutions(); - for ( RimFlowDiagSolution* flowSol : flowSols ) - { - options.push_back( caf::PdmOptionItemInfo( flowSol->userDescription(), flowSol ) ); - } - } - } - else if ( fieldNeedingOptions == &m_selectedInjectorTracersUiField ) - { - const bool isInjector = true; - options = RimFlowDiagnosticsTools::calcOptionsForSelectedTracerField( m_flowSolutionUiField(), isInjector ); - } - else if ( fieldNeedingOptions == &m_selectedProducerTracersUiField ) - { - const bool isInjector = false; - options = RimFlowDiagnosticsTools::calcOptionsForSelectedTracerField( m_flowSolutionUiField(), isInjector ); - } - } - else if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INJECTION_FLOODING ) - { - if ( fieldNeedingOptions == &m_selectedSouringTracersUiField ) - { - RigCaseCellResultsData* cellResultsStorage = currentGridCellResults(); - if ( cellResultsStorage ) - { - QStringList dynamicResultNames = cellResultsStorage->resultNames( RiaDefines::ResultCatType::DYNAMIC_NATIVE ); - - for ( const QString& resultName : dynamicResultNames ) - { - if ( !resultName.endsWith( "F" ) || resultName == RiaResultNames::completionTypeResultName() ) - { - continue; - } - options.push_back( caf::PdmOptionItemInfo( resultName, resultName ) ); - } - } - } - else if ( fieldNeedingOptions == &m_resultVariableUiField ) - { - options.push_back( caf::PdmOptionItemInfo( RIG_NUM_FLOODED_PV, RIG_NUM_FLOODED_PV ) ); - } - } - else - { - if ( fieldNeedingOptions == &m_resultVariableUiField ) - { - options = calcOptionsForVariableUiFieldStandard( m_resultTypeUiField(), - currentGridCellResults(), - showDerivedResultsFirstInVariableUiField(), - addPerCellFaceOptionsForVariableUiField(), - m_ternaryEnabled ); - } - else if ( fieldNeedingOptions == &m_differenceCase ) - { - options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); - - auto eclipseCase = firstAncestorOrThisOfTypeAsserted(); - if ( eclipseCase && eclipseCase->eclipseCaseData() && eclipseCase->eclipseCaseData()->mainGrid() ) - { - RimProject* proj = RimProject::current(); - - std::vector allCases = proj->eclipseCases(); - for ( RimEclipseCase* otherCase : allCases ) - { - if ( otherCase == eclipseCase ) continue; - - if ( otherCase->eclipseCaseData() && otherCase->eclipseCaseData()->mainGrid() ) - { - options.push_back( - caf::PdmOptionItemInfo( QString( "%1 (#%2)" ).arg( otherCase->caseUserDescription() ).arg( otherCase->caseId() ), - otherCase, - false, - otherCase->uiIconProvider() ) ); - } - } - } - } - else if ( fieldNeedingOptions == &m_timeLapseBaseTimestep ) - { - RimEclipseCase* currentCase = firstAncestorOrThisOfTypeAsserted(); - - RimEclipseCase* baseCase = currentCase; - if ( m_differenceCase ) - { - baseCase = m_differenceCase; - } - - options.push_back( caf::PdmOptionItemInfo( "Disabled", RigEclipseResultAddress::noTimeLapseValue() ) ); - - std::vector stepDates = baseCase->timeStepDates(); - for ( size_t stepIdx = 0; stepIdx < stepDates.size(); ++stepIdx ) - { - QString displayString = stepDates[stepIdx].toString( RiaQDateTimeTools::dateFormatString() ); - displayString += QString( " (#%1)" ).arg( stepIdx ); - - options.push_back( caf::PdmOptionItemInfo( displayString, static_cast( stepIdx ) ) ); - } - } - } - - return options; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RigEclipseResultAddress RimEclipseResultDefinition::eclipseResultAddress() const -{ - if ( !isChecked() ) return RigEclipseResultAddress(); - if ( isFlowDiagOrInjectionFlooding() ) return RigEclipseResultAddress(); - - const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - if ( gridCellResults ) - { - int timelapseTimeStep = RigEclipseResultAddress::noTimeLapseValue(); - int diffCaseId = RigEclipseResultAddress::noCaseDiffValue(); - - if ( isDeltaTimeStepActive() ) - { - timelapseTimeStep = m_timeLapseBaseTimestep(); - } - - if ( isDeltaCaseActive() ) - { - diffCaseId = m_differenceCase->caseId(); - } - - return RigEclipseResultAddress( m_resultType(), m_resultVariable(), timelapseTimeStep, diffCaseId, isDivideByCellFaceAreaActive() ); - } - else - { - return RigEclipseResultAddress(); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setFromEclipseResultAddress( const RigEclipseResultAddress& address ) -{ - RigEclipseResultAddress canonizedAddress = address; - - const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - if ( gridCellResults ) - { - auto rinfo = gridCellResults->resultInfo( address ); - if ( rinfo ) canonizedAddress = rinfo->eclipseResultAddress(); - } - - m_resultType = canonizedAddress.resultCatType(); - m_resultVariable = canonizedAddress.resultName(); - m_timeLapseBaseTimestep = canonizedAddress.deltaTimeStepIndex(); - m_divideByCellFaceArea = canonizedAddress.isDivideByCellFaceAreaActive(); - - if ( canonizedAddress.isDeltaCaseActive() ) - { - auto eclipseCases = RimProject::current()->eclipseCases(); - for ( RimEclipseCase* c : eclipseCases ) - { - if ( c && c->caseId() == canonizedAddress.deltaCaseId() ) - { - m_differenceCase = c; - } - } - } - - updateUiFieldsFromActiveResult(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RigFlowDiagResultAddress RimEclipseResultDefinition::flowDiagResAddress() const -{ - CVF_ASSERT( isFlowDiagOrInjectionFlooding() ); - - if ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - size_t timeStep = 0; - - auto rimView = firstAncestorOrThisOfType(); - if ( rimView ) - { - timeStep = rimView->currentTimeStep(); - } - RimWellLogExtractionCurve* wellLogExtractionCurve = firstAncestorOrThisOfType(); - if ( wellLogExtractionCurve ) - { - timeStep = static_cast( wellLogExtractionCurve->currentTimeStep() ); - } - - std::set selTracerNames; - if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) - { - for ( const QString& tName : m_selectedInjectorTracers() ) - { - selTracerNames.insert( tName.toStdString() ); - } - for ( const QString& tName : m_selectedProducerTracers() ) - { - selTracerNames.insert( tName.toStdString() ); - } - } - else - { - RimFlowDiagSolution* flowSol = m_flowSolution(); - if ( flowSol ) - { - std::vector tracerNames = flowSol->tracerNames(); - - if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_INJECTORS || - m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD ) - { - for ( const QString& tracerName : tracerNames ) - { - RimFlowDiagSolution::TracerStatusType status = flowSol->tracerStatusInTimeStep( tracerName, timeStep ); - if ( status == RimFlowDiagSolution::TracerStatusType::INJECTOR ) - { - selTracerNames.insert( tracerName.toStdString() ); - } - } - } - - if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_PRODUCERS || - m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD ) - { - for ( const QString& tracerName : tracerNames ) - { - RimFlowDiagSolution::TracerStatusType status = flowSol->tracerStatusInTimeStep( tracerName, timeStep ); - if ( status == RimFlowDiagSolution::TracerStatusType::PRODUCER ) - { - selTracerNames.insert( tracerName.toStdString() ); - } - } - } - } - } - - return RigFlowDiagResultAddress( m_resultVariable().toStdString(), m_phaseSelection(), selTracerNames ); - } - - std::set selTracerNames; - for ( const QString& selectedTracerName : m_selectedSouringTracers() ) - { - selTracerNames.insert( selectedTracerName.toUtf8().constData() ); - } - return RigFlowDiagResultAddress( m_resultVariable().toStdString(), RigFlowDiagResultAddress::PHASE_ALL, selTracerNames ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setFlowDiagTracerSelectionType( FlowTracerSelectionType selectionType ) -{ - m_flowTracerSelectionMode = selectionType; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RimEclipseResultDefinition::resultVariableUiName() const -{ - if ( resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - return flowDiagResUiText( false, 32 ); - } - - if ( isDivideByCellFaceAreaActive() ) - { - return m_resultVariable() + " /A"; - } - - return m_resultVariable(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RimEclipseResultDefinition::resultVariableUiShortName() const -{ - if ( resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - return flowDiagResUiText( true, 24 ); - } - - if ( isDivideByCellFaceAreaActive() ) - { - return m_resultVariable() + " /A"; - } - - return m_resultVariable(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RimEclipseResultDefinition::additionalResultText() const -{ - QStringList resultText; - - if ( isDeltaTimeStepActive() ) - { - std::vector stepDates; - const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - if ( gridCellResults ) - { - stepDates = gridCellResults->timeStepDates(); - resultText += QString( "Base Time Step: %1" ) - .arg( stepDates[m_timeLapseBaseTimestep()].toString( RiaQDateTimeTools::dateFormatString() ) ); - } - } - if ( isDeltaCaseActive() ) - { - resultText += QString( "Base Case: %1" ).arg( m_differenceCase()->caseUserDescription() ); - } - return resultText.join( "
" ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RimEclipseResultDefinition::additionalResultTextShort() const -{ - QString resultTextShort; - if ( isDeltaTimeStepActive() || isDeltaCaseActive() ) - { - QStringList resultTextLines; - resultTextLines += QString( "\nDiff. Options:" ); - if ( isDeltaCaseActive() ) - { - resultTextLines += QString( "Base Case: #%1" ).arg( m_differenceCase()->caseId() ); - } - if ( isDeltaTimeStepActive() ) - { - resultTextLines += QString( "Base Time: #%1" ).arg( m_timeLapseBaseTimestep() ); - } - resultTextShort = resultTextLines.join( "\n" ); - } - - return resultTextShort; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int RimEclipseResultDefinition::timeLapseBaseTimeStep() const -{ - return m_timeLapseBaseTimestep; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int RimEclipseResultDefinition::caseDiffIndex() const -{ - if ( m_differenceCase ) - { - return m_differenceCase->caseId(); - } - return -1; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::loadResult() -{ - if ( isFlowDiagOrInjectionFlooding() ) return; // Will load automatically on access - - if ( m_eclipseCase ) - { - if ( !m_eclipseCase->ensureReservoirCaseIsOpen() ) - { - RiaLogging::error( "Could not open the Eclipse Grid file: " + m_eclipseCase->gridFileName() ); - return; - } - } - - if ( m_differenceCase ) - { - if ( !m_differenceCase->ensureReservoirCaseIsOpen() ) - { - RiaLogging::error( "Could not open the Eclipse Grid file: " + m_eclipseCase->gridFileName() ); - return; - } - } - - RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - if ( gridCellResults ) - { - if ( isDeltaTimeStepActive() || isDeltaCaseActive() || isDivideByCellFaceAreaActive() ) - { - gridCellResults->createResultEntry( eclipseResultAddress(), false ); - } - - QString resultName = m_resultVariable(); - std::set eclipseResultNamesWithNncData = RiaResultNames::nncResultNames(); - if ( eclipseResultNamesWithNncData.find( resultName ) != eclipseResultNamesWithNncData.end() ) - { - eclipseCase()->ensureFaultDataIsComputed(); - - bool dataWasComputed = eclipseCase()->ensureNncDataIsComputed(); - if ( dataWasComputed ) - { - eclipseCase()->createDisplayModelAndUpdateAllViews(); - } - } - - gridCellResults->ensureKnownResultLoaded( eclipseResultAddress() ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// Returns whether the result requested by the definition is a single frame result -/// The result needs to be loaded before asking -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::hasStaticResult() const -{ - if ( isFlowDiagOrInjectionFlooding() ) return false; - - const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - RigEclipseResultAddress gridScalarResultIndex = eclipseResultAddress(); - - return hasResult() && gridCellResults->timeStepCount( gridScalarResultIndex ) == 1; -} - -//-------------------------------------------------------------------------------------------------- -/// Returns whether the result requested by the definition is loaded or possible to load from the result file -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::hasResult() const -{ - if ( isFlowDiagOrInjectionFlooding() ) - { - if ( m_flowSolution() && !m_resultVariable().isEmpty() ) return true; - } - else if ( currentGridCellResults() ) - { - const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - - return gridCellResults->hasResultEntry( eclipseResultAddress() ); - } - - return false; -} - -//-------------------------------------------------------------------------------------------------- -/// Returns whether the result requested by the definition is a multi frame result -/// The result needs to be loaded before asking -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::hasDynamicResult() const -{ - if ( hasResult() ) - { - if ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE ) - { - return true; - } - else if ( m_resultType() == RiaDefines::ResultCatType::SOURSIMRL ) - { - return true; - } - else if ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - return true; - } - else if ( m_resultType() == RiaDefines::ResultCatType::INJECTION_FLOODING ) - { - return true; - } - - if ( currentGridCellResults() ) - { - const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); - RigEclipseResultAddress gridScalarResultIndex = eclipseResultAddress(); - if ( gridCellResults->timeStepCount( gridScalarResultIndex ) > 1 ) - { - return true; - } - } - } - - return false; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::initAfterRead() -{ - if ( m_flowSolution() == nullptr ) - { - assignFlowSolutionFromCase(); - } - - if ( m_resultVariable() == "Formation Allen" ) - { - m_resultVariable = RiaResultNames::formationAllanResultName(); - m_resultType = RiaDefines::ResultCatType::ALLAN_DIAGRAMS; - } - else if ( m_resultVariable() == "Binary Formation Allen" ) - { - m_resultVariable = RiaResultNames::formationBinaryAllanResultName(); - m_resultType = RiaDefines::ResultCatType::ALLAN_DIAGRAMS; - } - - m_porosityModelUiField = m_porosityModel; - m_resultTypeUiField = m_resultType; - m_resultVariableUiField = m_resultVariable; - - m_flowSolutionUiField = m_flowSolution(); - m_selectedInjectorTracersUiField = m_selectedInjectorTracers; - - updateUiIconFromToggleField(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setResultType( RiaDefines::ResultCatType val ) -{ - m_resultType = val; - m_resultTypeUiField = val; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RiaDefines::PorosityModelType RimEclipseResultDefinition::porosityModel() const -{ - return m_porosityModel(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setPorosityModel( RiaDefines::PorosityModelType val ) -{ - m_porosityModel = val; - m_porosityModelUiField = val; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RimEclipseResultDefinition::resultVariable() const -{ - if ( !isChecked() ) return RiaResultNames::undefinedResultName(); - - return m_resultVariable(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setResultVariable( const QString& val ) -{ - m_resultVariable = val; - m_resultVariableUiField = val; -} - -//-------------------------------------------------------------------------------------------------- -/// Return phase type if the current result is known to be of a particular -/// fluid phase type. Otherwise the method will return PHASE_NOT_APPLICABLE. -//-------------------------------------------------------------------------------------------------- -RiaDefines::PhaseType RimEclipseResultDefinition::resultPhaseType() const -{ - if ( QRegularExpression( "OIL" ).match( m_resultVariable() ).hasMatch() ) - { - return RiaDefines::PhaseType::OIL_PHASE; - } - else if ( QRegularExpression( "GAS" ).match( m_resultVariable() ).hasMatch() ) - { - return RiaDefines::PhaseType::GAS_PHASE; - } - else if ( QRegularExpression( "WAT" ).match( m_resultVariable() ).hasMatch() ) - { - return RiaDefines::PhaseType::WATER_PHASE; - } - return RiaDefines::PhaseType::PHASE_NOT_APPLICABLE; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimFlowDiagSolution* RimEclipseResultDefinition::flowDiagSolution() const -{ - return m_flowSolution(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setFlowSolution( RimFlowDiagSolution* flowSol ) -{ - m_flowSolution = flowSol; - m_flowSolutionUiField = flowSol; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setSelectedTracers( const std::vector& selectedTracers ) -{ - if ( m_flowSolution() == nullptr ) - { - assignFlowSolutionFromCase(); - } - if ( m_flowSolution() ) - { - std::vector injectorTracers; - std::vector producerTracers; - for ( const QString& tracerName : selectedTracers ) - { - RimFlowDiagSolution::TracerStatusType tracerStatus = m_flowSolution()->tracerStatusOverall( tracerName ); - if ( tracerStatus == RimFlowDiagSolution::TracerStatusType::INJECTOR ) - { - injectorTracers.push_back( tracerName ); - } - else if ( tracerStatus == RimFlowDiagSolution::TracerStatusType::PRODUCER ) - { - producerTracers.push_back( tracerName ); - } - else if ( tracerStatus == RimFlowDiagSolution::TracerStatusType::VARYING || - tracerStatus == RimFlowDiagSolution::TracerStatusType::UNDEFINED ) - { - injectorTracers.push_back( tracerName ); - producerTracers.push_back( tracerName ); - } - } - setSelectedInjectorTracers( injectorTracers ); - setSelectedProducerTracers( producerTracers ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setSelectedInjectorTracers( const std::vector& selectedTracers ) -{ - m_selectedInjectorTracers = selectedTracers; - m_selectedInjectorTracersUiField = selectedTracers; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setSelectedProducerTracers( const std::vector& selectedTracers ) -{ - m_selectedProducerTracers = selectedTracers; - m_selectedProducerTracersUiField = selectedTracers; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setSelectedSouringTracers( const std::vector& selectedTracers ) -{ - m_selectedSouringTracers = selectedTracers; - m_selectedSouringTracersUiField = selectedTracers; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::updateUiFieldsFromActiveResult() -{ - m_resultTypeUiField = m_resultType; - m_resultVariableUiField = resultVariable(); - m_selectedInjectorTracersUiField = m_selectedInjectorTracers; - m_selectedProducerTracersUiField = m_selectedProducerTracers; - m_selectedSouringTracersUiField = m_selectedSouringTracers; - m_porosityModelUiField = m_porosityModel; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::enableDeltaResults( bool enable ) -{ - m_isDeltaResultEnabled = enable; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isTernarySaturationSelected() const -{ - bool isTernary = ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE ) && - ( m_resultVariable().compare( RiaResultNames::ternarySaturationResultName(), Qt::CaseInsensitive ) == 0 ); - - return isTernary; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isCompletionTypeSelected() const -{ - return ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE && m_resultVariable() == RiaResultNames::completionTypeResultName() ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::hasCategoryResult() const -{ - if ( auto* gridCellResults = currentGridCellResults() ) - { - const auto addresses = gridCellResults->existingResults(); - for ( const auto& address : addresses ) - { - if ( address.resultCatType() == m_resultType() && address.resultName() == m_resultVariable() ) - { - if ( address.dataType() == RiaDefines::ResultDataType::INTEGER ) return true; - break; - } - } - } - - if ( m_resultType() == RiaDefines::ResultCatType::FORMATION_NAMES && m_eclipseCase && m_eclipseCase->eclipseCaseData() && - !m_eclipseCase->eclipseCaseData()->formationNames().empty() ) - return true; - - if ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE && resultVariable() == RiaResultNames::completionTypeResultName() ) - return true; - - if ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && m_resultVariable() == RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) - return true; - - if ( resultVariable() == RiaResultNames::formationAllanResultName() || resultVariable() == RiaResultNames::formationBinaryAllanResultName() ) - { - return true; - } - - return false; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isFlowDiagOrInjectionFlooding() const -{ - return m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS || m_resultType() == RiaDefines::ResultCatType::INJECTION_FLOODING; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) -{ - uiOrdering.add( &m_resultTypeUiField ); - - if ( hasDualPorFractureResult() ) - { - uiOrdering.add( &m_porosityModelUiField ); - } - - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - uiOrdering.add( &m_flowSolutionUiField ); - - uiOrdering.add( &m_flowTracerSelectionMode ); - - if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) - { - caf::PdmUiGroup* selectionGroup = uiOrdering.addNewGroup( "Tracer Selection" ); - selectionGroup->setEnableFrame( false ); - - caf::PdmUiGroup* injectorGroup = selectionGroup->addNewGroup( "Injectors" ); - injectorGroup->add( &m_selectedInjectorTracersUiField ); - injectorGroup->add( &m_syncInjectorToProducerSelection ); - - caf::PdmUiGroup* producerGroup = selectionGroup->addNewGroup( "Producers", { .newRow = false } ); - producerGroup->add( &m_selectedProducerTracersUiField ); - producerGroup->add( &m_syncProducerToInjectorSelection ); - } - - uiOrdering.add( &m_phaseSelection ); - - if ( m_flowSolution() == nullptr ) - { - assignFlowSolutionFromCase(); - } - } - - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INJECTION_FLOODING ) - { - uiOrdering.add( &m_selectedSouringTracersUiField ); - } - - uiOrdering.add( &m_resultVariableUiField ); - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INPUT_PROPERTY ) - { - uiOrdering.add( &m_inputPropertyFileName ); - } - - if ( isDivideByCellFaceAreaPossible() ) - { - uiOrdering.add( &m_divideByCellFaceArea ); - - QString resultPropertyLabel = "Result Property"; - if ( isDivideByCellFaceAreaActive() ) - { - resultPropertyLabel += QString( "\nDivided by Area" ); - } - m_resultVariableUiField.uiCapability()->setUiName( resultPropertyLabel ); - } - - { - caf::PdmUiGroup* legendGroup = uiOrdering.addNewGroup( "Legend" ); - legendGroup->add( &m_showOnlyVisibleCategoriesInLegend ); - - bool showOnlyVisibleCategoriesOption = false; - - RimEclipseView* eclView = firstAncestorOrThisOfType(); - - if ( eclView ) - { - if ( eclView->cellResult() == this && hasCategoryResult() ) showOnlyVisibleCategoriesOption = true; - } - - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && - m_resultVariableUiField() == RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) - { - showOnlyVisibleCategoriesOption = true; - } - - legendGroup->setUiHidden( !showOnlyVisibleCategoriesOption ); - } - - if ( isDeltaCasePossible() || isDeltaTimeStepPossible() ) - { - caf::PdmUiGroup* differenceGroup = uiOrdering.addNewGroup( "Difference Options" ); - differenceGroup->setUiReadOnly( !( isDeltaTimeStepPossible() || isDeltaCasePossible() ) ); - - m_differenceCase.uiCapability()->setUiReadOnly( !isDeltaCasePossible() ); - m_timeLapseBaseTimestep.uiCapability()->setUiReadOnly( !isDeltaTimeStepPossible() ); - - if ( isDeltaCasePossible() ) differenceGroup->add( &m_differenceCase ); - if ( isDeltaTimeStepPossible() ) differenceGroup->add( &m_timeLapseBaseTimestep ); - - QString resultPropertyLabel = "Result Property"; - if ( isDeltaTimeStepActive() || isDeltaCaseActive() ) - { - resultPropertyLabel += QString( "\n%1" ).arg( additionalResultTextShort() ); - } - m_resultVariableUiField.uiCapability()->setUiName( resultPropertyLabel ); - } - - uiOrdering.skipRemainingFields( true ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) -{ - if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) - { - if ( field == &m_syncInjectorToProducerSelection || field == &m_syncProducerToInjectorSelection ) - { - caf::PdmUiToolButtonEditorAttribute* toolButtonAttr = dynamic_cast( attribute ); - if ( toolButtonAttr ) - { - toolButtonAttr->m_sizePolicy.setHorizontalPolicy( QSizePolicy::MinimumExpanding ); - } - } - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::assignFlowSolutionFromCase() -{ - RimFlowDiagSolution* defaultFlowDiagSolution = nullptr; - - RimEclipseResultCase* eclCase = dynamic_cast( m_eclipseCase.p() ); - - if ( eclCase ) - { - defaultFlowDiagSolution = eclCase->defaultFlowDiagSolution(); - } - setFlowSolution( defaultFlowDiagSolution ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::hasDualPorFractureResult() -{ - if ( m_eclipseCase && m_eclipseCase->eclipseCaseData() ) - { - return m_eclipseCase->eclipseCaseData()->hasFractureResults(); - } - - return false; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RimEclipseResultDefinition::flowDiagResUiText( bool shortLabel, int maxTracerStringLength ) const -{ - QString uiText = QString::fromStdString( flowDiagResAddress().variableName ); - if ( flowDiagResAddress().variableName == RIG_FLD_TOF_RESNAME ) - { - uiText = RimEclipseResultDefinitionTools::timeOfFlightString( injectorSelectionState(), producerSelectionState(), shortLabel ); - } - else if ( flowDiagResAddress().variableName == RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) - { - uiText = RimEclipseResultDefinitionTools::maxFractionTracerString( injectorSelectionState(), producerSelectionState(), shortLabel ); - } - - QString tracersString = RimEclipseResultDefinitionTools::selectedTracersString( injectorSelectionState(), - producerSelectionState(), - m_selectedInjectorTracers(), - m_selectedProducerTracers(), - maxTracerStringLength ); - - if ( !tracersString.isEmpty() ) - { - uiText += QString( "\n%1" ).arg( tracersString ); - } - return uiText; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QList RimEclipseResultDefinition::calcOptionsForVariableUiFieldStandard( RiaDefines::ResultCatType resultCatType, - const RigCaseCellResultsData* results, - bool showDerivedResultsFirst, - bool addPerCellFaceOptionItems, - bool ternaryEnabled ) -{ - CVF_ASSERT( resultCatType != RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && resultCatType != RiaDefines::ResultCatType::INJECTION_FLOODING ); - - return RimEclipseResultDefinitionTools::calcOptionsForVariableUiFieldStandard( resultCatType, - results, - showDerivedResultsFirst, - addPerCellFaceOptionItems, - ternaryEnabled ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::setTernaryEnabled( bool enabled ) -{ - m_ternaryEnabled = enabled; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::updateRangesForExplicitLegends( RimRegularLegendConfig* legendConfigToUpdate, - RimTernaryLegendConfig* ternaryLegendConfigToUpdate, - int currentTimeStep ) - -{ - if ( hasResult() ) - { - if ( isFlowDiagOrInjectionFlooding() ) - { - if ( currentTimeStep >= 0 ) - { - RimEclipseResultDefinitionTools::updateLegendForFlowDiagnostics( this, legendConfigToUpdate, currentTimeStep ); - } - } - else - { - RimEclipseResultDefinitionTools::updateCellResultLegend( this, legendConfigToUpdate, currentTimeStep ); - } - } - - if ( isTernarySaturationSelected() ) - { - RimEclipseResultDefinitionTools::updateTernaryLegend( currentGridCellResults(), ternaryLegendConfigToUpdate, currentTimeStep ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::updateLegendTitle( RimRegularLegendConfig* legendConfig, const QString& legendHeading ) -{ - QString title = legendHeading + resultVariableUiName(); - if ( !additionalResultTextShort().isEmpty() ) - { - title += additionalResultTextShort(); - } - - if ( hasDualPorFractureResult() ) - { - QString porosityModelText = caf::AppEnum::uiText( porosityModel() ); - - title += QString( "\nDual Por : %1" ).arg( porosityModelText ); - } - - legendConfig->setTitle( title ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::showOnlyVisibleCategoriesInLegend() const -{ - return m_showOnlyVisibleCategoriesInLegend(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimEclipseResultDefinition::FlowTracerSelectionState RimEclipseResultDefinition::injectorSelectionState() const -{ - const bool isInjector = true; - return RimEclipseResultDefinitionTools::getFlowTracerSelectionState( isInjector, - m_flowTracerSelectionMode(), - m_flowSolutionUiField(), - m_selectedInjectorTracers().size() ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimEclipseResultDefinition::FlowTracerSelectionState RimEclipseResultDefinition::producerSelectionState() const -{ - const bool isInjector = false; - return RimEclipseResultDefinitionTools::getFlowTracerSelectionState( isInjector, - m_flowTracerSelectionMode(), - m_flowSolutionUiField(), - m_selectedProducerTracers().size() ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::syncInjectorToProducerSelection() -{ - int timeStep = 0; - - auto rimView = firstAncestorOrThisOfType(); - if ( rimView ) - { - timeStep = rimView->currentTimeStep(); - } - - RimFlowDiagSolution* flowSol = m_flowSolution(); - if ( flowSol && m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) - { - std::set newProducerSelection = - RimFlowDiagnosticsTools::setOfProducerTracersFromInjectors( m_flowSolutionUiField(), m_selectedInjectorTracers(), timeStep ); - // Add all currently selected producers to set - for ( const QString& selectedProducer : m_selectedProducerTracers() ) - { - newProducerSelection.insert( selectedProducer ); - } - std::vector newProducerVector( newProducerSelection.begin(), newProducerSelection.end() ); - setSelectedProducerTracers( newProducerVector ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimEclipseResultDefinition::syncProducerToInjectorSelection() -{ - int timeStep = 0; - - auto rimView = firstAncestorOrThisOfType(); - if ( rimView ) - { - timeStep = rimView->currentTimeStep(); - } - - RimFlowDiagSolution* flowSol = m_flowSolution(); - if ( flowSol && m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) - { - std::set newInjectorSelection = - RimFlowDiagnosticsTools::setOfInjectorTracersFromProducers( m_flowSolutionUiField(), m_selectedProducerTracers(), timeStep ); - - // Add all currently selected injectors to set - for ( const QString& selectedInjector : m_selectedInjectorTracers() ) - { - newInjectorSelection.insert( selectedInjector ); - } - std::vector newInjectorVector( newInjectorSelection.begin(), newInjectorSelection.end() ); - setSelectedInjectorTracers( newInjectorVector ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDeltaResultEnabled() const -{ - return m_isDeltaResultEnabled; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDeltaTimeStepPossible() const -{ - return isDeltaResultEnabled() && !isTernarySaturationSelected() && - ( m_resultTypeUiField() == RiaDefines::ResultCatType::DYNAMIC_NATIVE || - m_resultTypeUiField() == RiaDefines::ResultCatType::GENERATED ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDeltaTimeStepActive() const -{ - return isDeltaTimeStepPossible() && m_timeLapseBaseTimestep() >= 0; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDeltaCasePossible() const -{ - return isDeltaResultEnabled() && !isTernarySaturationSelected() && - ( m_resultTypeUiField() == RiaDefines::ResultCatType::DYNAMIC_NATIVE || - m_resultTypeUiField() == RiaDefines::ResultCatType::STATIC_NATIVE || - m_resultTypeUiField() == RiaDefines::ResultCatType::GENERATED ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDeltaCaseActive() const -{ - return isDeltaCasePossible() && m_differenceCase() != nullptr; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDivideByCellFaceAreaPossible() const -{ - return RimEclipseResultDefinitionTools::isDivideByCellFaceAreaPossible( m_resultVariable ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::isDivideByCellFaceAreaActive() const -{ - return isDivideByCellFaceAreaPossible() && m_divideByCellFaceArea; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::showDerivedResultsFirstInVariableUiField() const -{ - // Cell Face result names - bool showDerivedResultsFirstInList = false; - RimEclipseFaultColors* rimEclipseFaultColors = firstAncestorOrThisOfType(); - - if ( rimEclipseFaultColors ) showDerivedResultsFirstInList = true; - - return showDerivedResultsFirstInList; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool RimEclipseResultDefinition::addPerCellFaceOptionsForVariableUiField() const -{ - RimPlotCurve* curve = firstAncestorOrThisOfType(); - RimEclipsePropertyFilter* propFilter = firstAncestorOrThisOfType(); - RimCellEdgeColors* cellEdge = firstAncestorOrThisOfType(); - - return !( propFilter || curve || cellEdge ); -} +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2011- Statoil ASA +// Copyright (C) 2013- Ceetron Solutions AS +// Copyright (C) 2011-2012 Ceetron AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimEclipseResultDefinition.h" + +#include "RiaLogging.h" +#include "RiaQDateTimeTools.h" + +#include "RicfCommandObject.h" + +#include "RigActiveCellInfo.h" +#include "RigCaseCellResultsData.h" +#include "RigEclipseCaseData.h" +#include "RigEclipseResultInfo.h" +#include "RigFlowDiagResultAddress.h" +#include "RigFlowDiagResults.h" +#include "RigFormationNames.h" + +#include "Rim3dView.h" +#include "Rim3dWellLogCurve.h" +#include "RimCellEdgeColors.h" +#include "RimContourMapProjection.h" +#include "RimEclipseCase.h" +#include "RimEclipseCellColors.h" +#include "RimEclipseContourMapProjection.h" +#include "RimEclipseContourMapView.h" +#include "RimEclipseFaultColors.h" +#include "RimEclipsePropertyFilter.h" +#include "RimEclipseResultCase.h" +#include "RimEclipseResultDefinitionTools.h" +#include "RimEclipseView.h" +#include "RimFlowDiagSolution.h" +#include "RimFlowDiagnosticsTools.h" +#include "RimGridCrossPlot.h" +#include "RimGridCrossPlotDataSet.h" +#include "RimGridTimeHistoryCurve.h" +#include "RimIntersectionCollection.h" +#include "RimIntersectionResultDefinition.h" +#include "RimPlotCurve.h" +#include "RimProject.h" +#include "RimRegularLegendConfig.h" +#include "RimReservoirCellResultsStorage.h" +#include "RimViewLinker.h" +#include "RimWellLogExtractionCurve.h" +#include "RimWellLogTrack.h" + +#ifdef USE_QTCHARTS +#include "RimGridStatisticsPlot.h" +#endif + +#include "cafPdmFieldScriptingCapability.h" +#include "cafPdmUiToolButtonEditor.h" +#include "cafPdmUiTreeSelectionEditor.h" +#include "cafUtils.h" + +#include + +namespace caf +{ +template <> +void RimEclipseResultDefinition::FlowTracerSelectionEnum::setUp() +{ + addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD, "FLOW_TR_INJ_AND_PROD", "All Injectors and Producers" ); + addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_PRODUCERS, "FLOW_TR_PRODUCERS", "All Producers" ); + addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_INJECTORS, "FLOW_TR_INJECTORS", "All Injectors" ); + addItem( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_BY_SELECTION, "FLOW_TR_BY_SELECTION", "By Selection" ); + + setDefault( RimEclipseResultDefinition::FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD ); +} +} // namespace caf + +CAF_PDM_SOURCE_INIT( RimEclipseResultDefinition, "ResultDefinition" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEclipseResultDefinition::RimEclipseResultDefinition( caf::PdmUiItemInfo::LabelPosType labelPosition ) + : m_isDeltaResultEnabled( false ) + , m_labelPosition( labelPosition ) + , m_ternaryEnabled( true ) +{ + CAF_PDM_InitScriptableObjectWithNameAndComment( "Result Definition", "", "", "", "EclipseResult", "An eclipse result definition" ); + + CAF_PDM_InitScriptableFieldNoDefault( &m_resultType, "ResultType", "Type" ); + m_resultType.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitScriptableFieldNoDefault( &m_porosityModel, "PorosityModelType", "Porosity" ); + m_porosityModel.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitScriptableField( &m_resultVariable, "ResultVariable", RiaResultNames::undefinedResultName(), "Variable" ); + m_resultVariable.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitFieldNoDefault( &m_flowSolution, "FlowDiagSolution", "Solution" ); + m_flowSolution.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitField( &m_timeLapseBaseTimestep, "TimeLapseBaseTimeStep", RigEclipseResultAddress::noTimeLapseValue(), "Base Time Step" ); + + CAF_PDM_InitFieldNoDefault( &m_differenceCase, "DifferenceCase", "Difference Case" ); + + CAF_PDM_InitField( &m_divideByCellFaceArea, "DivideByCellFaceArea", false, "Divide By Area" ); + + CAF_PDM_InitScriptableFieldNoDefault( &m_selectedInjectorTracers, "SelectedInjectorTracers", "Injector Tracers" ); + m_selectedInjectorTracers.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitScriptableFieldNoDefault( &m_selectedProducerTracers, "SelectedProducerTracers", "Producer Tracers" ); + m_selectedProducerTracers.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitScriptableFieldNoDefault( &m_selectedSouringTracers, "SelectedSouringTracers", "Tracers" ); + m_selectedSouringTracers.uiCapability()->setUiHidden( true ); + + CAF_PDM_InitScriptableFieldNoDefault( &m_flowTracerSelectionMode, "FlowTracerSelectionMode", "Tracers" ); + CAF_PDM_InitScriptableFieldNoDefault( &m_phaseSelection, "PhaseSelection", "Phases" ); + m_phaseSelection.uiCapability()->setUiLabelPosition( m_labelPosition ); + + CAF_PDM_InitScriptableField( &m_showOnlyVisibleCategoriesInLegend, + "ShowOnlyVisibleCategoriesInLegend", + true, + "Show Only Visible Categories In Legend" ); + + // Ui only fields + + CAF_PDM_InitFieldNoDefault( &m_resultTypeUiField, "MResultType", "Type" ); + m_resultTypeUiField.xmlCapability()->disableIO(); + m_resultTypeUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); + + CAF_PDM_InitFieldNoDefault( &m_porosityModelUiField, "MPorosityModelType", "Porosity" ); + m_porosityModelUiField.xmlCapability()->disableIO(); + m_porosityModelUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); + + CAF_PDM_InitField( &m_resultVariableUiField, "MResultVariable", RiaResultNames::undefinedResultName(), "Result Property" ); + m_resultVariableUiField.xmlCapability()->disableIO(); + m_resultVariableUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); + m_resultVariableUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); + + CAF_PDM_InitFieldNoDefault( &m_inputPropertyFileName, "InputPropertyFileName", "File Name" ); + m_inputPropertyFileName.xmlCapability()->disableIO(); + m_inputPropertyFileName.uiCapability()->setUiReadOnly( true ); + + CAF_PDM_InitFieldNoDefault( &m_flowSolutionUiField, "MFlowDiagSolution", "Solution" ); + m_flowSolutionUiField.xmlCapability()->disableIO(); + m_flowSolutionUiField.uiCapability()->setUiHidden( true ); // For now since there are only one to choose from + + CAF_PDM_InitField( &m_syncInjectorToProducerSelection, "MSyncSelectedInjProd", false, "Add Communicators ->" ); + m_syncInjectorToProducerSelection.uiCapability()->setUiEditorTypeName( caf::PdmUiToolButtonEditor::uiEditorTypeName() ); + + CAF_PDM_InitField( &m_syncProducerToInjectorSelection, "MSyncSelectedProdInj", false, "<- Add Communicators" ); + m_syncProducerToInjectorSelection.uiCapability()->setUiEditorTypeName( caf::PdmUiToolButtonEditor::uiEditorTypeName() ); + + CAF_PDM_InitFieldNoDefault( &m_selectedInjectorTracersUiField, "MSelectedInjectorTracers", "Injector Tracers" ); + m_selectedInjectorTracersUiField.xmlCapability()->disableIO(); + m_selectedInjectorTracersUiField.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + + CAF_PDM_InitFieldNoDefault( &m_selectedProducerTracersUiField, "MSelectedProducerTracers", "Producer Tracers" ); + m_selectedProducerTracersUiField.xmlCapability()->disableIO(); + m_selectedProducerTracersUiField.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + + CAF_PDM_InitFieldNoDefault( &m_selectedSouringTracersUiField, "MSelectedSouringTracers", "Tracers" ); + m_selectedSouringTracersUiField.xmlCapability()->disableIO(); + m_selectedSouringTracersUiField.uiCapability()->setUiLabelPosition( m_labelPosition ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEclipseResultDefinition::~RimEclipseResultDefinition() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::simpleCopy( const RimEclipseResultDefinition* other ) +{ + setResultVariable( other->resultVariable() ); + setPorosityModel( other->porosityModel() ); + setResultType( other->resultType() ); + setFlowSolution( other->m_flowSolution() ); + setSelectedInjectorTracers( other->m_selectedInjectorTracers() ); + setSelectedProducerTracers( other->m_selectedProducerTracers() ); + setSelectedSouringTracers( other->m_selectedSouringTracers() ); + m_flowTracerSelectionMode = other->m_flowTracerSelectionMode(); + m_phaseSelection = other->m_phaseSelection; + + m_differenceCase = other->m_differenceCase(); + m_timeLapseBaseTimestep = other->m_timeLapseBaseTimestep(); + m_divideByCellFaceArea = other->m_divideByCellFaceArea(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setEclipseCase( RimEclipseCase* eclipseCase ) +{ + m_eclipseCase = eclipseCase; + + assignFlowSolutionFromCase(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEclipseCase* RimEclipseResultDefinition::eclipseCase() const +{ + return m_eclipseCase; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RiaDefines::ResultCatType RimEclipseResultDefinition::resultType() const +{ + return m_resultType(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigCaseCellResultsData* RimEclipseResultDefinition::currentGridCellResults() const +{ + if ( !m_eclipseCase ) return nullptr; + + return m_eclipseCase->results( m_porosityModel() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + if ( &m_flowSolutionUiField == changedField || &m_resultTypeUiField == changedField || &m_porosityModelUiField == changedField ) + { + // If the user are seeing the list with the actually selected result, + // select that result in the list. Otherwise select nothing. + + QStringList varList = RimEclipseResultDefinitionTools::getResultNamesForResultType( m_resultTypeUiField(), currentGridCellResults() ); + + bool isFlowDiagFieldsRelevant = ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ); + + if ( ( m_flowSolutionUiField() == m_flowSolution() || !isFlowDiagFieldsRelevant ) && m_resultTypeUiField() == m_resultType() && + m_porosityModelUiField() == m_porosityModel() ) + { + if ( varList.contains( resultVariable() ) ) + { + m_resultVariableUiField = resultVariable(); + } + + if ( isFlowDiagFieldsRelevant ) + { + m_selectedInjectorTracersUiField = m_selectedInjectorTracers(); + m_selectedProducerTracersUiField = m_selectedProducerTracers(); + } + else + { + m_selectedInjectorTracersUiField = std::vector(); + m_selectedProducerTracersUiField = std::vector(); + } + } + else + { + m_resultVariableUiField = ""; + m_selectedInjectorTracersUiField = std::vector(); + m_selectedProducerTracersUiField = std::vector(); + } + } + + if ( &m_resultVariableUiField == changedField ) + { + m_porosityModel = m_porosityModelUiField; + m_resultType = m_resultTypeUiField; + m_resultVariable = m_resultVariableUiField; + + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + m_flowSolution = m_flowSolutionUiField(); + m_selectedInjectorTracers = m_selectedInjectorTracersUiField(); + m_selectedProducerTracers = m_selectedProducerTracersUiField(); + } + else if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INJECTION_FLOODING ) + { + m_selectedSouringTracers = m_selectedSouringTracersUiField(); + } + else if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INPUT_PROPERTY ) + { + m_inputPropertyFileName = RimEclipseResultDefinitionTools::getInputPropertyFileName( eclipseCase(), newValue.toString() ); + } + loadDataAndUpdate(); + } + + if ( &m_porosityModelUiField == changedField ) + { + m_porosityModel = m_porosityModelUiField; + m_resultVariableUiField = resultVariable(); + + auto eclipseView = firstAncestorOrThisOfType(); + if ( eclipseView ) + { + // Active cells can be different between matrix and fracture, make sure all geometry is recreated + eclipseView->scheduleReservoirGridGeometryRegen(); + } + + loadDataAndUpdate(); + } + + auto contourMapView = firstAncestorOrThisOfType(); + + if ( &m_differenceCase == changedField ) + { + m_timeLapseBaseTimestep = RigEclipseResultAddress::noTimeLapseValue(); + + if ( contourMapView ) + { + contourMapView->contourMapProjection()->clearGridMappingAndRedraw(); + } + + loadDataAndUpdate(); + } + + if ( &m_timeLapseBaseTimestep == changedField ) + { + if ( contourMapView ) + { + contourMapView->contourMapProjection()->clearGridMappingAndRedraw(); + } + + loadDataAndUpdate(); + } + + if ( &m_divideByCellFaceArea == changedField ) + { + loadDataAndUpdate(); + } + + if ( &m_flowTracerSelectionMode == changedField ) + { + loadDataAndUpdate(); + } + + if ( &m_selectedInjectorTracersUiField == changedField ) + { + changedTracerSelectionField( true ); + } + + if ( &m_selectedProducerTracersUiField == changedField ) + { + changedTracerSelectionField( false ); + } + + if ( &m_syncInjectorToProducerSelection == changedField ) + { + syncInjectorToProducerSelection(); + m_syncInjectorToProducerSelection = false; + } + + if ( &m_syncProducerToInjectorSelection == changedField ) + { + syncProducerToInjectorSelection(); + m_syncProducerToInjectorSelection = false; + } + + if ( &m_selectedSouringTracersUiField == changedField ) + { + if ( !m_resultVariable().isEmpty() ) + { + m_selectedSouringTracers = m_selectedSouringTracersUiField(); + loadDataAndUpdate(); + } + } + + if ( &m_phaseSelection == changedField ) + { + if ( m_phaseSelection() != RigFlowDiagResultAddress::PHASE_ALL ) + { + m_resultType = m_resultTypeUiField; + m_resultVariable = RIG_FLD_TOF_RESNAME; + m_resultVariableUiField = RIG_FLD_TOF_RESNAME; + } + loadDataAndUpdate(); + } + + if ( &m_showOnlyVisibleCategoriesInLegend == changedField ) + { + loadDataAndUpdate(); + } + + updateAnyFieldHasChanged(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::changedTracerSelectionField( bool injector ) +{ + m_flowSolution = m_flowSolutionUiField(); + + std::vector& selectedTracers = injector ? m_selectedInjectorTracers.v() : m_selectedProducerTracers.v(); + const std::vector& selectedTracersUi = injector ? m_selectedInjectorTracersUiField.v() : m_selectedProducerTracersUiField.v(); + + selectedTracers = selectedTracersUi; + + loadDataAndUpdate(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::updateAnyFieldHasChanged() +{ + RimEclipsePropertyFilter* propFilter = firstAncestorOrThisOfType(); + if ( propFilter ) + { + propFilter->updateConnectedEditors(); + } + + RimEclipseFaultColors* faultColors = firstAncestorOrThisOfType(); + if ( faultColors ) + { + faultColors->updateConnectedEditors(); + } + + RimCellEdgeColors* cellEdgeColors = firstAncestorOrThisOfType(); + if ( cellEdgeColors ) + { + cellEdgeColors->updateConnectedEditors(); + } + + RimEclipseCellColors* cellColors = firstAncestorOrThisOfType(); + if ( cellColors ) + { + cellColors->updateConnectedEditors(); + } + + RimIntersectionResultDefinition* intersectResDef = firstAncestorOrThisOfType(); + if ( intersectResDef ) + { + intersectResDef->setDefaultEclipseLegendConfig(); + intersectResDef->updateConnectedEditors(); + } + + RimGridCrossPlotDataSet* crossPlotCurveSet = firstAncestorOrThisOfType(); + if ( crossPlotCurveSet ) + { + crossPlotCurveSet->updateConnectedEditors(); + } + + RimPlotCurve* curve = firstAncestorOrThisOfType(); + if ( curve ) + { + curve->updateConnectedEditors(); + } + + Rim3dWellLogCurve* rim3dWellLogCurve = firstAncestorOrThisOfType(); + if ( rim3dWellLogCurve ) + { + rim3dWellLogCurve->resetMinMaxValues(); + } + + RimEclipseContourMapProjection* contourMap = firstAncestorOrThisOfType(); + if ( contourMap ) + { + contourMap->clearGridMappingAndRedraw(); + } + + RimWellLogTrack* wellLogTrack = firstAncestorOrThisOfType(); + if ( wellLogTrack ) + { + wellLogTrack->loadDataAndUpdate(); + wellLogTrack->updateEditors(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setTofAndSelectTracer( const QString& tracerName ) +{ + setResultType( RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ); + setResultVariable( "TOF" ); + setFlowDiagTracerSelectionType( FlowTracerSelectionType::FLOW_TR_BY_SELECTION ); + + if ( m_flowSolution() == nullptr ) + { + assignFlowSolutionFromCase(); + } + + if ( m_flowSolution() ) + { + RimFlowDiagSolution::TracerStatusType tracerStatus = m_flowSolution()->tracerStatusOverall( tracerName ); + + std::vector tracers; + tracers.push_back( tracerName ); + if ( ( tracerStatus == RimFlowDiagSolution::TracerStatusType::INJECTOR ) || + ( tracerStatus == RimFlowDiagSolution::TracerStatusType::VARYING ) ) + { + setSelectedInjectorTracers( tracers ); + } + + if ( ( tracerStatus == RimFlowDiagSolution::TracerStatusType::PRODUCER ) || + ( tracerStatus == RimFlowDiagSolution::TracerStatusType::VARYING ) ) + { + setSelectedProducerTracers( tracers ); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::loadDataAndUpdate() +{ + auto view = firstAncestorOrThisOfType(); + + loadResult(); + + RimEclipsePropertyFilter* propFilter = firstAncestorOrThisOfType(); + if ( propFilter ) + { + propFilter->setToDefaultValues(); + propFilter->updateFilterName(); + + if ( view ) + { + view->scheduleGeometryRegen( PROPERTY_FILTERED ); + view->scheduleCreateDisplayModelAndRedraw(); + } + } + + RimEclipseCellColors* cellColors = firstAncestorOrThisOfType(); + if ( cellColors ) + { + updateLegendCategorySettings(); + + if ( view ) + { + RimViewLinker* viewLinker = view->assosiatedViewLinker(); + if ( viewLinker ) + { + viewLinker->updateCellResult(); + } + RimGridView* eclView = dynamic_cast( view ); + if ( eclView ) eclView->intersectionCollection()->scheduleCreateDisplayModelAndRedraw2dIntersectionViews(); + } + } + + RimIntersectionResultDefinition* sepIntersectionResDef = firstAncestorOrThisOfType(); + if ( sepIntersectionResDef && sepIntersectionResDef->isInAction() ) + { + if ( view ) view->scheduleCreateDisplayModelAndRedraw(); + RimGridView* gridView = dynamic_cast( view ); + if ( gridView ) gridView->intersectionCollection()->scheduleCreateDisplayModelAndRedraw2dIntersectionViews(); + } + + RimCellEdgeColors* cellEdgeColors = firstAncestorOrThisOfType(); + if ( cellEdgeColors ) + { + cellEdgeColors->loadResult(); + + if ( view ) + { + view->scheduleCreateDisplayModelAndRedraw(); + } + } + + RimGridCrossPlotDataSet* crossPlotCurveSet = firstAncestorOrThisOfType(); + if ( crossPlotCurveSet ) + { + crossPlotCurveSet->destroyCurves(); + crossPlotCurveSet->loadDataAndUpdate( true ); + } + + RimPlotCurve* curve = firstAncestorOrThisOfType(); + if ( curve ) + { + curve->loadDataAndUpdate( true ); + } + + Rim3dWellLogCurve* rim3dWellLogCurve = firstAncestorOrThisOfType(); + if ( rim3dWellLogCurve ) + { + rim3dWellLogCurve->updateCurveIn3dView(); + } + +#ifdef USE_QTCHARTS + RimGridStatisticsPlot* gridStatisticsPlot = firstAncestorOrThisOfType(); + if ( gridStatisticsPlot ) + { + gridStatisticsPlot->loadDataAndUpdate(); + } +#endif +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QList RimEclipseResultDefinition::calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) +{ + QList options; + + if ( fieldNeedingOptions == &m_resultTypeUiField ) + { + bool hasSourSimRLFile = false; + RimEclipseResultCase* eclResCase = dynamic_cast( m_eclipseCase.p() ); + if ( eclResCase && eclResCase->eclipseCaseData() ) + { + hasSourSimRLFile = eclResCase->hasSourSimFile(); + } + +#ifndef USE_HDF5 + // If using ResInsight without HDF5 support, ignore SourSim files and + // do not show it as a result category. + hasSourSimRLFile = false; +#endif + + bool enableSouring = false; + +#ifdef USE_HDF5 + if ( m_eclipseCase.notNull() ) + { + RigCaseCellResultsData* cellResultsData = m_eclipseCase->results( porosityModel() ); + + if ( cellResultsData && cellResultsData->hasFlowDiagUsableFluxes() ) + { + enableSouring = true; + } + } +#endif /* USE_HDF5 */ + + RimGridTimeHistoryCurve* timeHistoryCurve = firstAncestorOrThisOfType(); + + bool isSeparateFaultResult = false; + { + RimEclipseFaultColors* sepFaultResult = firstAncestorOrThisOfType(); + if ( sepFaultResult ) isSeparateFaultResult = true; + } + + using ResCatEnum = caf::AppEnum; + for ( size_t i = 0; i < ResCatEnum::size(); ++i ) + { + RiaDefines::ResultCatType resType = ResCatEnum::fromIndex( i ); + + // Do not include flow diagnostics results if it is a time history curve + + if ( resType == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && ( timeHistoryCurve ) ) + { + continue; + } + + if ( resType == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && m_eclipseCase && m_eclipseCase->eclipseCaseData() && + m_eclipseCase->eclipseCaseData()->hasFractureResults() ) + { + // Flow diagnostics is not supported for dual porosity models + continue; + } + + // Do not include SourSimRL if no SourSim file is loaded + + if ( resType == RiaDefines::ResultCatType::SOURSIMRL && ( !hasSourSimRLFile ) ) + { + continue; + } + + if ( resType == RiaDefines::ResultCatType::INJECTION_FLOODING && !enableSouring ) + { + continue; + } + + if ( resType == RiaDefines::ResultCatType::ALLAN_DIAGRAMS && !isSeparateFaultResult ) + { + continue; + } + + QString uiString = ResCatEnum::uiTextFromIndex( i ); + options.push_back( caf::PdmOptionItemInfo( uiString, resType ) ); + } + } + + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + if ( fieldNeedingOptions == &m_resultVariableUiField ) + { + options.push_back( caf::PdmOptionItemInfo( RimEclipseResultDefinitionTools::timeOfFlightString( injectorSelectionState(), + producerSelectionState(), + false ), + RIG_FLD_TOF_RESNAME ) ); + if ( m_phaseSelection() == RigFlowDiagResultAddress::PHASE_ALL ) + { + options.push_back( caf::PdmOptionItemInfo( "Tracer Cell Fraction (Sum)", RIG_FLD_CELL_FRACTION_RESNAME ) ); + options.push_back( caf::PdmOptionItemInfo( RimEclipseResultDefinitionTools::maxFractionTracerString( injectorSelectionState(), + producerSelectionState(), + false ), + RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) ); + options.push_back( caf::PdmOptionItemInfo( "Injector Producer Communication", RIG_FLD_COMMUNICATION_RESNAME ) ); + } + } + else if ( fieldNeedingOptions == &m_flowSolutionUiField ) + { + RimEclipseResultCase* eclCase = dynamic_cast( m_eclipseCase.p() ); + if ( eclCase ) + { + std::vector flowSols = eclCase->flowDiagSolutions(); + for ( RimFlowDiagSolution* flowSol : flowSols ) + { + options.push_back( caf::PdmOptionItemInfo( flowSol->userDescription(), flowSol ) ); + } + } + } + else if ( fieldNeedingOptions == &m_selectedInjectorTracersUiField ) + { + const bool isInjector = true; + options = RimFlowDiagnosticsTools::calcOptionsForSelectedTracerField( m_flowSolutionUiField(), isInjector ); + } + else if ( fieldNeedingOptions == &m_selectedProducerTracersUiField ) + { + const bool isInjector = false; + options = RimFlowDiagnosticsTools::calcOptionsForSelectedTracerField( m_flowSolutionUiField(), isInjector ); + } + } + else if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INJECTION_FLOODING ) + { + if ( fieldNeedingOptions == &m_selectedSouringTracersUiField ) + { + RigCaseCellResultsData* cellResultsStorage = currentGridCellResults(); + if ( cellResultsStorage ) + { + QStringList dynamicResultNames = cellResultsStorage->resultNames( RiaDefines::ResultCatType::DYNAMIC_NATIVE ); + + for ( const QString& resultName : dynamicResultNames ) + { + if ( !resultName.endsWith( "F" ) || resultName == RiaResultNames::completionTypeResultName() ) + { + continue; + } + options.push_back( caf::PdmOptionItemInfo( resultName, resultName ) ); + } + } + } + else if ( fieldNeedingOptions == &m_resultVariableUiField ) + { + options.push_back( caf::PdmOptionItemInfo( RIG_NUM_FLOODED_PV, RIG_NUM_FLOODED_PV ) ); + } + } + else + { + if ( fieldNeedingOptions == &m_resultVariableUiField ) + { + options = calcOptionsForVariableUiFieldStandard( m_resultTypeUiField(), + currentGridCellResults(), + showDerivedResultsFirstInVariableUiField(), + addPerCellFaceOptionsForVariableUiField(), + m_ternaryEnabled ); + } + else if ( fieldNeedingOptions == &m_differenceCase ) + { + options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); + + auto eclipseCase = firstAncestorOrThisOfTypeAsserted(); + if ( eclipseCase && eclipseCase->eclipseCaseData() && eclipseCase->eclipseCaseData()->mainGrid() ) + { + RimProject* proj = RimProject::current(); + + std::vector allCases = proj->eclipseCases(); + for ( RimEclipseCase* otherCase : allCases ) + { + if ( otherCase == eclipseCase ) continue; + + if ( otherCase->eclipseCaseData() && otherCase->eclipseCaseData()->mainGrid() ) + { + options.push_back( + caf::PdmOptionItemInfo( QString( "%1 (#%2)" ).arg( otherCase->caseUserDescription() ).arg( otherCase->caseId() ), + otherCase, + false, + otherCase->uiIconProvider() ) ); + } + } + } + } + else if ( fieldNeedingOptions == &m_timeLapseBaseTimestep ) + { + RimEclipseCase* currentCase = firstAncestorOrThisOfTypeAsserted(); + + RimEclipseCase* baseCase = currentCase; + if ( m_differenceCase ) + { + baseCase = m_differenceCase; + } + + options.push_back( caf::PdmOptionItemInfo( "Disabled", RigEclipseResultAddress::noTimeLapseValue() ) ); + + std::vector stepDates = baseCase->timeStepDates(); + for ( size_t stepIdx = 0; stepIdx < stepDates.size(); ++stepIdx ) + { + QString displayString = stepDates[stepIdx].toString( RiaQDateTimeTools::dateFormatString() ); + displayString += QString( " (#%1)" ).arg( stepIdx ); + + options.push_back( caf::PdmOptionItemInfo( displayString, static_cast( stepIdx ) ) ); + } + } + } + + return options; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigEclipseResultAddress RimEclipseResultDefinition::eclipseResultAddress() const +{ + if ( !isChecked() ) return RigEclipseResultAddress(); + if ( isFlowDiagOrInjectionFlooding() ) return RigEclipseResultAddress(); + + const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + if ( gridCellResults ) + { + int timelapseTimeStep = RigEclipseResultAddress::noTimeLapseValue(); + int diffCaseId = RigEclipseResultAddress::noCaseDiffValue(); + + if ( isDeltaTimeStepActive() ) + { + timelapseTimeStep = m_timeLapseBaseTimestep(); + } + + if ( isDeltaCaseActive() ) + { + diffCaseId = m_differenceCase->caseId(); + } + + return RigEclipseResultAddress( m_resultType(), m_resultVariable(), timelapseTimeStep, diffCaseId, isDivideByCellFaceAreaActive() ); + } + else + { + return RigEclipseResultAddress(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setFromEclipseResultAddress( const RigEclipseResultAddress& address ) +{ + RigEclipseResultAddress canonizedAddress = address; + + const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + if ( gridCellResults ) + { + auto rinfo = gridCellResults->resultInfo( address ); + if ( rinfo ) canonizedAddress = rinfo->eclipseResultAddress(); + } + + m_resultType = canonizedAddress.resultCatType(); + m_resultVariable = canonizedAddress.resultName(); + m_timeLapseBaseTimestep = canonizedAddress.deltaTimeStepIndex(); + m_divideByCellFaceArea = canonizedAddress.isDivideByCellFaceAreaActive(); + + if ( canonizedAddress.isDeltaCaseActive() ) + { + auto eclipseCases = RimProject::current()->eclipseCases(); + for ( RimEclipseCase* c : eclipseCases ) + { + if ( c && c->caseId() == canonizedAddress.deltaCaseId() ) + { + m_differenceCase = c; + } + } + } + + updateUiFieldsFromActiveResult(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigFlowDiagResultAddress RimEclipseResultDefinition::flowDiagResAddress() const +{ + CVF_ASSERT( isFlowDiagOrInjectionFlooding() ); + + if ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + size_t timeStep = 0; + + auto rimView = firstAncestorOrThisOfType(); + if ( rimView ) + { + timeStep = rimView->currentTimeStep(); + } + RimWellLogExtractionCurve* wellLogExtractionCurve = firstAncestorOrThisOfType(); + if ( wellLogExtractionCurve ) + { + timeStep = static_cast( wellLogExtractionCurve->currentTimeStep() ); + } + + std::set selTracerNames; + if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) + { + for ( const QString& tName : m_selectedInjectorTracers() ) + { + selTracerNames.insert( tName.toStdString() ); + } + for ( const QString& tName : m_selectedProducerTracers() ) + { + selTracerNames.insert( tName.toStdString() ); + } + } + else + { + RimFlowDiagSolution* flowSol = m_flowSolution(); + if ( flowSol ) + { + std::vector tracerNames = flowSol->tracerNames(); + + if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_INJECTORS || + m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD ) + { + for ( const QString& tracerName : tracerNames ) + { + RimFlowDiagSolution::TracerStatusType status = flowSol->tracerStatusInTimeStep( tracerName, timeStep ); + if ( status == RimFlowDiagSolution::TracerStatusType::INJECTOR ) + { + selTracerNames.insert( tracerName.toStdString() ); + } + } + } + + if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_PRODUCERS || + m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_INJ_AND_PROD ) + { + for ( const QString& tracerName : tracerNames ) + { + RimFlowDiagSolution::TracerStatusType status = flowSol->tracerStatusInTimeStep( tracerName, timeStep ); + if ( status == RimFlowDiagSolution::TracerStatusType::PRODUCER ) + { + selTracerNames.insert( tracerName.toStdString() ); + } + } + } + } + } + + return RigFlowDiagResultAddress( m_resultVariable().toStdString(), m_phaseSelection(), selTracerNames ); + } + + std::set selTracerNames; + for ( const QString& selectedTracerName : m_selectedSouringTracers() ) + { + selTracerNames.insert( selectedTracerName.toUtf8().constData() ); + } + return RigFlowDiagResultAddress( m_resultVariable().toStdString(), RigFlowDiagResultAddress::PHASE_ALL, selTracerNames ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setFlowDiagTracerSelectionType( FlowTracerSelectionType selectionType ) +{ + m_flowTracerSelectionMode = selectionType; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEclipseResultDefinition::resultVariableUiName() const +{ + if ( resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + return flowDiagResUiText( false, 32 ); + } + + if ( isDivideByCellFaceAreaActive() ) + { + return m_resultVariable() + " /A"; + } + + return m_resultVariable(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEclipseResultDefinition::resultVariableUiShortName() const +{ + if ( resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + return flowDiagResUiText( true, 24 ); + } + + if ( isDivideByCellFaceAreaActive() ) + { + return m_resultVariable() + " /A"; + } + + return m_resultVariable(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEclipseResultDefinition::additionalResultText() const +{ + QStringList resultText; + + if ( isDeltaTimeStepActive() ) + { + std::vector stepDates; + const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + if ( gridCellResults ) + { + stepDates = gridCellResults->timeStepDates(); + resultText += QString( "Base Time Step: %1" ) + .arg( stepDates[m_timeLapseBaseTimestep()].toString( RiaQDateTimeTools::dateFormatString() ) ); + } + } + if ( isDeltaCaseActive() ) + { + resultText += QString( "Base Case: %1" ).arg( m_differenceCase()->caseUserDescription() ); + } + return resultText.join( "
" ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEclipseResultDefinition::additionalResultTextShort() const +{ + QString resultTextShort; + if ( isDeltaTimeStepActive() || isDeltaCaseActive() ) + { + QStringList resultTextLines; + resultTextLines += QString( "\nDiff. Options:" ); + if ( isDeltaCaseActive() ) + { + resultTextLines += QString( "Base Case: #%1" ).arg( m_differenceCase()->caseId() ); + } + if ( isDeltaTimeStepActive() ) + { + resultTextLines += QString( "Base Time: #%1" ).arg( m_timeLapseBaseTimestep() ); + } + resultTextShort = resultTextLines.join( "\n" ); + } + + return resultTextShort; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RimEclipseResultDefinition::timeLapseBaseTimeStep() const +{ + return m_timeLapseBaseTimestep; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int RimEclipseResultDefinition::caseDiffIndex() const +{ + if ( m_differenceCase ) + { + return m_differenceCase->caseId(); + } + return -1; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::loadResult() +{ + if ( isFlowDiagOrInjectionFlooding() ) return; // Will load automatically on access + + if ( m_eclipseCase ) + { + if ( !m_eclipseCase->ensureReservoirCaseIsOpen() ) + { + RiaLogging::error( "Could not open the Eclipse Grid file: " + m_eclipseCase->gridFileName() ); + return; + } + } + + if ( m_differenceCase ) + { + if ( !m_differenceCase->ensureReservoirCaseIsOpen() ) + { + RiaLogging::error( "Could not open the Eclipse Grid file: " + m_eclipseCase->gridFileName() ); + return; + } + } + + RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + if ( gridCellResults ) + { + if ( isDeltaTimeStepActive() || isDeltaCaseActive() || isDivideByCellFaceAreaActive() ) + { + gridCellResults->createResultEntry( eclipseResultAddress(), false ); + } + + QString resultName = m_resultVariable(); + std::set eclipseResultNamesWithNncData = RiaResultNames::nncResultNames(); + if ( eclipseResultNamesWithNncData.find( resultName ) != eclipseResultNamesWithNncData.end() ) + { + eclipseCase()->ensureFaultDataIsComputed(); + + bool dataWasComputed = eclipseCase()->ensureNncDataIsComputed(); + if ( dataWasComputed ) + { + eclipseCase()->createDisplayModelAndUpdateAllViews(); + } + } + + gridCellResults->ensureKnownResultLoaded( eclipseResultAddress() ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// Returns whether the result requested by the definition is a single frame result +/// The result needs to be loaded before asking +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::hasStaticResult() const +{ + if ( isFlowDiagOrInjectionFlooding() ) return false; + + const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + RigEclipseResultAddress gridScalarResultIndex = eclipseResultAddress(); + + return hasResult() && gridCellResults->timeStepCount( gridScalarResultIndex ) == 1; +} + +//-------------------------------------------------------------------------------------------------- +/// Returns whether the result requested by the definition is loaded or possible to load from the result file +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::hasResult() const +{ + if ( isFlowDiagOrInjectionFlooding() ) + { + if ( m_flowSolution() && !m_resultVariable().isEmpty() ) return true; + } + else if ( currentGridCellResults() ) + { + const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + + return gridCellResults->hasResultEntry( eclipseResultAddress() ); + } + + return false; +} + +//-------------------------------------------------------------------------------------------------- +/// Returns whether the result requested by the definition is a multi frame result +/// The result needs to be loaded before asking +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::hasDynamicResult() const +{ + if ( hasResult() ) + { + if ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE ) + { + return true; + } + else if ( m_resultType() == RiaDefines::ResultCatType::SOURSIMRL ) + { + return true; + } + else if ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + return true; + } + else if ( m_resultType() == RiaDefines::ResultCatType::INJECTION_FLOODING ) + { + return true; + } + + if ( currentGridCellResults() ) + { + const RigCaseCellResultsData* gridCellResults = currentGridCellResults(); + RigEclipseResultAddress gridScalarResultIndex = eclipseResultAddress(); + if ( gridCellResults->timeStepCount( gridScalarResultIndex ) > 1 ) + { + return true; + } + } + } + + return false; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::initAfterRead() +{ + if ( m_flowSolution() == nullptr ) + { + assignFlowSolutionFromCase(); + } + + if ( m_resultVariable() == "Formation Allen" ) + { + m_resultVariable = RiaResultNames::formationAllanResultName(); + m_resultType = RiaDefines::ResultCatType::ALLAN_DIAGRAMS; + } + else if ( m_resultVariable() == "Binary Formation Allen" ) + { + m_resultVariable = RiaResultNames::formationBinaryAllanResultName(); + m_resultType = RiaDefines::ResultCatType::ALLAN_DIAGRAMS; + } + + m_porosityModelUiField = m_porosityModel; + m_resultTypeUiField = m_resultType; + m_resultVariableUiField = m_resultVariable; + + m_flowSolutionUiField = m_flowSolution(); + m_selectedInjectorTracersUiField = m_selectedInjectorTracers; + + updateUiIconFromToggleField(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setResultType( RiaDefines::ResultCatType val ) +{ + m_resultType = val; + m_resultTypeUiField = val; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RiaDefines::PorosityModelType RimEclipseResultDefinition::porosityModel() const +{ + return m_porosityModel(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setPorosityModel( RiaDefines::PorosityModelType val ) +{ + m_porosityModel = val; + m_porosityModelUiField = val; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEclipseResultDefinition::resultVariable() const +{ + if ( !isChecked() ) return RiaResultNames::undefinedResultName(); + + return m_resultVariable(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setResultVariable( const QString& val ) +{ + m_resultVariable = val; + m_resultVariableUiField = val; +} + +//-------------------------------------------------------------------------------------------------- +/// Return phase type if the current result is known to be of a particular +/// fluid phase type. Otherwise the method will return PHASE_NOT_APPLICABLE. +//-------------------------------------------------------------------------------------------------- +RiaDefines::PhaseType RimEclipseResultDefinition::resultPhaseType() const +{ + if ( QRegularExpression( "OIL" ).match( m_resultVariable() ).hasMatch() ) + { + return RiaDefines::PhaseType::OIL_PHASE; + } + else if ( QRegularExpression( "GAS" ).match( m_resultVariable() ).hasMatch() ) + { + return RiaDefines::PhaseType::GAS_PHASE; + } + else if ( QRegularExpression( "WAT" ).match( m_resultVariable() ).hasMatch() ) + { + return RiaDefines::PhaseType::WATER_PHASE; + } + return RiaDefines::PhaseType::PHASE_NOT_APPLICABLE; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFlowDiagSolution* RimEclipseResultDefinition::flowDiagSolution() const +{ + return m_flowSolution(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setFlowSolution( RimFlowDiagSolution* flowSol ) +{ + m_flowSolution = flowSol; + m_flowSolutionUiField = flowSol; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setSelectedTracers( const std::vector& selectedTracers ) +{ + if ( m_flowSolution() == nullptr ) + { + assignFlowSolutionFromCase(); + } + if ( m_flowSolution() ) + { + std::vector injectorTracers; + std::vector producerTracers; + for ( const QString& tracerName : selectedTracers ) + { + RimFlowDiagSolution::TracerStatusType tracerStatus = m_flowSolution()->tracerStatusOverall( tracerName ); + if ( tracerStatus == RimFlowDiagSolution::TracerStatusType::INJECTOR ) + { + injectorTracers.push_back( tracerName ); + } + else if ( tracerStatus == RimFlowDiagSolution::TracerStatusType::PRODUCER ) + { + producerTracers.push_back( tracerName ); + } + else if ( tracerStatus == RimFlowDiagSolution::TracerStatusType::VARYING || + tracerStatus == RimFlowDiagSolution::TracerStatusType::UNDEFINED ) + { + injectorTracers.push_back( tracerName ); + producerTracers.push_back( tracerName ); + } + } + setSelectedInjectorTracers( injectorTracers ); + setSelectedProducerTracers( producerTracers ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setSelectedInjectorTracers( const std::vector& selectedTracers ) +{ + m_selectedInjectorTracers = selectedTracers; + m_selectedInjectorTracersUiField = selectedTracers; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setSelectedProducerTracers( const std::vector& selectedTracers ) +{ + m_selectedProducerTracers = selectedTracers; + m_selectedProducerTracersUiField = selectedTracers; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setSelectedSouringTracers( const std::vector& selectedTracers ) +{ + m_selectedSouringTracers = selectedTracers; + m_selectedSouringTracersUiField = selectedTracers; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::updateUiFieldsFromActiveResult() +{ + m_resultTypeUiField = m_resultType; + m_resultVariableUiField = resultVariable(); + m_selectedInjectorTracersUiField = m_selectedInjectorTracers; + m_selectedProducerTracersUiField = m_selectedProducerTracers; + m_selectedSouringTracersUiField = m_selectedSouringTracers; + m_porosityModelUiField = m_porosityModel; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::enableDeltaResults( bool enable ) +{ + m_isDeltaResultEnabled = enable; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isTernarySaturationSelected() const +{ + bool isTernary = ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE ) && + ( m_resultVariable().compare( RiaResultNames::ternarySaturationResultName(), Qt::CaseInsensitive ) == 0 ); + + return isTernary; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isCompletionTypeSelected() const +{ + return ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE && m_resultVariable() == RiaResultNames::completionTypeResultName() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::hasCategoryResult() const +{ + if ( auto* gridCellResults = currentGridCellResults() ) + { + const auto addresses = gridCellResults->existingResults(); + for ( const auto& address : addresses ) + { + if ( address.resultCatType() == m_resultType() && address.resultName() == m_resultVariable() ) + { + if ( address.dataType() == RiaDefines::ResultDataType::INTEGER ) return true; + break; + } + } + } + + if ( m_resultType() == RiaDefines::ResultCatType::FORMATION_NAMES && m_eclipseCase && m_eclipseCase->eclipseCaseData() && + !m_eclipseCase->eclipseCaseData()->formationNames().empty() ) + return true; + + if ( m_resultType() == RiaDefines::ResultCatType::DYNAMIC_NATIVE && resultVariable() == RiaResultNames::completionTypeResultName() ) + return true; + + if ( m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && m_resultVariable() == RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) + return true; + + if ( resultVariable() == RiaResultNames::formationAllanResultName() || resultVariable() == RiaResultNames::formationBinaryAllanResultName() ) + { + return true; + } + + return false; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isFlowDiagOrInjectionFlooding() const +{ + return m_resultType() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS || m_resultType() == RiaDefines::ResultCatType::INJECTION_FLOODING; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( &m_resultTypeUiField ); + + if ( hasDualPorFractureResult() ) + { + uiOrdering.add( &m_porosityModelUiField ); + } + + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + uiOrdering.add( &m_flowSolutionUiField ); + + uiOrdering.add( &m_flowTracerSelectionMode ); + + if ( m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) + { + caf::PdmUiGroup* selectionGroup = uiOrdering.addNewGroup( "Tracer Selection" ); + selectionGroup->setEnableFrame( false ); + + caf::PdmUiGroup* injectorGroup = selectionGroup->addNewGroup( "Injectors" ); + injectorGroup->add( &m_selectedInjectorTracersUiField ); + injectorGroup->add( &m_syncInjectorToProducerSelection ); + + caf::PdmUiGroup* producerGroup = selectionGroup->addNewGroup( "Producers", { .newRow = false } ); + producerGroup->add( &m_selectedProducerTracersUiField ); + producerGroup->add( &m_syncProducerToInjectorSelection ); + } + + uiOrdering.add( &m_phaseSelection ); + + if ( m_flowSolution() == nullptr ) + { + assignFlowSolutionFromCase(); + } + } + + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INJECTION_FLOODING ) + { + uiOrdering.add( &m_selectedSouringTracersUiField ); + } + + uiOrdering.add( &m_resultVariableUiField ); + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::INPUT_PROPERTY ) + { + uiOrdering.add( &m_inputPropertyFileName ); + } + + if ( isDivideByCellFaceAreaPossible() ) + { + uiOrdering.add( &m_divideByCellFaceArea ); + + QString resultPropertyLabel = "Result Property"; + if ( isDivideByCellFaceAreaActive() ) + { + resultPropertyLabel += QString( "\nDivided by Area" ); + } + m_resultVariableUiField.uiCapability()->setUiName( resultPropertyLabel ); + } + + { + caf::PdmUiGroup* legendGroup = uiOrdering.addNewGroup( "Legend" ); + legendGroup->add( &m_showOnlyVisibleCategoriesInLegend ); + + bool showOnlyVisibleCategoriesOption = false; + + RimEclipseView* eclView = firstAncestorOrThisOfType(); + + if ( eclView ) + { + if ( eclView->cellResult() == this && hasCategoryResult() ) showOnlyVisibleCategoriesOption = true; + } + + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && + m_resultVariableUiField() == RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) + { + showOnlyVisibleCategoriesOption = true; + } + + legendGroup->setUiHidden( !showOnlyVisibleCategoriesOption ); + } + + if ( isDeltaCasePossible() || isDeltaTimeStepPossible() ) + { + caf::PdmUiGroup* differenceGroup = uiOrdering.addNewGroup( "Difference Options" ); + differenceGroup->setUiReadOnly( !( isDeltaTimeStepPossible() || isDeltaCasePossible() ) ); + + m_differenceCase.uiCapability()->setUiReadOnly( !isDeltaCasePossible() ); + m_timeLapseBaseTimestep.uiCapability()->setUiReadOnly( !isDeltaTimeStepPossible() ); + + if ( isDeltaCasePossible() ) differenceGroup->add( &m_differenceCase ); + if ( isDeltaTimeStepPossible() ) differenceGroup->add( &m_timeLapseBaseTimestep ); + + QString resultPropertyLabel = "Result Property"; + if ( isDeltaTimeStepActive() || isDeltaCaseActive() ) + { + resultPropertyLabel += QString( "\n%1" ).arg( additionalResultTextShort() ); + } + m_resultVariableUiField.uiCapability()->setUiName( resultPropertyLabel ); + } + + uiOrdering.skipRemainingFields( true ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( m_resultTypeUiField() == RiaDefines::ResultCatType::FLOW_DIAGNOSTICS ) + { + if ( field == &m_syncInjectorToProducerSelection || field == &m_syncProducerToInjectorSelection ) + { + caf::PdmUiToolButtonEditorAttribute* toolButtonAttr = dynamic_cast( attribute ); + if ( toolButtonAttr ) + { + toolButtonAttr->m_sizePolicy.setHorizontalPolicy( QSizePolicy::MinimumExpanding ); + } + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::assignFlowSolutionFromCase() +{ + RimFlowDiagSolution* defaultFlowDiagSolution = nullptr; + + RimEclipseResultCase* eclCase = dynamic_cast( m_eclipseCase.p() ); + + if ( eclCase ) + { + defaultFlowDiagSolution = eclCase->defaultFlowDiagSolution(); + } + setFlowSolution( defaultFlowDiagSolution ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::hasDualPorFractureResult() +{ + if ( m_eclipseCase && m_eclipseCase->eclipseCaseData() ) + { + return m_eclipseCase->eclipseCaseData()->hasFractureResults(); + } + + return false; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEclipseResultDefinition::flowDiagResUiText( bool shortLabel, int maxTracerStringLength ) const +{ + QString uiText = QString::fromStdString( flowDiagResAddress().variableName ); + if ( flowDiagResAddress().variableName == RIG_FLD_TOF_RESNAME ) + { + uiText = RimEclipseResultDefinitionTools::timeOfFlightString( injectorSelectionState(), producerSelectionState(), shortLabel ); + } + else if ( flowDiagResAddress().variableName == RIG_FLD_MAX_FRACTION_TRACER_RESNAME ) + { + uiText = RimEclipseResultDefinitionTools::maxFractionTracerString( injectorSelectionState(), producerSelectionState(), shortLabel ); + } + + QString tracersString = RimEclipseResultDefinitionTools::selectedTracersString( injectorSelectionState(), + producerSelectionState(), + m_selectedInjectorTracers(), + m_selectedProducerTracers(), + maxTracerStringLength ); + + if ( !tracersString.isEmpty() ) + { + uiText += QString( "\n%1" ).arg( tracersString ); + } + return uiText; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QList RimEclipseResultDefinition::calcOptionsForVariableUiFieldStandard( RiaDefines::ResultCatType resultCatType, + const RigCaseCellResultsData* results, + bool showDerivedResultsFirst, + bool addPerCellFaceOptionItems, + bool ternaryEnabled ) +{ + CVF_ASSERT( resultCatType != RiaDefines::ResultCatType::FLOW_DIAGNOSTICS && resultCatType != RiaDefines::ResultCatType::INJECTION_FLOODING ); + + return RimEclipseResultDefinitionTools::calcOptionsForVariableUiFieldStandard( resultCatType, + results, + showDerivedResultsFirst, + addPerCellFaceOptionItems, + ternaryEnabled ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::setTernaryEnabled( bool enabled ) +{ + m_ternaryEnabled = enabled; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::updateRangesForExplicitLegends( RimRegularLegendConfig* legendConfigToUpdate, + RimTernaryLegendConfig* ternaryLegendConfigToUpdate, + int currentTimeStep ) + +{ + if ( hasResult() ) + { + if ( isFlowDiagOrInjectionFlooding() ) + { + if ( currentTimeStep >= 0 ) + { + RimEclipseResultDefinitionTools::updateLegendForFlowDiagnostics( this, legendConfigToUpdate, currentTimeStep ); + } + } + else + { + RimEclipseResultDefinitionTools::updateCellResultLegend( this, legendConfigToUpdate, currentTimeStep ); + } + } + + if ( isTernarySaturationSelected() ) + { + RimEclipseResultDefinitionTools::updateTernaryLegend( currentGridCellResults(), ternaryLegendConfigToUpdate, currentTimeStep ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::updateLegendTitle( RimRegularLegendConfig* legendConfig, const QString& legendHeading ) +{ + QString title = legendHeading + resultVariableUiName(); + if ( !additionalResultTextShort().isEmpty() ) + { + title += additionalResultTextShort(); + } + + if ( hasDualPorFractureResult() ) + { + QString porosityModelText = caf::AppEnum::uiText( porosityModel() ); + + title += QString( "\nDual Por : %1" ).arg( porosityModelText ); + } + + legendConfig->setTitle( title ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::showOnlyVisibleCategoriesInLegend() const +{ + return m_showOnlyVisibleCategoriesInLegend(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEclipseResultDefinition::FlowTracerSelectionState RimEclipseResultDefinition::injectorSelectionState() const +{ + const bool isInjector = true; + return RimEclipseResultDefinitionTools::getFlowTracerSelectionState( isInjector, + m_flowTracerSelectionMode(), + m_flowSolutionUiField(), + m_selectedInjectorTracers().size() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEclipseResultDefinition::FlowTracerSelectionState RimEclipseResultDefinition::producerSelectionState() const +{ + const bool isInjector = false; + return RimEclipseResultDefinitionTools::getFlowTracerSelectionState( isInjector, + m_flowTracerSelectionMode(), + m_flowSolutionUiField(), + m_selectedProducerTracers().size() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::syncInjectorToProducerSelection() +{ + int timeStep = 0; + + auto rimView = firstAncestorOrThisOfType(); + if ( rimView ) + { + timeStep = rimView->currentTimeStep(); + } + + RimFlowDiagSolution* flowSol = m_flowSolution(); + if ( flowSol && m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) + { + std::set newProducerSelection = + RimFlowDiagnosticsTools::setOfProducerTracersFromInjectors( m_flowSolutionUiField(), m_selectedInjectorTracers(), timeStep ); + // Add all currently selected producers to set + for ( const QString& selectedProducer : m_selectedProducerTracers() ) + { + newProducerSelection.insert( selectedProducer ); + } + std::vector newProducerVector( newProducerSelection.begin(), newProducerSelection.end() ); + setSelectedProducerTracers( newProducerVector ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseResultDefinition::syncProducerToInjectorSelection() +{ + int timeStep = 0; + + auto rimView = firstAncestorOrThisOfType(); + if ( rimView ) + { + timeStep = rimView->currentTimeStep(); + } + + RimFlowDiagSolution* flowSol = m_flowSolution(); + if ( flowSol && m_flowTracerSelectionMode == FlowTracerSelectionType::FLOW_TR_BY_SELECTION ) + { + std::set newInjectorSelection = + RimFlowDiagnosticsTools::setOfInjectorTracersFromProducers( m_flowSolutionUiField(), m_selectedProducerTracers(), timeStep ); + + // Add all currently selected injectors to set + for ( const QString& selectedInjector : m_selectedInjectorTracers() ) + { + newInjectorSelection.insert( selectedInjector ); + } + std::vector newInjectorVector( newInjectorSelection.begin(), newInjectorSelection.end() ); + setSelectedInjectorTracers( newInjectorVector ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDeltaResultEnabled() const +{ + return m_isDeltaResultEnabled; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDeltaTimeStepPossible() const +{ + return isDeltaResultEnabled() && !isTernarySaturationSelected() && + ( m_resultTypeUiField() == RiaDefines::ResultCatType::DYNAMIC_NATIVE || + m_resultTypeUiField() == RiaDefines::ResultCatType::GENERATED ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDeltaTimeStepActive() const +{ + return isDeltaTimeStepPossible() && m_timeLapseBaseTimestep() >= 0; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDeltaCasePossible() const +{ + return isDeltaResultEnabled() && !isTernarySaturationSelected() && + ( m_resultTypeUiField() == RiaDefines::ResultCatType::DYNAMIC_NATIVE || + m_resultTypeUiField() == RiaDefines::ResultCatType::STATIC_NATIVE || + m_resultTypeUiField() == RiaDefines::ResultCatType::GENERATED ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDeltaCaseActive() const +{ + return isDeltaCasePossible() && m_differenceCase() != nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDivideByCellFaceAreaPossible() const +{ + return RimEclipseResultDefinitionTools::isDivideByCellFaceAreaPossible( m_resultVariable ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::isDivideByCellFaceAreaActive() const +{ + return isDivideByCellFaceAreaPossible() && m_divideByCellFaceArea; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::showDerivedResultsFirstInVariableUiField() const +{ + // Cell Face result names + bool showDerivedResultsFirstInList = false; + RimEclipseFaultColors* rimEclipseFaultColors = firstAncestorOrThisOfType(); + + if ( rimEclipseFaultColors ) showDerivedResultsFirstInList = true; + + return showDerivedResultsFirstInList; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEclipseResultDefinition::addPerCellFaceOptionsForVariableUiField() const +{ + RimPlotCurve* curve = firstAncestorOrThisOfType(); + RimEclipsePropertyFilter* propFilter = firstAncestorOrThisOfType(); + RimCellEdgeColors* cellEdge = firstAncestorOrThisOfType(); + + return !( propFilter || curve || cellEdge ); +} diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.cpp index 070b9e55b2..1feb6ca34b 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.cpp @@ -82,7 +82,7 @@ RimEclipseStatisticsCase::RimEclipseStatisticsCase() CAF_PDM_InitScriptableObject( "Case Group Statistics", ":/Histogram16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_calculateEditCommand, "m_editingAllowed", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_calculateEditCommand ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_calculateEditCommand ); m_calculateEditCommand = false; CAF_PDM_InitField( &m_selectionSummary, "SelectionSummary", QString( "" ), "Summary of Calculation Setup" ); @@ -285,6 +285,14 @@ void RimEclipseStatisticsCase::selectAllTimeSteps() } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEclipseStatisticsCase::setWellDataSourceCase( const QString& reservoirDescription ) +{ + m_wellDataSourceCase = reservoirDescription; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.h b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.h index e9c0a825c2..9af7e47b12 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.h +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCase.h @@ -85,6 +85,8 @@ class RimEclipseStatisticsCase : public RimEclipseCase void setSourceProperties( RiaDefines::ResultCatType propertyType, const std::vector& propertyNames ); void selectAllTimeSteps(); + void setWellDataSourceCase( const QString& reservoirDescription ); + private: void scheduleACTIVEGeometryRegenOnReservoirViews(); diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseCollection.cpp index 77942cd549..55b5f12057 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseCollection.cpp @@ -34,7 +34,6 @@ RimEclipseStatisticsCaseCollection::RimEclipseStatisticsCaseCollection() CAF_PDM_InitObject( "Derived Statistics" ); CAF_PDM_InitFieldNoDefault( &cases, "Reservoirs", "" ); - cases.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseEvaluator.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseEvaluator.cpp index 17f10eb79d..3fcf0c53fd 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseEvaluator.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseStatisticsCaseEvaluator.cpp @@ -63,6 +63,9 @@ void RimEclipseStatisticsCaseEvaluator::addNamedResult( RigCaseCellResultsData* size_t timeStepCount = std::max( size_t( 1 ), sourceTimeStepInfos.size() ); + // Limit to one time step for static native results + if ( resultType == RiaDefines::ResultCatType::STATIC_NATIVE ) timeStepCount = 1; + dataValues->resize( timeStepCount ); // Initializes the size of the destination dataset to active union cell count diff --git a/ApplicationLibCode/ProjectDataModel/RimEclipseView.cpp b/ApplicationLibCode/ProjectDataModel/RimEclipseView.cpp index 53c72285d5..0668713db3 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEclipseView.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEclipseView.cpp @@ -20,6 +20,7 @@ #include "RimEclipseView.h" +#include "RiaApplication.h" #include "RiaColorTables.h" #include "RiaFieldHandleTools.h" #include "RiaLogging.h" @@ -41,6 +42,7 @@ #include "RigWellResultFrame.h" #include "RigWellResultPoint.h" +#include "Polygons/RimPolygonInViewCollection.h" #include "Rim2dIntersectionView.h" #include "Rim3dOverlayInfoConfig.h" #include "RimAnnotationCollection.h" @@ -146,52 +148,40 @@ RimEclipseView::RimEclipseView() CAF_PDM_InitScriptableFieldWithScriptKeywordNoDefault( &m_cellResult, "GridCellResult", "CellResult", "Cell Result", ":/CellResult.png" ); m_cellResult = new RimEclipseCellColors(); - m_cellResult.uiCapability()->setUiTreeHidden( true ); m_cellResult->enableDeltaResults( true ); CAF_PDM_InitFieldNoDefault( &m_cellEdgeResult, "GridCellEdgeResult", "Cell Edge Result", ":/EdgeResult_1.png" ); m_cellEdgeResult = new RimCellEdgeColors(); - m_cellEdgeResult.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_elementVectorResult, "ElementVectorResult", "Vector Result", ":/CellResult.png" ); m_elementVectorResult = new RimElementVectorResult; - m_elementVectorResult.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_faultResultSettings, "FaultResultSettings", "Fault Result" ); m_faultResultSettings = new RimEclipseFaultColors(); - m_faultResultSettings.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_fractureColors, "StimPlanColors", "Fracture" ); m_fractureColors = new RimStimPlanColors(); - m_fractureColors.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_virtualPerforationResult, "VirtualPerforationResult", "" ); m_virtualPerforationResult = new RimVirtualPerforationResults(); - m_virtualPerforationResult.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wellCollection, "WellCollection", "Simulation Wells" ); m_wellCollection = new RimSimWellInViewCollection; - m_wellCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_faultCollection, "FaultCollection", "Faults" ); m_faultCollection = new RimFaultInViewCollection; - m_faultCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_faultReactivationModelCollection, "FaultReactivationModelCollection", "Fault Reactivation Models" ); m_faultReactivationModelCollection = new RimFaultReactivationModelCollection; - m_faultReactivationModelCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_annotationCollection, "AnnotationCollection", "Annotations" ); m_annotationCollection = new RimAnnotationInViewCollection; - m_annotationCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_streamlineCollection, "StreamlineCollection", "Streamlines" ); m_streamlineCollection = new RimStreamlineInViewCollection(); - m_streamlineCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_propertyFilterCollection, "PropertyFilters", "Property Filters" ); m_propertyFilterCollection = new RimEclipsePropertyFilterCollection(); - m_propertyFilterCollection.uiCapability()->setUiTreeHidden( true ); // Visualization fields CAF_PDM_InitField( &m_showInactiveCells, "ShowInactiveCells", false, "Show Inactive Cells" ); @@ -659,6 +649,9 @@ void RimEclipseView::onCreateDisplayModel() nativeOrOverrideViewer()->addStaticModelOnce( m_surfaceVizModel.p(), isUsingOverrideViewer() ); } + // Polygons + appendPolygonPartsToModel( transform.p(), ownerCase()->allCellsBoundingBox() ); + // Well path model m_wellPathPipeVizModel->removeAllParts(); @@ -1089,7 +1082,7 @@ void RimEclipseView::appendStreamlinesToModel() //-------------------------------------------------------------------------------------------------- void RimEclipseView::onLoadDataAndUpdate() { - updateSurfacesInViewTreeItems(); + updateViewTreeItems( RiaDefines::ItemIn3dView::ALL ); onUpdateScaleTransform(); @@ -1953,12 +1946,14 @@ void RimEclipseView::defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrderin if ( faultReactivationModelCollection()->shouldBeVisibleInTree() ) uiTreeOrdering.add( faultReactivationModelCollection() ); - uiTreeOrdering.add( annotationCollection() ); uiTreeOrdering.add( intersectionCollection() ); + uiTreeOrdering.add( m_polygonInViewCollection ); if ( surfaceInViewCollection() ) uiTreeOrdering.add( surfaceInViewCollection() ); if ( seismicSectionCollection()->shouldBeVisibleInTree() ) uiTreeOrdering.add( seismicSectionCollection() ); + uiTreeOrdering.add( annotationCollection() ); + uiTreeOrdering.skipRemainingChildren( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/RimElementVectorResult.cpp b/ApplicationLibCode/ProjectDataModel/RimElementVectorResult.cpp index 3fcc4e52d5..dfeeeb75f0 100644 --- a/ApplicationLibCode/ProjectDataModel/RimElementVectorResult.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimElementVectorResult.cpp @@ -75,7 +75,6 @@ RimElementVectorResult::RimElementVectorResult() CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendDefinition", "Color Legend" ); m_legendConfig = new RimRegularLegendConfig(); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_showOil, "ShowOil", true, "Oil" ); CAF_PDM_InitField( &m_showGas, "ShowGas", true, "Gas" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimEmCase.cpp b/ApplicationLibCode/ProjectDataModel/RimEmCase.cpp new file mode 100644 index 0000000000..4d6bd87d97 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/RimEmCase.cpp @@ -0,0 +1,281 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Ceetron Solutions AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimEmCase.h" + +#include "RiaDefines.h" +#include "RiaLogging.h" +#include "RiaPreferences.h" + +#include "RigActiveCellInfo.h" +#include "RigCaseCellResultsData.h" +#include "RigEclipseCaseData.h" +#include "RigEclipseResultAddress.h" +#include "RigMainGrid.h" +#include "RigReservoirBuilder.h" + +#ifdef USE_HDF5 +#include "H5Cpp.h" +#endif + +#include "cafPdmObjectScriptingCapability.h" + +#include +#include + +CAF_PDM_SOURCE_INIT( RimEmCase, "RimEmCase" ); +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEmCase::RimEmCase() +{ + CAF_PDM_InitScriptableObject( "RimEmCase", ":/EclipseInput48x48.png" ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEmCase::~RimEmCase() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimEmCase::openEclipseGridFile() +{ + if ( eclipseCaseData() ) + { + // Early exit if reservoir data is created + return true; + } + + setReservoirData( new RigEclipseCaseData( this ) ); + + auto emDataFromFile = readDataFromFile(); + + auto emData = emDataFromFile; + + // Flip X and Y axis + emData.cellSizes[0] = emDataFromFile.cellSizes[1]; + emData.cellSizes[1] = emDataFromFile.cellSizes[0]; + + emData.ijkNumCells[0] = emDataFromFile.ijkNumCells[1]; + emData.ijkNumCells[1] = emDataFromFile.ijkNumCells[0]; + + emData.originNED[0] = emDataFromFile.originNED[1]; + emData.originNED[1] = emDataFromFile.originNED[0]; + + { + RigReservoirBuilder builder; + + builder.setWorldCoordinates( cvf::Vec3d( emData.originNED[0], emData.originNED[1], emData.originNED[2] ), + cvf::Vec3d( emData.originNED[0] + emData.cellSizes[0] * emData.ijkNumCells[0], + emData.originNED[1] + emData.cellSizes[1] * emData.ijkNumCells[1], + -( emData.originNED[2] + emData.cellSizes[2] * emData.ijkNumCells[2] ) ) ); + + builder.setIJKCount( cvf::Vec3st( emData.ijkNumCells[0], emData.ijkNumCells[1], emData.ijkNumCells[2] ) ); + builder.createGridsAndCells( eclipseCaseData() ); + } + + results( RiaDefines::PorosityModelType::MATRIX_MODEL )->createPlaceholderResultEntries(); + + if ( RiaPreferences::current()->autocomputeDepthRelatedProperties ) + { + results( RiaDefines::PorosityModelType::MATRIX_MODEL )->computeDepthRelatedResults(); + results( RiaDefines::PorosityModelType::FRACTURE_MODEL )->computeDepthRelatedResults(); + } + + results( RiaDefines::PorosityModelType::MATRIX_MODEL )->computeCellVolumes(); + + { + // Compute resistivity as the inverted value for sigmaN and sigmaT + + std::map> additionalData; + for ( auto [resultName, resultData] : emData.resultData ) + { + auto fullResultName = QString::fromStdString( resultName ); + auto resultWords = fullResultName.split( "::" ); + auto lastResultName = resultWords.last(); + resultWords.removeLast(); + auto resultNameSpace = resultWords.join( "::" ); + + std::map invertedResultNameMap = { { "Sigma", "Resistivity" }, + { "SigmaN", "ResistivityN" }, + { "SigmaT", "ResistivityT" } }; + + for ( auto [originalName, invertedName] : invertedResultNameMap ) + { + if ( lastResultName.compare( originalName, Qt::CaseInsensitive ) == 0 ) + { + std::vector inverted; + inverted.resize( resultData.size() ); + std::transform( resultData.begin(), resultData.end(), inverted.begin(), []( float val ) { return 1.0f / val; } ); + additionalData[( resultNameSpace + "::" + invertedName ).toStdString()] = inverted; + } + } + } + + for ( const auto& obj : additionalData ) + { + emData.resultData[obj.first] = obj.second; + } + } + + for ( auto [resultName, data] : emData.resultData ) + { + QString riResultName = + eclipseCaseData()->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->makeResultNameUnique( QString::fromStdString( resultName ) ); + + RigEclipseResultAddress resAddr( RiaDefines::ResultCatType::STATIC_NATIVE, RiaDefines::ResultDataType::FLOAT, riResultName ); + eclipseCaseData()->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->createResultEntry( resAddr, false ); + + auto newPropertyData = + eclipseCaseData()->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->modifiableCellScalarResultTimesteps( resAddr ); + + std::vector reorganizedData; + + // Switch cell size ordering from IJK to KJI to make the data layout fit internal ResInsight result ordering + auto kjiNumCells = emData.ijkNumCells; + kjiNumCells[0] = emData.ijkNumCells[2]; + kjiNumCells[2] = emData.ijkNumCells[0]; + + for ( int k = 0; k < kjiNumCells[0]; k++ ) + { + for ( int i = 0; i < kjiNumCells[2]; i++ ) + { + for ( int j = 0; j < kjiNumCells[1]; j++ ) + { + reorganizedData.push_back( data[k + j * kjiNumCells[0] + i * kjiNumCells[0] * kjiNumCells[1]] ); + } + } + } + + newPropertyData->push_back( reorganizedData ); + } + + computeCachedData(); + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEmCase::reloadEclipseGridFile() +{ + setReservoirData( nullptr ); + openReserviorCase(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimEmCase::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) +{ + uiOrdering.add( &m_caseUserDescription ); + uiOrdering.add( &m_displayNameOption ); + uiOrdering.add( &m_caseId ); + uiOrdering.add( &m_caseFileName ); + + auto group = uiOrdering.addNewGroup( "Case Options" ); + group->add( &m_activeFormationNames ); + group->add( &m_flipXAxis ); + group->add( &m_flipYAxis ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEmData RimEmCase::readDataFromFile() +{ +#ifndef USE_HDF5 + return {}; +#else + + QString fileName = gridFileName(); + + std::array originNED; + std::array cellSizes; + std::array ijkNumCells; + std::map> resultData; + + try + { + H5::Exception::dontPrint(); // Turn off auto-printing of failures to handle the errors appropriately + + H5::H5File mainFile( fileName.toStdString().c_str(), H5F_ACC_RDONLY ); + + { + auto attr = mainFile.openAttribute( "description::OriginNED" ); + H5::DataType type = attr.getDataType(); + attr.read( type, originNED.data() ); + } + + { + H5::Group group = mainFile.openGroup( "Mesh" ); + + { + auto attr = group.openAttribute( "cell_sizes" ); + H5::DataType type = attr.getDataType(); + attr.read( type, cellSizes.data() ); + } + { + auto attr = group.openAttribute( "num_cells" ); + H5::DataType type = attr.getDataType(); + attr.read( type, ijkNumCells.data() ); + } + } + + H5::Group group = mainFile.openGroup( "Data" ); + auto numObj = group.getNumObjs(); + for ( size_t i = 0; i < numObj; i++ ) + { + auto resultName = group.getObjnameByIdx( i ); + + std::vector resultValues; + H5::DataSet dataset = H5::DataSet( group.openDataSet( resultName ) ); + + hsize_t dims[3]; + H5::DataSpace dataspace = dataset.getSpace(); + dataspace.getSimpleExtentDims( dims, nullptr ); + + resultValues.resize( dims[0] * dims[1] * dims[2] ); + dataset.read( resultValues.data(), H5::PredType::NATIVE_FLOAT ); + + resultData[resultName] = resultValues; + } + } + catch ( ... ) + { + } + + return { originNED, cellSizes, ijkNumCells, resultData }; +#endif +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimEmCase::locationOnDisc() const +{ + if ( gridFileName().isEmpty() ) return QString(); + + QFileInfo fi( gridFileName() ); + return fi.absolutePath(); +} diff --git a/ApplicationLibCode/ProjectDataModel/RimEmCase.h b/ApplicationLibCode/ProjectDataModel/RimEmCase.h new file mode 100644 index 0000000000..408286e7cf --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/RimEmCase.h @@ -0,0 +1,58 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Ceetron Solutions AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RimEclipseCase.h" + +#include "cafPdmChildField.h" +#include "cafPdmField.h" +#include "cafPdmObject.h" +#include + +struct RimEmData +{ + std::array originNED; + std::array cellSizes; + std::array ijkNumCells; + std::map> resultData; +}; + +//================================================================================================== +// +// +//================================================================================================== +class RimEmCase : public RimEclipseCase +{ + CAF_PDM_HEADER_INIT; + +public: + RimEmCase(); + ~RimEmCase() override; + + bool openEclipseGridFile() override; + void reloadEclipseGridFile() override; + + QString locationOnDisc() const override; + +protected: + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; + +private: + RimEmData readDataFromFile(); +}; diff --git a/ApplicationLibCode/ProjectDataModel/RimEnsembleFractureStatisticsPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimEnsembleFractureStatisticsPlotCollection.cpp index 92ffe61dda..5b60340048 100644 --- a/ApplicationLibCode/ProjectDataModel/RimEnsembleFractureStatisticsPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimEnsembleFractureStatisticsPlotCollection.cpp @@ -33,7 +33,6 @@ RimEnsembleFractureStatisticsPlotCollection::RimEnsembleFractureStatisticsPlotCo CAF_PDM_InitObject( "Ensemble Fracture Statistics Plots", ":/WellLogPlots16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_ensembleFractureStatisticsPlots, "EnsembleFractureStatisticsPlots", "" ); - m_ensembleFractureStatisticsPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimFormationNamesCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimFormationNamesCollection.cpp index 65ca0ade2f..3925ea453c 100644 --- a/ApplicationLibCode/ProjectDataModel/RimFormationNamesCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimFormationNamesCollection.cpp @@ -32,7 +32,6 @@ RimFormationNamesCollection::RimFormationNamesCollection() CAF_PDM_InitObject( "Formations", ":/FormationCollection16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_formationNamesList, "FormationNamesList", "Formations" ); - m_formationNamesList.uiCapability()->setUiTreeHidden( true ); setDeletable( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/RimGridCalculation.cpp b/ApplicationLibCode/ProjectDataModel/RimGridCalculation.cpp index 6b93ceccf8..7160b3d9ed 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridCalculation.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridCalculation.cpp @@ -33,19 +33,27 @@ #include "RigResultAccessorFactory.h" #include "RigStatisticsMath.h" +#include "RimCaseCollection.h" #include "RimEclipseCase.h" +#include "RimEclipseCaseCollection.h" #include "RimEclipseCaseTools.h" #include "RimEclipseCellColors.h" +#include "RimEclipseResultAddress.h" #include "RimEclipseStatisticsCase.h" #include "RimEclipseView.h" #include "RimGridCalculationCollection.h" #include "RimGridCalculationVariable.h" +#include "RimIdenticalGridCaseGroup.h" +#include "RimOilField.h" #include "RimProject.h" #include "RimReloadCaseTools.h" +#include "RimResultSelectionUi.h" #include "RimTools.h" #include "expressionparser/ExpressionParser.h" +#include "cafPdmUiPropertyViewDialog.h" +#include "cafPdmUiPushButtonEditor.h" #include "cafPdmUiTreeSelectionEditor.h" #include @@ -63,6 +71,14 @@ void caf::AppEnum::setUp() addItem( RimGridCalculation::DefaultValueType::USER_DEFINED, "USER_DEFINED", "User Defined Custom Value" ); setDefault( RimGridCalculation::DefaultValueType::POSITIVE_INFINITY ); } +template <> +void caf::AppEnum::setUp() +{ + addItem( RimGridCalculation::AdditionalCasesType::NONE, "NONE", "None" ); + addItem( RimGridCalculation::AdditionalCasesType::GRID_CASE_GROUP, "GRID_CASE_GROUP", "Case Group" ); + addItem( RimGridCalculation::AdditionalCasesType::ALL_CASES, "NONE", "All Cases" ); + setDefault( RimGridCalculation::AdditionalCasesType::NONE ); +} }; // namespace caf //-------------------------------------------------------------------------------------------------- @@ -75,8 +91,23 @@ RimGridCalculation::RimGridCalculation() CAF_PDM_InitFieldNoDefault( &m_defaultValueType, "DefaultValueType", "Non-visible Cell Value" ); CAF_PDM_InitField( &m_defaultValue, "DefaultValue", 0.0, "Custom Value" ); CAF_PDM_InitFieldNoDefault( &m_destinationCase, "DestinationCase", "Destination Case" ); - CAF_PDM_InitField( &m_applyToAllCases, "AllDestinationCase", false, "Apply to All Cases" ); - CAF_PDM_InitField( &m_defaultPropertyVariableIndex, "DefaultPropertyVariableName", 0, "Property Variable Name" ); + + CAF_PDM_InitField( &m_applyToAllCases_OBSOLETE, "AllDestinationCase", false, "Apply to All Cases" ); + m_applyToAllCases_OBSOLETE.xmlCapability()->setIOWritable( false ); + + CAF_PDM_InitFieldNoDefault( &m_additionalCasesType, "AdditionalCasesType", "Apply To Additional Cases" ); + CAF_PDM_InitFieldNoDefault( &m_additionalCaseGroup, "AdditionalCaseGroup", "Case Group" ); + + CAF_PDM_InitFieldNoDefault( &m_nonVisibleResultAddress, "NonVisibleResultAddress", "" ); + m_nonVisibleResultAddress = new RimEclipseResultAddress; + + CAF_PDM_InitField( &m_editNonVisibleResultAddress, "EditNonVisibleResultAddress", false, "Edit" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_editNonVisibleResultAddress ); + + CAF_PDM_InitFieldNoDefault( &m_nonVisibleResultText, "NonVisibleResultText", "" ); + m_nonVisibleResultText.registerGetMethod( this, &RimGridCalculation::nonVisibleResultAddressText ); + m_nonVisibleResultText.uiCapability()->setUiReadOnly( true ); + m_nonVisibleResultText.xmlCapability()->disableIO(); CAF_PDM_InitFieldNoDefault( &m_selectedTimeSteps, "SelectedTimeSteps", "Time Step Selection" ); m_selectedTimeSteps.uiCapability()->setUiEditorTypeName( caf::PdmUiTreeSelectionEditor::uiEditorTypeName() ); @@ -87,7 +118,7 @@ RimGridCalculation::RimGridCalculation() //-------------------------------------------------------------------------------------------------- bool RimGridCalculation::preCalculate() const { - if ( RiaGuiApplication::isRunning() && m_applyToAllCases() ) + if ( RiaGuiApplication::isRunning() && m_additionalCasesType() != RimGridCalculation::AdditionalCasesType::NONE ) { const QString cacheKey = "GridCalculatorMessage"; @@ -156,6 +187,29 @@ bool RimGridCalculation::calculate() } } + if ( m_defaultValueType() == DefaultValueType::FROM_PROPERTY ) + { + bool isDataSourceAvailable = false; + + if ( m_nonVisibleResultAddress->eclipseCase() ) + { + auto data = m_nonVisibleResultAddress->eclipseCase()->results( RiaDefines::PorosityModelType::MATRIX_MODEL ); + if ( data && data->hasResultEntry( + RigEclipseResultAddress( m_nonVisibleResultAddress->resultType(), m_nonVisibleResultAddress->resultName() ) ) ) + { + isDataSourceAvailable = true; + } + } + + if ( !isDataSourceAvailable ) + { + QString msg = "No data available for result defined in 'Non-visible Cell Value'"; + + RiaLogging::errorInMessageBox( nullptr, "Grid Property Calculator", msg ); + return false; + } + } + cvf::UByteArray* inputValueVisibilityFilter = nullptr; if ( m_cellFilterView() ) { @@ -184,17 +238,19 @@ bool RimGridCalculation::calculate() //-------------------------------------------------------------------------------------------------- std::vector RimGridCalculation::outputEclipseCases() const { - if ( m_applyToAllCases ) + if ( m_additionalCasesType() == RimGridCalculation::AdditionalCasesType::ALL_CASES ) { // Find all Eclipse cases suitable for grid calculations. This includes all single grid cases and source cases in a grid case group. // Exclude the statistics cases, as it is not possible to use them in a grid calculations. - // - // Note that data read from file can be released from memory when statistics for a time step is calculated. See - // RimEclipseStatisticsCaseEvaluator::evaluateForResults() - return RimEclipseCaseTools::allEclipseGridCases(); } + if ( m_additionalCasesType() == RimGridCalculation::AdditionalCasesType::GRID_CASE_GROUP ) + { + if ( m_additionalCaseGroup() && m_additionalCaseGroup()->caseCollection() ) + return m_additionalCaseGroup()->caseCollection()->reservoirs.childrenByType(); + } + return { m_destinationCase }; } @@ -226,6 +282,20 @@ RimGridCalculation::DefaultValueConfig RimGridCalculation::defaultValueConfigura return std::make_pair( m_defaultValueType(), HUGE_VAL ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimGridCalculation::nonVisibleResultAddressText() const +{ + QString txt; + + if ( m_nonVisibleResultAddress->eclipseCase() ) txt += m_nonVisibleResultAddress->eclipseCase()->caseUserDescription() + " : "; + + txt += m_nonVisibleResultAddress->resultName(); + + return txt; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -235,12 +305,9 @@ void RimGridCalculation::defineUiOrdering( QString uiConfigName, caf::PdmUiOrder uiOrdering.add( &m_destinationCase ); - uiOrdering.add( &m_applyToAllCases ); - if ( !allSourceCasesAreEqualToDestinationCase() ) - { - m_applyToAllCases = false; - } - m_applyToAllCases.uiCapability()->setUiReadOnly( !allSourceCasesAreEqualToDestinationCase() ); + uiOrdering.add( &m_additionalCasesType ); + uiOrdering.add( &m_additionalCaseGroup ); + m_additionalCaseGroup.uiCapability()->setUiHidden( m_additionalCasesType() != RimGridCalculation::AdditionalCasesType::GRID_CASE_GROUP ); caf::PdmUiGroup* filterGroup = uiOrdering.addNewGroup( "Cell Filter" ); filterGroup->setCollapsedByDefault(); @@ -251,7 +318,10 @@ void RimGridCalculation::defineUiOrdering( QString uiConfigName, caf::PdmUiOrder filterGroup->add( &m_defaultValueType ); if ( m_defaultValueType() == RimGridCalculation::DefaultValueType::FROM_PROPERTY ) - filterGroup->add( &m_defaultPropertyVariableIndex ); + { + filterGroup->add( &m_nonVisibleResultText ); + filterGroup->add( &m_editNonVisibleResultAddress, { .newRow = false } ); + } else if ( m_defaultValueType() == RimGridCalculation::DefaultValueType::USER_DEFINED ) filterGroup->add( &m_defaultValue ); } @@ -278,7 +348,16 @@ QList RimGridCalculation::calculateValueOptions( const c RimProject::current()->allViews( views ); RimEclipseCase* firstEclipseCase = nullptr; - if ( !inputCases().empty() ) firstEclipseCase = inputCases().front(); + if ( !inputCases().empty() ) + { + firstEclipseCase = inputCases().front(); + } + else + { + // If no input cases are defined, use the destination case to determine the grid size. This will enable use of expressions + // with no input cases like "calculation := 1.0" + firstEclipseCase = m_destinationCase(); + } if ( firstEclipseCase ) { @@ -311,16 +390,6 @@ QList RimGridCalculation::calculateValueOptions( const c options.push_front( caf::PdmOptionItemInfo( "None", nullptr ) ); } - else if ( fieldNeedingOptions == &m_defaultPropertyVariableIndex ) - { - for ( int i = 0; i < static_cast( m_variables.size() ); i++ ) - { - auto v = dynamic_cast( m_variables[i] ); - - QString optionText = v->name(); - options.push_back( caf::PdmOptionItemInfo( optionText, i ) ); - } - } else if ( &m_selectedTimeSteps == fieldNeedingOptions ) { RimEclipseCase* firstEclipseCase = nullptr; @@ -337,6 +406,20 @@ QList RimGridCalculation::calculateValueOptions( const c } } } + else if ( &m_additionalCaseGroup == fieldNeedingOptions ) + { + options.push_back( caf::PdmOptionItemInfo( "None", nullptr ) ); + + RimProject* proj = RimProject::current(); + if ( proj->activeOilField() && proj->activeOilField()->analysisModels() ) + { + auto analysisModels = proj->activeOilField()->analysisModels(); + for ( RimIdenticalGridCaseGroup* cg : analysisModels->caseGroups() ) + { + options.push_back( caf::PdmOptionItemInfo( cg->name(), cg, false, cg->uiIconProvider() ) ); + } + } + } return options; } @@ -356,6 +439,51 @@ void RimGridCalculation::initAfterRead() if ( m_destinationCase == nullptr ) m_destinationCase = gridVar->eclipseCase(); } } + + if ( m_applyToAllCases_OBSOLETE ) m_additionalCasesType = RimGridCalculation::AdditionalCasesType::ALL_CASES; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimGridCalculation::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + RimUserDefinedCalculation::fieldChangedByUi( changedField, oldValue, newValue ); + + if ( changedField == &m_editNonVisibleResultAddress ) + { + auto eclipseCase = m_nonVisibleResultAddress->eclipseCase(); + if ( !eclipseCase ) eclipseCase = m_destinationCase; + + RimResultSelectionUi selectionUi; + selectionUi.setEclipseResultAddress( eclipseCase, m_nonVisibleResultAddress->resultType(), m_nonVisibleResultAddress->resultName() ); + + caf::PdmUiPropertyViewDialog propertyDialog( nullptr, &selectionUi, "Select Result", "" ); + if ( propertyDialog.exec() == QDialog::Accepted ) + { + m_nonVisibleResultAddress->setEclipseCase( selectionUi.eclipseCase() ); + m_nonVisibleResultAddress->setResultType( selectionUi.resultType() ); + m_nonVisibleResultAddress->setResultName( selectionUi.resultVariable() ); + } + + m_editNonVisibleResultAddress = false; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimGridCalculation::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + RimUserDefinedCalculation::defineEditorAttribute( field, uiConfigName, attribute ); + + if ( field == &m_editNonVisibleResultAddress ) + { + if ( auto attrib = dynamic_cast( attribute ) ) + { + attrib->m_buttonText = "Edit"; + } + } } //-------------------------------------------------------------------------------------------------- @@ -414,16 +542,12 @@ RigEclipseResultAddress RimGridCalculation::outputAddress() const std::vector RimGridCalculation::getDataForVariable( RimGridCalculationVariable* variable, size_t tsId, RiaDefines::PorosityModelType porosityModel, - RimEclipseCase* destinationCase, - bool useDataFromDestinationCase ) const + RimEclipseCase* sourceCase, + RimEclipseCase* destinationCase ) const { - // The data can be taken from the destination case or from the calculation variable. - auto eclipseCase = useDataFromDestinationCase ? destinationCase : variable->eclipseCase(); - - if ( !eclipseCase ) return {}; - - int timeStep = variable->timeStep(); + if ( !sourceCase || !destinationCase ) return {}; + int timeStep = variable->timeStep(); auto resultCategoryType = variable->resultCategoryType(); // General case is to use the data from the given time step @@ -440,20 +564,44 @@ std::vector RimGridCalculation::getDataForVariable( RimGridCalculationVa timeStepToUse = timeStep; } - RigEclipseResultAddress resAddr( resultCategoryType, variable->resultVariable() ); + return getDataForResult( variable->resultVariable(), resultCategoryType, timeStepToUse, porosityModel, sourceCase, destinationCase ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimGridCalculation::getDataForResult( const QString& resultName, + const RiaDefines::ResultCatType resultCategoryType, + size_t tsId, + RiaDefines::PorosityModelType porosityModel, + RimEclipseCase* sourceCase, + RimEclipseCase* destinationCase ) const +{ + if ( !sourceCase || !destinationCase ) return {}; - auto eclipseCaseData = eclipseCase->eclipseCaseData(); + size_t timeStepToUse = tsId; + if ( resultCategoryType == RiaDefines::ResultCatType::STATIC_NATIVE ) + { + // Use the first time step for static data for all time steps + timeStepToUse = 0; + } + + RigEclipseResultAddress resAddr( resultCategoryType, resultName ); + + auto eclipseCaseData = sourceCase->eclipseCaseData(); auto rigCaseCellResultsData = eclipseCaseData->results( porosityModel ); - if ( !rigCaseCellResultsData->ensureKnownResultLoaded( resAddr ) ) return {}; + if ( !rigCaseCellResultsData->findOrLoadKnownScalarResultForTimeStep( resAddr, timeStepToUse ) ) return {}; - // Active cell info must always be retrieved from the destination case, as the returned vector must be of the same size as number of - // active cells in the destination case. + // Active cell info must always be retrieved from the destination case, as the returned vector must be of the same size as + // number of active cells in the destination case. Active cells can be different between source and destination case. auto activeCellInfoDestination = destinationCase->eclipseCaseData()->activeCellInfo( porosityModel ); auto activeReservoirCells = activeCellInfoDestination->activeReservoirCellIndices(); std::vector values( activeCellInfoDestination->activeReservoirCellIndices().size() ); - auto resultAccessor = RigResultAccessorFactory::createFromResultAddress( eclipseCaseData, 0, porosityModel, timeStepToUse, resAddr ); + size_t gridIndex = 0; + auto resultAccessor = + RigResultAccessorFactory::createFromResultAddress( eclipseCaseData, gridIndex, porosityModel, timeStepToUse, resAddr ); #pragma omp parallel for for ( int i = 0; i < static_cast( activeReservoirCells.size() ); i++ ) @@ -461,6 +609,14 @@ std::vector RimGridCalculation::getDataForVariable( RimGridCalculationVa values[i] = resultAccessor->cellScalarGlobIdx( activeReservoirCells[i] ); } + if ( m_releaseMemoryAfterDataIsExtracted ) + { + auto categoriesToExclude = { RiaDefines::ResultCatType::GENERATED }; + + sourceCase->results( RiaDefines::PorosityModelType::MATRIX_MODEL )->freeAllocatedResultsData( categoriesToExclude, timeStepToUse ); + sourceCase->results( RiaDefines::PorosityModelType::FRACTURE_MODEL )->freeAllocatedResultsData( categoriesToExclude, timeStepToUse ); + } + return values; } @@ -517,6 +673,7 @@ void RimGridCalculation::replaceFilteredValuesWithDefaultValue( double //-------------------------------------------------------------------------------------------------- void RimGridCalculation::filterResults( RimGridView* cellFilterView, const std::vector>& values, + size_t timeStep, RimGridCalculation::DefaultValueType defaultValueType, double defaultValue, std::vector& resultValues, @@ -528,12 +685,22 @@ void RimGridCalculation::filterResults( RimGridView* if ( defaultValueType == RimGridCalculation::DefaultValueType::FROM_PROPERTY ) { - if ( m_defaultPropertyVariableIndex < static_cast( values.size() ) ) - replaceFilteredValuesWithVector( values[m_defaultPropertyVariableIndex], visibility, resultValues, porosityModel, outputEclipseCase ); + auto nonVisibleValues = getDataForResult( m_nonVisibleResultAddress->resultName(), + m_nonVisibleResultAddress->resultType(), + timeStep, + porosityModel, + m_nonVisibleResultAddress->eclipseCase(), + outputEclipseCase ); + + if ( !nonVisibleValues.empty() ) + { + replaceFilteredValuesWithVector( nonVisibleValues, visibility, resultValues, porosityModel, outputEclipseCase ); + } else { - QString errorMessage = "Invalid input data for default result property, no data assigned to non-visible cells."; - RiaLogging::errorInMessageBox( nullptr, "Grid Property Calculator", errorMessage ); + QString errorMessage = + "Grid Property Calculator: Invalid input data for default result property, no data assigned to non-visible cells."; + RiaLogging::error( errorMessage ); } } else @@ -618,6 +785,9 @@ bool RimGridCalculation::calculateForCases( const std::vector& m_expression().contains( "min" ) || m_expression().contains( "max" ) || m_expression().contains( "count" ); + // If multiple cases are present, release memory after data is extracted to avoid memory issues. + m_releaseMemoryAfterDataIsExtracted = isMultipleCasesPresent; + if ( isMultipleCasesPresent ) { QString txt = "Starting calculation '" + description() + "' for " + QString::number( calculationCases.size() ) + " cases."; @@ -702,14 +872,15 @@ bool RimGridCalculation::calculateForCases( const std::vector& RimGridCalculationVariable* v = dynamic_cast( m_variables[i] ); CAF_ASSERT( v != nullptr ); - bool useDataFromDestinationCase = ( v->eclipseCase() == m_destinationCase ); + bool useDataFromSourceCase = ( v->eclipseCase() == m_destinationCase ); + auto sourceCase = useDataFromSourceCase ? calculationCase : v->eclipseCase(); - auto dataForVariable = getDataForVariable( v, tsId, porosityModel, calculationCase, useDataFromDestinationCase ); + auto dataForVariable = getDataForVariable( v, tsId, porosityModel, sourceCase, calculationCase ); if ( dataForVariable.empty() ) { RiaLogging::error( QString( " No data found for variable '%1'." ).arg( v->name() ) ); } - else if ( inputValueVisibilityFilter ) + else if ( inputValueVisibilityFilter && hasAggregationExpression ) { const double defaultValue = 0.0; replaceFilteredValuesWithDefaultValue( defaultValue, inputValueVisibilityFilter, dataForVariable, porosityModel, calculationCase ); @@ -727,7 +898,15 @@ bool RimGridCalculation::calculateForCases( const std::vector& } std::vector resultValues; - resultValues.resize( dataForAllVariables[0].size() ); + if ( m_destinationCase && m_destinationCase->eclipseCaseData() ) + { + // Find number of active cells in the destination case. + auto activeCellInfoDestination = m_destinationCase->eclipseCaseData()->activeCellInfo( porosityModel ); + if ( activeCellInfoDestination ) + { + resultValues.resize( activeCellInfoDestination->reservoirActiveCellCount() ); + } + } parser.assignVector( leftHandSideVariableName, resultValues ); QString errorText; @@ -753,6 +932,7 @@ bool RimGridCalculation::calculateForCases( const std::vector& { filterResults( m_cellFilterView(), dataForAllVariables, + tsId, m_defaultValueType(), m_defaultValue(), resultValues, @@ -829,9 +1009,9 @@ void RimGridCalculation::findAndEvaluateDependentCalculations( const std::vector { if ( dependentCalc == this ) continue; - // Propagate the settings for this calculation to the dependent calculation. This will allow changes on top level calculation to be - // propagated to dependent calculations automatically. Do not trigger findAndEvaluateDependentCalculations() recursively, as all - // dependent calculations are traversed in this function. + // Propagate the settings for this calculation to the dependent calculation. This will allow changes on top level + // calculation to be propagated to dependent calculations automatically. Do not trigger + // findAndEvaluateDependentCalculations() recursively, as all dependent calculations are traversed in this function. bool evaluateDependentCalculations = false; dependentCalc->calculateForCases( calculationCases, inputValueVisibilityFilter, timeSteps, evaluateDependentCalculations ); diff --git a/ApplicationLibCode/ProjectDataModel/RimGridCalculation.h b/ApplicationLibCode/ProjectDataModel/RimGridCalculation.h index 9a922da6c1..45f1e75309 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridCalculation.h +++ b/ApplicationLibCode/ProjectDataModel/RimGridCalculation.h @@ -22,7 +22,9 @@ #include "RimGridCalculationVariable.h" #include "RimUserDefinedCalculation.h" +#include "cafPdmChildField.h" #include "cafSignal.h" + #include "cvfArray.h" #include @@ -30,6 +32,8 @@ class RimEclipseCase; class RimGridView; class RigEclipseResultAddress; +class RimEclipseResultAddress; +class RimIdenticalGridCaseGroup; //================================================================================================== /// @@ -47,6 +51,13 @@ class RimGridCalculation : public RimUserDefinedCalculation USER_DEFINED }; + enum class AdditionalCasesType + { + NONE, + GRID_CASE_GROUP, + ALL_CASES + }; + RimGridCalculation(); bool preCalculate() const override; @@ -80,11 +91,19 @@ class RimGridCalculation : public RimUserDefinedCalculation std::vector getDataForVariable( RimGridCalculationVariable* variable, size_t tsId, RiaDefines::PorosityModelType porosityModel, - RimEclipseCase* destinationCase, - bool useDataFromDestinationCase ) const; + RimEclipseCase* sourceCase, + RimEclipseCase* destinationCase ) const; + + std::vector getDataForResult( const QString& resultName, + const RiaDefines::ResultCatType resultCategoryType, + size_t tsId, + RiaDefines::PorosityModelType porosityModel, + RimEclipseCase* sourceCase, + RimEclipseCase* destinationCase ) const; void filterResults( RimGridView* cellFilterView, const std::vector>& values, + size_t timeStep, RimGridCalculation::DefaultValueType defaultValueType, double defaultValue, std::vector& resultValues, @@ -106,9 +125,13 @@ class RimGridCalculation : public RimUserDefinedCalculation using DefaultValueConfig = std::pair; DefaultValueConfig defaultValueConfiguration() const; + QString nonVisibleResultAddressText() const; + void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; QList calculateValueOptions( const caf::PdmFieldHandle* fieldNeedingOptions ) override; void initAfterRead() override; + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; private: void onVariableUpdated( const SignalEmitter* emitter ); @@ -121,9 +144,17 @@ class RimGridCalculation : public RimUserDefinedCalculation caf::PdmField> m_defaultValueType; caf::PdmField m_defaultValue; caf::PdmPtrField m_destinationCase; - caf::PdmField m_applyToAllCases; + + caf::PdmField> m_additionalCasesType; + caf::PdmPtrField m_additionalCaseGroup; caf::PdmField> m_selectedTimeSteps; - caf::PdmField m_defaultPropertyVariableIndex; + caf::PdmProxyValueField m_nonVisibleResultText; + caf::PdmChildField m_nonVisibleResultAddress; + caf::PdmField m_editNonVisibleResultAddress; + + caf::PdmField m_applyToAllCases_OBSOLETE; + + bool m_releaseMemoryAfterDataIsExtracted = false; }; diff --git a/ApplicationLibCode/ProjectDataModel/RimGridCalculationVariable.cpp b/ApplicationLibCode/ProjectDataModel/RimGridCalculationVariable.cpp index 14dcd9c3a7..21040520c6 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridCalculationVariable.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridCalculationVariable.cpp @@ -56,8 +56,7 @@ RimGridCalculationVariable::RimGridCalculationVariable() CAF_PDM_InitField( &m_timeStep, "TimeStep", allTimeStepsValue(), "Time Step" ); CAF_PDM_InitFieldNoDefault( &m_button, "PushButton", "" ); - m_button.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_button.xmlCapability()->disableIO(); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_button ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimGridCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimGridCollection.cpp index d988fa9262..6afed2a8bb 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridCollection.cpp @@ -156,8 +156,6 @@ RimGridInfoCollection::RimGridInfoCollection() m_isActive.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_gridInfos, "GridInfos", "Grid Infos" ); - - m_gridInfos.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlot.cpp b/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlot.cpp index 0e3da97f96..0325337b75 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlot.cpp @@ -62,7 +62,6 @@ RimGridStatisticsPlot::RimGridStatisticsPlot() CAF_PDM_InitFieldNoDefault( &m_property, "Property", "Property" ); m_property = new RimEclipseResultDefinition( caf::PdmUiItemInfo::TOP ); - m_property.uiCapability()->setUiTreeHidden( true ); m_property.uiCapability()->setUiTreeChildrenHidden( true ); m_property->setTernaryEnabled( false ); diff --git a/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlotCollection.cpp index f8a55ca2d4..bd69dce51b 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridStatisticsPlotCollection.cpp @@ -33,7 +33,6 @@ RimGridStatisticsPlotCollection::RimGridStatisticsPlotCollection() CAF_PDM_InitObject( "Grid Statistics Plots", ":/WellLogPlots16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_gridStatisticsPlots, "GridStatisticsPlots", "" ); - m_gridStatisticsPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimGridTimeHistoryCurve.cpp b/ApplicationLibCode/ProjectDataModel/RimGridTimeHistoryCurve.cpp index ad934e1a31..8377899de8 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridTimeHistoryCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridTimeHistoryCurve.cpp @@ -59,15 +59,12 @@ RimGridTimeHistoryCurve::RimGridTimeHistoryCurve() m_geometrySelectionText.uiCapability()->setUiReadOnly( true ); CAF_PDM_InitFieldNoDefault( &m_eclipseResultDefinition, "EclipseResultDefinition", "Eclipse Result Definition" ); - m_eclipseResultDefinition.uiCapability()->setUiTreeHidden( true ); m_eclipseResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_geoMechResultDefinition, "GeoMechResultDefinition", "GeoMech Result Definition" ); - m_geoMechResultDefinition.uiCapability()->setUiTreeHidden( true ); m_geoMechResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_geometrySelectionItem, "GeometrySelectionItem", "Geometry Selection" ); - m_geometrySelectionItem.uiCapability()->setUiTreeHidden( true ); m_geometrySelectionItem.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_plotAxis, "PlotAxis", caf::AppEnum( RiaDefines::PlotAxis::PLOT_AXIS_LEFT ), "Axis" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimGridView.cpp b/ApplicationLibCode/ProjectDataModel/RimGridView.cpp index 6ae573bdcc..d9074993b9 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridView.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimGridView.cpp @@ -41,6 +41,9 @@ #include "RimWellMeasurementInViewCollection.h" #include "RimWellPathCollection.h" +#include "Polygons/RimPolygonInView.h" +#include "Polygons/RimPolygonInViewCollection.h" + #include "Riu3DMainWindowTools.h" #include "Riu3dSelectionManager.h" #include "RiuMainWindow.h" @@ -66,25 +69,20 @@ RimGridView::RimGridView() : cellVisibilityChanged( this ) { CAF_PDM_InitFieldNoDefault( &m_overrideCellFilterCollection, "CellFiltersControlled", "Cell Filters (controlled)" ); - m_overrideCellFilterCollection.uiCapability()->setUiTreeHidden( true ); m_overrideCellFilterCollection.xmlCapability()->disableIO(); CAF_PDM_InitFieldNoDefault( &m_intersectionCollection, "CrossSections", "Intersections" ); - m_intersectionCollection.uiCapability()->setUiTreeHidden( true ); m_intersectionCollection = new RimIntersectionCollection(); CAF_PDM_InitFieldNoDefault( &m_intersectionResultDefCollection, "IntersectionResultDefColl", "Intersection Results" ); - m_intersectionResultDefCollection.uiCapability()->setUiTreeHidden( true ); m_intersectionResultDefCollection = new RimIntersectionResultsDefinitionCollection; CAF_PDM_InitFieldNoDefault( &m_surfaceResultDefCollection, "ReservoirSurfaceResultDefColl", "Surface Results" ); - m_surfaceResultDefCollection.uiCapability()->setUiTreeHidden( true ); m_surfaceResultDefCollection = new RimIntersectionResultsDefinitionCollection; m_surfaceResultDefCollection->uiCapability()->setUiName( "Surface Results" ); m_surfaceResultDefCollection->uiCapability()->setUiIcon( caf::IconProvider( ":/ReservoirSurface16x16.png" ) ); CAF_PDM_InitFieldNoDefault( &m_gridCollection, "GridCollection", "GridCollection" ); - m_gridCollection.uiCapability()->setUiTreeHidden( true ); m_gridCollection = new RimGridCollection(); m_previousGridModeMeshLinesWasFaults = false; @@ -92,28 +90,29 @@ RimGridView::RimGridView() CAF_PDM_InitFieldNoDefault( &m_overlayInfoConfig, "OverlayInfoConfig", "Info Box" ); m_overlayInfoConfig = new Rim3dOverlayInfoConfig(); m_overlayInfoConfig->setReservoirView( this ); - m_overlayInfoConfig.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wellMeasurementCollection, "WellMeasurements", "Well Measurements" ); m_wellMeasurementCollection = new RimWellMeasurementInViewCollection; - m_wellMeasurementCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_surfaceCollection, "SurfaceInViewCollection", "Surface Collection Field" ); - m_surfaceCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_seismicSectionCollection, "SeismicSectionCollection", "Seismic Collection Field" ); - m_seismicSectionCollection.uiCapability()->setUiTreeHidden( true ); m_seismicSectionCollection = new RimSeismicSectionCollection(); + CAF_PDM_InitFieldNoDefault( &m_polygonInViewCollection, "PolygonInViewCollection", "Polygon Collection Field" ); + m_polygonInViewCollection = new RimPolygonInViewCollection(); + CAF_PDM_InitFieldNoDefault( &m_cellFilterCollection, "RangeFilters", "Cell Filter Collection Field" ); m_cellFilterCollection = new RimCellFilterCollection(); - m_cellFilterCollection.uiCapability()->setUiTreeHidden( true ); m_surfaceVizModel = new cvf::ModelBasicList; m_surfaceVizModel->setName( "SurfaceModel" ); m_intersectionVizModel = new cvf::ModelBasicList; m_intersectionVizModel->setName( "CrossSectionModel" ); + + m_polygonVizModel = new cvf::ModelBasicList; + m_polygonVizModel->setName( "PolygonModel" ); } //-------------------------------------------------------------------------------------------------- @@ -171,6 +170,14 @@ RimSeismicSectionCollection* RimGridView::seismicSectionCollection() const return m_seismicSectionCollection(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonInViewCollection* RimGridView::polygonInViewCollection() const +{ + return m_polygonInViewCollection(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -390,6 +397,36 @@ void RimGridView::onCreatePartCollectionFromSelection( cvf::CollectionremoveAllParts(); + + std::vector polygonsInView; + if ( m_polygonInViewCollection ) + { + polygonsInView = m_polygonInViewCollection->visiblePolygonsInView(); + } + + if ( cellFilterCollection() && cellFilterCollection()->isActive() ) + { + auto cellFilterPolygonsInView = cellFilterCollection()->enabledCellFilterPolygons(); + polygonsInView.insert( polygonsInView.end(), cellFilterPolygonsInView.begin(), cellFilterPolygonsInView.end() ); + } + + for ( RimPolygonInView* polygonInView : polygonsInView ) + { + if ( polygonInView ) + { + polygonInView->appendPartsToModel( m_polygonVizModel.p(), scaleTransform, boundingBox ); + } + } + + nativeOrOverrideViewer()->addStaticModelOnce( m_polygonVizModel.p(), isUsingOverrideViewer() ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -465,23 +502,32 @@ void RimGridView::updateWellMeasurements() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimGridView::updateSurfacesInViewTreeItems() +void RimGridView::updateViewTreeItems( RiaDefines::ItemIn3dView itemType ) { - RimSurfaceCollection* surfColl = RimTools::surfaceCollection(); + auto bitmaskEnum = BitmaskEnum( itemType ); - if ( surfColl && surfColl->containsSurface() ) + if ( bitmaskEnum.AnyOf( RiaDefines::ItemIn3dView::SURFACE ) ) { - if ( !m_surfaceCollection() ) + RimSurfaceCollection* surfColl = RimTools::surfaceCollection(); + if ( surfColl && surfColl->containsSurface() ) { - m_surfaceCollection = new RimSurfaceInViewCollection(); - } + if ( !m_surfaceCollection() ) + { + m_surfaceCollection = new RimSurfaceInViewCollection(); + } - m_surfaceCollection->setSurfaceCollection( surfColl ); - m_surfaceCollection->updateFromSurfaceCollection(); + m_surfaceCollection->setSurfaceCollection( surfColl ); + m_surfaceCollection->updateFromSurfaceCollection(); + } + else + { + delete m_surfaceCollection; + } } - else + + if ( bitmaskEnum.AnyOf( RiaDefines::ItemIn3dView::POLYGON ) ) { - delete m_surfaceCollection; + m_polygonInViewCollection->updateFromPolygonCollection(); } updateConnectedEditors(); diff --git a/ApplicationLibCode/ProjectDataModel/RimGridView.h b/ApplicationLibCode/ProjectDataModel/RimGridView.h index f3115e2f34..e7132010c8 100644 --- a/ApplicationLibCode/ProjectDataModel/RimGridView.h +++ b/ApplicationLibCode/ProjectDataModel/RimGridView.h @@ -32,6 +32,7 @@ class RimCellFilterCollection; class RimWellMeasurementInViewCollection; class RimSurfaceInViewCollection; class RimSeismicSectionCollection; +class RimPolygonInViewCollection; class RimGridView : public Rim3dView { @@ -54,6 +55,7 @@ class RimGridView : public Rim3dView RimIntersectionResultsDefinitionCollection* separateSurfaceResultsCollection() const; RimWellMeasurementInViewCollection* measurementCollection() const; RimSeismicSectionCollection* seismicSectionCollection() const; + RimPolygonInViewCollection* polygonInViewCollection() const; virtual const RimPropertyFilterCollection* propertyFilterCollection() const = 0; @@ -68,7 +70,7 @@ class RimGridView : public Rim3dView bool isGridVisualizationMode() const override; void updateWellMeasurements(); - void updateSurfacesInViewTreeItems() override; + void updateViewTreeItems( RiaDefines::ItemIn3dView itemType ) override; protected: virtual void updateViewFollowingCellFilterUpdates(); @@ -78,6 +80,7 @@ class RimGridView : public Rim3dView RimGridCollection* gridCollection() const; void clearReservoirCellVisibilities(); void addRequiredUiTreeObjects( caf::PdmUiTreeOrdering& uiTreeOrdering ); + void appendPolygonPartsToModel( caf::DisplayCoordTransform* scaleTransform, const cvf::BoundingBox& boundingBox ); void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; void initAfterRead() override; @@ -90,6 +93,7 @@ class RimGridView : public Rim3dView protected: cvf::ref m_surfaceVizModel; cvf::ref m_intersectionVizModel; + cvf::ref m_polygonVizModel; // Fields caf::PdmChildField m_intersectionCollection; @@ -104,10 +108,12 @@ class RimGridView : public Rim3dView caf::PdmChildField m_cellFilterCollection; caf::PdmChildField m_overrideCellFilterCollection; caf::PdmChildField m_seismicSectionCollection; + caf::PdmChildField m_polygonInViewCollection; private: void onCreatePartCollectionFromSelection( cvf::Collection* parts ) override; +private: cvf::ref m_currentReservoirCellVisibility; bool m_previousGridModeMeshLinesWasFaults; }; diff --git a/ApplicationLibCode/ProjectDataModel/RimIdenticalGridCaseGroup.cpp b/ApplicationLibCode/ProjectDataModel/RimIdenticalGridCaseGroup.cpp index 6d95200da1..8b740585af 100644 --- a/ApplicationLibCode/ProjectDataModel/RimIdenticalGridCaseGroup.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimIdenticalGridCaseGroup.cpp @@ -63,10 +63,8 @@ RimIdenticalGridCaseGroup::RimIdenticalGridCaseGroup() groupId.capability()->setIOWriteable( false ); CAF_PDM_InitFieldNoDefault( &statisticsCaseCollection, "StatisticsCaseCollection", "statisticsCaseCollection ChildArrayField" ); - statisticsCaseCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &caseCollection, "CaseCollection", "Source Cases ChildArrayField" ); - caseCollection.uiCapability()->setUiTreeHidden( true ); caseCollection = new RimCaseCollection; caseCollection->uiCapability()->setUiName( "Source Cases" ); @@ -247,7 +245,7 @@ void RimIdenticalGridCaseGroup::loadMainCaseAndActiveCellInfo() if ( i == 0 ) { - rimReservoir->eclipseCaseData()->computeActiveCellBoundingBoxes(); + rimReservoir->computeActiveCellsBoundingBox(); } } } @@ -375,7 +373,7 @@ void RimIdenticalGridCaseGroup::updateMainGridAndActiveCellsForStatisticsCases() if ( i == 0 ) { - rimStaticsCase->eclipseCaseData()->computeActiveCellBoundingBoxes(); + rimStaticsCase->computeActiveCellsBoundingBox(); } } } @@ -431,8 +429,15 @@ RimEclipseStatisticsCase* RimIdenticalGridCaseGroup::createStatisticsCase( bool if ( selectDefaultResults ) newStatisticsCase->populateResultSelectionAfterLoadingGrid(); + auto reservoirs = caseCollection->reservoirs().childrenByType(); + if ( !reservoirs.empty() ) + { + auto caseDescription = reservoirs.front()->caseUserDescription(); + newStatisticsCase->setWellDataSourceCase( caseDescription ); + } + newStatisticsCase->openEclipseGridFile(); - newStatisticsCase->eclipseCaseData()->computeActiveCellBoundingBoxes(); + newStatisticsCase->computeActiveCellsBoundingBox(); newStatisticsCase->selectAllTimeSteps(); return newStatisticsCase; diff --git a/ApplicationLibCode/ProjectDataModel/RimMainPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimMainPlotCollection.cpp index fbae6cd76d..b93aaf4915 100644 --- a/ApplicationLibCode/ProjectDataModel/RimMainPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimMainPlotCollection.cpp @@ -84,52 +84,36 @@ RimMainPlotCollection::RimMainPlotCollection() m_show.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wellLogPlotCollection, "WellLogPlotCollection", "" ); - m_wellLogPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_rftPlotCollection, "RftPlotCollection", "" ); - m_rftPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_pltPlotCollection, "PltPlotCollection", "" ); - m_pltPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_summaryMultiPlotCollection, "SummaryMultiPlotCollection", "Multi Summary Plots" ); - m_summaryMultiPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_analysisPlotCollection, "AnalysisPlotCollection", "Analysis Plots" ); - m_analysisPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_correlationPlotCollection, "CorrelationPlotCollection", "Correlation Plots" ); - m_correlationPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_summaryCrossPlotCollection_OBSOLETE, "SummaryCrossPlotCollection", "Summary Cross Plots" ); - m_summaryCrossPlotCollection_OBSOLETE.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_summaryTableCollection, "SummaryTableCollection", "Summary Tables" ); - m_summaryTableCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_flowPlotCollection, "FlowPlotCollection", "Flow Diagnostics Plots" ); - m_flowPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_gridCrossPlotCollection, "Rim3dCrossPlotCollection", "3d Cross Plots" ); - m_gridCrossPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_saturationPressurePlotCollection, "RimSaturationPressurePlotCollection", "Saturation Pressure Plots" ); - m_saturationPressurePlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_multiPlotCollection, "RimMultiPlotCollection", "Multi Plots" ); - m_multiPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_stimPlanModelPlotCollection, "StimPlanModelPlotCollection", "" ); - m_stimPlanModelPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_vfpPlotCollection, "VfpPlotCollection", "" ); - m_vfpPlotCollection.uiCapability()->setUiTreeHidden( true ); #ifdef USE_QTCHARTS CAF_PDM_InitFieldNoDefault( &m_gridStatisticsPlotCollection, "GridStatisticsPlotCollection", "" ); - m_gridStatisticsPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_ensembleFractureStatisticsPlotCollection, "EnsembleFractureStatisticsPlotCollection", "" ); - m_ensembleFractureStatisticsPlotCollection.uiCapability()->setUiTreeHidden( true ); #endif m_wellLogPlotCollection = new RimWellLogPlotCollection(); @@ -152,7 +136,6 @@ RimMainPlotCollection::RimMainPlotCollection() #endif CAF_PDM_InitFieldNoDefault( &m_summaryPlotCollection_OBSOLETE, "SummaryPlotCollection", "Summary Plots" ); - m_summaryPlotCollection_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_summaryPlotCollection_OBSOLETE.xmlCapability()->setIOWritable( false ); m_summaryPlotCollection_OBSOLETE = new RimSummaryPlotCollection(); } diff --git a/ApplicationLibCode/ProjectDataModel/RimMudWeightWindowParameters.cpp b/ApplicationLibCode/ProjectDataModel/RimMudWeightWindowParameters.cpp index 6cdaae94ee..6d783a8255 100644 --- a/ApplicationLibCode/ProjectDataModel/RimMudWeightWindowParameters.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimMudWeightWindowParameters.cpp @@ -585,7 +585,7 @@ QList RimMudWeightWindowParameters::calculateValueOption { if ( geoMechCase->geoMechData() ) { - size_t kCount = geoMechCase->geoMechData()->femParts()->part( 0 )->getOrCreateStructGrid()->gridPointCountK() - 1; + size_t kCount = geoMechCase->geoMechData()->femParts()->part( 0 )->getOrCreateStructGrid()->cellCountK(); for ( size_t layerIdx = 0; layerIdx < kCount; ++layerIdx ) { options.push_back( caf::PdmOptionItemInfo( QString::number( layerIdx + 1 ), (int)layerIdx ) ); diff --git a/ApplicationLibCode/ProjectDataModel/RimMultiPlot.cpp b/ApplicationLibCode/ProjectDataModel/RimMultiPlot.cpp index 0012c8f1dd..2949f0c5f2 100644 --- a/ApplicationLibCode/ProjectDataModel/RimMultiPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimMultiPlot.cpp @@ -57,7 +57,6 @@ RimMultiPlot::RimMultiPlot() CAF_PDM_InitField( &m_plotWindowTitle, "PlotDescription", QString( "" ), "Name" ); CAF_PDM_InitFieldNoDefault( &m_plots, "Plots", "" ); - m_plots.uiCapability()->setUiTreeHidden( true ); auto reorderability = caf::PdmFieldReorderCapability::addToField( &m_plots ); reorderability->orderChanged.connect( this, &RimMultiPlot::onPlotsReordered ); diff --git a/ApplicationLibCode/ProjectDataModel/RimMultiPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimMultiPlotCollection.cpp index 08f121deac..646ac9752c 100644 --- a/ApplicationLibCode/ProjectDataModel/RimMultiPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimMultiPlotCollection.cpp @@ -32,7 +32,6 @@ RimMultiPlotCollection::RimMultiPlotCollection() CAF_PDM_InitObject( "Multi Plots", ":/MultiPlot16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_multiPlots, "MultiPlots", "Plots Reports" ); - m_multiPlots.uiCapability()->setUiTreeHidden( true ); caf::PdmFieldReorderCapability::addToField( &m_multiPlots ); } diff --git a/ApplicationLibCode/ProjectDataModel/RimObservedDataCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimObservedDataCollection.cpp index a102ea9b40..73dabb85e8 100644 --- a/ApplicationLibCode/ProjectDataModel/RimObservedDataCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimObservedDataCollection.cpp @@ -56,9 +56,6 @@ RimObservedDataCollection::RimObservedDataCollection() CAF_PDM_InitFieldNoDefault( &m_observedDataArray, "ObservedDataArray", "" ); CAF_PDM_InitFieldNoDefault( &m_observedFmuRftArray, "ObservedFmuRftDataArray", "" ); CAF_PDM_InitFieldNoDefault( &m_observedPressureDepthArray, "PressureDepthDataArray", "" ); - m_observedDataArray.uiCapability()->setUiTreeHidden( true ); - m_observedFmuRftArray.uiCapability()->setUiTreeHidden( true ); - m_observedPressureDepthArray.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimOilField.cpp b/ApplicationLibCode/ProjectDataModel/RimOilField.cpp index f0f421c609..ac36308e79 100644 --- a/ApplicationLibCode/ProjectDataModel/RimOilField.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimOilField.cpp @@ -35,6 +35,8 @@ #include "RimSurfaceCollection.h" #include "RimWellPathCollection.h" +#include "Polygons/RimPolygonCollection.h" + CAF_PDM_SOURCE_INIT( RimOilField, "ResInsightOilField" ); //-------------------------------------------------------------------------------------------------- /// @@ -55,6 +57,7 @@ RimOilField::RimOilField() CAF_PDM_InitFieldNoDefault( &annotationCollection, "AnnotationCollection", "Annotations" ); CAF_PDM_InitFieldNoDefault( &ensembleWellLogsCollection, "EnsembleWellLogsCollection", "Ensemble Well Logs" ); + CAF_PDM_InitFieldNoDefault( &polygonCollection, "PolygonCollection", "Polygons" ); CAF_PDM_InitFieldNoDefault( &m_fractureTemplateCollection_OBSOLETE, "FractureDefinitionCollection", "Defenition of Fractures" ); @@ -80,6 +83,7 @@ RimOilField::RimOilField() formationNamesCollection = new RimFormationNamesCollection(); annotationCollection = new RimAnnotationCollection(); ensembleWellLogsCollection = new RimEnsembleWellLogsCollection(); + polygonCollection = new RimPolygonCollection(); m_fractureTemplateCollection_OBSOLETE = new RimFractureTemplateCollection; m_fractureTemplateCollection_OBSOLETE.xmlCapability()->setIOWritable( false ); diff --git a/ApplicationLibCode/ProjectDataModel/RimOilField.h b/ApplicationLibCode/ProjectDataModel/RimOilField.h index a45ed80936..60b17c698b 100644 --- a/ApplicationLibCode/ProjectDataModel/RimOilField.h +++ b/ApplicationLibCode/ProjectDataModel/RimOilField.h @@ -41,6 +41,7 @@ class RimSeismicDataCollection; class RimSeismicViewCollection; class RimSurfaceCollection; class RimEnsembleWellLogsCollection; +class RimPolygonCollection; //================================================================================================== /// @@ -73,6 +74,7 @@ class RimOilField : public caf::PdmObject caf::PdmChildField seismicDataCollection; caf::PdmChildField seismicViewCollection; caf::PdmChildField ensembleWellLogsCollection; + caf::PdmChildField polygonCollection; protected: void initAfterRead() override; diff --git a/ApplicationLibCode/ProjectDataModel/RimPlotAxisProperties.cpp b/ApplicationLibCode/ProjectDataModel/RimPlotAxisProperties.cpp index f58c2ae03f..25060d3655 100644 --- a/ApplicationLibCode/ProjectDataModel/RimPlotAxisProperties.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimPlotAxisProperties.cpp @@ -101,7 +101,6 @@ RimPlotAxisProperties::RimPlotAxisProperties() CAF_PDM_InitFieldNoDefault( &m_valuesFontSize, "ValueDeltaFontSize", "Font Size" ); CAF_PDM_InitFieldNoDefault( &m_annotations, "Annotations", "" ); - m_annotations.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_majorTickmarkCount, "MajorTickmarkCount", "Major Tickmark Count" ); @@ -732,7 +731,7 @@ void RimPlotAxisProperties::defineObjectEditorAttribute( QString uiConfigName, c if ( treeItemAttribute ) { treeItemAttribute->tags.clear(); - auto tag = caf::PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = caf::PdmUiTreeViewItemAttribute::createTag(); tag->icon = caf::IconProvider( ":/chain.png" ); treeItemAttribute->tags.push_back( std::move( tag ) ); diff --git a/ApplicationLibCode/ProjectDataModel/RimPlotCurve.cpp b/ApplicationLibCode/ProjectDataModel/RimPlotCurve.cpp index ba905fb0df..52c4784268 100644 --- a/ApplicationLibCode/ProjectDataModel/RimPlotCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimPlotCurve.cpp @@ -127,7 +127,6 @@ RimPlotCurve::RimPlotCurve() CAF_PDM_InitFieldNoDefault( &m_curveAppearance, "PlotCurveAppearance", "PlotCurveAppearance" ); m_curveAppearance = new RimPlotCurveAppearance; - m_curveAppearance.uiCapability()->setUiTreeHidden( true ); m_curveAppearance.uiCapability()->setUiTreeChildrenHidden( true ); m_curveAppearance->appearanceChanged.connect( this, &RimPlotCurve::onCurveAppearanceChanged ); m_curveAppearance->fillColorChanged.connect( this, &RimPlotCurve::onFillColorChanged ); @@ -1163,7 +1162,7 @@ void RimPlotCurve::setParentPlotNoReplot( RiuPlotWidget* plotWidget ) } auto color = RiaColorTools::toQColor( m_curveAppearance->color() ); - m_plotCurve = m_parentPlot->createPlotCurve( this, "" ); + m_plotCurve = m_parentPlot->createPlotCurve( this, m_curveName ); m_plotCurve->updateErrorBarsAppearance( m_showErrorBars, color ); // PERFORMANCE NOTE @@ -1263,19 +1262,10 @@ void RimPlotCurve::defineObjectEditorAttribute( QString uiConfigName, caf::PdmUi if ( auto* treeItemAttribute = dynamic_cast( attribute ) ) { treeItemAttribute->tags.clear(); - auto tag = caf::PdmUiTreeViewItemAttribute::Tag::create(); - - // Blend with background for a nice look - auto backgroundColor = RiuGuiTheme::getColorByVariableName( "backgroundColor1" ); - auto color = RiaColorTools::toQColor( m_curveAppearance->color() ); - auto sourceWeight = 100; - double transparency = 0.3; - int backgroundWeight = std::max( 1, static_cast( sourceWeight * 10 * transparency ) ); - auto blendedColor = RiaColorTools::blendQColors( backgroundColor, color, backgroundWeight, sourceWeight ); - - tag->bgColor = blendedColor; - tag->fgColor = RiaColorTools::toQColor( m_curveAppearance->color() ); - tag->text = "---"; + + auto tag = caf::PdmUiTreeViewItemAttribute::createTag( RiaColorTools::toQColor( m_curveAppearance->color() ), + RiuGuiTheme::getColorByVariableName( "backgroundColor1" ), + "---" ); tag->clicked.connect( this, &RimPlotCurve::onColorTagClicked ); diff --git a/ApplicationLibCode/ProjectDataModel/RimPltPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimPltPlotCollection.cpp index 301677de3a..3b7a0deb49 100644 --- a/ApplicationLibCode/ProjectDataModel/RimPltPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimPltPlotCollection.cpp @@ -42,7 +42,6 @@ RimPltPlotCollection::RimPltPlotCollection() CAF_PDM_InitObject( "PLT Plots", ":/WellAllocPlots16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_pltPlots, "PltPlots", "" ); - m_pltPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.cpp b/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.cpp new file mode 100644 index 0000000000..8c04d6124c --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.cpp @@ -0,0 +1,56 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimPolylinePickerInterface.h" + +#include "RimPolylineTarget.h" + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RimPolylinePickerInterface::scalingFactorForTarget() const +{ + return 1.0; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair + RimPolylinePickerInterface::findActiveTargetsAroundInsertionPoint( const RimPolylineTarget* targetToInsertBefore ) +{ + auto targets = activeTargets(); + + RimPolylineTarget* before = nullptr; + RimPolylineTarget* after = nullptr; + + bool foundTarget = false; + for ( const auto& wt : targets ) + { + if ( wt == targetToInsertBefore ) + { + foundTarget = true; + } + + if ( !after && foundTarget ) after = wt; + + if ( !foundTarget ) before = wt; + } + + return { before, after }; +} diff --git a/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.h b/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.h index 5a99bed648..7dc6b61a9a 100644 --- a/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.h +++ b/ApplicationLibCode/ProjectDataModel/RimPolylinePickerInterface.h @@ -18,11 +18,16 @@ #pragma once -#include "RimPolylineTarget.h" -#include "cafPickEventHandler.h" - +#include #include +namespace caf +{ +class PickEventHandler; +} + +class RimPolylineTarget; + class RimPolylinePickerInterface { public: @@ -33,4 +38,7 @@ class RimPolylinePickerInterface virtual std::vector activeTargets() const = 0; virtual bool pickingEnabled() const = 0; virtual caf::PickEventHandler* pickEventHandler() const = 0; + virtual double scalingFactorForTarget() const; + + std::pair findActiveTargetsAroundInsertionPoint( const RimPolylineTarget* targetToInsertBefore ); }; diff --git a/ApplicationLibCode/ProjectDataModel/RimProject.cpp b/ApplicationLibCode/ProjectDataModel/RimProject.cpp index 7e51274652..2fa9253844 100644 --- a/ApplicationLibCode/ProjectDataModel/RimProject.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimProject.cpp @@ -33,6 +33,7 @@ #include "RigGridBase.h" #include "PlotTemplates/RimPlotTemplateFolderItem.h" +#include "Polygons/RimPolygonCollection.h" #include "RimAdvancedSnapshotExportDefinition.h" #include "RimAnalysisPlotCollection.h" #include "RimAnnotationCollection.h" @@ -145,26 +146,21 @@ RimProject::RimProject() m_globalPathList.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &oilFields, "OilFields", "Oil Fields" ); - oilFields.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &colorLegendCollection, "ColorLegendCollection", "Color Legend Collection" ); colorLegendCollection = new RimColorLegendCollection(); colorLegendCollection->createStandardColorLegends(); CAF_PDM_InitFieldNoDefault( &scriptCollection, "ScriptCollection", "Octave Scripts", ":/octave.png" ); - scriptCollection.uiCapability()->setUiTreeHidden( true ); scriptCollection.xmlCapability()->disableIO(); CAF_PDM_InitFieldNoDefault( &wellPathImport, "WellPathImport", "WellPathImport" ); wellPathImport = new RimWellPathImport(); - wellPathImport.uiCapability()->setUiTreeHidden( true ); wellPathImport.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_mainPlotCollection, "MainPlotCollection", "Plots" ); - m_mainPlotCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &viewLinkerCollection, "LinkedViews", "Linked Views", ":/LinkView.svg" ); - viewLinkerCollection.uiCapability()->setUiTreeHidden( true ); viewLinkerCollection = new RimViewLinkerCollection; CAF_PDM_InitFieldNoDefault( &calculationCollection, "CalculationCollection", "Calculation Collection" ); @@ -204,7 +200,6 @@ RimProject::RimProject() CAF_PDM_InitFieldNoDefault( &m_dialogData, "DialogData", "DialogData" ); m_dialogData = new RimDialogData(); - m_dialogData.uiCapability()->setUiTreeHidden( true ); m_dialogData.uiCapability()->setUiTreeChildrenHidden( true ); // Obsolete fields. The content is moved to OilFields and friends @@ -1529,6 +1524,7 @@ void RimProject::defineUiTreeOrdering( caf::PdmUiTreeOrdering& uiTreeOrdering, Q if ( oilField->analysisModels() ) uiTreeOrdering.add( oilField->analysisModels() ); if ( oilField->geoMechModels() ) uiTreeOrdering.add( oilField->geoMechModels() ); if ( oilField->wellPathCollection() ) uiTreeOrdering.add( oilField->wellPathCollection() ); + if ( oilField->polygonCollection() ) uiTreeOrdering.add( oilField->polygonCollection() ); if ( oilField->surfaceCollection() ) uiTreeOrdering.add( oilField->surfaceCollection() ); if ( oilField->seismicDataCollection() ) { diff --git a/ApplicationLibCode/ProjectDataModel/RimRegularLegendConfig.cpp b/ApplicationLibCode/ProjectDataModel/RimRegularLegendConfig.cpp index 0a038c0a84..32e799bb2c 100644 --- a/ApplicationLibCode/ProjectDataModel/RimRegularLegendConfig.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimRegularLegendConfig.cpp @@ -203,8 +203,7 @@ RimRegularLegendConfig::RimRegularLegendConfig() m_categoryLegend = new caf::CategoryLegend( standardFont, m_categoryMapper.p() ); CAF_PDM_InitField( &m_resetUserDefinedValuesButton, "ResetDefaultValues", false, "Reset Default Values" ); - m_resetUserDefinedValuesButton.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_resetUserDefinedValuesButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_resetUserDefinedValuesButton ); CAF_PDM_InitField( &m_centerLegendAroundZero, "CenterLegendAroundZero", false, "Center Legend Around Zero" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.cpp b/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.cpp index 219ba0637f..102b488bf8 100644 --- a/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.cpp @@ -18,9 +18,14 @@ #include "RimReloadCaseTools.h" +#include "RiaEclipseFileNameTools.h" #include "RiaFractureDefines.h" +#include "RiaImportEclipseCaseTools.h" +#include "RiaLogging.h" #include "RiaSummaryTools.h" +#include "ApplicationCommands/RicShowMainWindowFeature.h" + #include "RigCaseCellResultsData.h" #include "RigEclipseCaseData.h" @@ -31,33 +36,39 @@ #include "RimEclipseContourMapProjection.h" #include "RimEclipseContourMapView.h" #include "RimEclipseContourMapViewCollection.h" +#include "RimEclipseResultCase.h" #include "RimEclipseView.h" #include "RimGridCalculation.h" #include "RimGridCalculationCollection.h" #include "RimMainPlotCollection.h" #include "RimProject.h" +#include "RimSummaryCase.h" #include "RimSummaryCaseMainCollection.h" +#include "Riu3DMainWindowTools.h" + +#include + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimReloadCaseTools::reloadAllEclipseData( RimEclipseCase* eclipseCase ) +void RimReloadCaseTools::reloadEclipseGridAndSummary( RimEclipseCase* eclipseCase ) { - reloadAllEclipseData( eclipseCase, true ); + reloadEclipseData( eclipseCase, true ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimReloadCaseTools::reloadAllEclipseGridData( RimEclipseCase* eclipseCase ) +void RimReloadCaseTools::reloadEclipseGrid( RimEclipseCase* eclipseCase ) { - reloadAllEclipseData( eclipseCase, false ); + reloadEclipseData( eclipseCase, false ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimReloadCaseTools::reloadAllEclipseData( RimEclipseCase* eclipseCase, bool reloadSummaryData ) +void RimReloadCaseTools::reloadEclipseData( RimEclipseCase* eclipseCase, bool reloadSummaryData ) { CVF_ASSERT( eclipseCase ); @@ -85,11 +96,8 @@ void RimReloadCaseTools::reloadAllEclipseData( RimEclipseCase* eclipseCase, bool if ( reloadSummaryData ) { - RimSummaryCaseMainCollection* sumCaseColl = RiaSummaryTools::summaryCaseMainCollection(); - if ( sumCaseColl ) - { - sumCaseColl->loadAllSummaryCaseData(); - } + auto summaryCase = RimReloadCaseTools::findSummaryCaseFromEclipseResultCase( dynamic_cast( eclipseCase ) ); + RiaSummaryTools::reloadSummaryCase( summaryCase ); } updateAllPlots(); @@ -155,6 +163,71 @@ void RimReloadCaseTools::updateAll3dViews( RimEclipseCase* eclipseCase ) } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimEclipseCase* RimReloadCaseTools::gridModelFromSummaryCase( const RimSummaryCase* summaryCase ) +{ + if ( summaryCase ) + { + QString summaryFileName = summaryCase->summaryHeaderFilename(); + RiaEclipseFileNameTools fileHelper( summaryFileName ); + + auto candidateGridFileName = fileHelper.findRelatedGridFile(); + return RimProject::current()->eclipseCaseFromGridFileName( candidateGridFileName ); + } + + return nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimSummaryCase* RimReloadCaseTools::findSummaryCaseFromEclipseResultCase( const RimEclipseResultCase* eclipseResultCase ) +{ + RiaEclipseFileNameTools helper( eclipseResultCase->gridFileName() ); + + RimSummaryCaseMainCollection* sumCaseColl = RiaSummaryTools::summaryCaseMainCollection(); + + auto summaryFileNames = helper.findSummaryFileCandidates(); + for ( const auto& fileName : summaryFileNames ) + { + return sumCaseColl->findTopLevelSummaryCaseFromFileName( fileName ); + } + + return nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimReloadCaseTools::openOrImportGridModelFromSummaryCase( const RimSummaryCase* summaryCase ) +{ + if ( !summaryCase ) return false; + + if ( findGridModelAndActivateFirstView( summaryCase ) ) return true; + + QString summaryFileName = summaryCase->summaryHeaderFilename(); + RiaEclipseFileNameTools fileHelper( summaryFileName ); + auto candidateGridFileName = fileHelper.findRelatedGridFile(); + + if ( QFileInfo::exists( candidateGridFileName ) ) + { + bool createView = true; + auto id = RiaImportEclipseCaseTools::openEclipseCaseFromFile( candidateGridFileName, createView ); + if ( id > -1 ) + { + RiaLogging::info( QString( "Imported %1" ).arg( candidateGridFileName ) ); + + return true; + } + } + + RiaLogging::info( QString( "No grid case found based on summary file %1" ).arg( summaryFileName ) ); + + return false; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -162,3 +235,24 @@ void RimReloadCaseTools::updateAllPlots() { RimMainPlotCollection::current()->loadDataAndUpdateAllPlots(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimReloadCaseTools::findGridModelAndActivateFirstView( const RimSummaryCase* summaryCase ) +{ + auto gridCase = RimReloadCaseTools::gridModelFromSummaryCase( summaryCase ); + if ( gridCase ) + { + if ( !gridCase->gridViews().empty() ) + { + RicShowMainWindowFeature::showMainWindow(); + + Riu3DMainWindowTools::selectAsCurrentItem( gridCase->gridViews().front() ); + } + + return true; + } + + return false; +} diff --git a/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.h b/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.h index 37a2ae81dc..b3ec14132a 100644 --- a/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.h +++ b/ApplicationLibCode/ProjectDataModel/RimReloadCaseTools.h @@ -20,6 +20,8 @@ class RimEclipseCase; class RigEclipseCaseData; +class RimSummaryCase; +class RimEclipseResultCase; //-------------------------------------------------------------------------------------------------- /// @@ -28,15 +30,21 @@ class RimReloadCaseTools { public: // Reload all eclipse data, both grid and summary - static void reloadAllEclipseData( RimEclipseCase* eclipseCase ); + static void reloadEclipseGridAndSummary( RimEclipseCase* eclipseCase ); // Reload grid data, but not summary - static void reloadAllEclipseGridData( RimEclipseCase* eclipseCase ); + static void reloadEclipseGrid( RimEclipseCase* eclipseCase ); static void updateAll3dViews( RimEclipseCase* eclipseCase ); + static RimEclipseCase* gridModelFromSummaryCase( const RimSummaryCase* summaryCase ); + static RimSummaryCase* findSummaryCaseFromEclipseResultCase( const RimEclipseResultCase* eclResCase ); + static bool openOrImportGridModelFromSummaryCase( const RimSummaryCase* summaryCase ); + private: - static void reloadAllEclipseData( RimEclipseCase* eclipseCase, bool reloadSummaryData ); + static void reloadEclipseData( RimEclipseCase* eclipseCase, bool reloadSummaryData ); static void clearAllGridData( RigEclipseCaseData* eclipseCaseData ); static void updateAllPlots(); + + static bool findGridModelAndActivateFirstView( const RimSummaryCase* summaryCase ); }; diff --git a/ApplicationLibCode/ProjectDataModel/RimReservoirCellResultsStorage.cpp b/ApplicationLibCode/ProjectDataModel/RimReservoirCellResultsStorage.cpp index 011209b48f..bfa24e1397 100644 --- a/ApplicationLibCode/ProjectDataModel/RimReservoirCellResultsStorage.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimReservoirCellResultsStorage.cpp @@ -56,7 +56,6 @@ RimReservoirCellResultsStorage::RimReservoirCellResultsStorage() CAF_PDM_InitField( &m_resultCacheFileName, "ResultCacheFileName", QString(), "UiDummyname" ); m_resultCacheFileName.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_resultCacheMetaData, "ResultCacheEntries", "UiDummyname" ); - m_resultCacheMetaData.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimRftPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimRftPlotCollection.cpp index ad7d9bb161..d827dabcbc 100644 --- a/ApplicationLibCode/ProjectDataModel/RimRftPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimRftPlotCollection.cpp @@ -42,7 +42,6 @@ RimRftPlotCollection::RimRftPlotCollection() CAF_PDM_InitObject( "RFT Plots", ":/RFTPlots16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_rftPlots, "RftPlots", "" ); - m_rftPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimRoffCase.cpp b/ApplicationLibCode/ProjectDataModel/RimRoffCase.cpp index b1aa62727d..f7fafa1c30 100644 --- a/ApplicationLibCode/ProjectDataModel/RimRoffCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimRoffCase.cpp @@ -73,7 +73,7 @@ bool RimRoffCase::openEclipseGridFile() QString fileName = gridFileName(); // First find and read the grid data - if ( eclipseCaseData()->mainGrid()->gridPointDimensions() == cvf::Vec3st( 0, 0, 0 ) ) + if ( eclipseCaseData()->mainGrid()->cellCount() == 0 ) { QString errorMessages; if ( RifRoffFileTools::openGridFile( fileName, eclipseCaseData(), &errorMessages ) ) diff --git a/ApplicationLibCode/ProjectDataModel/RimScriptCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimScriptCollection.cpp index 053af15e30..b2ba21531b 100644 --- a/ApplicationLibCode/ProjectDataModel/RimScriptCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimScriptCollection.cpp @@ -42,9 +42,7 @@ RimScriptCollection::RimScriptCollection() directory.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &calcScripts, "CalcScripts", "" ); - calcScripts.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &subDirectories, "SubDirectories", "" ); - subDirectories.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimSimWellInView.cpp b/ApplicationLibCode/ProjectDataModel/RimSimWellInView.cpp index 970c6c841f..7bf1c10071 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSimWellInView.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimSimWellInView.cpp @@ -26,6 +26,7 @@ #include "RigCell.h" #include "RigEclipseCaseData.h" #include "RigMainGrid.h" +#include "RigMswCenterLineCalculator.h" #include "RigSimWellData.h" #include "RigSimulationWellCenterLineCalculator.h" #include "RigWellResultFrame.h" @@ -188,6 +189,21 @@ std::vector RimSimWellInView::wellPipeBranches() const return std::vector(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimSimWellInView::wellBranchesForVisualization() const +{ + const RigSimWellData* simWellData = this->simWellData(); + + if ( simWellData && simWellData->isMultiSegmentWell() ) + { + return RigMswCenterLineCalculator::calculateMswWellPipeGeometry( this ); + } + + return RigSimulationWellCenterLineCalculator::calculateWellPipeStaticCenterline( this ); +} + //-------------------------------------------------------------------------------------------------- /// frameIndex = -1 will use the static well frame //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimSimWellInView.h b/ApplicationLibCode/ProjectDataModel/RimSimWellInView.h index 73fb48ede2..ed8060a0dc 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSimWellInView.h +++ b/ApplicationLibCode/ProjectDataModel/RimSimWellInView.h @@ -23,6 +23,7 @@ #include "Rim3dPropertiesInterface.h" #include "RigWellDiskData.h" +#include "RigWellResultBranch.h" #include "cafAppEnum.h" #include "cafPdmChildField.h" @@ -76,6 +77,8 @@ class RimSimWellInView : public caf::PdmObject, public Rim3dPropertiesInterface std::vector wellPipeBranches() const; + std::vector wellBranchesForVisualization() const; + void wellHeadTopBottomPosition( int frameIndex, cvf::Vec3d* top, cvf::Vec3d* bottom ); double pipeRadius(); int pipeCrossSectionVertexCount(); diff --git a/ApplicationLibCode/ProjectDataModel/RimSimWellInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimSimWellInViewCollection.cpp index d1e4ac6085..4124a28645 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSimWellInViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimSimWellInViewCollection.cpp @@ -31,7 +31,6 @@ #include "RimEclipseContourMapView.h" #include "RimEclipseResultCase.h" #include "RimEclipseView.h" -#include "RimIntersectionCollection.h" #include "RimProject.h" #include "RimSimWellFractureCollection.h" #include "RimSimWellInView.h" @@ -207,7 +206,6 @@ RimSimWellInViewCollection::RimSimWellInViewCollection() CAF_PDM_InitField( &wellHeadPosition, "WellHeadPosition", WellHeadPositionEnum( WELLHEAD_POS_ACTIVE_CELLS_BB ), "Well Head Position" ); CAF_PDM_InitFieldNoDefault( &wells, "Wells", "Wells" ); - wells.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_showWellCellFence, "ShowWellCellFenceTristate", "Show Well Cell Fence" ); m_showWellCellFence.uiCapability()->setUiEditorTypeName( caf::PdmUiCheckBoxTristateEditor::uiEditorTypeName() ); @@ -484,10 +482,7 @@ void RimSimWellInViewCollection::fieldChangedByUi( const caf::PdmFieldHandle* ch if ( &wellPipeCoordType == changedField || &isAutoDetectingBranches == changedField ) { - if ( m_reservoirView ) - { - m_reservoirView->intersectionCollection()->recomputeSimWellBranchData(); - } + if ( m_reservoirView ) m_reservoirView->scheduleCreateDisplayModelAndRedraw(); for ( RimSimWellInView* w : wells ) { diff --git a/ApplicationLibCode/ProjectDataModel/RimSimWellInViewTools.cpp b/ApplicationLibCode/ProjectDataModel/RimSimWellInViewTools.cpp index 6f4e234d10..557fc7a057 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSimWellInViewTools.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimSimWellInViewTools.cpp @@ -31,6 +31,7 @@ #include "RimEclipseResultCase.h" #include "RimOilField.h" #include "RimProject.h" +#include "RimReloadCaseTools.h" #include "RimSimWellInView.h" #include "RimSimWellInViewCollection.h" #include "RimSummaryCaseMainCollection.h" @@ -45,13 +46,10 @@ RimSummaryCase* RimSimWellInViewTools::summaryCaseForWell( RimSimWellInView* wel RimProject* project = RimProject::current(); if ( !project ) return nullptr; - RimSummaryCaseMainCollection* sumCaseColl = project->activeOilField() ? project->activeOilField()->summaryCaseMainCollection() : nullptr; - if ( !sumCaseColl ) return nullptr; - auto eclCase = well->firstAncestorOrThisOfType(); if ( eclCase ) { - return sumCaseColl->findSummaryCaseFromEclipseResultCase( eclCase ); + return RimReloadCaseTools::findSummaryCaseFromEclipseResultCase( eclCase ); } return nullptr; diff --git a/ApplicationLibCode/ProjectDataModel/RimStimPlanColors.cpp b/ApplicationLibCode/ProjectDataModel/RimStimPlanColors.cpp index ece71ebffa..edef2776a0 100644 --- a/ApplicationLibCode/ProjectDataModel/RimStimPlanColors.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimStimPlanColors.cpp @@ -69,7 +69,6 @@ RimStimPlanColors::RimStimPlanColors() CAF_PDM_InitField( &m_defaultColor, "DefaultColor", cvf::Color3f( cvf::Color3::BROWN ), "Default Color" ); CAF_PDM_InitFieldNoDefault( &m_legendConfigurations, "LegendConfigurations", "" ); - m_legendConfigurations.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_showStimPlanMesh, "ShowStimPlanMesh", true, "Show Mesh" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimStimPlanLegendConfig.cpp b/ApplicationLibCode/ProjectDataModel/RimStimPlanLegendConfig.cpp index 93cf19c2d3..46cdf42dd7 100644 --- a/ApplicationLibCode/ProjectDataModel/RimStimPlanLegendConfig.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimStimPlanLegendConfig.cpp @@ -20,7 +20,6 @@ #include "RimRegularLegendConfig.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiTreeOrdering.h" CAF_PDM_SOURCE_INIT( RimStimPlanLegendConfig, "RimStimPlanLegendConfig" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculation.cpp b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculation.cpp index 111c7b7bad..c83a240de3 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculation.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculation.cpp @@ -27,26 +27,17 @@ #include "RifSummaryReaderInterface.h" #include "RimDataSourceSteppingTools.h" -#include "RimObservedDataCollection.h" -#include "RimObservedSummaryData.h" #include "RimProject.h" #include "RimSummaryAddress.h" #include "RimSummaryCalculationCollection.h" #include "RimSummaryCalculationVariable.h" #include "RimSummaryCase.h" -#include "RimSummaryCaseCollection.h" -#include "RimSummaryCaseMainCollection.h" #include "RimSummaryCurve.h" #include "RimSummaryMultiPlot.h" #include "RimSummaryMultiPlotCollection.h" #include "RimSummaryPlot.h" -#include "RiuExpressionContextMenuManager.h" - #include "cafPdmUiCheckBoxEditor.h" -#include "cafPdmUiLineEditor.h" -#include "cafPdmUiTableViewEditor.h" -#include "cafPdmUiTextEditor.h" #include "expressionparser/ExpressionParser.h" @@ -402,35 +393,6 @@ std::optional, std::vector>> //-------------------------------------------------------------------------------------------------- void RimSummaryCalculation::updateDependentObjects() { - RimSummaryCalculationCollection* calcColl = firstAncestorOrThisOfTypeAsserted(); - calcColl->rebuildCaseMetaData(); - - // Refresh data sources tree. - // TODO: refresh too much: would be enough to only refresh calculated resutls. - RimSummaryCaseMainCollection* summaryCaseCollection = RiaSummaryTools::summaryCaseMainCollection(); - auto summaryCases = summaryCaseCollection->allSummaryCases(); - for ( RimSummaryCase* summaryCase : summaryCases ) - { - summaryCase->createSummaryReaderInterface(); - summaryCase->createRftReaderInterface(); - summaryCase->refreshMetaData(); - } - - RimObservedDataCollection* observedDataCollection = RiaSummaryTools::observedDataCollection(); - auto observedData = observedDataCollection->allObservedSummaryData(); - for ( auto obs : observedData ) - { - obs->createSummaryReaderInterface(); - obs->createRftReaderInterface(); - obs->refreshMetaData(); - } - - auto summaryCaseCollections = summaryCaseCollection->summaryCaseCollections(); - for ( RimSummaryCaseCollection* summaryCaseCollection : summaryCaseCollections ) - { - summaryCaseCollection->refreshMetaData(); - } - RimSummaryMultiPlotCollection* summaryPlotCollection = RiaSummaryTools::summaryMultiPlotCollection(); for ( auto multiPlot : summaryPlotCollection->multiPlots() ) { @@ -438,7 +400,7 @@ void RimSummaryCalculation::updateDependentObjects() { bool plotContainsCalculatedCurves = false; - for ( RimSummaryCurve* sumCurve : sumPlot->summaryCurves() ) + for ( RimSummaryCurve* sumCurve : sumPlot->summaryAndEnsembleCurves() ) { if ( sumCurve->summaryAddressY().isCalculated() ) { @@ -461,6 +423,7 @@ void RimSummaryCalculation::updateDependentObjects() //-------------------------------------------------------------------------------------------------- void RimSummaryCalculation::removeDependentObjects() { + updateDependentObjects(); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.cpp index e8e8cf5eda..9e97481b73 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.cpp @@ -18,7 +18,15 @@ #include "RimSummaryCalculationCollection.h" +#include "RiaSummaryTools.h" + +#include "RifSummaryReaderInterface.h" + +#include "RimObservedSummaryData.h" #include "RimSummaryCalculation.h" +#include "RimSummaryCase.h" +#include "RimSummaryCaseCollection.h" +#include "RimSummaryCaseMainCollection.h" CAF_PDM_SOURCE_INIT( RimSummaryCalculationCollection, "RimSummaryCalculationCollection" ); //-------------------------------------------------------------------------------------------------- @@ -40,15 +48,52 @@ RimSummaryCalculation* RimSummaryCalculationCollection::createCalculation() cons //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimSummaryCalculationCollection::rebuildCaseMetaData() +void RimSummaryCalculationCollection::updateDataDependingOnCalculations() { - ensureValidCalculationIds(); + // Refresh data sources tree + // Refresh meta data for all summary cases and rebuild AddressNodes in the summary tree + RimSummaryCaseMainCollection* summaryCaseCollection = RiaSummaryTools::summaryCaseMainCollection(); + auto summaryCases = summaryCaseCollection->allSummaryCases(); + for ( RimSummaryCase* summaryCase : summaryCases ) + { + if ( !summaryCase ) continue; + + if ( auto reader = summaryCase->summaryReader() ) + { + reader->buildMetaData(); + + if ( summaryCase->showRealizationDataSources() ) + { + summaryCase->onCalculationUpdated(); + } + } + } + + RimObservedDataCollection* observedDataCollection = RiaSummaryTools::observedDataCollection(); + auto observedData = observedDataCollection->allObservedSummaryData(); + for ( auto obs : observedData ) + { + if ( !obs ) continue; + + if ( auto reader = obs->summaryReader() ) + { + reader->buildMetaData(); + obs->onCalculationUpdated(); + } + } + + auto summaryCaseCollections = summaryCaseCollection->summaryCaseCollections(); + for ( RimSummaryCaseCollection* summaryCaseCollection : summaryCaseCollections ) + { + summaryCaseCollection->onCalculationUpdated(); + } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimSummaryCalculationCollection::initAfterRead() +void RimSummaryCalculationCollection::rebuildCaseMetaData() { - rebuildCaseMetaData(); + ensureValidCalculationIds(); + updateDataDependingOnCalculations(); } diff --git a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.h b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.h index 8d7f21d06c..eea4c734c5 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.h +++ b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationCollection.h @@ -42,5 +42,5 @@ class RimSummaryCalculationCollection : public RimUserDefinedCalculationCollecti RimSummaryCalculation* createCalculation() const override; private: - void initAfterRead() override; + void updateDataDependingOnCalculations(); }; diff --git a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationVariable.cpp b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationVariable.cpp index 1578e48f6b..3c90249bef 100644 --- a/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationVariable.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimSummaryCalculationVariable.cpp @@ -47,8 +47,7 @@ RimSummaryCalculationVariable::RimSummaryCalculationVariable() CAF_PDM_InitObject( "RimSummaryCalculationVariable", ":/octave.png" ); CAF_PDM_InitFieldNoDefault( &m_button, "PushButton", "" ); - m_button.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_button.xmlCapability()->disableIO(); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_button ); CAF_PDM_InitFieldNoDefault( &m_case, "SummaryCase", "Summary Case" ); CAF_PDM_InitFieldNoDefault( &m_summaryAddress, "SummaryAddress", "Summary Address" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimTensorResults.cpp b/ApplicationLibCode/ProjectDataModel/RimTensorResults.cpp index 5541fb98ff..777563d050 100644 --- a/ApplicationLibCode/ProjectDataModel/RimTensorResults.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimTensorResults.cpp @@ -65,7 +65,6 @@ RimTensorResults::RimTensorResults() CAF_PDM_InitFieldNoDefault( &arrowColorLegendConfig, "LegendDefinition", "Color Legend" ); arrowColorLegendConfig = new RimRegularLegendConfig(); - arrowColorLegendConfig.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_resultFieldName, "ResultVariable", QString( "ST" ), "Value" ); m_resultFieldName.uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/RimTernaryLegendConfig.cpp b/ApplicationLibCode/ProjectDataModel/RimTernaryLegendConfig.cpp index 45df0d9e93..2ac160a382 100644 --- a/ApplicationLibCode/ProjectDataModel/RimTernaryLegendConfig.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimTernaryLegendConfig.cpp @@ -59,15 +59,15 @@ RimTernaryLegendConfig::RimTernaryLegendConfig() "" ); CAF_PDM_InitFieldNoDefault( &applyLocalMinMax, "m_applyLocalMinMax", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &applyLocalMinMax ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &applyLocalMinMax ); applyLocalMinMax = false; CAF_PDM_InitFieldNoDefault( &applyGlobalMinMax, "m_applyGlobalMinMax", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &applyGlobalMinMax ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &applyGlobalMinMax ); applyGlobalMinMax = false; CAF_PDM_InitFieldNoDefault( &applyFullRangeMinMax, "m_applyFullRangeMinMax", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &applyFullRangeMinMax ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &applyFullRangeMinMax ); applyFullRangeMinMax = false; CAF_PDM_InitFieldNoDefault( &ternaryRangeSummary, "ternaryRangeSummary", "Range summary" ); diff --git a/ApplicationLibCode/ProjectDataModel/RimTimeStepFilter.cpp b/ApplicationLibCode/ProjectDataModel/RimTimeStepFilter.cpp index 9a5a53908d..fcdca27964 100644 --- a/ApplicationLibCode/ProjectDataModel/RimTimeStepFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimTimeStepFilter.cpp @@ -89,7 +89,7 @@ RimTimeStepFilter::RimTimeStepFilter() caf::PdmUiNativeCheckBoxEditor::configureFieldForEditor( &m_readOnlyLastFrame ); CAF_PDM_InitFieldNoDefault( &m_applyReloadOfCase, "ApplyReloadOfCase", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_applyReloadOfCase ); + caf::PdmUiPushButtonEditor::configureEditorLabelLeft( &m_applyReloadOfCase ); } //-------------------------------------------------------------------------------------------------- @@ -289,7 +289,7 @@ void RimTimeStepFilter::fieldChangedByUi( const caf::PdmFieldHandle* changedFiel if ( rimEclipseResultCase ) { - RimReloadCaseTools::reloadAllEclipseGridData( rimEclipseResultCase ); + RimReloadCaseTools::reloadEclipseGrid( rimEclipseResultCase ); } else if ( rimGeoMechCase ) { diff --git a/ApplicationLibCode/ProjectDataModel/RimTools.cpp b/ApplicationLibCode/ProjectDataModel/RimTools.cpp index 5e3bad0eb7..47c6e8d9a3 100644 --- a/ApplicationLibCode/ProjectDataModel/RimTools.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimTools.cpp @@ -25,6 +25,8 @@ #include "RigGeoMechCaseData.h" #include "RigReservoirGridTools.h" +#include "Polygons/RimPolygon.h" +#include "Polygons/RimPolygonCollection.h" #include "RimCase.h" #include "RimColorLegend.h" #include "RimColorLegendCollection.h" @@ -493,6 +495,20 @@ void RimTools::seismicDataOptionItems( QList* options, c } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimTools::polygonOptionItems( QList* options ) +{ + auto project = RimProject::current(); + auto coll = project->activeOilField()->polygonCollection(); + + for ( auto* p : coll->allPolygons() ) + { + options->push_back( caf::PdmOptionItemInfo( p->name(), p, false, p->uiIconProvider() ) ); + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -546,6 +562,15 @@ RimSurfaceCollection* RimTools::surfaceCollection() return proj->activeOilField()->surfaceCollection(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimPolygonCollection* RimTools::polygonCollection() +{ + RimProject* proj = RimProject::current(); + return proj->activeOilField()->polygonCollection(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimTools.h b/ApplicationLibCode/ProjectDataModel/RimTools.h index 187e5d684f..8985404324 100644 --- a/ApplicationLibCode/ProjectDataModel/RimTools.h +++ b/ApplicationLibCode/ProjectDataModel/RimTools.h @@ -41,6 +41,7 @@ class RimCase; class RimWellPath; class RimSurfaceCollection; class RimFaultInViewCollection; +class RimPolygonCollection; //-------------------------------------------------------------------------------------------------- /// @@ -69,6 +70,7 @@ class RimTools static void colorLegendOptionItems( QList* options ); static void seismicDataOptionItems( QList* options, cvf::BoundingBox worldBBox, bool basicDataOnly = false ); static void seismicDataOptionItems( QList* options ); + static void polygonOptionItems( QList* options ); static void faultOptionItems( QList* options, RimFaultInViewCollection* coll ); @@ -76,9 +78,9 @@ class RimTools static RimWellPath* firstWellPath(); static RimSurfaceCollection* surfaceCollection(); + static RimPolygonCollection* polygonCollection(); static void timeStepsForCase( RimCase* gridCase, QList* options ); -private: static void optionItemsForSpecifiedWellPaths( const std::vector& wellPaths, QList* options ); }; diff --git a/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculation.cpp b/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculation.cpp index 6601ac4588..cdfdb98b86 100644 --- a/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculation.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculation.cpp @@ -53,8 +53,7 @@ RimUserDefinedCalculation::RimUserDefinedCalculation() m_expression.uiCapability()->setUiEditorTypeName( caf::PdmUiTextEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_helpButton, "HelpButton", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_helpButton ); - m_helpButton.xmlCapability()->disableIO(); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_helpButton ); CAF_PDM_InitFieldNoDefault( &m_helpText, "Label", diff --git a/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculationCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculationCollection.cpp index b30dcf0ec4..b8572c84b1 100644 --- a/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculationCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimUserDefinedCalculationCollection.cpp @@ -103,9 +103,11 @@ RimUserDefinedCalculation* RimUserDefinedCalculationCollection::addCalculationCo //-------------------------------------------------------------------------------------------------- void RimUserDefinedCalculationCollection::deleteCalculation( RimUserDefinedCalculation* calculation ) { - calculation->removeDependentObjects(); m_calculations.removeChild( calculation ); + // Call this function after the object is removed from the collection + calculation->removeDependentObjects(); + rebuildCaseMetaData(); delete calculation; diff --git a/ApplicationLibCode/ProjectDataModel/RimVfpPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimVfpPlotCollection.cpp index 9bba3182d0..970fa95273 100644 --- a/ApplicationLibCode/ProjectDataModel/RimVfpPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimVfpPlotCollection.cpp @@ -39,7 +39,6 @@ RimVfpPlotCollection::RimVfpPlotCollection() CAF_PDM_InitObject( "VFP Plots", ":/VfpPlotCollection.svg" ); CAF_PDM_InitFieldNoDefault( &m_vfpPlots, "VfpPlots", "Vertical Flow Performance Plots" ); - m_vfpPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimViewLinker.cpp b/ApplicationLibCode/ProjectDataModel/RimViewLinker.cpp index 23f3db1f7a..a9e45617b6 100644 --- a/ApplicationLibCode/ProjectDataModel/RimViewLinker.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimViewLinker.cpp @@ -63,11 +63,9 @@ RimViewLinker::RimViewLinker() CAF_PDM_InitFieldNoDefault( &m_masterView, "MainView", "Main View" ); m_masterView.uiCapability()->setUiTreeChildrenHidden( true ); - m_masterView.uiCapability()->setUiTreeHidden( true ); m_masterView.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_viewControllers, "ManagedViews", "Managed Views" ); - m_viewControllers.uiCapability()->setUiTreeHidden( true ); m_viewControllers.uiCapability()->setUiTreeChildrenHidden( true ); setDeletable( true ); diff --git a/ApplicationLibCode/ProjectDataModel/RimViewLinkerCollection.cpp b/ApplicationLibCode/ProjectDataModel/RimViewLinkerCollection.cpp index 171cbece93..11e5c7a494 100644 --- a/ApplicationLibCode/ProjectDataModel/RimViewLinkerCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimViewLinkerCollection.cpp @@ -37,7 +37,6 @@ RimViewLinkerCollection::RimViewLinkerCollection() isActive.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &viewLinker, "ViewLinkers", "View Linkers" ); - viewLinker.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/RimViewWindow.cpp b/ApplicationLibCode/ProjectDataModel/RimViewWindow.cpp index 2d579c3009..516128c6c2 100644 --- a/ApplicationLibCode/ProjectDataModel/RimViewWindow.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimViewWindow.cpp @@ -45,7 +45,6 @@ RimViewWindow::RimViewWindow() CAF_PDM_InitScriptableObjectWithNameAndComment( "View window", "", "", "", "ViewWindow", "The Base Class for all Views and Plots in ResInsight" ); CAF_PDM_InitFieldNoDefault( &m_windowController, "WindowController", "" ); - m_windowController.uiCapability()->setUiTreeHidden( true ); m_windowController.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_showWindow, "ShowWindow", true, "Show Window" ); @@ -320,7 +319,7 @@ void RimViewWindow::defineObjectEditorAttribute( QString uiConfigName, caf::PdmU if ( treeItemAttribute && RiaPreferencesSystem::current()->showViewIdInProjectTree() && id() >= 0 ) { treeItemAttribute->tags.clear(); - auto tag = caf::PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = caf::PdmUiTreeViewItemAttribute::createTag(); tag->text = QString( "%1" ).arg( id() ); cvf::Color3f viewColor = RiaColorTables::contrastCategoryPaletteColors().cycledColor3f( (size_t)id() ); cvf::Color3f viewTextColor = RiaColorTools::contrastColor( viewColor ); diff --git a/ApplicationLibCode/ProjectDataModel/RimVirtualPerforationResults.cpp b/ApplicationLibCode/ProjectDataModel/RimVirtualPerforationResults.cpp index fc5aa6b718..2710820aa3 100644 --- a/ApplicationLibCode/ProjectDataModel/RimVirtualPerforationResults.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimVirtualPerforationResults.cpp @@ -36,7 +36,6 @@ RimVirtualPerforationResults::RimVirtualPerforationResults() CAF_PDM_InitField( &m_geometryScaleFactor, "GeometryScaleFactor", 2.0, "Geometry Scale Factor" ); CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendDefinition", "Color Legend" ); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); m_legendConfig = new RimRegularLegendConfig(); } diff --git a/ApplicationLibCode/ProjectDataModel/RimWbsParameters.cpp b/ApplicationLibCode/ProjectDataModel/RimWbsParameters.cpp index dc3567aeae..5b644a9add 100644 --- a/ApplicationLibCode/ProjectDataModel/RimWbsParameters.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimWbsParameters.cpp @@ -120,6 +120,8 @@ RimWbsParameters::RimWbsParameters() { RigWbsParameter::K0_FG(), &m_userDefinedK0FG }, { RigWbsParameter::K0_SH(), &m_userDefinedK0SH }, { RigWbsParameter::FG_Shale(), &m_FGShaleMultiplier }, + { RigWbsParameter::FG_MkMin(), &m_FGShaleMultiplier }, + { RigWbsParameter::FG_MkExp(), &m_FGShaleMultiplier }, { RigWbsParameter::waterDensity(), &m_userDefinedDensity } }; for ( auto parameterFieldPair : m_parameterSourceFields ) diff --git a/ApplicationLibCode/ProjectDataModel/RimWellBoreStabilityPlot.cpp b/ApplicationLibCode/ProjectDataModel/RimWellBoreStabilityPlot.cpp index 5974c2474e..9bb6eccb3d 100644 --- a/ApplicationLibCode/ProjectDataModel/RimWellBoreStabilityPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/RimWellBoreStabilityPlot.cpp @@ -50,7 +50,6 @@ RimWellBoreStabilityPlot::RimWellBoreStabilityPlot() CAF_PDM_InitScriptableFieldWithScriptKeywordNoDefault( &m_wbsParameters, "WbsParameters", "Parameters", "Well Bore Stability Parameters" ); m_wbsParameters = new RimWbsParameters; - m_wbsParameters.uiCapability()->setUiTreeHidden( true ); m_wbsParameters.uiCapability()->setUiTreeChildrenHidden( true ); m_nameConfig->setCustomName( "Well Bore Stability" ); diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicData.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicData.cpp index 72c0112dca..f65651af82 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicData.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicData.cpp @@ -70,7 +70,6 @@ RimSeismicData::RimSeismicData() m_metadata.uiCapability()->setUiEditorTypeName( caf::PdmUiTableViewEditor::uiEditorTypeName() ); m_metadata.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); m_metadata.uiCapability()->setUiTreeChildrenHidden( true ); - m_metadata.uiCapability()->setUiTreeHidden( true ); m_metadata.uiCapability()->setUiReadOnly( true ); m_metadata.xmlCapability()->disableIO(); diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataCollection.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataCollection.cpp index 76f7523d59..935f165949 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataCollection.cpp @@ -40,10 +40,8 @@ RimSeismicDataCollection::RimSeismicDataCollection() CAF_PDM_InitObject( "Data", ":/SeismicData24x24.png" ); CAF_PDM_InitFieldNoDefault( &m_seismicData, "SeismicData", "Seismic Data" ); - m_seismicData.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_differenceData, "DifferenceData", "Seismic Difference Data" ); - m_differenceData.uiCapability()->setUiTreeHidden( true ); setDeletable( false ); } diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataInterface.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataInterface.cpp index 1e1661913d..abc1ef9428 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataInterface.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicDataInterface.cpp @@ -36,7 +36,6 @@ RimSeismicDataInterface::RimSeismicDataInterface() CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendDefinition", "Color Legend" ); m_legendConfig = new RimRegularLegendConfig(); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_userClipValue, "userClipValue", std::make_pair( false, 0.0 ), "Clip Value" ); CAF_PDM_InitField( &m_userMuteThreshold, diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSection.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSection.cpp index eccc174573..6a34ebdf63 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSection.cpp @@ -22,6 +22,7 @@ #include "RiuSeismicHistogramPanel.h" #include "Rim3dView.h" +#include "RimPolylineTarget.h" #include "RimRegularLegendConfig.h" #include "RimSeismicAlphaMapper.h" #include "RimSeismicDataInterface.h" @@ -84,12 +85,10 @@ RimSeismicSection::RimSeismicSection() CAF_PDM_InitFieldNoDefault( &m_wellPath, "WellPath", "Well Path" ); CAF_PDM_InitField( &m_enablePicking, "EnablePicking", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_enablePicking ); - m_enablePicking.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_enablePicking ); CAF_PDM_InitField( &m_showImage, "ShowImage", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_showImage ); - m_showImage.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LabelPosType::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_showImage ); CAF_PDM_InitFieldNoDefault( &m_targets, "Targets", "Targets" ); m_targets.uiCapability()->setUiEditorTypeName( caf::PdmUiTableViewEditor::uiEditorTypeName() ); @@ -599,7 +598,7 @@ cvf::ref RimSeismicSection::texturedSection() for ( int i = 0; i < (int)m_targets.size(); i++ ) { - if ( m_targets[i]->isEnabled() ) points.push_back( m_targets[i]->targetPointXYZ() ); + points.push_back( m_targets[i]->targetPointXYZ() ); } updateTextureSectionFromPoints( points, zmin, zmax ); } diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSectionCollection.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSectionCollection.cpp index 746c245511..2d00df21e0 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSectionCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicSectionCollection.cpp @@ -51,7 +51,6 @@ RimSeismicSectionCollection::RimSeismicSectionCollection() CAF_PDM_InitField( &m_userDescription, "UserDescription", QString( "Seismic Sections" ), "Name" ); CAF_PDM_InitFieldNoDefault( &m_seismicSections, "SeismicSections", "SeismicSections" ); - m_seismicSections.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_surfaceIntersectionLinesScaleFactor, "SurfaceIntersectionLinesScaleFactor", 5.0, "Line Scale Factor ( >= 1.0 )" ); diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.cpp index ec31c0d791..800bc01985 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.cpp @@ -58,20 +58,16 @@ RimSeismicView::RimSeismicView() CAF_PDM_InitFieldNoDefault( &m_seismicData, "SeismicData", "Seismic Data" ); CAF_PDM_InitFieldNoDefault( &m_surfaceCollection, "SurfaceInViewCollection", "Surface Collection Field" ); - m_surfaceCollection.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_seismicSectionCollection, "SeismicSectionCollection", "Seismic Collection Field" ); - m_seismicSectionCollection.uiCapability()->setUiTreeHidden( true ); m_seismicSectionCollection = new RimSeismicSectionCollection(); CAF_PDM_InitFieldNoDefault( &m_annotationCollection, "AnnotationCollection", "Annotations" ); - m_annotationCollection.uiCapability()->setUiTreeHidden( true ); m_annotationCollection = new RimAnnotationInViewCollection; CAF_PDM_InitFieldNoDefault( &m_overlayInfoConfig, "OverlayInfoConfig", "Info Box" ); m_overlayInfoConfig = new Rim3dOverlayInfoConfig(); m_overlayInfoConfig->setReservoirView( this ); - m_overlayInfoConfig.uiCapability()->setUiTreeHidden( true ); m_scaleTransform = new cvf::Transform(); @@ -411,7 +407,7 @@ void RimSeismicView::onUpdateLegends() //-------------------------------------------------------------------------------------------------- void RimSeismicView::onLoadDataAndUpdate() { - updateSurfacesInViewTreeItems(); + updateViewTreeItems( RiaDefines::ItemIn3dView::ALL ); syncronizeLocalAnnotationsFromGlobal(); onUpdateScaleTransform(); @@ -465,23 +461,28 @@ void RimSeismicView::updateGridBoxData() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimSeismicView::updateSurfacesInViewTreeItems() +void RimSeismicView::updateViewTreeItems( RiaDefines::ItemIn3dView itemType ) { - RimSurfaceCollection* surfColl = RimTools::surfaceCollection(); + auto bitmaskEnum = BitmaskEnum( itemType ); - if ( surfColl && surfColl->containsSurface() ) + if ( bitmaskEnum.AnyOf( RiaDefines::ItemIn3dView::SURFACE ) ) { - if ( !m_surfaceCollection() ) + RimSurfaceCollection* surfColl = RimTools::surfaceCollection(); + + if ( surfColl && surfColl->containsSurface() ) { - m_surfaceCollection = new RimSurfaceInViewCollection(); - } + if ( !m_surfaceCollection() ) + { + m_surfaceCollection = new RimSurfaceInViewCollection(); + } - m_surfaceCollection->setSurfaceCollection( surfColl ); - m_surfaceCollection->updateFromSurfaceCollection(); - } - else - { - delete m_surfaceCollection; + m_surfaceCollection->setSurfaceCollection( surfColl ); + m_surfaceCollection->updateFromSurfaceCollection(); + } + else + { + delete m_surfaceCollection; + } } updateConnectedEditors(); diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.h b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.h index dbfb1a6db5..b18d60a1e2 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.h +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicView.h @@ -90,7 +90,7 @@ class RimSeismicView : public Rim3dView, public RimPolylinesDataInterface void setDefaultView() override; - void updateSurfacesInViewTreeItems() override; + void updateViewTreeItems( RiaDefines::ItemIn3dView itemType ) override; private: caf::PdmChildField m_surfaceCollection; diff --git a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicViewCollection.cpp index 803f428446..669f8faa34 100644 --- a/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Seismic/RimSeismicViewCollection.cpp @@ -35,7 +35,6 @@ RimSeismicViewCollection::RimSeismicViewCollection() CAF_PDM_InitObject( "Views", ":/SeismicViews24x24.png" ); CAF_PDM_InitFieldNoDefault( &m_views, "Views", "Seismic Views" ); - m_views.uiCapability()->setUiTreeHidden( true ); setDeletable( false ); } diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticProperties.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticProperties.cpp index dfa9eca764..528cb9c081 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticProperties.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticProperties.cpp @@ -51,7 +51,6 @@ RimElasticProperties::RimElasticProperties() CAF_PDM_InitScriptableField( &m_showScaledProperties, "ShowScaledProperties", true, "Show Scaled Properties" ); CAF_PDM_InitScriptableFieldNoDefault( &m_scalings, "PropertyScalingCollection", "PropertyScalingCollection" ); - m_scalings.uiCapability()->setUiTreeHidden( true ); m_scalings = new RimElasticPropertyScalingCollection; m_scalings->changed.connect( this, &RimElasticProperties::elasticPropertyScalingCollectionChanged ); diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticPropertyScalingCollection.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticPropertyScalingCollection.cpp index 960c9fb380..9b504765ec 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticPropertyScalingCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimElasticPropertyScalingCollection.cpp @@ -35,7 +35,6 @@ RimElasticPropertyScalingCollection::RimElasticPropertyScalingCollection() CAF_PDM_InitScriptableObject( "Elastic Property Scalings" ); CAF_PDM_InitScriptableFieldNoDefault( &m_elasticPropertyScalings, "ElasticPropertyScalings", "Elastic Property Scalings" ); - m_elasticPropertyScalings.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimFaciesProperties.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimFaciesProperties.cpp index f6bb36a653..00dfe04cd0 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimFaciesProperties.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimFaciesProperties.cpp @@ -53,7 +53,6 @@ RimFaciesProperties::RimFaciesProperties() m_propertiesTable.xmlCapability()->disableIO(); CAF_PDM_InitScriptableFieldNoDefault( &m_faciesDefinition, "FaciesDefinition", "" ); - m_faciesDefinition.uiCapability()->setUiTreeHidden( true ); m_faciesDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_faciesDefinition = new RimEclipseResultDefinition; m_faciesDefinition->findField( "MResultType" )->uiCapability()->setUiName( "Facies Definiton" ); diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimNonNetLayers.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimNonNetLayers.cpp index 5766c72349..6b8d71d51f 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimNonNetLayers.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimNonNetLayers.cpp @@ -50,7 +50,6 @@ RimNonNetLayers::RimNonNetLayers() CAF_PDM_InitScriptableFieldNoDefault( &m_facies, "Facies", "Facies" ); CAF_PDM_InitScriptableFieldNoDefault( &m_resultDefinition, "FaciesDefinition", "" ); - m_resultDefinition.uiCapability()->setUiTreeHidden( true ); m_resultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_resultDefinition = new RimEclipseResultDefinition; m_resultDefinition->findField( "MResultType" )->uiCapability()->setUiName( "Facies Definiton" ); diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelCollection.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelCollection.cpp index 4776d33dab..edf47926eb 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelCollection.cpp @@ -35,7 +35,6 @@ RimStimPlanModelCollection::RimStimPlanModelCollection() CAF_PDM_InitScriptableObject( "StimPlan Models" ); CAF_PDM_InitScriptableFieldNoDefault( &m_stimPlanModels, "StimPlanModels", "" ); - m_stimPlanModels.uiCapability()->setUiTreeHidden( true ); setName( "StimPlan Models" ); nameField()->uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelPlotCollection.cpp index 2c9672cbe4..da70a84418 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelPlotCollection.cpp @@ -33,7 +33,6 @@ RimStimPlanModelPlotCollection::RimStimPlanModelPlotCollection() CAF_PDM_InitScriptableObject( "StimPlan Model Plots", ":/WellLogPlots16x16.png" ); CAF_PDM_InitScriptableFieldNoDefault( &m_stimPlanModelPlots, "StimPlanModelPlots", "" ); - m_stimPlanModelPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplate.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplate.cpp index d1c966d33a..dead357728 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplate.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplate.cpp @@ -139,17 +139,13 @@ RimStimPlanModelTemplate::RimStimPlanModelTemplate() m_faciesInitialPressureConfigs.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitScriptableFieldNoDefault( &m_pressureTable, "PressureTable", "Pressure Table" ); - m_pressureTable.uiCapability()->setUiTreeHidden( true ); setPressureTable( new RimPressureTable ); CAF_PDM_InitScriptableFieldNoDefault( &m_elasticProperties, "ElasticProperties", "Elastic Properties" ); - m_elasticProperties.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitScriptableFieldNoDefault( &m_faciesProperties, "FaciesProperties", "Facies Properties" ); - m_faciesProperties.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitScriptableFieldNoDefault( &m_nonNetLayers, "NonNetLayers", "Non-Net Layers" ); - m_nonNetLayers.uiCapability()->setUiTreeHidden( true ); setNonNetLayers( new RimNonNetLayers ); setDeletable( true ); diff --git a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplateCollection.cpp b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplateCollection.cpp index bb73fd355a..b9b819be84 100644 --- a/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplateCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/StimPlanModel/RimStimPlanModelTemplateCollection.cpp @@ -39,7 +39,6 @@ RimStimPlanModelTemplateCollection::RimStimPlanModelTemplateCollection() CAF_PDM_InitScriptableObject( "StimPlan Model Templates", ":/FractureTemplates16x16.png" ); CAF_PDM_InitScriptableFieldNoDefault( &m_stimPlanModelTemplates, "StimPlanModelTemplates", "StimPlan Model Templates" ); - m_stimPlanModelTemplates.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_nextValidId, "NextValidId", 0, "" ); m_nextValidId.uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Streamlines/RimStreamlineInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Streamlines/RimStreamlineInViewCollection.cpp index ea6154c4eb..c81e896588 100644 --- a/ApplicationLibCode/ProjectDataModel/Streamlines/RimStreamlineInViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Streamlines/RimStreamlineInViewCollection.cpp @@ -100,7 +100,6 @@ RimStreamlineInViewCollection::RimStreamlineInViewCollection() CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendDefinition", "Color Legend" ); m_legendConfig = new RimRegularLegendConfig(); m_legendConfig->setMappingMode( RimRegularLegendConfig::MappingType::LOG10_CONTINUOUS ); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_collectionName, "Name", "Name" ); m_collectionName = "Streamlines"; @@ -150,7 +149,6 @@ RimStreamlineInViewCollection::RimStreamlineInViewCollection() m_tracerLength = 100; CAF_PDM_InitFieldNoDefault( &m_streamlines, "Streamlines", "Streamlines" ); - m_streamlines.uiCapability()->setUiTreeHidden( true ); m_streamlines.xmlCapability()->disableIO(); m_eclipseCase = nullptr; diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.cpp index e5efa6f85e..22f0a32fca 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.cpp @@ -87,11 +87,11 @@ void RifCalculatedSummaryCurveReader::buildMetaData() for ( RimUserDefinedCalculation* calc : m_calculationCollection->calculations() ) { - RimSummaryCalculation* sumCalc = dynamic_cast( calc ); + auto* sumCalc = dynamic_cast( calc ); CAF_ASSERT( sumCalc ); const auto& allAddresses = sumCalc->allAddressesForSummaryCase( m_summaryCase ); - for ( auto calculationAddress : allAddresses ) + for ( const auto& calculationAddress : allAddresses ) { if ( calculationAddress.address().isValid() ) { diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.h b/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.h index b8f036a5f2..5eb786d75a 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimCalculatedSummaryCurveReader.h @@ -39,7 +39,7 @@ class RifCalculatedSummaryCurveReader : public RifSummaryReaderInterface std::pair> values( const RifEclipseSummaryAddress& resultAddress ) const override; std::string unitName( const RifEclipseSummaryAddress& resultAddress ) const override; - void buildMetaData(); + void buildMetaData() override; RiaDefines::EclipseUnitSystem unitSystem() const override; diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimCsvUserData.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimCsvUserData.cpp index 6717d067ab..4d5eb1a447 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimCsvUserData.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimCsvUserData.cpp @@ -48,7 +48,6 @@ RimCsvUserData::RimCsvUserData() CAF_PDM_InitFieldNoDefault( &m_parseOptions, "ParseOptions", "" ); m_parseOptions = new RicPasteAsciiDataToSummaryPlotFeatureUi(); m_parseOptions.uiCapability()->setUiTreeChildrenHidden( true ); - m_parseOptions.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimDerivedEnsembleCaseCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimDerivedEnsembleCaseCollection.cpp index 1da0afbd4f..3d09020a86 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimDerivedEnsembleCaseCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimDerivedEnsembleCaseCollection.cpp @@ -67,9 +67,7 @@ RimDerivedEnsembleCaseCollection::RimDerivedEnsembleCaseCollection() CAF_PDM_InitFieldNoDefault( &m_operator, "Operator", "Operator" ); CAF_PDM_InitField( &m_swapEnsemblesButton, "SwapEnsembles", false, "SwapEnsembles" ); - m_swapEnsemblesButton.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_swapEnsemblesButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); - m_swapEnsemblesButton.xmlCapability()->disableIO(); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_swapEnsemblesButton ); CAF_PDM_InitField( &m_caseCount, "CaseCount", QString( "" ), "Matching Cases" ); m_caseCount.uiCapability()->setUiReadOnly( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.cpp index dac5bc9f3d..5ab3e25ade 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.cpp @@ -19,6 +19,7 @@ #include "RimEnsembleCurveFilter.h" #include "RiaCurveDataTools.h" +#include "RiaStdStringTools.h" #include "RiaSummaryCurveDefinition.h" #include "RimCustomObjectiveFunction.h" @@ -84,17 +85,14 @@ RimEnsembleCurveFilter::RimEnsembleCurveFilter() m_objectiveValuesSummaryAddressesUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_objectiveValuesSummaryAddresses, "ObjectiveSummaryAddress", "Summary Address" ); - m_objectiveValuesSummaryAddresses.uiCapability()->setUiTreeHidden( true ); m_objectiveValuesSummaryAddresses.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_objectiveValuesSelectSummaryAddressPushButton, "SelectObjectiveSummaryAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_objectiveValuesSelectSummaryAddressPushButton ); - m_objectiveValuesSelectSummaryAddressPushButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_objectiveValuesSelectSummaryAddressPushButton ); m_objectiveValuesSelectSummaryAddressPushButton = false; CAF_PDM_InitFieldNoDefault( &m_objectiveFunction, "ObjectiveFunction", "Objective Function" ); m_objectiveFunction = new RimObjectiveFunction(); - m_objectiveFunction.uiCapability()->setUiTreeHidden( true ); m_objectiveFunction.uiCapability()->setUiTreeChildrenHidden( true ); m_objectiveFunction->changed.connect( this, &RimEnsembleCurveFilter::onObjectionFunctionChanged ); @@ -109,6 +107,8 @@ RimEnsembleCurveFilter::RimEnsembleCurveFilter() CAF_PDM_InitFieldNoDefault( &m_categories, "Categories", "Categories" ); + CAF_PDM_InitFieldNoDefault( &m_realizationFilter, "RealizationFilter", "Realization Filter" ); + setDeletable( true ); } @@ -188,6 +188,11 @@ QString RimEnsembleCurveFilter::description() const QString descriptor; if ( m_filterMode() == FilterMode::BY_ENSEMBLE_PARAMETER ) { + if ( m_ensembleParameterName() == RiaDefines::summaryRealizationNumber() ) + { + return "Realizations : " + m_realizationFilter; + } + descriptor = QString( "%0" ).arg( m_ensembleParameterName() ); } else if ( m_filterMode() == FilterMode::BY_OBJECTIVE_FUNCTION ) @@ -360,7 +365,8 @@ void RimEnsembleCurveFilter::fieldChangedByUi( const caf::PdmFieldHandle* change } updateMaxMinAndDefaultValues( true ); } - else if ( changedField == &m_active || changedField == &m_minValue || changedField == &m_maxValue || changedField == &m_categories ) + else if ( changedField == &m_active || changedField == &m_minValue || changedField == &m_maxValue || changedField == &m_categories || + changedField == &m_realizationFilter ) { if ( curveSet ) { @@ -461,7 +467,11 @@ void RimEnsembleCurveFilter::defineUiOrdering( QString uiConfigName, caf::PdmUiO uiOrdering.add( &m_customObjectiveFunction ); } - if ( eParam.isNumeric() ) + if ( m_ensembleParameterName() == RiaDefines::summaryRealizationNumber() ) + { + uiOrdering.add( &m_realizationFilter ); + } + else if ( eParam.isNumeric() ) { uiOrdering.add( &m_minValue ); uiOrdering.add( &m_maxValue ); @@ -509,6 +519,19 @@ std::vector RimEnsembleCurveFilter::applyFilter( const std::vec auto ensemble = curveSet ? curveSet->summaryCaseCollection() : nullptr; if ( !ensemble || !isActive() ) return allSumCases; + bool useIntegerSelection = false; + std::set integerSelection; + + if ( m_ensembleParameterName() == RiaDefines::summaryRealizationNumber() ) + { + auto eParam = selectedEnsembleParameter(); + int minValue = eParam.minValue; + int maxValue = eParam.maxValue; + + integerSelection = RiaStdStringTools::valuesFromRangeSelection( m_realizationFilter().toStdString(), minValue, maxValue ); + useIntegerSelection = true; + } + std::set casesToRemove; for ( const auto& sumCase : allSumCases ) { @@ -520,7 +543,16 @@ std::vector RimEnsembleCurveFilter::applyFilter( const std::vec auto crpValue = sumCase->caseRealizationParameters()->parameterValue( m_ensembleParameterName() ); - if ( eParam.isNumeric() ) + if ( useIntegerSelection ) + { + int integerValue = crpValue.numericValue(); + + if ( !integerSelection.contains( integerValue ) ) + { + casesToRemove.insert( sumCase ); + } + } + else if ( eParam.isNumeric() ) { if ( !crpValue.isNumeric() || crpValue.numericValue() < m_minValue() || crpValue.numericValue() > m_maxValue() ) { @@ -656,6 +688,19 @@ void RimEnsembleCurveFilter::updateMaxMinAndDefaultValues( bool forceDefault ) m_minValue.uiCapability()->setUiName( QString( "Min (%1)" ).arg( m_lowerLimit ) ); m_maxValue.uiCapability()->setUiName( QString( "Max (%1)" ).arg( m_upperLimit ) ); + + if ( m_ensembleParameterName() == RiaDefines::summaryRealizationNumber() ) + { + int lower = eParam.minValue; + int upper = eParam.maxValue; + + m_realizationFilter.uiCapability()->setUiName( QString( "Integer Selection\n[%1..%2]" ).arg( lower ).arg( upper ) ); + + if ( m_realizationFilter().isEmpty() ) + { + m_realizationFilter = QString( "%1-%2" ).arg( lower ).arg( upper ); + } + } } } else if ( m_filterMode() == FilterMode::BY_OBJECTIVE_FUNCTION ) diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.h b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.h index eedcd48e79..cddc4ea4d3 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilter.h @@ -105,6 +105,8 @@ class RimEnsembleCurveFilter : public caf::PdmObject caf::PdmField m_maxValue; caf::PdmField> m_categories; + caf::PdmField m_realizationFilter; + double m_lowerLimit; double m_upperLimit; }; diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilterCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilterCollection.cpp index 066a1f106d..dd8ea5da0e 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilterCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveFilterCollection.cpp @@ -25,11 +25,8 @@ #include "RiuTextContentFrame.h" #include -#include #include -#include - CAF_PDM_SOURCE_INIT( RimEnsembleCurveFilterCollection, "RimEnsembleCurveFilterCollection" ); //-------------------------------------------------------------------------------------------------- @@ -43,13 +40,11 @@ RimEnsembleCurveFilterCollection::RimEnsembleCurveFilterCollection() CAF_PDM_InitFieldNoDefault( &m_filters, "CurveFilters", "" ); m_filters.uiCapability()->setUiTreeChildrenHidden( true ); - // m_filters.uiCapability()->setUiEditorTypeName(caf::PdmUiTableViewEditor::uiEditorTypeName()); m_filters.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); CAF_PDM_InitFieldNoDefault( &m_newFilterButton, "NewEnsembleFilter", "New Filter" ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_newFilterButton ); m_newFilterButton = false; - m_newFilterButton.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_newFilterButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); } //-------------------------------------------------------------------------------------------------- @@ -248,7 +243,18 @@ RiuTextContentFrame* RimEnsembleCurveFilterCollection::makeFilterDescriptionFram { QString descriptions = filterDescriptions(); descriptions.replace( "+", "\n+" ); - return new RiuTextContentFrame( nullptr, QString( "Active curve filters:" ), descriptions ); + + // A size of -1 use default plot font + int fontSize = -1; + + auto plotWindow = firstAncestorOrThisOfType(); + if ( plotWindow ) + { + const double scalingFactor = 1.4; + fontSize = scalingFactor * plotWindow->fontSize(); + } + + return new RiuTextContentFrame( nullptr, QString( "Active curve filters:" ), descriptions, fontSize ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSet.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSet.cpp index a853a227c6..76d5b59f02 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSet.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSet.cpp @@ -120,7 +120,6 @@ RimEnsembleCurveSet::RimEnsembleCurveSet() CAF_PDM_InitObject( "Ensemble Curve Set", ":/EnsembleCurveSet16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_curves, "EnsembleCurveSet", "Ensemble Curve Set" ); - m_curves.uiCapability()->setUiTreeHidden( true ); m_curves.uiCapability()->setUiTreeChildrenHidden( false ); CAF_PDM_InitField( &m_showCurves, "IsActive", true, "Show Curves" ); @@ -136,13 +135,11 @@ RimEnsembleCurveSet::RimEnsembleCurveSet() m_yValuesSummaryAddressUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_yValuesSummaryAddress, "SummaryAddress", "Summary Address" ); - m_yValuesSummaryAddress.uiCapability()->setUiTreeHidden( true ); m_yValuesSummaryAddress.uiCapability()->setUiTreeChildrenHidden( true ); m_yValuesSummaryAddress = new RimSummaryAddress; CAF_PDM_InitFieldNoDefault( &m_yPushButtonSelectSummaryAddress, "SelectAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_yPushButtonSelectSummaryAddress ); - m_yPushButtonSelectSummaryAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_yPushButtonSelectSummaryAddress ); m_yPushButtonSelectSummaryAddress = false; CAF_PDM_InitFieldNoDefault( &m_resampling, "Resampling", "Resampling" ); @@ -157,7 +154,6 @@ RimEnsembleCurveSet::RimEnsembleCurveSet() m_xAddressSelector = new RimSummaryAddressSelector; m_xAddressSelector->setAxisOrientation( RimPlotAxisProperties::Orientation::HORIZONTAL ); m_xAddressSelector->setShowResampling( false ); - m_xAddressSelector.uiCapability()->setUiTreeHidden( true ); m_xAddressSelector.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitField( &m_colorMode, "ColorMode", caf::AppEnum( ColorMode::SINGLE_COLOR_WITH_ALPHA ), "Coloring Mode" ); @@ -191,12 +187,10 @@ RimEnsembleCurveSet::RimEnsembleCurveSet() m_objectiveValuesSummaryAddressesUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_objectiveValuesSummaryAddresses, "ObjectiveSummaryAddress", "Summary Address" ); - m_objectiveValuesSummaryAddresses.uiCapability()->setUiTreeHidden( true ); m_objectiveValuesSummaryAddresses.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_objectiveValuesSelectSummaryAddressPushButton, "SelectObjectiveSummaryAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_objectiveValuesSelectSummaryAddressPushButton ); - m_objectiveValuesSelectSummaryAddressPushButton.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_objectiveValuesSelectSummaryAddressPushButton ); m_objectiveValuesSelectSummaryAddressPushButton = false; CAF_PDM_InitFieldNoDefault( &m_customObjectiveFunction, "CustomObjectiveFunction", "Objective Function" ); @@ -242,12 +236,10 @@ RimEnsembleCurveSet::RimEnsembleCurveSet() CAF_PDM_InitFieldNoDefault( &m_objectiveFunction, "ObjectiveFunction", "Objective Function" ); m_objectiveFunction = new RimObjectiveFunction(); - m_objectiveFunction.uiCapability()->setUiTreeHidden( true ); m_objectiveFunction->changed.connect( this, &RimEnsembleCurveSet::onObjectiveFunctionChanged ); CAF_PDM_InitFieldNoDefault( &m_statistics, "Statistics", "Statistics" ); m_statistics = new RimEnsembleStatistics( this ); - m_statistics.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_userDefinedName, "UserDefinedName", QString( "Ensemble Curve Set" ), "Curve Set Name" ); @@ -258,7 +250,6 @@ RimEnsembleCurveSet::RimEnsembleCurveSet() CAF_PDM_InitField( &m_isUsingAutoName, "AutoName", true, "Auto Name" ); CAF_PDM_InitFieldNoDefault( &m_summaryAddressNameTools, "SummaryAddressNameTools", "SummaryAddressNameTools" ); - m_summaryAddressNameTools.uiCapability()->setUiTreeHidden( true ); m_summaryAddressNameTools.uiCapability()->setUiTreeChildrenHidden( true ); m_summaryAddressNameTools = new RimSummaryCurveAutoName; @@ -1071,7 +1062,7 @@ void RimEnsembleCurveSet::defineObjectEditorAttribute( QString uiConfigName, caf if ( auto* treeItemAttribute = dynamic_cast( attribute ) ) { treeItemAttribute->tags.clear(); - auto tag = caf::PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = caf::PdmUiTreeViewItemAttribute::createTag(); tag->bgColor = RiaColorTools::toQColor( m_colorForRealizations ); tag->fgColor = RiaColorTools::toQColor( m_statistics->color() ); tag->text = "---"; @@ -1765,7 +1756,7 @@ void RimEnsembleCurveSet::updateObjectiveFunctionLegend() } if ( !title.isEmpty() && !description.isEmpty() ) { - m_objectiveFunctionOverlayFrame->setContentFrame( new RiuTextContentFrame( nullptr, title, description ) ); + m_objectiveFunctionOverlayFrame->setContentFrame( new RiuTextContentFrame( nullptr, title, description, -1 ) ); m_objectiveFunctionOverlayFrame->setMaximumWidth( 10000 ); plot->plotWidget()->addOverlayFrame( m_objectiveFunctionOverlayFrame ); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSetCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSetCollection.cpp index 6892254a68..cd592cbe5d 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSetCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimEnsembleCurveSetCollection.cpp @@ -42,7 +42,6 @@ RimEnsembleCurveSetCollection::RimEnsembleCurveSetCollection() CAF_PDM_InitObject( "Ensemble Curve Sets", ":/EnsembleCurveSets16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_curveSets, "EnsembleCurveSets", "Ensemble Curve Sets" ); - m_curveSets.uiCapability()->setUiTreeHidden( true ); m_curveSets.uiCapability()->setUiTreeChildrenHidden( false ); caf::PdmFieldReorderCapability::addToFieldWithCallback( &m_curveSets, this, &RimEnsembleCurveSetCollection::onCurveSetsReordered ); @@ -51,7 +50,6 @@ RimEnsembleCurveSetCollection::RimEnsembleCurveSetCollection() CAF_PDM_InitFieldNoDefault( &m_ySourceStepping, "YSourceStepping", "" ); m_ySourceStepping = new RimSummaryPlotSourceStepping; - m_ySourceStepping.uiCapability()->setUiTreeHidden( true ); m_ySourceStepping.uiCapability()->setUiTreeChildrenHidden( true ); m_ySourceStepping.xmlCapability()->disableIO(); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.cpp index 550fb6bf63..e4815a8c2b 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.cpp @@ -20,14 +20,12 @@ #include "RiaApplication.h" #include "RiaLogging.h" - -#include "RicfCommandObject.h" +#include "RiaPreferencesSummary.h" #include "RifEclipseSummaryTools.h" #include "RifMultipleSummaryReaders.h" #include "RifOpmCommonSummary.h" #include "RifProjectSummaryDataWriter.h" -#include "RifReaderEclipseRft.h" #include "RifReaderEclipseSummary.h" #include "RifReaderOpmRft.h" #include "RifSummaryReaderMultipleFiles.h" @@ -36,7 +34,6 @@ #include "RimProject.h" #include "RimRftCase.h" #include "RimSummaryCalculationCollection.h" -#include "RimTools.h" #include "cafPdmFieldScriptingCapability.h" #include "cafPdmObjectScriptingCapability.h" @@ -102,8 +99,18 @@ QString RimFileSummaryCase::caseName() const //-------------------------------------------------------------------------------------------------- void RimFileSummaryCase::createSummaryReaderInterfaceThreadSafe( RiaThreadSafeLogger* threadSafeLogger ) { - m_fileSummaryReader = - RimFileSummaryCase::findRelatedFilesAndCreateReader( summaryHeaderFilename(), m_includeRestartFiles, threadSafeLogger ); + bool lookForRestartFiles = false; + + if ( RiaPreferencesSummary::current()->summaryDataReader() == RiaPreferencesSummary::SummaryReaderMode::LIBECL ) + { + // It is only the libecl reader that requires manual search for referenced restart files + // opm-common reader handles restart files internally based on m_includeRestartFiles in RifOpmCommonEclipseSummary::openFileReader + // + // The performance of the function looking for restart files is bad, and will affect the performance significantly + lookForRestartFiles = m_includeRestartFiles; + } + + m_fileSummaryReader = RimFileSummaryCase::findRelatedFilesAndCreateReader( summaryHeaderFilename(), lookForRestartFiles, threadSafeLogger ); m_multiSummaryReader = new RifMultipleSummaryReaders; m_multiSummaryReader->addReader( m_fileSummaryReader.p() ); @@ -159,10 +166,10 @@ void RimFileSummaryCase::createRftReaderInterface() /// //-------------------------------------------------------------------------------------------------- RifSummaryReaderInterface* RimFileSummaryCase::findRelatedFilesAndCreateReader( const QString& headerFileName, - bool includeRestartFiles, + bool lookForRestartFiles, RiaThreadSafeLogger* threadSafeLogger ) { - if ( includeRestartFiles ) + if ( lookForRestartFiles ) { std::vector warnings; std::vector restartFileInfos = RifEclipseSummaryTools::getRestartFiles( headerFileName, warnings ); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.h b/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.h index 927e6c3a78..dacc7e5670 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimFileSummaryCase.h @@ -61,7 +61,7 @@ class RimFileSummaryCase : public RimSummaryCase void onProjectBeingSaved(); static RifSummaryReaderInterface* - findRelatedFilesAndCreateReader( const QString& headerFileName, bool includeRestartFiles, RiaThreadSafeLogger* threadSafeLogger ); + findRelatedFilesAndCreateReader( const QString& headerFileName, bool lookForRestartFiles, RiaThreadSafeLogger* threadSafeLogger ); protected: void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimRftCase.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimRftCase.cpp index 946cd00de6..c271bfdeb2 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimRftCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimRftCase.cpp @@ -18,7 +18,7 @@ #include "RimRftCase.h" -#include "RicReloadSummaryCaseFeature.h" +#include "RiaSummaryTools.h" #include "RimMainPlotCollection.h" #include "RimSummaryCase.h" @@ -84,7 +84,7 @@ void RimRftCase::fieldChangedByUi( const caf::PdmFieldHandle* changedField, cons { auto parentCase = firstAncestorOfType(); - if ( parentCase ) RicReloadSummaryCaseFeature::reloadSummaryCase( parentCase ); + if ( parentCase ) RiaSummaryTools::reloadSummaryCase( parentCase ); RimMainPlotCollection::current()->loadDataAndUpdateAllPlots(); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.cpp index b5f6db53f4..c27e0140a6 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.cpp @@ -72,10 +72,8 @@ RimSummaryAddressCollection::RimSummaryAddressCollection() m_contentType.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_adresses, "SummaryAddresses", "Addresses" ); - m_adresses.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_subfolders, "AddressSubfolders", "Subfolders" ); - m_subfolders.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_caseId, "CaseId", -1, "CaseId" ); m_caseId.uiCapability()->setUiHidden( true ); @@ -101,7 +99,7 @@ RimSummaryAddressCollection::~RimSummaryAddressCollection() //-------------------------------------------------------------------------------------------------- bool RimSummaryAddressCollection::hasDataVector( const QString quantityName ) const { - for ( auto& address : m_adresses ) + for ( const auto& address : m_adresses ) { if ( address->quantityName() == quantityName ) return true; } @@ -348,6 +346,32 @@ void RimSummaryAddressCollection::deleteChildren() m_subfolders.deleteChildren(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimSummaryAddressCollection::deleteCalculatedObjects() +{ + std::vector toDelete; + for ( const auto& a : m_adresses ) + { + if ( a->address().isCalculated() ) + { + toDelete.push_back( a ); + } + } + + for ( auto a : toDelete ) + { + m_adresses.removeChild( a ); + delete a; + } + + for ( auto& folder : m_subfolders ) + { + folder->deleteCalculatedObjects(); + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.h b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.h index b0b2f02a92..9381c94813 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressCollection.h @@ -66,6 +66,7 @@ class RimSummaryAddressCollection : public RimNamedObject void updateFolderStructure( const std::set& addresses, int caseId, int ensembleId = -1 ); void deleteChildren(); + void deleteCalculatedObjects(); bool isEmpty() const; bool isEnsemble() const; diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressSelector.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressSelector.cpp index ffcc9e5464..5bc5789dd9 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressSelector.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryAddressSelector.cpp @@ -61,12 +61,10 @@ RimSummaryAddressSelector::RimSummaryAddressSelector() m_summaryAddressUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_summaryAddress, "SummaryAddress", "Summary Address" ); - m_summaryAddress.uiCapability()->setUiTreeHidden( true ); m_summaryAddress.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_pushButtonSelectSummaryAddress, "SelectAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_pushButtonSelectSummaryAddress ); - m_pushButtonSelectSummaryAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonSelectSummaryAddress ); m_pushButtonSelectSummaryAddress = false; CAF_PDM_InitFieldNoDefault( &m_plotAxisProperties, "PlotAxisProperties", "Axis" ); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.cpp index dd301f6d83..1ba6917fa4 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.cpp @@ -18,31 +18,19 @@ #include "RimSummaryCase.h" -#include "RiaFilePathTools.h" -#include "RiaSummaryTools.h" +#include "RiaEnsembleNameTools.h" #include "RicfCommandObject.h" #include "RifSummaryReaderInterface.h" -#include "RifEclipseSummaryAddress.h" - -#include "RimMainPlotCollection.h" #include "RimProject.h" -#include "RimSummaryAddress.h" #include "RimSummaryAddressCollection.h" -#include "RimSummaryCalculationCollection.h" #include "RimSummaryCaseCollection.h" #include "cafPdmFieldScriptingCapability.h" #include "cafPdmUiCheckBoxEditor.h" #include "cafPdmUiTreeOrdering.h" -#include "cvfAssert.h" - -#include "RiaEnsembleNameTools.h" -#include -#include - CAF_PDM_ABSTRACT_SOURCE_INIT( RimSummaryCase, "SummaryCase" ); //-------------------------------------------------------------------------------------------------- @@ -56,7 +44,7 @@ RimSummaryCase::RimSummaryCase() CAF_PDM_InitScriptableFieldNoDefault( &m_displayName, "ShortName", "Display Name" ); CAF_PDM_InitScriptableFieldNoDefault( &m_displayNameOption, "NameSetting", "Name Setting" ); - CAF_PDM_InitScriptableField( &m_showSubNodesInTree, "ShowSubNodesInTree", false, "Show Summary Data Sub-Tree" ); + CAF_PDM_InitScriptableField( &m_showSubNodesInTree, "ShowSubNodesInTree", true, "Show Summary Data Sub-Tree" ); caf::PdmUiNativeCheckBoxEditor::configureFieldForEditor( &m_showSubNodesInTree ); CAF_PDM_InitScriptableField( &m_useAutoShortName_OBSOLETE, "AutoShortyName", false, "Use Auto Display Name" ); @@ -400,3 +388,23 @@ void RimSummaryCase::refreshMetaData() buildChildNodes(); updateConnectedEditors(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimSummaryCase::onCalculationUpdated() +{ + // NB! Performance critical method + if ( !m_showSubNodesInTree ) return; + + // Delete all calculated address objects + m_dataVectorFolders->deleteCalculatedObjects(); + + if ( auto reader = summaryReader() ) + { + auto addresses = reader->allResultAddresses(); + m_dataVectorFolders->updateFolderStructure( addresses, m_caseId ); + } + + updateConnectedEditors(); +} diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.h b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.h index 1ea198777a..7c6f36a3c3 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCase.h @@ -23,7 +23,6 @@ #include "RimCaseDisplayNameTools.h" #include "cafFilePath.h" -#include "cafPdmChildArrayField.h" #include "cafPdmChildField.h" #include "cafPdmField.h" #include "cafPdmObject.h" @@ -66,6 +65,7 @@ class RimSummaryCase : public caf::PdmObject int caseId() const; void refreshMetaData(); + void onCalculationUpdated(); virtual void createSummaryReaderInterface() = 0; virtual void createRftReaderInterface() {} diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.cpp index ecb17f346b..21fc2c4738 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.cpp @@ -22,30 +22,23 @@ #include "RiaFieldHandleTools.h" #include "RiaLogging.h" #include "RiaStatisticsTools.h" -#include "RiaStdStringTools.h" #include "RiaSummaryAddressAnalyzer.h" -#include "RiaWeightedMeanCalculator.h" - -#include "RicfCommandObject.h" #include "RifReaderRftInterface.h" #include "RifSummaryReaderInterface.h" -#include "RimAnalysisPlotDataEntry.h" #include "RimDerivedEnsembleCaseCollection.h" #include "RimEnsembleCurveSet.h" #include "RimProject.h" #include "RimSummaryAddressCollection.h" -#include "RimSummaryCalculationCollection.h" #include "RimSummaryCase.h" #include "cafPdmFieldScriptingCapability.h" +#include "cafPdmObjectScriptingCapability.h" #include "cafPdmUiTreeOrdering.h" -#include #include -#include #include CAF_PDM_SOURCE_INIT( RimSummaryCaseCollection, "SummaryCaseSubCollection" ); @@ -110,7 +103,6 @@ RimSummaryCaseCollection::RimSummaryCaseCollection() CAF_PDM_InitScriptableObject( "Summary Case Group", ":/SummaryGroup16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_cases, "SummaryCases", "" ); - m_cases.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitScriptableField( &m_name, "SummaryCollectionName", QString( "Group" ), "Name" ); CAF_PDM_InitScriptableField( &m_autoName, "CreateAutoName", true, "Auto Name" ); @@ -130,7 +122,6 @@ RimSummaryCaseCollection::RimSummaryCaseCollection() CAF_PDM_InitFieldNoDefault( &m_dataVectorFolders, "DataVectorFolders", "Data Folders" ); m_dataVectorFolders = new RimSummaryAddressCollection(); m_dataVectorFolders.uiCapability()->setUiHidden( true ); - m_dataVectorFolders.uiCapability()->setUiTreeHidden( true ); m_dataVectorFolders->uiCapability()->setUiTreeHidden( true ); m_dataVectorFolders.xmlCapability()->disableIO(); @@ -180,7 +171,7 @@ void RimSummaryCaseCollection::addCase( RimSummaryCase* summaryCase ) { summaryCase->nameChanged.connect( this, &RimSummaryCaseCollection::onCaseNameChanged ); - if ( m_cases.empty() ) summaryCase->setShowRealizationDataSource( true ); + summaryCase->setShowRealizationDataSource( m_cases.empty() ); m_cases.push_back( summaryCase ); m_cachedSortedEnsembleParameters.clear(); @@ -257,7 +248,9 @@ void RimSummaryCaseCollection::ensureNameIsUpdated() RiaEnsembleNameTools::EnsembleGroupingMode groupingMode = RiaEnsembleNameTools::EnsembleGroupingMode::FMU_FOLDER_STRUCTURE; QString ensembleName = RiaEnsembleNameTools::findSuitableEnsembleName( fileNames, groupingMode ); - m_name = ensembleName; + if ( m_name == ensembleName ) return; + + m_name = ensembleName; caseNameChanged.send(); } } @@ -286,7 +279,7 @@ void RimSummaryCaseCollection::setAsEnsemble( bool isEnsemble ) calculateEnsembleParametersIntersectionHash(); } - refreshMetaData(); + buildMetaData(); } } @@ -1157,13 +1150,26 @@ void RimSummaryCaseCollection::buildChildNodes() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimSummaryCaseCollection::refreshMetaData() +void RimSummaryCaseCollection::buildMetaData() { clearChildNodes(); buildChildNodes(); updateConnectedEditors(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimSummaryCaseCollection::onCalculationUpdated() +{ + m_dataVectorFolders->deleteCalculatedObjects(); + m_dataVectorFolders->updateFolderStructure( ensembleSummaryAddresses(), -1, m_ensembleId ); + + m_analyzer.reset(); + + updateConnectedEditors(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.h b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.h index 725f7d376a..b2798c954e 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseCollection.h @@ -19,20 +19,17 @@ #pragma once #include "RiaDefines.h" + #include "RifEclipseSummaryAddress.h" #include "RigEnsembleParameter.h" -#include "RimObjectiveFunction.h" - #include "cafPdmChildArrayField.h" #include "cafPdmChildField.h" #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmProxyValueField.h" -#include "cvfObject.h" - #include #include @@ -103,7 +100,7 @@ class RimSummaryCaseCollection : public caf::PdmObject RiaDefines::EclipseUnitSystem unitSystem() const; - void refreshMetaData(); + void onCalculationUpdated(); void updateReferringCurveSets(); @@ -127,6 +124,7 @@ class RimSummaryCaseCollection : public caf::PdmObject void onCaseNameChanged( const SignalEmitter* emitter ); + void buildMetaData(); void buildChildNodes(); void clearChildNodes(); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.cpp index c78e7c47d6..fb52c03c40 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.cpp @@ -47,6 +47,7 @@ #include "cafProgressInfo.h" +#include #include CAF_PDM_SOURCE_INIT( RimSummaryCaseMainCollection, "SummaryCaseCollection" ); @@ -81,7 +82,7 @@ void addCaseRealizationParametersIfFound( RimSummaryCase& sumCase, const QString int realizationNumber = RifCaseRealizationParametersFileLocator::realizationNumber( modelFolderOrFile ); parameters->setRealizationNumber( realizationNumber ); - parameters->addParameter( "RI:REALIZATION_NUM", realizationNumber ); + parameters->addParameter( RiaDefines::summaryRealizationNumber(), realizationNumber ); sumCase.setCaseRealizationParameters( parameters ); } @@ -96,9 +97,6 @@ RimSummaryCaseMainCollection::RimSummaryCaseMainCollection() CAF_PDM_InitFieldNoDefault( &m_cases, "SummaryCases", "" ); CAF_PDM_InitFieldNoDefault( &m_caseCollections, "SummaryCaseCollections", "" ); - - m_cases.uiCapability()->setUiTreeHidden( true ); - m_caseCollections.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- @@ -110,26 +108,6 @@ RimSummaryCaseMainCollection::~RimSummaryCaseMainCollection() m_caseCollections.deleteChildrenAsync(); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimSummaryCase* RimSummaryCaseMainCollection::findSummaryCaseFromEclipseResultCase( const RimEclipseResultCase* eclipseResultCase ) const -{ - RiaEclipseFileNameTools helper( eclipseResultCase->gridFileName() ); - - auto summaryFileName = helper.findSummaryFileCandidates(); - for ( const auto& candidateFileName : summaryFileName ) - { - auto summaryCase = findTopLevelSummaryCaseFromFileName( candidateFileName ); - if ( summaryCase ) - { - return summaryCase; - } - } - - return nullptr; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -482,6 +460,7 @@ void RimSummaryCaseMainCollection::loadFileSummaryCaseData( std::vectorcreateSummaryReaderInterfaceThreadSafe( &threadSafeLogger ); + addCaseRealizationParametersIfFound( *fileSummaryCase, fileSummaryCase->summaryHeaderFilename() ); } progInfo.setProgress( cIdx ); @@ -504,7 +483,6 @@ void RimSummaryCaseMainCollection::loadFileSummaryCaseData( std::vectorcreateRftReaderInterface(); - addCaseRealizationParametersIfFound( *fileSummaryCase, fileSummaryCase->summaryHeaderFilename() ); } } } @@ -670,9 +648,13 @@ void RimSummaryCaseMainCollection::updateAutoShortName() // // https://github.com/OPM/ResInsight/issues/7438 - for ( auto s : allSummaryCases() ) + auto sumCases = allSummaryCases(); + +#pragma omp parallel for + for ( int cIdx = 0; cIdx < static_cast( sumCases.size() ); ++cIdx ) { - s->updateAutoShortName(); + auto sumCase = sumCases[cIdx]; + sumCase->updateAutoShortName(); } } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.h b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.h index 598dbd1008..2d1e6fe22b 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.h +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCaseMainCollection.h @@ -54,7 +54,6 @@ class RimSummaryCaseMainCollection : public caf::PdmObject std::vector createSummaryCasesFromFileInfos( const std::vector& summaryHeaderFileInfos, bool showProgress = false ); - RimSummaryCase* findSummaryCaseFromEclipseResultCase( const RimEclipseResultCase* eclResCase ) const; RimSummaryCase* findTopLevelSummaryCaseFromFileName( const QString& fileName ) const; void addCases( const std::vector cases ); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCrossPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCrossPlotCollection.cpp index 2c16415a29..761bbfd944 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCrossPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCrossPlotCollection.cpp @@ -34,7 +34,6 @@ RimSummaryCrossPlotCollection::RimSummaryCrossPlotCollection() CAF_PDM_InitObject( "Summary Cross Plots", ":/SummaryXPlotsLight16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_summaryCrossPlots, "SummaryCrossPlots", "Summary Cross Plots" ); - m_summaryCrossPlots.uiCapability()->setUiTreeHidden( true ); caf::PdmFieldReorderCapability::addToField( &m_summaryCrossPlots ); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurve.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurve.cpp index 2e99a4e360..1521504979 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurve.cpp @@ -77,12 +77,10 @@ RimSummaryCurve::RimSummaryCurve() m_yValuesSummaryAddressUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_yValuesSummaryAddress, "SummaryAddress", "Summary Address" ); - m_yValuesSummaryAddress.uiCapability()->setUiTreeHidden( true ); m_yValuesSummaryAddress.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_yPushButtonSelectSummaryAddress, "SelectAddress", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_yPushButtonSelectSummaryAddress ); - m_yPushButtonSelectSummaryAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_yPushButtonSelectSummaryAddress ); m_yPushButtonSelectSummaryAddress = false; m_yValuesSummaryAddress = new RimSummaryAddress; @@ -105,13 +103,10 @@ RimSummaryCurve::RimSummaryCurve() m_xValuesSummaryAddressUiField.uiCapability()->setUiEditorTypeName( caf::PdmUiLineEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_xValuesSummaryAddress, "SummaryAddressX", "Summary Address" ); - m_xValuesSummaryAddress.uiCapability()->setUiTreeHidden( true ); m_xValuesSummaryAddress.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_xPushButtonSelectSummaryAddress, "SelectAddressX", "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_xPushButtonSelectSummaryAddress ); - m_xPushButtonSelectSummaryAddress.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); - + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_xPushButtonSelectSummaryAddress ); m_xPushButtonSelectSummaryAddress = false; m_xValuesSummaryAddress = new RimSummaryAddress; @@ -127,7 +122,6 @@ RimSummaryCurve::RimSummaryCurve() CAF_PDM_InitFieldNoDefault( &m_xPlotAxisProperties, "XAxis", "Axis" ); CAF_PDM_InitFieldNoDefault( &m_curveNameConfig, "SummaryCurveNameConfig", "SummaryCurveNameConfig" ); - m_curveNameConfig.uiCapability()->setUiTreeHidden( true ); m_curveNameConfig.uiCapability()->setUiTreeChildrenHidden( true ); m_curveNameConfig = new RimSummaryCurveAutoName; diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveAutoName.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveAutoName.cpp index abff633c20..4bb8fff39f 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveAutoName.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveAutoName.cpp @@ -252,18 +252,6 @@ QString RimSummaryCurveAutoName::buildCurveName( const RifEclipseSummaryAddress& { text = summaryAddress.vectorName(); } - else if ( summaryAddress.isCalculated() ) - { - // Need to add case name for calculated summary - RimProject* proj = RimProject::current(); - RimSummaryCalculationCollection* calcColl = proj->calculationCollection(); - - RimUserDefinedCalculation* calculation = calcColl->findCalculationById( summaryAddress.id() ); - if ( calculation ) - { - text = calculation->shortName().toStdString(); - } - } if ( m_unit && !unitText.empty() ) { @@ -273,7 +261,7 @@ QString RimSummaryCurveAutoName::buildCurveName( const RifEclipseSummaryAddress& appendAddressDetails( text, summaryAddress, plotNameHelper ); - if ( !caseName.empty() && !summaryAddress.isCalculated() ) + if ( !caseName.empty() ) { bool skipSubString = plotNameHelper && plotNameHelper->isCaseInTitle(); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveCollection.cpp index cecd9a0381..8ea9fda02b 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryCurveCollection.cpp @@ -51,21 +51,16 @@ RimSummaryCurveCollection::RimSummaryCurveCollection() CAF_PDM_InitObject( "Summary Curves", ":/SummaryCurveFilter16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_curves, "CollectionCurves", "Curves" ); - m_curves.uiCapability()->setUiTreeHidden( true ); - m_curves.uiCapability()->setUiTreeChildrenHidden( false ); caf::PdmFieldReorderCapability::addToFieldWithCallback( &m_curves, this, &RimSummaryCurveCollection::onCurvesReordered ); CAF_PDM_InitField( &m_showCurves, "IsActive", true, "Show Curves" ); m_showCurves.uiCapability()->setUiHidden( true ); - m_showCurves.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_editPlot, "EditPlot", false, "" ); - m_editPlot.xmlCapability()->disableIO(); - m_editPlot.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_editPlot ); CAF_PDM_InitFieldNoDefault( &m_ySourceStepping, "YSourceStepping", "" ); m_ySourceStepping = new RimSummaryPlotSourceStepping; - m_ySourceStepping.uiCapability()->setUiTreeHidden( true ); m_ySourceStepping.uiCapability()->setUiTreeChildrenHidden( true ); m_ySourceStepping.xmlCapability()->disableIO(); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlot.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlot.cpp index 204dc6d3e1..ba6620c1a1 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlot.cpp @@ -114,33 +114,27 @@ RimSummaryMultiPlot::RimSummaryMultiPlot() CAF_PDM_InitField( &m_autoSubPlotTitle, "AutoSubPlotTitle", true, "Auto Sub Plot Title" ); CAF_PDM_InitField( &m_createPlotDuplicate, "DuplicatePlot", false, "", "", "Duplicate Plot" ); - m_createPlotDuplicate.xmlCapability()->disableIO(); - m_createPlotDuplicate.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_createPlotDuplicate ); m_createPlotDuplicate.uiCapability()->setUiIconFromResourceString( ":/Copy.svg" ); CAF_PDM_InitField( &m_disableWheelZoom, "DisableWheelZoom", true, "", "", "Disable Mouse Wheel Zooming in Multi Summary Plot" ); - m_disableWheelZoom.xmlCapability()->disableIO(); - m_disableWheelZoom.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_disableWheelZoom ); m_disableWheelZoom.uiCapability()->setUiIconFromResourceString( ":/DisableZoom.png" ); CAF_PDM_InitField( &m_appendNextPlot, "AppendNextPlot", false, "", "", "Step Next and Add to New Plot" ); - m_appendNextPlot.xmlCapability()->disableIO(); - m_appendNextPlot.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_appendNextPlot ); m_appendNextPlot.uiCapability()->setUiIconFromResourceString( ":/AppendNext.png" ); CAF_PDM_InitField( &m_appendPrevPlot, "AppendPrevPlot", false, "", "", "Step Previous and Add to New Plot" ); - m_appendPrevPlot.xmlCapability()->disableIO(); - m_appendPrevPlot.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_appendPrevPlot ); m_appendPrevPlot.uiCapability()->setUiIconFromResourceString( ":/AppendPrev.png" ); CAF_PDM_InitField( &m_appendNextCurve, "AppendNextCurve", false, "", "", "Step Next and Add Curve to Plot" ); - m_appendNextCurve.xmlCapability()->disableIO(); - m_appendNextCurve.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_appendNextCurve ); m_appendNextCurve.uiCapability()->setUiIconFromResourceString( ":/AppendNextCurve.png" ); CAF_PDM_InitField( &m_appendPrevCurve, "AppendPrevCurve", false, "", "", "Step Previous and Add Curve to Plot" ); - m_appendPrevCurve.xmlCapability()->disableIO(); - m_appendPrevCurve.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_appendPrevCurve ); m_appendPrevCurve.uiCapability()->setUiIconFromResourceString( ":/AppendPrevCurve.png" ); CAF_PDM_InitField( &m_linkSubPlotAxes, "LinkSubPlotAxes", false, "Link Y Axes" ); @@ -155,8 +149,7 @@ RimSummaryMultiPlot::RimSummaryMultiPlot() CAF_PDM_InitFieldNoDefault( &m_axisRangeAggregation, "AxisRangeAggregation", "Y Axis Range" ); CAF_PDM_InitField( &m_hidePlotsWithValuesBelow, "HidePlotsWithValuesBelow", false, "" ); - m_hidePlotsWithValuesBelow.xmlCapability()->disableIO(); - m_hidePlotsWithValuesBelow.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_hidePlotsWithValuesBelow ); CAF_PDM_InitField( &m_plotFilterYAxisThreshold, "PlotFilterYAxisThreshold", 0.0, "Y-Axis Filter Threshold" ); @@ -164,7 +157,6 @@ RimSummaryMultiPlot::RimSummaryMultiPlot() m_sourceStepping = new RimSummaryPlotSourceStepping; m_sourceStepping->setSourceSteppingObject( this ); - m_sourceStepping.uiCapability()->setUiTreeHidden( true ); m_sourceStepping.uiCapability()->setUiTreeChildrenHidden( true ); m_sourceStepping.xmlCapability()->disableIO(); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlotCollection.cpp index 458f7eb621..a53964e00d 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryMultiPlotCollection.cpp @@ -36,7 +36,6 @@ RimSummaryMultiPlotCollection::RimSummaryMultiPlotCollection() CAF_PDM_InitObject( "Summary Plots", ":/MultiPlot16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_summaryMultiPlots, "MultiSummaryPlots", "Summary Plots" ); - m_summaryMultiPlots.uiCapability()->setUiTreeHidden( true ); caf::PdmFieldReorderCapability::addToField( &m_summaryMultiPlots ); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlot.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlot.cpp index 48865ab7fa..73623f3d3d 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlot.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlot.cpp @@ -141,21 +141,18 @@ RimSummaryPlot::RimSummaryPlot() m_useQtChartsPlot.uiCapability()->setUiHidden( true ); #endif CAF_PDM_InitFieldNoDefault( &m_summaryCurveCollection, "SummaryCurveCollection", "" ); - m_summaryCurveCollection.uiCapability()->setUiTreeHidden( true ); m_summaryCurveCollection = new RimSummaryCurveCollection; m_summaryCurveCollection->curvesChanged.connect( this, &RimSummaryPlot::onCurveCollectionChanged ); CAF_PDM_InitFieldNoDefault( &m_ensembleCurveSetCollection, "EnsembleCurveSetCollection", "" ); - m_ensembleCurveSetCollection.uiCapability()->setUiTreeHidden( true ); m_ensembleCurveSetCollection = new RimEnsembleCurveSetCollection(); CAF_PDM_InitFieldNoDefault( &m_gridTimeHistoryCurves, "GridTimeHistoryCurves", "" ); - m_gridTimeHistoryCurves.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_asciiDataCurves, "AsciiDataCurves", "" ); - m_asciiDataCurves.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_axisPropertiesArray, "AxisProperties", "Axes", ":/Axes16x16.png" ); + m_axisPropertiesArray.uiCapability()->setUiTreeHidden( false ); auto leftAxis = addNewAxisProperties( RiuPlotAxis::defaultLeft(), "Left" ); leftAxis->setAlwaysRequired( true ); @@ -169,7 +166,6 @@ RimSummaryPlot::RimSummaryPlot() m_sourceStepping = new RimSummaryPlotSourceStepping; m_sourceStepping->setSourceSteppingObject( this ); - m_sourceStepping.uiCapability()->setUiTreeHidden( true ); m_sourceStepping.uiCapability()->setUiTreeChildrenHidden( true ); m_sourceStepping.xmlCapability()->disableIO(); @@ -182,22 +178,18 @@ RimSummaryPlot::RimSummaryPlot() // Obsolete axis fields CAF_PDM_InitFieldNoDefault( &m_leftYAxisProperties_OBSOLETE, "LeftYAxisProperties", "Left Y Axis" ); - m_leftYAxisProperties_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_leftYAxisProperties_OBSOLETE.xmlCapability()->setIOWritable( false ); m_leftYAxisProperties_OBSOLETE = new RimPlotAxisProperties; CAF_PDM_InitFieldNoDefault( &m_rightYAxisProperties_OBSOLETE, "RightYAxisProperties", "Right Y Axis" ); - m_rightYAxisProperties_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_rightYAxisProperties_OBSOLETE.xmlCapability()->setIOWritable( false ); m_rightYAxisProperties_OBSOLETE = new RimPlotAxisProperties; CAF_PDM_InitFieldNoDefault( &m_bottomAxisProperties_OBSOLETE, "BottomAxisProperties", "Bottom X Axis" ); - m_bottomAxisProperties_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_bottomAxisProperties_OBSOLETE.xmlCapability()->setIOWritable( false ); m_bottomAxisProperties_OBSOLETE = new RimPlotAxisProperties; CAF_PDM_InitFieldNoDefault( &m_timeAxisProperties_OBSOLETE, "TimeAxisProperties", "Time Axis" ); - m_timeAxisProperties_OBSOLETE.uiCapability()->setUiTreeHidden( true ); m_timeAxisProperties_OBSOLETE.xmlCapability()->setIOWritable( false ); m_timeAxisProperties_OBSOLETE = new RimSummaryTimeAxisProperties; @@ -2850,24 +2842,12 @@ void RimSummaryPlot::updateNameHelperWithCurveData( RimSummaryPlotNameHelper* na { for ( RimSummaryCurve* curve : m_summaryCurveCollection->curves() ) { - if ( curve->summaryAddressY().isCalculated() ) - { - std::vector calcAddresses; - RiaSummaryTools::getSummaryCasesAndAddressesForCalculation( curve->summaryAddressY().id(), sumCases, calcAddresses ); - for ( const auto& adr : calcAddresses ) - { - addresses.emplace_back( adr ); - } - } - else - { - addresses.push_back( curve->curveAddress() ); - sumCases.push_back( curve->summaryCaseY() ); + addresses.push_back( curve->curveAddress() ); + sumCases.push_back( curve->summaryCaseY() ); - if ( curve->summaryCaseX() ) - { - sumCases.push_back( curve->summaryCaseX() ); - } + if ( curve->summaryCaseX() ) + { + sumCases.push_back( curve->summaryCaseX() ); } } } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotCollection.cpp index 9459513ad7..3c84c1c237 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotCollection.cpp @@ -40,7 +40,6 @@ RimSummaryPlotCollection::RimSummaryPlotCollection() CAF_PDM_InitScriptableObject( "Single Summary Plots", ":/SummaryPlotsLight16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_summaryPlots, "SummaryPlots", "Single Summary Plots" ); - m_summaryPlots.uiCapability()->setUiTreeHidden( true ); caf::PdmFieldReorderCapability::addToField( &m_summaryPlots ); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotManager.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotManager.cpp index a3f9be3ff2..c71a20221e 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotManager.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotManager.cpp @@ -93,16 +93,13 @@ RimSummaryPlotManager::RimSummaryPlotManager() m_includeDiffCurves.uiCapability()->setUiEditorTypeName( caf::PdmUiNativeCheckBoxEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_pushButtonReplace, "PushButtonReplace", "Replace (CTRL + Enter)" ); - m_pushButtonReplace.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButtonReplace.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonReplace ); CAF_PDM_InitFieldNoDefault( &m_pushButtonNewPlot, "PushButtonNewPlot", "New (Alt + Enter)" ); - m_pushButtonNewPlot.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButtonNewPlot.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonNewPlot ); CAF_PDM_InitFieldNoDefault( &m_pushButtonAppend, "PushButtonAppend", "Append (Shift + Enter)" ); - m_pushButtonAppend.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButtonAppend.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonAppend ); CAF_PDM_InitFieldNoDefault( &m_labelA, "LabelA", "" ); m_labelA.uiCapability()->setUiEditorTypeName( caf::PdmUiLabelEditor::uiEditorTypeName() ); diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotSourceStepping.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotSourceStepping.cpp index 5119e94faf..f8222e1975 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotSourceStepping.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryPlotSourceStepping.cpp @@ -529,9 +529,6 @@ void RimSummaryPlotSourceStepping::fieldChangedByUi( const caf::PdmFieldHandle* // The time axis can be zoomed and will be used for all plots. Do not zoom time axis in this case. summaryMultiPlot->zoomAllYAxes(); } - - RiuPlotMainWindow* mainPlotWindow = RiaGuiApplication::instance()->mainPlotWindow(); - mainPlotWindow->updateMultiPlotToolBar(); } else { @@ -541,6 +538,11 @@ void RimSummaryPlotSourceStepping::fieldChangedByUi( const caf::PdmFieldHandle* summaryPlot->curvesChanged.send(); } + updateAllRequiredEditors(); + + RiuPlotMainWindow* mainPlotWindow = RiaGuiApplication::instance()->mainPlotWindow(); + mainPlotWindow->updateMultiPlotToolBar(); + auto ensembleCurveColl = firstAncestorOrThisOfType(); if ( ensembleCurveColl ) { diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTableCollection.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTableCollection.cpp index 5a34c3faea..af063c553a 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTableCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTableCollection.cpp @@ -34,7 +34,6 @@ RimSummaryTableCollection::RimSummaryTableCollection() CAF_PDM_InitObject( "Summary Tables", ":/CorrelationMatrixPlot16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_summaryTables, "SummaryTables", "Summary Tables" ); - m_summaryTables.uiCapability()->setUiTreeHidden( true ); caf::PdmFieldReorderCapability::addToField( &m_summaryTables ); } diff --git a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTimeAxisProperties.cpp b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTimeAxisProperties.cpp index bc1dd831e3..4d10357f62 100644 --- a/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTimeAxisProperties.cpp +++ b/ApplicationLibCode/ProjectDataModel/Summary/RimSummaryTimeAxisProperties.cpp @@ -149,7 +149,6 @@ RimSummaryTimeAxisProperties::RimSummaryTimeAxisProperties() m_majorTickmarkCount.uiCapability()->enableAutoValueSupport( true ); CAF_PDM_InitFieldNoDefault( &m_annotations, "Annotations", "" ); - m_annotations.uiCapability()->setUiTreeHidden( true ); m_annotations.uiCapability()->setUiTreeChildrenHidden( true ); } @@ -205,7 +204,7 @@ void RimSummaryTimeAxisProperties::defineObjectEditorAttribute( QString uiConfig if ( treeItemAttribute ) { treeItemAttribute->tags.clear(); - auto tag = caf::PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = caf::PdmUiTreeViewItemAttribute::createTag(); tag->icon = caf::IconProvider( ":/chain.png" ); treeItemAttribute->tags.push_back( std::move( tag ) ); diff --git a/ApplicationLibCode/ProjectDataModel/Surfaces/RimFileSurface.cpp b/ApplicationLibCode/ProjectDataModel/Surfaces/RimFileSurface.cpp index f316d28129..80808175be 100644 --- a/ApplicationLibCode/ProjectDataModel/Surfaces/RimFileSurface.cpp +++ b/ApplicationLibCode/ProjectDataModel/Surfaces/RimFileSurface.cpp @@ -178,7 +178,7 @@ bool RimFileSurface::loadDataFromFile() surface = m_gocadData->gocadGeometry(); } - else if ( filePath.endsWith( "dat", Qt::CaseInsensitive ) ) + else if ( filePath.endsWith( "dat", Qt::CaseInsensitive ) || filePath.endsWith( "xyz", Qt::CaseInsensitive ) ) { double resamplingDistance = RiaPreferences::current()->surfaceImportResamplingDistance(); surface = RifSurfaceImporter::readOpenWorksXyzFile( filePath, resamplingDistance ); diff --git a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceCollection.cpp b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceCollection.cpp index 3dcc2a8f7b..6332511ee5 100644 --- a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceCollection.cpp @@ -56,12 +56,10 @@ RimSurfaceCollection::RimSurfaceCollection() m_collectionName = "Surfaces"; CAF_PDM_InitScriptableFieldNoDefault( &m_subCollections, "SubCollections", "Surfaces" ); - m_subCollections.uiCapability()->setUiTreeHidden( true ); auto reorderability = caf::PdmFieldReorderCapability::addToField( &m_subCollections ); reorderability->orderChanged.connect( this, &RimSurfaceCollection::orderChanged ); CAF_PDM_InitScriptableFieldNoDefault( &m_surfaces, "SurfacesField", "Surfaces" ); - m_surfaces.uiCapability()->setUiTreeHidden( true ); setDeletable( true ); } @@ -304,7 +302,7 @@ void RimSurfaceCollection::updateViews( const std::vector& surfsToR proj->allViews( views ); for ( auto view : views ) { - view->updateSurfacesInViewTreeItems(); + view->updateViewTreeItems( RiaDefines::ItemIn3dView::SURFACE ); if ( auto gridView = dynamic_cast( view ) ) { @@ -357,7 +355,7 @@ void RimSurfaceCollection::updateViews() for ( auto view : views ) { - view->updateSurfacesInViewTreeItems(); + view->updateViewTreeItems( RiaDefines::ItemIn3dView::SURFACE ); } for ( auto view : views ) diff --git a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInView.cpp b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInView.cpp index 95bfb8be9e..9451addc1c 100644 --- a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInView.cpp +++ b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInView.cpp @@ -49,10 +49,8 @@ RimSurfaceInView::RimSurfaceInView() CAF_PDM_InitFieldNoDefault( &m_surface, "SurfaceRef", "Surface" ); m_surface.uiCapability()->setUiHidden( true ); - m_surface.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_resultDefinition, "ResultDefinition", "Result Definition" ); - m_resultDefinition.uiCapability()->setUiTreeHidden( true ); m_resultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_resultDefinition = new RimSurfaceResultDefinition; m_resultDefinition->setCheckState( false ); diff --git a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInViewCollection.cpp index 0d7db550ba..85dd50db06 100644 --- a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceInViewCollection.cpp @@ -50,10 +50,8 @@ RimSurfaceInViewCollection::RimSurfaceInViewCollection() m_collectionName.xmlCapability()->disableIO(); CAF_PDM_InitFieldNoDefault( &m_collectionsInView, "SurfacesInViewFieldCollections", "SurfacesInViewFieldCollections" ); - m_collectionsInView.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_surfacesInView, "SurfacesInViewField", "Surfaces" ); - m_surfacesInView.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_surfaceCollection, "SurfaceCollectionRef", "SurfaceCollection" ); m_surfaceCollection.uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceResultDefinition.cpp b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceResultDefinition.cpp index b0ffe7c695..9c037d37db 100644 --- a/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceResultDefinition.cpp +++ b/ApplicationLibCode/ProjectDataModel/Surfaces/RimSurfaceResultDefinition.cpp @@ -41,7 +41,6 @@ RimSurfaceResultDefinition::RimSurfaceResultDefinition() CAF_PDM_InitFieldNoDefault( &m_propertyName, "PropertyName", "Property Name" ); CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendConfig", "Legend" ); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); m_legendConfig.uiCapability()->setUiTreeChildrenHidden( false ); m_legendConfig = new RimRegularLegendConfig; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/CMakeLists_files.cmake b/ApplicationLibCode/ProjectDataModel/WellLog/CMakeLists_files.cmake index 1b2f2bbe05..f3030b156c 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/CMakeLists_files.cmake +++ b/ApplicationLibCode/ProjectDataModel/WellLog/CMakeLists_files.cmake @@ -19,6 +19,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RimWellLogLasCurve.h ${CMAKE_CURRENT_LIST_DIR}/RimWellLogExtractionCurve.h ${CMAKE_CURRENT_LIST_DIR}/RimWellLogLasFile.h + ${CMAKE_CURRENT_LIST_DIR}/RimWellLogCsvFile.h ${CMAKE_CURRENT_LIST_DIR}/RimWellLogFile.h ${CMAKE_CURRENT_LIST_DIR}/RimWellLogFileUtil.h ${CMAKE_CURRENT_LIST_DIR}/RimWellLogChannel.h @@ -38,6 +39,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RimWellLogCurve.cpp ${CMAKE_CURRENT_LIST_DIR}/RimWellLogExtractionCurve.cpp ${CMAKE_CURRENT_LIST_DIR}/RimWellLogLasFile.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimWellLogCsvFile.cpp ${CMAKE_CURRENT_LIST_DIR}/RimWellLogFile.cpp ${CMAKE_CURRENT_LIST_DIR}/RimWellLogFileUtil.cpp ${CMAKE_CURRENT_LIST_DIR}/RimWellLogFileChannel.cpp diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogExtractionCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogExtractionCurve.cpp index 9cb4580608..8bbf4755e3 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogExtractionCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogExtractionCurve.cpp @@ -74,13 +74,11 @@ Rim3dWellLogExtractionCurve::Rim3dWellLogExtractionCurve() CAF_PDM_InitField( &m_geomPartId, "GeomPartId", 0, "Part Id" ); CAF_PDM_InitFieldNoDefault( &m_eclipseResultDefinition, "CurveEclipseResult", "" ); - m_eclipseResultDefinition.uiCapability()->setUiTreeHidden( true ); m_eclipseResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_eclipseResultDefinition = new RimEclipseResultDefinition; m_eclipseResultDefinition->findField( "MResultType" )->uiCapability()->setUiName( "Result Type" ); CAF_PDM_InitFieldNoDefault( &m_geomResultDefinition, "CurveGeomechResult", "" ); - m_geomResultDefinition.uiCapability()->setUiTreeHidden( true ); m_geomResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_geomResultDefinition = new RimGeoMechResultDefinition; m_geomResultDefinition->setAddWellPathDerivedResults( true ); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.cpp index f143200c63..78673e7dd7 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.cpp @@ -25,6 +25,8 @@ #include "RimWellLogLasFileCurveNameConfig.h" #include "RimWellPath.h" +#include "RiaQDateTimeTools.h" + #include //================================================================================================== @@ -89,7 +91,7 @@ void Rim3dWellLogFileCurve::curveValuesAndMds( std::vector* values, std: if ( m_wellLogFile ) { - RigWellLogLasFile* wellLogFile = m_wellLogFile->wellLogFileData(); + RigWellLogFile* wellLogFile = m_wellLogFile->wellLogFileData(); if ( wellLogFile ) { *values = wellLogFile->values( m_wellLogChannelName ); @@ -135,7 +137,7 @@ QString Rim3dWellLogFileCurve::createAutoName() const channelNameAvailable = true; } - RigWellLogLasFile* wellLogFile = m_wellLogFile ? m_wellLogFile->wellLogFileData() : nullptr; + RigWellLogFile* wellLogFile = m_wellLogFile ? m_wellLogFile->wellLogFileData() : nullptr; if ( wellLogFile ) { @@ -153,10 +155,10 @@ QString Rim3dWellLogFileCurve::createAutoName() const } */ } - QString date = wellLogFile->date(); + QString date = m_wellLogFile->date().toString( RiaQDateTimeTools::dateFormatString() ); if ( !date.isEmpty() ) { - name.push_back( wellLogFile->date() ); + name.push_back( date ); } } @@ -223,7 +225,7 @@ QList Rim3dWellLogFileCurve::calculateValueOptions( cons if ( wellPath && !wellPath->wellLogFiles().empty() ) { - for ( RimWellLogLasFile* const wellLogFile : wellPath->wellLogFiles() ) + for ( RimWellLogFile* const wellLogFile : wellPath->wellLogFiles() ) { QFileInfo fileInfo( wellLogFile->fileName() ); options.push_back( caf::PdmOptionItemInfo( fileInfo.baseName(), wellLogFile ) ); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.h b/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.h index 838cf3c5f9..e4adbb1be6 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/Rim3dWellLogFileCurve.h @@ -24,7 +24,7 @@ #include "cafPdmField.h" #include "cafPdmPtrField.h" -class RimWellLogLasFile; +class RimWellLogFile; class RimWellLogLasFileCurveNameConfig; //================================================================================================== @@ -55,7 +55,7 @@ class Rim3dWellLogFileCurve : public Rim3dWellLogCurve void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; private: - caf::PdmPtrField m_wellLogFile; + caf::PdmPtrField m_wellLogFile; caf::PdmField m_wellLogChannelName; caf::PdmChildField m_nameConfig; }; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.cpp index 9bd9af99b6..38f891bd31 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.cpp @@ -118,7 +118,6 @@ RimEnsembleWellLogCurveSet::RimEnsembleWellLogCurveSet() CAF_PDM_InitFieldNoDefault( &m_statistics, "Statistics", "Statistics" ); m_statistics = new RimEnsembleStatistics( this ); - m_statistics.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_userDefinedName, "UserDefinedName", QString( "Ensemble Curve Set" ), "Curve Set Name" ); @@ -131,7 +130,6 @@ RimEnsembleWellLogCurveSet::RimEnsembleWellLogCurveSet() CAF_PDM_InitFieldNoDefault( &m_curveAppearance, "PlotCurveAppearance", "PlotCurveAppearance" ); m_curveAppearance = new RimPlotCurveAppearance; - m_curveAppearance.uiCapability()->setUiTreeHidden( true ); m_curveAppearance->setInterpolationVisible( false ); m_curveAppearance->setColorVisible( false ); m_curveAppearance->setFillOptionsVisible( false ); @@ -1021,7 +1019,7 @@ std::vector RimEnsembleWellLogCurveSet::filterEnsembleCases( //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool RimEnsembleWellLogCurveSet::isSameRealization( RimSummaryCase* summaryCase, RimWellLogLasFile* wellLogFile ) const +bool RimEnsembleWellLogCurveSet::isSameRealization( RimSummaryCase* summaryCase, RimWellLogFile* wellLogFile ) const { QString wellLogFileName = wellLogFile->fileName(); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.h index 3834101bb5..c8af6c95e4 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogCurveSet.h @@ -45,7 +45,7 @@ class RimEnsembleStatistics; class RimEnsembleStatisticsCase; class RimWellLogCurve; class RimWellLogLasFileCurve; -class RimWellLogLasFile; +class RimWellLogFile; class RimPlotCurveAppearance; class RigWellPathFormations; @@ -150,7 +150,7 @@ class RimEnsembleWellLogCurveSet : public caf::PdmObject, public RimEnsembleCurv void updateCurveColors(); - bool isSameRealization( RimSummaryCase* summaryCase, RimWellLogLasFile* wellLogFile ) const; + bool isSameRealization( RimSummaryCase* summaryCase, RimWellLogFile* wellLogFile ) const; RimSummaryCase* findMatchingSummaryCase( RimWellLogLasFileCurve* wellLogCurve ) const; void connectEnsembleCurveSetFilterSignals(); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogStatisticsCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogStatisticsCurve.cpp index 951a89a0a8..8b7969ecde 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogStatisticsCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogStatisticsCurve.cpp @@ -43,7 +43,6 @@ RimEnsembleWellLogStatisticsCurve::RimEnsembleWellLogStatisticsCurve() CAF_PDM_InitFieldNoDefault( &m_ensembleWellLogCurveSet, "EnsembleWellLogCurveSet", "Ensemble Well Log Curve Set" ); m_ensembleWellLogCurveSet.uiCapability()->setUiTreeChildrenHidden( true ); - m_ensembleWellLogCurveSet.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_statisticsType, "StatisticsType", "Statistics Type" ); m_statisticsType.uiCapability()->setUiHidden( true ); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogs.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogs.cpp index cc6e0e5cdb..b2c28471d9 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogs.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogs.cpp @@ -35,7 +35,6 @@ RimEnsembleWellLogs::RimEnsembleWellLogs() CAF_PDM_InitScriptableObject( "Ensemble Well Logs" ); CAF_PDM_InitFieldNoDefault( &m_wellLogFiles, "WellLogFiles", "" ); - m_wellLogFiles.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogsCollection.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogsCollection.cpp index 88eebd918a..c44197ff15 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogsCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimEnsembleWellLogsCollection.cpp @@ -32,7 +32,6 @@ RimEnsembleWellLogsCollection::RimEnsembleWellLogsCollection() CAF_PDM_InitObject( "Ensemble Well Logs", ":/LasFile16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_ensembleWellLogs, "EnsembleWellLogsCollection", "" ); - m_ensembleWellLogs.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.cpp index b88cfdb79b..b6ac8e17f7 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.cpp @@ -178,27 +178,48 @@ QList RimRftTools::segmentBranchIndexOptions( RifReaderR //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RimRftTools::seglenstValues( RifReaderRftInterface* readerRft, - const QString& wellName, - const QDateTime& dateTime, - int segmentBranchIndex, - RiaDefines::RftBranchType segmentBranchType ) +std::vector RimRftTools::segmentStartMdValues( RifReaderRftInterface* readerRft, + const QString& wellName, + const QDateTime& dateTime, + int segmentBranchIndex, + RiaDefines::RftBranchType segmentBranchType ) { - std::vector seglenstValues; + std::vector values; auto resultNameSeglenst = RifEclipseRftAddress::createBranchSegmentAddress( wellName, dateTime, RiaDefines::segmentStartDepthResultName(), segmentBranchIndex, segmentBranchType ); - readerRft->values( resultNameSeglenst, &seglenstValues ); + readerRft->values( resultNameSeglenst, &values ); - if ( seglenstValues.size() > 2 ) + if ( values.size() > 2 ) { // Segment 1 has zero length, assign seglenst to the start value of segment 2 // Ref mail dated June 10, 2022, topic "SELENST fix" - seglenstValues[0] = seglenstValues[1]; + values[0] = values[1]; } - return seglenstValues; + return values; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RimRftTools::segmentEndMdValues( RifReaderRftInterface* readerRft, + const QString& wellName, + const QDateTime& dateTime, + int segmentBranchIndex, + RiaDefines::RftBranchType segmentBranchType ) +{ + std::vector values; + + auto resultNameSeglenst = RifEclipseRftAddress::createBranchSegmentAddress( wellName, + dateTime, + RiaDefines::segmentEndDepthResultName(), + segmentBranchIndex, + segmentBranchType ); + readerRft->values( resultNameSeglenst, &values ); + + return values; } diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.h index c73e4474e2..acc7f79437 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTools.h @@ -46,9 +46,15 @@ class RimRftTools const QDateTime& timeStep, RiaDefines::RftBranchType branchType ); - static std::vector seglenstValues( RifReaderRftInterface* readerRft, - const QString& wellName, - const QDateTime& dateTime, - int segmentBranchIndex, - RiaDefines::RftBranchType segmentBranchType ); + static std::vector segmentStartMdValues( RifReaderRftInterface* readerRft, + const QString& wellName, + const QDateTime& dateTime, + int segmentBranchIndex, + RiaDefines::RftBranchType segmentBranchType ); + + static std::vector segmentEndMdValues( RifReaderRftInterface* readerRft, + const QString& wellName, + const QDateTime& dateTime, + int segmentBranchIndex, + RiaDefines::RftBranchType segmentBranchType ); }; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.cpp index 771eefbf2d..e0e638839b 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.cpp @@ -48,6 +48,15 @@ void caf::AppEnum::setUp() setDefault( RimRftTopologyCurve::CurveType::TUBING ); } +template <> +void caf::AppEnum::setUp() +{ + addItem( RimRftTopologyCurve::SymbolLocationType::START, "START", "Start" ); + addItem( RimRftTopologyCurve::SymbolLocationType::MID, "MID", "Midpoint" ); + addItem( RimRftTopologyCurve::SymbolLocationType::END, "END", "End" ); + + setDefault( RimRftTopologyCurve::SymbolLocationType::END ); +} } // End namespace caf @@ -68,6 +77,7 @@ RimRftTopologyCurve::RimRftTopologyCurve() CAF_PDM_InitFieldNoDefault( &m_segmentBranchType, "SegmentBranchType", "Completion" ); CAF_PDM_InitFieldNoDefault( &m_curveType, "CurveType", "Curve Type" ); + CAF_PDM_InitFieldNoDefault( &m_symbolLocation, "SymbolLocation", "Symbol Location on Segment" ); } //-------------------------------------------------------------------------------------------------- @@ -221,6 +231,7 @@ void RimRftTopologyCurve::defineUiOrdering( QString uiConfigName, caf::PdmUiOrde curveDataGroup->add( &m_wellName ); curveDataGroup->add( &m_timeStep ); curveDataGroup->add( &m_curveType ); + curveDataGroup->add( &m_symbolLocation ); curveDataGroup->add( &m_segmentBranchIndex ); curveDataGroup->add( &m_segmentBranchType ); @@ -289,8 +300,32 @@ void RimRftTopologyCurve::onLoadDataAndUpdate( bool updateParentPlot ) std::vector depths; std::vector propertyValues; - std::vector seglenstValues = - RimRftTools::seglenstValues( rftReader, m_wellName, m_timeStep, -1, RiaDefines::RftBranchType::RFT_UNKNOWN ); + std::vector symbolLocationDepths; + if ( m_symbolLocation() == SymbolLocationType::START ) + { + symbolLocationDepths = + RimRftTools::segmentStartMdValues( rftReader, m_wellName, m_timeStep, -1, RiaDefines::RftBranchType::RFT_UNKNOWN ); + } + else if ( m_symbolLocation() == SymbolLocationType::MID ) + { + symbolLocationDepths = + RimRftTools::segmentStartMdValues( rftReader, m_wellName, m_timeStep, -1, RiaDefines::RftBranchType::RFT_UNKNOWN ); + auto endDepths = + RimRftTools::segmentEndMdValues( rftReader, m_wellName, m_timeStep, -1, RiaDefines::RftBranchType::RFT_UNKNOWN ); + + if ( symbolLocationDepths.size() == endDepths.size() ) + { + for ( size_t i = 0; i < symbolLocationDepths.size(); ++i ) + { + symbolLocationDepths[i] = ( symbolLocationDepths[i] + endDepths[i] ) / 2.0; + } + } + } + else if ( m_symbolLocation() == SymbolLocationType::END ) + { + symbolLocationDepths = + RimRftTools::segmentEndMdValues( rftReader, m_wellName, m_timeStep, -1, RiaDefines::RftBranchType::RFT_UNKNOWN ); + } auto segment = rftReader->segmentForWell( m_wellName, m_timeStep ); auto segmentIndices = segment.segmentIndicesForBranchIndex( m_segmentBranchIndex(), m_segmentBranchType() ); @@ -317,7 +352,7 @@ void RimRftTopologyCurve::onLoadDataAndUpdate( bool updateParentPlot ) for ( auto segmentIndex : packerSegmentIndices ) { - depths.push_back( seglenstValues[segmentIndex] ); + depths.push_back( symbolLocationDepths[segmentIndex] ); propertyValues.push_back( curveValue ); } @@ -326,7 +361,7 @@ void RimRftTopologyCurve::onLoadDataAndUpdate( bool updateParentPlot ) { for ( auto segmentIndex : segmentIndices ) { - depths.push_back( seglenstValues[segmentIndex] ); + depths.push_back( symbolLocationDepths[segmentIndex] ); propertyValues.push_back( curveValue ); } diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.h index 449d7daeca..893e9c7abf 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimRftTopologyCurve.h @@ -44,6 +44,13 @@ class RimRftTopologyCurve : public RimWellLogCurve ANNULUS }; + enum class SymbolLocationType + { + START, + MID, + END + }; + public: RimRftTopologyCurve(); @@ -77,12 +84,13 @@ class RimRftTopologyCurve : public RimWellLogCurve void onLoadDataAndUpdate( bool updateParentPlot ) override; private: - caf::PdmPtrField m_summaryCase; - caf::PdmField m_timeStep; - caf::PdmField m_wellName; - caf::PdmField m_segmentBranchIndex; - caf::PdmField> m_segmentBranchType; - caf::PdmField> m_curveType; + caf::PdmPtrField m_summaryCase; + caf::PdmField m_timeStep; + caf::PdmField m_wellName; + caf::PdmField m_segmentBranchIndex; + caf::PdmField> m_segmentBranchType; + caf::PdmField> m_curveType; + caf::PdmField> m_symbolLocation; public: void setAdditionalDataSources( const std::vector& additionalDataSources ); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCsvFile.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCsvFile.cpp new file mode 100644 index 0000000000..cc71b7b498 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCsvFile.cpp @@ -0,0 +1,150 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RimWellLogCsvFile.h" + +#include "RiaFieldHandleTools.h" +#include "RiaLogging.h" + +#include "RigWellLogCsvFile.h" + +#include "RimFileWellPath.h" +#include "RimTools.h" +#include "RimWellLogFileChannel.h" + +#include +#include +#include + +CAF_PDM_SOURCE_INIT( RimWellLogCsvFile, "WellLogCsvFile" ); + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimWellLogCsvFile::RimWellLogCsvFile() +{ + CAF_PDM_InitObject( "Well CSV File Info", ":/LasFile16x16.png" ); + + CAF_PDM_InitFieldNoDefault( &m_wellName, "WellName", "" ); + m_wellName.uiCapability()->setUiReadOnly( true ); + RiaFieldHandleTools::disableWriteAndSetFieldHidden( &m_wellName ); + + CAF_PDM_InitFieldNoDefault( &m_name, "Name", "" ); + m_name.uiCapability()->setUiReadOnly( true ); + RiaFieldHandleTools::disableWriteAndSetFieldHidden( &m_name ); + + m_wellLogDataFile = nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimWellLogCsvFile::~RimWellLogCsvFile() +{ + m_wellLogChannelNames.deleteChildren(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RimWellLogCsvFile::readFile( QString* errorMessage ) +{ + if ( !m_wellLogDataFile.p() ) + { + m_wellLogDataFile = new RigWellLogCsvFile; + } + + m_name = QFileInfo( m_fileName().path() ).fileName(); + + auto wellPath = firstAncestorOrThisOfType(); + if ( !wellPath ) + { + RiaLogging::error( "No well path found" ); + return false; + } + + if ( !m_wellLogDataFile->open( m_fileName().path(), wellPath->wellPathGeometry(), errorMessage ) ) + { + m_wellLogDataFile = nullptr; + RiaLogging::error( "Failed to open file." ); + + return false; + } + + m_wellLogChannelNames.deleteChildren(); + + QStringList wellLogNames = m_wellLogDataFile->wellLogChannelNames(); + for ( int logIdx = 0; logIdx < wellLogNames.size(); logIdx++ ) + { + RimWellLogFileChannel* wellLog = new RimWellLogFileChannel(); + wellLog->setName( wellLogNames[logIdx] ); + m_wellLogChannelNames.push_back( wellLog ); + } + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RimWellLogCsvFile::wellName() const +{ + return m_wellName; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector> RimWellLogCsvFile::findMdAndChannelValuesForWellPath( const RimWellPath& wellPath, + const QString& channelName, + QString* unitString /*=nullptr*/ ) +{ + std::vector wellLogFiles = wellPath.descendantsIncludingThisOfType(); + for ( RimWellLogCsvFile* wellLogFile : wellLogFiles ) + { + RigWellLogCsvFile* fileData = wellLogFile->wellLogFileData(); + if ( fileData ) + { + std::vector channelValues = fileData->values( channelName ); + if ( !channelValues.empty() ) + { + if ( unitString ) + { + *unitString = fileData->wellLogChannelUnitString( channelName ); + } + std::vector depthValues = fileData->depthValues(); + CVF_ASSERT( depthValues.size() == channelValues.size() ); + std::vector> depthValuePairs; + for ( size_t i = 0; i < depthValues.size(); ++i ) + { + depthValuePairs.push_back( std::make_pair( depthValues[i], channelValues[i] ) ); + } + return depthValuePairs; + } + } + } + return std::vector>(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWellLogCsvFile* RimWellLogCsvFile::wellLogFileData() +{ + return m_wellLogDataFile.p(); +} diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCsvFile.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCsvFile.h new file mode 100644 index 0000000000..c67a0b4058 --- /dev/null +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCsvFile.h @@ -0,0 +1,64 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2015- Statoil ASA +// Copyright (C) 2015- Ceetron Solutions AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RimWellLogFile.h" + +#include "RigWellLogCsvFile.h" + +#include "cafPdmField.h" +#include "cafPdmObject.h" + +#include +#include + +class RimWellPath; + +//================================================================================================== +/// +/// +//================================================================================================== +class RimWellLogCsvFile : public RimWellLogFile +{ + CAF_PDM_HEADER_INIT; + +public: + RimWellLogCsvFile(); + ~RimWellLogCsvFile() override; + + QString name() const override { return m_name; } + + bool readFile( QString* errorMessage ) override; + + QString wellName() const override; + + RigWellLogCsvFile* wellLogFileData() override; + + std::vector> + findMdAndChannelValuesForWellPath( const RimWellPath& wellPath, const QString& channelName, QString* unitString = nullptr ) override; + +private: + caf::PdmFieldHandle* userDescriptionField() override { return &m_name; } + +private: + cvf::ref m_wellLogDataFile; + caf::PdmField m_wellName; + caf::PdmField m_name; +}; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.cpp index 11c7d2757f..8cfc90978c 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.cpp @@ -527,7 +527,7 @@ void RimWellLogCurveCommonDataSource::applyDataSourceChanges( const std::vector< fileCurve->setWellPath( wellPathToApply() ); if ( !fileCurve->wellLogChannelUiName().isEmpty() ) { - RimWellLogLasFile* logFile = wellPathToApply()->firstWellLogFileMatchingChannelName( fileCurve->wellLogChannelUiName() ); + RimWellLogFile* logFile = wellPathToApply()->firstWellLogFileMatchingChannelName( fileCurve->wellLogChannelUiName() ); fileCurve->setWellLogFile( logFile ); auto parentPlot = fileCurve->firstAncestorOrThisOfTypeAsserted(); plots.insert( parentPlot ); diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.h index fe7c9fd36b..d5bc0d0191 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogCurveCommonDataSource.h @@ -24,7 +24,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmPtrField.h" -#include "cafPdmUiOrdering.h" #include "cafTristate.h" #include diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogExtractionCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogExtractionCurve.cpp index 471553c879..67d6bb34c5 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogExtractionCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogExtractionCurve.cpp @@ -122,13 +122,11 @@ RimWellLogExtractionCurve::RimWellLogExtractionCurve() m_case.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_eclipseResultDefinition, "CurveEclipseResult", "" ); - m_eclipseResultDefinition.uiCapability()->setUiTreeHidden( true ); m_eclipseResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_eclipseResultDefinition = new RimEclipseResultDefinition; m_eclipseResultDefinition->findField( "MResultType" )->uiCapability()->setUiName( "Result Type" ); CAF_PDM_InitFieldNoDefault( &m_geomResultDefinition, "CurveGeomechResult", "" ); - m_geomResultDefinition.uiCapability()->setUiTreeHidden( true ); m_geomResultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_geomResultDefinition = new RimGeoMechResultDefinition; m_geomResultDefinition->setAddWellPathDerivedResults( true ); @@ -885,12 +883,10 @@ void RimWellLogExtractionCurve::findAndLoadWbsParametersFromFiles( const RimWell else { QString errMsg = - QString( "Could not convert units of LAS-channel %1 from %2 to %3" ).arg( lasAddress ).arg( lasUnits ).arg( extractorUnits ); + QString( "Could not convert units of LAS-channel '%1' from '%2' to '%3'" ).arg( lasAddress ).arg( lasUnits ).arg( extractorUnits ); RiaLogging::error( errMsg ); } } - - // csv } } diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.cpp index a84520b0ed..c863c37bce 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.cpp @@ -23,11 +23,19 @@ #include "RimWellLogFileChannel.h" #include "RiaFieldHandleTools.h" +#include "RiaQDateTimeTools.h" + +#include "cafPdmUiDateEditor.h" #include CAF_PDM_ABSTRACT_SOURCE_INIT( RimWellLogFile, "WellLogFileInterface" ); +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +const QDateTime RimWellLogFile::DEFAULT_DATE_TIME = RiaQDateTimeTools::createUtcDateTime( QDate( 1900, 1, 1 ) ); + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -38,6 +46,8 @@ RimWellLogFile::RimWellLogFile() CAF_PDM_InitFieldNoDefault( &m_fileName, "FileName", "Filename" ); m_fileName.uiCapability()->setUiReadOnly( true ); + CAF_PDM_InitFieldNoDefault( &m_date, "Date", "Date" ); + CAF_PDM_InitFieldNoDefault( &m_wellLogChannelNames, "WellLogFileChannels", "" ); RiaFieldHandleTools::disableWriteAndSetFieldHidden( &m_wellLogChannelNames ); } @@ -78,3 +88,33 @@ std::vector RimWellLogFile::wellLogChannels() const } return channels; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QDateTime RimWellLogFile::date() const +{ + return m_date; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimWellLogFile::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) +{ + if ( changedField == &m_date ) + { + // Due to a possible bug in QDateEdit/PdmUiDateEditor, convert m_date to a QDateTime having UTC timespec + m_date = RiaQDateTimeTools::createUtcDateTime( m_date().date(), m_date().time() ); + } +} +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimWellLogFile::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) +{ + if ( caf::PdmUiDateEditorAttribute* attrib = dynamic_cast( attribute ) ) + { + attrib->dateFormat = RiaQDateTimeTools::dateFormatString(); + } +} diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.h index 3c38d5afda..399cf23367 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogFile.h @@ -22,11 +22,14 @@ #include "cafPdmField.h" #include "cafPdmObject.h" +#include #include class RimWellLogFileChannel; class RimWellPath; +class RigWellLogFile; + //================================================================================================== /// /// @@ -43,10 +46,23 @@ class RimWellLogFile : public caf::PdmObject virtual QString fileName() const; virtual std::vector wellLogChannels() const; + virtual QString wellName() const = 0; + virtual QString name() const = 0; + virtual bool readFile( QString* errorMessage ) = 0; + virtual RigWellLogFile* wellLogFileData() = 0; + + virtual QDateTime date() const; + virtual std::vector> findMdAndChannelValuesForWellPath( const RimWellPath& wellPath, const QString& channelName, QString* unitString = nullptr ) = 0; + const static QDateTime DEFAULT_DATE_TIME; + protected: + void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; + void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; + caf::PdmChildArrayField m_wellLogChannelNames; caf::PdmField m_fileName; + caf::PdmField m_date; }; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.cpp index 964aadc33e..45ccea42ee 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.cpp @@ -36,8 +36,6 @@ #include "Riu3DMainWindowTools.h" -#include "cafPdmUiDateEditor.h" - #include #include #include @@ -54,11 +52,6 @@ void caf::AppEnum::setUp() } } // namespace caf -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -const QDateTime RimWellLogLasFile::DEFAULT_DATE_TIME = RiaQDateTimeTools::createUtcDateTime( QDate( 1900, 1, 1 ) ); - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -70,13 +63,12 @@ RimWellLogLasFile::RimWellLogLasFile() m_wellName.uiCapability()->setUiReadOnly( true ); RiaFieldHandleTools::disableWriteAndSetFieldHidden( &m_wellName ); - CAF_PDM_InitFieldNoDefault( &m_date, "Date", "Date" ); - m_date.uiCapability()->setUiReadOnly( true ); - CAF_PDM_InitFieldNoDefault( &m_name, "Name", "" ); m_name.uiCapability()->setUiReadOnly( true ); RiaFieldHandleTools::disableWriteAndSetFieldHidden( &m_name ); + m_date.uiCapability()->setUiReadOnly( true ); + CAF_PDM_InitField( &m_wellFlowCondition, "WellFlowCondition", caf::AppEnum( RimWellLogLasFile::WELL_FLOW_COND_STANDARD ), @@ -188,14 +180,6 @@ QString RimWellLogLasFile::wellName() const return m_wellName; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QDateTime RimWellLogLasFile::date() const -{ - return m_date; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -265,30 +249,6 @@ void RimWellLogLasFile::defineUiOrdering( QString uiConfigName, caf::PdmUiOrderi uiOrdering.skipRemainingFields( true ); } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimWellLogLasFile::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) -{ - if ( changedField == &m_date ) - { - // Due to a possible bug in QDateEdit/PdmUiDateEditor, convert m_date to a QDateTime having UTC timespec - m_date = RiaQDateTimeTools::createUtcDateTime( m_date().date(), m_date().time() ); - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RimWellLogLasFile::defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) -{ - caf::PdmUiDateEditorAttribute* attrib = dynamic_cast( attribute ); - if ( attrib != nullptr ) - { - attrib->dateFormat = RiaQDateTimeTools::dateFormatString(); - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.h index f2d8f1c9a6..cc34eb4499 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFile.h @@ -42,22 +42,19 @@ class RimWellLogLasFile : public RimWellLogFile { CAF_PDM_HEADER_INIT; - const static QDateTime DEFAULT_DATE_TIME; - public: RimWellLogLasFile(); ~RimWellLogLasFile() override; static RimWellLogLasFile* readWellLogFile( const QString& logFilePath, QString* errorMessage ); - QString name() const { return m_name; } + QString name() const override { return m_name; } - bool readFile( QString* errorMessage ); + bool readFile( QString* errorMessage ) override; - QString wellName() const; - QDateTime date() const; + QString wellName() const override; - RigWellLogLasFile* wellLogFileData() { return m_wellLogDataFile.p(); } + RigWellLogLasFile* wellLogFileData() override { return m_wellLogDataFile.p(); } bool hasFlowData() const; @@ -75,8 +72,6 @@ class RimWellLogLasFile : public RimWellLogFile private: void setupBeforeSave() override; void defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) override; - void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) override; - void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; caf::PdmFieldHandle* userDescriptionField() override { return &m_name; } @@ -86,7 +81,6 @@ class RimWellLogLasFile : public RimWellLogFile cvf::ref m_wellLogDataFile; caf::PdmField m_wellName; caf::PdmField m_name; - caf::PdmField m_date; bool m_lasFileHasValidDate; caf::PdmField> m_wellFlowCondition; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.cpp index 99eed65c98..4f857a210e 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.cpp @@ -22,6 +22,7 @@ #include "RiaLogging.h" #include "RiaPreferences.h" +#include "RiaQDateTimeTools.h" #include "RiaResultNames.h" #include "RigWellLogCurveData.h" #include "RigWellLogIndexDepthOffset.h" @@ -84,7 +85,7 @@ void RimWellLogLasFileCurve::onLoadDataAndUpdate( bool updateParentPlot ) if ( m_wellPath && m_wellLogFile ) { - RigWellLogLasFile* wellLogFile = m_wellLogFile->wellLogFileData(); + RigWellLogFile* wellLogFile = m_wellLogFile->wellLogFileData(); if ( wellLogFile ) { std::vector values = wellLogFile->values( m_wellLogChannelName ); @@ -286,7 +287,7 @@ void RimWellLogLasFileCurve::setWellLogChannelName( const QString& name ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimWellLogLasFileCurve::setWellLogFile( RimWellLogLasFile* wellLogFile ) +void RimWellLogLasFileCurve::setWellLogFile( RimWellLogFile* wellLogFile ) { m_wellLogFile = wellLogFile; } @@ -401,7 +402,7 @@ QList RimWellLogLasFileCurve::calculateValueOptions( con { if ( m_wellPath() && !m_wellPath->wellLogFiles().empty() ) { - for ( RimWellLogLasFile* const wellLogFile : m_wellPath->wellLogFiles() ) + for ( RimWellLogFile* const wellLogFile : m_wellPath->wellLogFiles() ) { QFileInfo fileInfo( wellLogFile->fileName() ); options.push_back( caf::PdmOptionItemInfo( fileInfo.baseName(), wellLogFile ) ); @@ -423,7 +424,7 @@ void RimWellLogLasFileCurve::initAfterRead() if ( m_wellPath->wellLogFiles().size() == 1 ) { - m_wellLogFile = m_wellPath->wellLogFiles().front(); + m_wellLogFile = dynamic_cast( m_wellPath->wellLogFiles().front() ); } } @@ -456,14 +457,14 @@ QString RimWellLogLasFileCurve::createCurveAutoName() channelNameAvailable = true; } - RigWellLogLasFile* wellLogFile = m_wellLogFile ? m_wellLogFile->wellLogFileData() : nullptr; + RigWellLogFile* wellLogFile = m_wellLogFile ? m_wellLogFile->wellLogFileData() : nullptr; if ( wellLogFile ) { if ( channelNameAvailable ) { auto wellLogPlot = firstAncestorOrThisOfTypeAsserted(); - QString unitName = wellLogFile->wellLogChannelUnitString( m_wellLogChannelName, wellLogPlot->depthUnit() ); + QString unitName = wellLogFile->convertedWellLogChannelUnitString( m_wellLogChannelName, wellLogPlot->depthUnit() ); if ( !unitName.isEmpty() ) { @@ -471,10 +472,10 @@ QString RimWellLogLasFileCurve::createCurveAutoName() } } - QString date = wellLogFile->date(); + QString date = m_wellLogFile->date().toString( RiaQDateTimeTools::dateFormatString() ); if ( !date.isEmpty() ) { - name.push_back( wellLogFile->date() ); + name.push_back( date ); } } @@ -507,7 +508,7 @@ QString RimWellLogLasFileCurve::wellLogChannelUnits() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimWellLogLasFile* RimWellLogLasFileCurve::wellLogFile() const +RimWellLogFile* RimWellLogLasFileCurve::wellLogFile() const { return m_wellLogFile(); } diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.h b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.h index 37c3531cac..12c8bca896 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.h +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogLasFileCurve.h @@ -28,7 +28,7 @@ class RimWellPath; class RimWellLogFileChannel; -class RimWellLogLasFile; +class RimWellLogFile; class RigWellLogIndexDepthOffset; //================================================================================================== @@ -46,7 +46,7 @@ class RimWellLogLasFileCurve : public RimWellLogCurve void setWellPath( RimWellPath* wellPath ); RimWellPath* wellPath() const; void setWellLogChannelName( const QString& name ); - void setWellLogFile( RimWellLogLasFile* wellLogFile ); + void setWellLogFile( RimWellLogFile* wellLogFile ); void setIndexDepthOffsets( std::shared_ptr depthOffsets ); // Overrides from RimWellLogPlotCurve @@ -54,7 +54,7 @@ class RimWellLogLasFileCurve : public RimWellLogCurve QString wellLogChannelUiName() const override; QString wellLogChannelUnits() const override; - RimWellLogLasFile* wellLogFile() const; + RimWellLogFile* wellLogFile() const; protected: // Overrides from RimWellLogPlotCurve @@ -75,10 +75,10 @@ class RimWellLogLasFileCurve : public RimWellLogCurve const std::vector& kIndexValues ) const; protected: - caf::PdmPtrField m_wellPath; - caf::PdmPtrField m_wellLogFile; - caf::PdmField m_wellLogChannelName; - caf::PdmField m_wellLogChannnelUnit; + caf::PdmPtrField m_wellPath; + caf::PdmPtrField m_wellLogFile; + caf::PdmField m_wellLogChannelName; + caf::PdmField m_wellLogChannnelUnit; std::shared_ptr m_indexDepthOffsets; }; diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogPlotCollection.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogPlotCollection.cpp index 4a53fcac87..0be0394586 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogPlotCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogPlotCollection.cpp @@ -49,7 +49,6 @@ RimWellLogPlotCollection::RimWellLogPlotCollection() CAF_PDM_InitScriptableObject( "Well Log Plots", ":/WellLogPlots16x16.png" ); CAF_PDM_InitScriptableFieldNoDefault( &m_wellLogPlots, "WellLogPlots", "" ); - m_wellLogPlots.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogRftCurve.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogRftCurve.cpp index 6b01a74ac3..3ed71e357f 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogRftCurve.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogRftCurve.cpp @@ -1152,7 +1152,8 @@ std::vector RimWellLogRftCurve::measuredDepthValues( QString& prefixText { prefixText = "SEGMENT/"; - return RimRftTools::seglenstValues( reader, m_wellName(), m_timeStep, segmentBranchIndex(), m_segmentBranchType() ); + // Always use segment end MD values for segment data, as the curve is plotted as step left + return RimRftTools::segmentEndMdValues( reader, m_wellName(), m_timeStep, segmentBranchIndex(), m_segmentBranchType() ); } return {}; } diff --git a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogTrack.cpp b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogTrack.cpp index 3f344e78f2..dbac5651a0 100644 --- a/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogTrack.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellLog/RimWellLogTrack.cpp @@ -186,7 +186,6 @@ RimWellLogTrack::RimWellLogTrack() CAF_PDM_InitFieldNoDefault( &m_description, "TrackDescription", "Name" ); CAF_PDM_InitFieldNoDefault( &m_curves, "Curves", "Curves" ); - m_curves.uiCapability()->setUiTreeHidden( true ); auto reorderability = caf::PdmFieldReorderCapability::addToField( &m_curves ); reorderability->orderChanged.connect( this, &RimWellLogTrack::curveDataChanged ); @@ -278,12 +277,10 @@ RimWellLogTrack::RimWellLogTrack() m_underburdenHeight.uiCapability()->setUiHidden( true ); CAF_PDM_InitFieldNoDefault( &m_resultDefinition, "ResultDefinition", "Result Definition" ); - m_resultDefinition.uiCapability()->setUiTreeHidden( true ); m_resultDefinition.uiCapability()->setUiTreeChildrenHidden( true ); m_resultDefinition = new RimEclipseResultDefinition; CAF_PDM_InitFieldNoDefault( &m_ensembleWellLogCurveSet, "EnsembleWellLogCurveSet", "Ensemble Well Logs Curve Set" ); - m_ensembleWellLogCurveSet.uiCapability()->setUiTreeHidden( true ); m_formationsForCaseWithSimWellOnly = false; } @@ -377,7 +374,6 @@ void RimWellLogTrack::calculatePropertyValueZoomRange() double maxValue = -HUGE_VAL; size_t topologyCurveCount = 0; - size_t visibleCurves = 0u; for ( const auto& curve : m_curves ) { double minCurveValue = HUGE_VAL; @@ -385,7 +381,6 @@ void RimWellLogTrack::calculatePropertyValueZoomRange() if ( curve->isChecked() ) { - visibleCurves++; if ( curve->propertyValueRangeInData( &minCurveValue, &maxCurveValue ) ) { if ( minCurveValue < minValue ) diff --git a/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementCollection.cpp b/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementCollection.cpp index eafb20925b..f4bb1b8f01 100644 --- a/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementCollection.cpp @@ -42,10 +42,8 @@ RimWellMeasurementCollection::RimWellMeasurementCollection() CAF_PDM_InitFieldNoDefault( &m_measurements, "Measurements", "Well Measurements" ); m_measurements.uiCapability()->setUiEditorTypeName( caf::PdmUiTableViewEditor::uiEditorTypeName() ); m_measurements.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); - m_measurements.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_importedFiles, "ImportedFiles", "Imported Files" ); - m_importedFiles.uiCapability()->setUiTreeHidden( true ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInView.cpp b/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInView.cpp index 335eaee716..7fd5069663 100644 --- a/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInView.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInView.cpp @@ -55,7 +55,6 @@ RimWellMeasurementInView::RimWellMeasurementInView() CAF_PDM_InitFieldNoDefault( &m_legendConfig, "LegendDefinition", "Color Legend" ); m_legendConfig = new RimRegularLegendConfig(); - m_legendConfig.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wells, "Wells", "Wells" ); m_wells.uiCapability()->setAutoAddingOptionFromValue( false ); diff --git a/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInViewCollection.cpp b/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInViewCollection.cpp index 99f7cf8be3..22763be91e 100644 --- a/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInViewCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellMeasurement/RimWellMeasurementInViewCollection.cpp @@ -49,7 +49,6 @@ RimWellMeasurementInViewCollection::RimWellMeasurementInViewCollection() CAF_PDM_InitObject( "Well Measurements", ":/WellMeasurement16x16.png" ); CAF_PDM_InitFieldNoDefault( &m_measurementsInView, "MeasurementKinds", "Measurement Kinds" ); - m_measurementsInView.uiCapability()->setUiTreeHidden( true ); m_isChecked = false; diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIADataAccess.cpp b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIADataAccess.cpp index c2bcf99ee3..5a2060c417 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIADataAccess.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIADataAccess.cpp @@ -71,8 +71,7 @@ int RimWellIADataAccess::elementIndex( cvf::Vec3d position ) auto part = m_caseData->femParts()->part( 0 ); - std::vector closeElements; - part->findIntersectingElementIndices( bb, &closeElements ); + std::vector closeElements = part->findIntersectingElementIndices( bb ); if ( closeElements.empty() ) return -1; for ( auto elmIdx : closeElements ) diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIASettingsCollection.cpp b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIASettingsCollection.cpp index cba7d9e25d..b20e620e8d 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIASettingsCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellIASettingsCollection.cpp @@ -42,7 +42,6 @@ RimWellIASettingsCollection::RimWellIASettingsCollection() CAF_PDM_InitFieldNoDefault( &m_wellIASettings, "WellIASettings", "Settings" ); m_wellIASettings.uiCapability()->setUiHidden( true ); - m_wellIASettings.uiCapability()->setUiTreeHidden( true ); setDeletable( true ); } diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.cpp b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.cpp index 049a8e56d2..19afdd1bcf 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.cpp @@ -127,17 +127,14 @@ RimWellPath::RimWellPath() CAF_PDM_InitScriptableFieldNoDefault( &m_completions, "Completions", "Completions" ); m_completions = new RimWellPathCompletions; - m_completions.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitScriptableFieldNoDefault( &m_completionSettings, "CompletionSettings", "Completion Settings" ); m_completionSettings = new RimWellPathCompletionSettings; CAF_PDM_InitFieldNoDefault( &m_wellLogFiles, "WellLogFiles", "Well Log Files" ); - m_wellLogFiles.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_3dWellLogCurves, "CollectionOf3dWellLogCurves", "3D Track" ); m_3dWellLogCurves = new Rim3dWellLogCurveCollection; - m_3dWellLogCurves.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitField( &m_formationKeyInFile, "WellPathFormationKeyInFile", QString( "" ), "Key in File" ); m_formationKeyInFile.uiCapability()->setUiReadOnly( true ); @@ -578,18 +575,18 @@ void RimWellPath::setNameNoUpdateOfExportName( const QString& name ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RimWellPath::wellLogFiles() const +std::vector RimWellPath::wellLogFiles() const { - return std::vector( m_wellLogFiles.begin(), m_wellLogFiles.end() ); + return std::vector( m_wellLogFiles.begin(), m_wellLogFiles.end() ); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RimWellLogLasFile* RimWellPath::firstWellLogFileMatchingChannelName( const QString& channelName ) const +RimWellLogFile* RimWellPath::firstWellLogFileMatchingChannelName( const QString& channelName ) const { - std::vector allWellLogFiles = wellLogFiles(); - for ( RimWellLogLasFile* logFile : allWellLogFiles ) + std::vector allWellLogFiles = wellLogFiles(); + for ( RimWellLogFile* logFile : allWellLogFiles ) { std::vector channels = logFile->wellLogChannels(); for ( RimWellLogFileChannel* channel : channels ) @@ -895,12 +892,12 @@ double RimWellPath::datumElevation() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimWellPath::addWellLogFile( RimWellLogLasFile* logFileInfo ) +void RimWellPath::addWellLogFile( RimWellLogFile* logFileInfo ) { // Prevent the same file from being loaded more than once auto itr = std::find_if( m_wellLogFiles.begin(), m_wellLogFiles.end(), - [&]( const RimWellLogLasFile* file ) + [&]( const RimWellLogFile* file ) { return QString::compare( file->fileName(), logFileInfo->fileName(), Qt::CaseInsensitive ) == 0; } ); // Todo: Verify well name to ensure all well log files having the same well name @@ -919,7 +916,7 @@ void RimWellPath::addWellLogFile( RimWellLogLasFile* logFileInfo ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimWellPath::deleteWellLogFile( RimWellLogLasFile* logFileInfo ) +void RimWellPath::deleteWellLogFile( RimWellLogFile* logFileInfo ) { detachWellLogFile( logFileInfo ); delete logFileInfo; @@ -928,7 +925,7 @@ void RimWellPath::deleteWellLogFile( RimWellLogLasFile* logFileInfo ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RimWellPath::detachWellLogFile( RimWellLogLasFile* logFileInfo ) +void RimWellPath::detachWellLogFile( RimWellLogFile* logFileInfo ) { auto pdmObject = dynamic_cast( logFileInfo ); for ( size_t i = 0; i < m_wellLogFiles.size(); i++ ) diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.h b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.h index a19f02eedc..8bf83163cf 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.h +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPath.h @@ -47,7 +47,7 @@ class RigWellPath; class RigWellPathFormations; class RimProject; -class RimWellLogLasFile; +class RimWellLogFile; class RimFractureTemplateCollection; class RimStimPlanModelCollection; class RimFishbonesCollection; @@ -61,6 +61,7 @@ class Rim3dWellLogCurveCollection; class RimWellPathTieIn; class RimMswCompletionParameters; class RimWellIASettingsCollection; +class RimWellLogFile; //================================================================================================== /// @@ -104,11 +105,11 @@ class RimWellPath : public caf::PdmObject, public RimWellPathComponentInterface double uniqueStartMD() const; double uniqueEndMD() const; - void addWellLogFile( RimWellLogLasFile* logFileInfo ); - void deleteWellLogFile( RimWellLogLasFile* logFileInfo ); - void detachWellLogFile( RimWellLogLasFile* logFileInfo ); - std::vector wellLogFiles() const; - RimWellLogLasFile* firstWellLogFileMatchingChannelName( const QString& channelName ) const; + void addWellLogFile( RimWellLogFile* logFileInfo ); + void deleteWellLogFile( RimWellLogFile* logFileInfo ); + void detachWellLogFile( RimWellLogFile* logFileInfo ); + std::vector wellLogFiles() const; + RimWellLogFile* firstWellLogFileMatchingChannelName( const QString& channelName ) const; void setFormationsGeometry( cvf::ref wellPathFormations ); bool readWellPathFormationsFile( QString* errorMessage, RifWellPathFormationsImporter* wellPathFormationsImporter ); @@ -169,7 +170,7 @@ class RimWellPath : public caf::PdmObject, public RimWellPathComponentInterface std::vector wellPathLaterals() const; RimWellPathTieIn* wellPathTieIn() const; - void connectWellPaths( RimWellPath* childWell, double tieInMeasuredDepth ); + void connectWellPaths( RimWellPath* parentWell, double tieInMeasuredDepth ); protected: // Override PdmObject @@ -209,7 +210,7 @@ class RimWellPath : public caf::PdmObject, public RimWellPathComponentInterface caf::PdmField m_wellPathRadiusScaleFactor; caf::PdmField m_wellPathColor; - caf::PdmChildArrayField m_wellLogFiles; + caf::PdmChildArrayField m_wellLogFiles; caf::PdmChildField m_3dWellLogCurves; caf::PdmChildField m_completionSettings; caf::PdmChildField m_completions; diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.cpp b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.cpp index 574cfb2ebc..e258825897 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.cpp @@ -107,12 +107,10 @@ RimWellPathCollection::RimWellPathCollection() CAF_PDM_InitField( &wellPathClipZDistance, "WellPathClipZDistance", 100, "Well Path Clipping Depth Distance" ); CAF_PDM_InitScriptableFieldNoDefault( &m_wellPaths, "WellPaths", "Well Paths" ); - m_wellPaths.uiCapability()->setUiTreeHidden( true ); m_wellPaths.uiCapability()->setUiTreeChildrenHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wellMeasurements, "WellMeasurements", "Measurements" ); m_wellMeasurements = new RimWellMeasurementCollection; - m_wellMeasurements.uiCapability()->setUiTreeHidden( true ); CAF_PDM_InitFieldNoDefault( &m_wellPathNodes, "WellPathNodes", "Well Path Nodes" ); m_wellPathNodes.xmlCapability()->disableIO(); @@ -169,7 +167,7 @@ void RimWellPathCollection::loadDataAndUpdate() if ( wellPath ) { - for ( RimWellLogLasFile* const wellLogFile : wellPath->wellLogFiles() ) + for ( RimWellLogFile* const wellLogFile : wellPath->wellLogFiles() ) { if ( wellLogFile ) { @@ -386,6 +384,16 @@ std::vector RimWellPathCollection::addWellLogs( const QStrin return logFileInfos; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RimWellPathCollection::addWellLog( RimWellLogFile* wellLogFile, RimWellPath* wellPath ) +{ + wellPath->addWellLogFile( wellLogFile ); + sortWellsByName(); + updateAllRequiredEditors(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.h b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.h index c102be81bc..db57a69225 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.h +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathCollection.h @@ -44,6 +44,7 @@ class RimFileWellPath; class RimEclipseView; class RimProject; class RimWellLogLasFile; +class RimWellLogFile; class RimWellPath; class RifWellPathFormationsImporter; class RimWellMeasurementCollection; @@ -116,6 +117,7 @@ class RimWellPathCollection : public caf::PdmObject std::vector addWellLogs( const QStringList& filePaths, QStringList* errorMessages ); void addWellPathFormations( const QStringList& filePaths ); + void addWellLog( RimWellLogFile* wellLogFile, RimWellPath* wellPath ); void scheduleRedrawAffectedViews(); diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathGeometryDef.cpp b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathGeometryDef.cpp index b76b3c9de8..f6bd5bda93 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathGeometryDef.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathGeometryDef.cpp @@ -102,7 +102,7 @@ RimWellPathGeometryDef::RimWellPathGeometryDef() CAF_PDM_InitFieldNoDefault( &m_fixedMeasuredDepths, "FixedMeasuredDepths", "" ); CAF_PDM_InitField( &m_pickPointsEnabled, "m_pickPointsEnabled", false, "" ); - caf::PdmUiPushButtonEditor::configureEditorForField( &m_pickPointsEnabled ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pickPointsEnabled ); CAF_PDM_InitScriptableField( &m_showSpheres, "ShowSpheres", true, "Spheres" ); CAF_PDM_InitField( &m_sphereColor, "SphereColor", cvf::Color3f( cvf::Color3f::CEETRON ), "Sphere Color" ); diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.cpp b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.cpp index d29d0e7aba..6cf36935b1 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.cpp +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.cpp @@ -30,8 +30,8 @@ #include "RiuMainWindow.h" -#include "RigWellPathGeometryTools.h" #include "cafPdmUiDoubleSliderEditor.h" +#include "cafPdmUiLabelEditor.h" CAF_PDM_SOURCE_INIT( RimWellPathTieIn, "RimWellPathTieIn" ); @@ -42,7 +42,14 @@ RimWellPathTieIn::RimWellPathTieIn() { CAF_PDM_InitObject( "Well Path Tie In", ":/NotDefined.png", "", "Well Path Tie In description" ); + CAF_PDM_InitFieldNoDefault( &m_infoLabel, "InfoLabel", "Use right-click menu of well to set parent well." ); + m_infoLabel.uiCapability()->setUiEditorTypeName( caf::PdmUiLabelEditor::uiEditorTypeName() ); + m_infoLabel.xmlCapability()->disableIO(); + m_infoLabel.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::TOP ); + CAF_PDM_InitFieldNoDefault( &m_parentWell, "ParentWellPath", "Parent Well Path" ); + m_parentWell.uiCapability()->setUiReadOnly( true ); + CAF_PDM_InitFieldNoDefault( &m_childWell, "ChildWellPath", "ChildWellPath" ); CAF_PDM_InitFieldNoDefault( &m_tieInMeasuredDepth, "TieInMeasuredDepth", "Tie In Measured Depth" ); m_tieInMeasuredDepth.uiCapability()->setUiEditorTypeName( caf::PdmUiDoubleSliderEditor::uiEditorTypeName() ); @@ -161,6 +168,7 @@ const RimWellPathValve* RimWellPathTieIn::outletValve() const void RimWellPathTieIn::defineUiOrdering( QString uiConfigName, caf::PdmUiOrdering& uiOrdering ) { auto tieInGroup = uiOrdering.addNewGroup( "Tie In Settings" ); + tieInGroup->add( &m_infoLabel ); tieInGroup->add( &m_parentWell ); if ( m_parentWell() != nullptr ) { @@ -187,6 +195,11 @@ void RimWellPathTieIn::defineUiOrdering( QString uiConfigName, caf::PdmUiOrderin //-------------------------------------------------------------------------------------------------- void RimWellPathTieIn::fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue ) { + // TODO: It is not possible to change the parent well from the UI as the field is set to read only. Refactor and possibly delete this + // method. + // https://github.com/OPM/ResInsight/issues/11312 + // https://github.com/OPM/ResInsight/issues/11313 + if ( changedField == &m_parentWell ) { updateFirstTargetFromParentWell(); diff --git a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.h b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.h index 09a82f4054..35576f85cc 100644 --- a/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.h +++ b/ApplicationLibCode/ProjectDataModel/WellPath/RimWellPathTieIn.h @@ -55,6 +55,8 @@ class RimWellPathTieIn : public caf::PdmObject void defineEditorAttribute( const caf::PdmFieldHandle* field, QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) override; private: + caf::PdmField m_infoLabel; + caf::PdmPtrField m_parentWell; caf::PdmPtrField m_childWell; caf::PdmField m_tieInMeasuredDepth; diff --git a/ApplicationLibCode/ProjectDataModel/cafTreeNode.cpp b/ApplicationLibCode/ProjectDataModel/cafTreeNode.cpp index 42328d5767..a07f3c151d 100644 --- a/ApplicationLibCode/ProjectDataModel/cafTreeNode.cpp +++ b/ApplicationLibCode/ProjectDataModel/cafTreeNode.cpp @@ -194,8 +194,6 @@ cafObjectReferenceTreeNode::cafObjectReferenceTreeNode() CAF_PDM_InitFieldNoDefault( &m_referencedObject, "ReferencedObject", "Referenced Object" ); - m_childNodes.uiCapability()->setUiTreeHidden( true ); - uiCapability()->setUiTreeHidden( true ); } diff --git a/ApplicationLibCode/ProjectDataModelCommands/RimcSummaryCase.cpp b/ApplicationLibCode/ProjectDataModelCommands/RimcSummaryCase.cpp index ff72e12f58..4365293243 100644 --- a/ApplicationLibCode/ProjectDataModelCommands/RimcSummaryCase.cpp +++ b/ApplicationLibCode/ProjectDataModelCommands/RimcSummaryCase.cpp @@ -18,7 +18,6 @@ #include "RimcSummaryCase.h" -#include "RiaQDateTimeTools.h" #include "RiaSummaryTools.h" #include "RifSummaryReaderInterface.h" @@ -276,7 +275,27 @@ caf::PdmObjectHandle* RimSummaryCase_setSummaryVectorValues::execute() auto* fileSummaryCase = dynamic_cast( summaryCase ); if ( fileSummaryCase ) { + bool rebuildUserInterface = true; + + if ( auto reader = fileSummaryCase->summaryReader() ) + { + auto allAddr = reader->allResultAddresses(); + for ( auto adr : allAddr ) + { + if ( adr.uiText() == m_addressString().toStdString() ) + { + rebuildUserInterface = false; + break; + } + } + } + fileSummaryCase->setSummaryData( m_addressString().toStdString(), m_unitString().toStdString(), m_values() ); + + if ( rebuildUserInterface ) + { + fileSummaryCase->refreshMetaData(); + } } return nullptr; diff --git a/ApplicationLibCode/ReservoirDataModel/CMakeLists_files.cmake b/ApplicationLibCode/ReservoirDataModel/CMakeLists_files.cmake index e913f2ac12..f37b87b270 100644 --- a/ApplicationLibCode/ReservoirDataModel/CMakeLists_files.cmake +++ b/ApplicationLibCode/ReservoirDataModel/CMakeLists_files.cmake @@ -2,6 +2,7 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RigActiveCellInfo.h ${CMAKE_CURRENT_LIST_DIR}/RigCell.h ${CMAKE_CURRENT_LIST_DIR}/RigEclipseCaseData.h + ${CMAKE_CURRENT_LIST_DIR}/RigEclipseCaseDataTools.h ${CMAKE_CURRENT_LIST_DIR}/RigGridBase.h ${CMAKE_CURRENT_LIST_DIR}/RigGridManager.h ${CMAKE_CURRENT_LIST_DIR}/RigCellGeometryTools.h @@ -96,12 +97,14 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RigWellAllocationOverTime.h ${CMAKE_CURRENT_LIST_DIR}/RigWellResultBranch.h ${CMAKE_CURRENT_LIST_DIR}/RigWellResultFrame.h + ${CMAKE_CURRENT_LIST_DIR}/RigReservoirBuilder.h ) set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RigActiveCellInfo.cpp ${CMAKE_CURRENT_LIST_DIR}/RigCell.cpp ${CMAKE_CURRENT_LIST_DIR}/RigEclipseCaseData.cpp + ${CMAKE_CURRENT_LIST_DIR}/RigEclipseCaseDataTools.cpp ${CMAKE_CURRENT_LIST_DIR}/RigGridBase.cpp ${CMAKE_CURRENT_LIST_DIR}/RigGridManager.cpp ${CMAKE_CURRENT_LIST_DIR}/RigCellGeometryTools.cpp @@ -190,6 +193,7 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RigWellResultBranch.cpp ${CMAKE_CURRENT_LIST_DIR}/RigWellResultFrame.cpp ${CMAKE_CURRENT_LIST_DIR}/RigDeclineCurveCalculator.cpp + ${CMAKE_CURRENT_LIST_DIR}/RigReservoirBuilder.cpp ) list(APPEND CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) diff --git a/ApplicationLibCode/ReservoirDataModel/CMakeLists_filesNotToUnitTest.cmake b/ApplicationLibCode/ReservoirDataModel/CMakeLists_filesNotToUnitTest.cmake index 5de8178360..a004e95cd4 100644 --- a/ApplicationLibCode/ReservoirDataModel/CMakeLists_filesNotToUnitTest.cmake +++ b/ApplicationLibCode/ReservoirDataModel/CMakeLists_filesNotToUnitTest.cmake @@ -4,7 +4,9 @@ set(SOURCE_GROUP_HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/RigCaseToCaseCellMapperTools.h ${CMAKE_CURRENT_LIST_DIR}/RigCaseToCaseRangeFilterMapper.h ${CMAKE_CURRENT_LIST_DIR}/RigSimulationWellCenterLineCalculator.h + ${CMAKE_CURRENT_LIST_DIR}/RigWellLogFile.h ${CMAKE_CURRENT_LIST_DIR}/RigWellLogLasFile.h + ${CMAKE_CURRENT_LIST_DIR}/RigWellLogCsvFile.h ${CMAKE_CURRENT_LIST_DIR}/RigReservoirGridTools.h ) @@ -14,7 +16,9 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RigCaseToCaseCellMapperTools.cpp ${CMAKE_CURRENT_LIST_DIR}/RigCaseToCaseRangeFilterMapper.cpp ${CMAKE_CURRENT_LIST_DIR}/RigSimulationWellCenterLineCalculator.cpp + ${CMAKE_CURRENT_LIST_DIR}/RigWellLogFile.cpp ${CMAKE_CURRENT_LIST_DIR}/RigWellLogLasFile.cpp + ${CMAKE_CURRENT_LIST_DIR}/RigWellLogCsvFile.cpp ${CMAKE_CURRENT_LIST_DIR}/RigReservoirGridTools.cpp ) diff --git a/ApplicationLibCode/ReservoirDataModel/Completions/RigEclipseToStimPlanCellTransmissibilityCalculator.cpp b/ApplicationLibCode/ReservoirDataModel/Completions/RigEclipseToStimPlanCellTransmissibilityCalculator.cpp index 25f5470e55..e4a6fc7742 100644 --- a/ApplicationLibCode/ReservoirDataModel/Completions/RigEclipseToStimPlanCellTransmissibilityCalculator.cpp +++ b/ApplicationLibCode/ReservoirDataModel/Completions/RigEclipseToStimPlanCellTransmissibilityCalculator.cpp @@ -217,7 +217,6 @@ void RigEclipseToStimPlanCellTransmissibilityCalculator::calculateStimPlanCellsM } std::vector> polygonsForStimPlanCellInEclipseCell; - cvf::Vec3d areaVector; std::vector stimPlanPolygon = m_stimPlanCell.getPolygon(); for ( const std::vector& planeCellPolygon : planeCellPolygons ) @@ -233,7 +232,6 @@ void RigEclipseToStimPlanCellTransmissibilityCalculator::calculateStimPlanCellsM if ( polygonsForStimPlanCellInEclipseCell.empty() ) continue; std::vector areaOfFractureParts; - double length; std::vector lengthXareaOfFractureParts; double Ax = 0.0; double Ay = 0.0; @@ -241,11 +239,11 @@ void RigEclipseToStimPlanCellTransmissibilityCalculator::calculateStimPlanCellsM for ( const std::vector& fracturePartPolygon : polygonsForStimPlanCellInEclipseCell ) { - areaVector = cvf::GeometryTools::polygonAreaNormal3D( fracturePartPolygon ); - double area = areaVector.length(); + cvf::Vec3d areaVector = cvf::GeometryTools::polygonAreaNormal3D( fracturePartPolygon ); + double area = areaVector.length(); areaOfFractureParts.push_back( area ); - length = RigCellGeometryTools::polygonLengthInLocalXdirWeightedByArea( fracturePartPolygon ); + double length = RigCellGeometryTools::polygonLengthInLocalXdirWeightedByArea( fracturePartPolygon ); lengthXareaOfFractureParts.push_back( length * area ); cvf::Plane fracturePlane; @@ -265,6 +263,9 @@ void RigEclipseToStimPlanCellTransmissibilityCalculator::calculateStimPlanCellsM for ( double lengtXarea : lengthXareaOfFractureParts ) totalAreaXLength += lengtXarea; + // Guard against numerical issues for very small intersections + if ( std::isnan( totalAreaXLength ) || std::isnan( fractureArea ) ) continue; + double fractureAreaWeightedlength = totalAreaXLength / fractureArea; // Transmissibility for inactive cells is set to zero @@ -343,10 +344,8 @@ void RigEclipseToStimPlanCellTransmissibilityCalculator::calculateStimPlanCellsM std::vector RigEclipseToStimPlanCellTransmissibilityCalculator::getPotentiallyFracturedCellsForPolygon( const std::vector& polygon ) const { - std::vector cellIndices; - const RigMainGrid* mainGrid = m_case->eclipseCaseData()->mainGrid(); - if ( !mainGrid ) return cellIndices; + if ( !mainGrid ) return {}; cvf::BoundingBox polygonBBox; for ( const cvf::Vec3d& nodeCoord : polygon ) @@ -354,7 +353,7 @@ std::vector polygonBBox.add( nodeCoord ); } - mainGrid->findIntersectingCells( polygonBBox, &cellIndices ); + std::vector cellIndices = mainGrid->findIntersectingCells( polygonBBox ); std::vector cellIndicesToLeafCells; for ( const size_t& index : cellIndices ) diff --git a/ApplicationLibCode/ReservoirDataModel/Completions/RigFractureTransmissibilityEquations.cpp b/ApplicationLibCode/ReservoirDataModel/Completions/RigFractureTransmissibilityEquations.cpp index f20dc4997a..fc8dd3c510 100644 --- a/ApplicationLibCode/ReservoirDataModel/Completions/RigFractureTransmissibilityEquations.cpp +++ b/ApplicationLibCode/ReservoirDataModel/Completions/RigFractureTransmissibilityEquations.cpp @@ -132,17 +132,15 @@ double RigFractureTransmissibilityEquations::matrixToFractureTrans( double perm, double fractureAreaWeightedlength, double cDarcy ) { - double transmissibility; - double slDivPi = 0.0; if ( cvf::Math::abs( skinfactor ) > EPSILON ) { slDivPi = ( skinfactor * fractureAreaWeightedlength ) / cvf::PI_D; } - transmissibility = 8 * cDarcy * ( perm * NTG ) * A / ( cellSizeLength + slDivPi ); + double transmissibility = 8 * cDarcy * ( perm * NTG ) * A / ( cellSizeLength + slDivPi ); - CVF_ASSERT( transmissibility == transmissibility ); + CVF_ASSERT( !std::isnan( transmissibility ) ); return transmissibility; } diff --git a/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.cpp b/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.cpp index 2ecf32f6c7..92fd87fe97 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.cpp @@ -139,7 +139,7 @@ size_t RigActiveCellInfo::reservoirActiveCellCount() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigActiveCellInfo::setIJKBoundingBox( const cvf::Vec3st& min, const cvf::Vec3st& max ) +void RigActiveCellInfo::setIjkBoundingBox( const cvf::Vec3st& min, const cvf::Vec3st& max ) { m_activeCellPositionMin = min; m_activeCellPositionMax = max; @@ -148,10 +148,9 @@ void RigActiveCellInfo::setIJKBoundingBox( const cvf::Vec3st& min, const cvf::Ve //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigActiveCellInfo::IJKBoundingBox( cvf::Vec3st& min, cvf::Vec3st& max ) const +std::pair RigActiveCellInfo::ijkBoundingBox() const { - min = m_activeCellPositionMin; - max = m_activeCellPositionMax; + return std::make_pair( m_activeCellPositionMin, m_activeCellPositionMax ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.h b/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.h index f016e2c2dd..2ebf272b98 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.h +++ b/ApplicationLibCode/ReservoirDataModel/RigActiveCellInfo.h @@ -45,8 +45,8 @@ class RigActiveCellInfo : public cvf::Object size_t gridActiveCellCounts( size_t gridIndex ) const; void computeDerivedData(); - void setIJKBoundingBox( const cvf::Vec3st& min, const cvf::Vec3st& max ); - void IJKBoundingBox( cvf::Vec3st& min, cvf::Vec3st& max ) const; + void setIjkBoundingBox( const cvf::Vec3st& min, const cvf::Vec3st& max ); + std::pair ijkBoundingBox() const; cvf::BoundingBox geometryBoundingBox() const; void setGeometryBoundingBox( cvf::BoundingBox bb ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.cpp b/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.cpp index b6e186c211..cb64d22518 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.cpp @@ -216,6 +216,24 @@ void RigCaseCellResultsData::mobileVolumeWeightedMean( const RigEclipseResultAdd statistics( resVarAddr )->mobileVolumeWeightedMean( timeStepIndex, meanValue ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::map RigCaseCellResultsData::resultValueCount() const +{ + std::map memoryUse; + + for ( size_t i = 0; i < m_cellScalarResults.size(); i++ ) + { + if ( allocatedValueCount( i ) > 0 ) + { + memoryUse[m_resultInfos[i].resultName().toStdString()] = allocatedValueCount( i ); + } + } + + return memoryUse; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -724,10 +742,14 @@ void RigCaseCellResultsData::freeAllocatedResultsData( std::vector empty; - dataForTimeStep.swap( empty ); + + if ( !dataForTimeStep.empty() ) + { + // Using swap with an empty vector as that is the safest way to really get rid of the allocated data in a + // vector + std::vector empty; + dataForTimeStep.swap( empty ); + } } } } @@ -1845,7 +1867,8 @@ void RigCaseCellResultsData::computeDepthRelatedResults() } } - for ( size_t cellIdx = 0; cellIdx < m_ownerMainGrid->globalCellArray().size(); cellIdx++ ) +#pragma omp parallel for + for ( long cellIdx = 0; cellIdx < static_cast( m_ownerMainGrid->globalCellArray().size() ); cellIdx++ ) { const RigCell& cell = m_ownerMainGrid->globalCellArray()[cellIdx]; @@ -2756,6 +2779,13 @@ void RigCaseCellResultsData::setActiveFormationNames( RigFormationNames* activeF { m_activeFormationNamesData = activeFormationNames; + if ( !activeFormationNames ) + { + clearScalarResult( + RigEclipseResultAddress( RiaDefines::ResultCatType::FORMATION_NAMES, RiaResultNames::activeFormationNamesResultName() ) ); + return; + } + size_t totalGlobCellCount = m_ownerMainGrid->globalCellArray().size(); addStaticScalarResult( RiaDefines::ResultCatType::FORMATION_NAMES, RiaResultNames::activeFormationNamesResultName(), false, totalGlobCellCount ); @@ -2837,22 +2867,25 @@ RigAllanDiagramData* RigCaseCellResultsData::allanDiagramData() //-------------------------------------------------------------------------------------------------- bool RigCaseCellResultsData::isDataPresent( size_t scalarResultIndex ) const { - if ( scalarResultIndex >= resultCount() ) - { - return false; - } + return allocatedValueCount( scalarResultIndex ) > 0; +} - const std::vector>& data = m_cellScalarResults[scalarResultIndex]; +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigCaseCellResultsData::allocatedValueCount( size_t scalarResultIndex ) const +{ + if ( scalarResultIndex >= resultCount() ) return 0; + + const std::vector>& valuesAllTimeSteps = m_cellScalarResults[scalarResultIndex]; - for ( size_t tsIdx = 0; tsIdx < data.size(); ++tsIdx ) + size_t valueCount = 0; + for ( const auto& values : valuesAllTimeSteps ) { - if ( !data[tsIdx].empty() ) - { - return true; - } + valueCount += values.size(); } - return false; + return valueCount; } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.h b/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.h index d86abf5a26..24a917f6ed 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.h +++ b/ApplicationLibCode/ReservoirDataModel/RigCaseCellResultsData.h @@ -99,6 +99,9 @@ class RigCaseCellResultsData : public cvf::Object void mobileVolumeWeightedMean( const RigEclipseResultAddress& resVarAddr, double& meanValue ); void mobileVolumeWeightedMean( const RigEclipseResultAddress& resVarAddr, size_t timeStepIndex, double& meanValue ); + // Return the number of double values allocated for each result + std::map resultValueCount() const; + // Access meta-information about the results size_t timeStepCount( const RigEclipseResultAddress& resVarAddr ) const; @@ -128,9 +131,12 @@ class RigCaseCellResultsData : public cvf::Object QString makeResultNameUnique( const QString& resultNameProposal ) const; bool ensureKnownResultLoaded( const RigEclipseResultAddress& resultAddress ); - bool findAndLoadResultByName( const QString& resultName, const std::vector& resultCategorySearchOrder ); + // Load result for a single time step. This can be used to process data for a single time step + // Other data access functions assume all time steps are loaded at the same time + size_t findOrLoadKnownScalarResultForTimeStep( const RigEclipseResultAddress& resVarAddr, size_t timeStepIndex ); + bool hasResultEntry( const RigEclipseResultAddress& resultAddress ) const; bool isResultLoaded( const RigEclipseResultAddress& resultAddress ) const; void createResultEntry( const RigEclipseResultAddress& resultAddress, bool needsToBeStored ); @@ -164,7 +170,6 @@ class RigCaseCellResultsData : public cvf::Object friend class RigOilVolumeResultCalculator; friend class RigCellVolumeResultCalculator; friend class RigCellsWithNncsCalculator; - size_t findOrLoadKnownScalarResultForTimeStep( const RigEclipseResultAddress& resVarAddr, size_t timeStepIndex ); size_t findOrCreateScalarResultIndex( const RigEclipseResultAddress& resVarAddr, bool needsToBeStored ); @@ -199,7 +204,8 @@ class RigCaseCellResultsData : public cvf::Object void computeFaultDistance(); void computeNncsCells(); - bool isDataPresent( size_t scalarResultIndex ) const; + bool isDataPresent( size_t scalarResultIndex ) const; + size_t allocatedValueCount( size_t scalarResultIndex ) const; void assignValuesToTemporaryLgrs( const QString& resultName, std::vector& values ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapper.cpp b/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapper.cpp index 9d1eb68647..356651abce 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapper.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapper.cpp @@ -159,8 +159,7 @@ void RigCaseToCaseCellMapper::calculateEclToGeomCellMapping( RigMainGrid* master for ( int i = 0; i < 8; ++i ) elmBBox.add( geoMechConvertedEclCell[i] ); - std::vector closeElements; - dependentFemPart->findIntersectingElementIndices( elmBBox, &closeElements ); + std::vector closeElements = dependentFemPart->findIntersectingElementIndices( elmBBox ); for ( size_t ccIdx = 0; ccIdx < closeElements.size(); ++ccIdx ) { diff --git a/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapperTools.cpp b/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapperTools.cpp index 910c0c2caf..7c334efb48 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapperTools.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseCellMapperTools.cpp @@ -277,7 +277,7 @@ int RigCaseToCaseCellMapperTools::quadVxClosestToXYOfPoint( const cvf::Vec3d poi bool RigCaseToCaseCellMapperTools::elementCorners( const RigFemPart* femPart, int elmIdx, cvf::Vec3d elmCorners[8] ) { RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType != HEX8 && elmType != HEX8P ) return false; + if ( !RigFemTypes::is8NodeElement( elmType ) ) return false; const std::vector& nodeCoords = femPart->nodes().coordinates; const int* cornerIndices = femPart->connectivities( elmIdx ); @@ -300,7 +300,8 @@ bool RigCaseToCaseCellMapperTools::elementCorners( const RigFemPart* femPart, in int RigCaseToCaseCellMapperTools::findMatchingPOSKFaceIdx( const cvf::Vec3d baseCell[8], bool isBaseCellNormalsOutwards, const cvf::Vec3d c2[8] ) { int faceNodeCount; - const int* posKFace = RigFemTypes::localElmNodeIndicesForFace( HEX8, (int)( cvf::StructGridInterface::POS_K ), &faceNodeCount ); + const int* posKFace = + RigFemTypes::localElmNodeIndicesForFace( RigElementType::HEX8, (int)( cvf::StructGridInterface::POS_K ), &faceNodeCount ); double sign = isBaseCellNormalsOutwards ? 1.0 : -1.0; @@ -311,7 +312,7 @@ int RigCaseToCaseCellMapperTools::findMatchingPOSKFaceIdx( const cvf::Vec3d base int bestFace = -1; for ( int faceIdx = 5; faceIdx >= 0; --faceIdx ) // Backwards. might hit earlier more often { - const int* face = RigFemTypes::localElmNodeIndicesForFace( HEX8, faceIdx, &faceNodeCount ); + const int* face = RigFemTypes::localElmNodeIndicesForFace( RigElementType::HEX8, faceIdx, &faceNodeCount ); cvf::Vec3d normal = ( c2[face[2]] - c2[face[0]] ) ^ ( c2[face[3]] - c2[face[1]] ); normal.normalize(); double sqDiff = ( posKnormal - normal ).lengthSquared(); @@ -367,11 +368,13 @@ void RigCaseToCaseCellMapperTools::rotateCellTopologicallyToMatchBaseCell( const tmpFemCorners[6] = cell[6]; tmpFemCorners[7] = cell[7]; - int femShallowZFaceIdx = RigFemTypes::oppositeFace( HEX8, femDeepZFaceIdx ); + int femShallowZFaceIdx = RigFemTypes::oppositeFace( RigElementType::HEX8, femDeepZFaceIdx ); int faceNodeCount; - const int* localElmNodeIndicesForPOSKFace = RigFemTypes::localElmNodeIndicesForFace( HEX8, femDeepZFaceIdx, &faceNodeCount ); - const int* localElmNodeIndicesForNEGKFace = RigFemTypes::localElmNodeIndicesForFace( HEX8, femShallowZFaceIdx, &faceNodeCount ); + const int* localElmNodeIndicesForPOSKFace = + RigFemTypes::localElmNodeIndicesForFace( RigElementType::HEX8, femDeepZFaceIdx, &faceNodeCount ); + const int* localElmNodeIndicesForNEGKFace = + RigFemTypes::localElmNodeIndicesForFace( RigElementType::HEX8, femShallowZFaceIdx, &faceNodeCount ); cell[0] = tmpFemCorners[localElmNodeIndicesForNEGKFace[0]]; cell[1] = tmpFemCorners[localElmNodeIndicesForNEGKFace[1]]; diff --git a/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseRangeFilterMapper.cpp b/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseRangeFilterMapper.cpp index 6e9698f9a9..f69eaa0933 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseRangeFilterMapper.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigCaseToCaseRangeFilterMapper.cpp @@ -382,8 +382,7 @@ RigCaseToCaseRangeFilterMapper::CellMatchType RigCaseToCaseRangeFilterMapper::fi for ( int i = 0; i < 8; ++i ) elmBBox.add( geoMechConvertedEclCell[i] ); - std::vector closeElements; - dependentFemPart->findIntersectingElementIndices( elmBBox, &closeElements ); + std::vector closeElements = dependentFemPart->findIntersectingElementIndices( elmBBox ); cvf::Vec3d elmCorners[8]; int elmIdxToBestMatch = -1; @@ -465,10 +464,8 @@ RigCaseToCaseRangeFilterMapper::CellMatchType RigCaseToCaseRangeFilterMapper::fi for ( int i = 0; i < 8; ++i ) elmBBox.add( elmCorners[i] ); - std::vector closeCells; - masterEclGrid->findIntersectingCells( elmBBox, - &closeCells ); // This might actually miss the exact one, but we have no other - // alternative yet. + // This might actually miss the exact one, but we have no other alternative yet. + std::vector closeCells = masterEclGrid->findIntersectingCells( elmBBox ); size_t globCellIdxToBestMatch = cvf::UNDEFINED_SIZE_T; double sqDistToClosestCellCenter = HUGE_VAL; diff --git a/ApplicationLibCode/ReservoirDataModel/RigCellFaceGeometryTools.cpp b/ApplicationLibCode/ReservoirDataModel/RigCellFaceGeometryTools.cpp index 6aacf9d7f0..e01fc78421 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCellFaceGeometryTools.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigCellFaceGeometryTools.cpp @@ -236,8 +236,7 @@ void RigCellFaceGeometryTools::extractConnectionsForFace( const RigFault::FaultF bb.add( mainGridNodes[sourceFaceIndices[2]] ); bb.add( mainGridNodes[sourceFaceIndices[3]] ); - std::vector closeCells; - mainGrid->findIntersectingCells( bb, &closeCells ); + std::vector closeCells = mainGrid->findIntersectingCells( bb ); cvf::StructGridInterface::FaceType candidateFace = cvf::StructGridInterface::oppositeFace( sourceCellFace ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.cpp b/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.cpp index 3d51910552..9a78a40f7d 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.cpp @@ -28,6 +28,8 @@ #include #include +#include +#include #include //-------------------------------------------------------------------------------------------------- @@ -698,7 +700,7 @@ double RigCellGeometryTools::getLengthOfPolygonAlongLine( const std::pair + RigCellGeometryTools::lineLineIntersection2D( const cvf::Vec3d a1, const cvf::Vec3d b1, const cvf::Vec3d a2, const cvf::Vec3d b2 ) +{ + constexpr double EPS = 0.000001; + double mua, mub; + double denom, numera, numerb; + const double x1 = a1.x(), x2 = b1.x(); + const double x3 = a2.x(), x4 = b2.x(); + const double y1 = a1.y(), y2 = b1.y(); + const double y3 = a2.y(), y4 = b2.y(); + + denom = ( y4 - y3 ) * ( x2 - x1 ) - ( x4 - x3 ) * ( y2 - y1 ); + numera = ( x4 - x3 ) * ( y1 - y3 ) - ( y4 - y3 ) * ( x1 - x3 ); + numerb = ( x2 - x1 ) * ( y1 - y3 ) - ( y2 - y1 ) * ( x1 - x3 ); + + // Are the lines coincident? + if ( ( std::abs( numera ) < EPS ) && ( std::abs( numerb ) < EPS ) && ( std::abs( denom ) < EPS ) ) + { + return std::make_pair( true, cvf::Vec2d( ( x1 + x2 ) / 2, ( y1 + y2 ) / 2 ) ); + } + + // Are the lines parallel? + if ( std::abs( denom ) < EPS ) + { + return std::make_pair( false, cvf::Vec2d() ); + } + + // Is the intersection along the segments? + mua = numera / denom; + mub = numerb / denom; + if ( mua < 0 || mua > 1 || mub < 0 || mub > 1 ) + { + return std::make_pair( false, cvf::Vec2d() ); + } + + return std::make_pair( true, cvf::Vec2d( x1 + mua * ( x2 - x1 ), y1 + mua * ( y2 - y1 ) ) ); +} + +//-------------------------------------------------------------------------------------------------- +/// +/// Returns true if the line from a1 to b1 intersects the line from a2 to b2 +/// Operates only in the XY plane +/// +//-------------------------------------------------------------------------------------------------- +bool RigCellGeometryTools::lineIntersectsLine2D( const cvf::Vec3d a1, const cvf::Vec3d b1, const cvf::Vec3d a2, const cvf::Vec3d b2 ) +{ + return lineLineIntersection2D( a1, b1, a2, b2 ).first; +} + +//-------------------------------------------------------------------------------------------------- +/// +/// Returns true if the line from a to b intersects the closed, simple polygon defined by the corner +/// points in the input polygon vector, otherwise false +/// Operates only in the XY plane +/// +//-------------------------------------------------------------------------------------------------- +bool RigCellGeometryTools::lineIntersectsPolygon2D( const cvf::Vec3d a, const cvf::Vec3d b, const std::vector& polygon ) +{ + int nPolyLines = (int)polygon.size(); + + for ( int i = 1; i < nPolyLines; i++ ) + { + if ( lineIntersectsLine2D( a, b, polygon[i - 1], polygon[i] ) ) return true; + } + + return lineIntersectsLine2D( a, b, polygon[nPolyLines - 1], polygon[0] ); +} + +//-------------------------------------------------------------------------------------------------- +/// +/// Returns true if the polyline intersects the simple polygon defined by the NEGK face corners of the input cell +/// Operates only in the XY plane +/// +//-------------------------------------------------------------------------------------------------- +bool RigCellGeometryTools::polylineIntersectsCellNegK2D( const std::vector& polyline, const std::array& cellCorners ) +{ + const int nPoints = (int)polyline.size(); + const int nCorners = 4; + + for ( int i = 1; i < nPoints; i++ ) + { + for ( int j = 1; j < nCorners; j++ ) + { + if ( lineIntersectsLine2D( polyline[i - 1], polyline[i], cellCorners[j - 1], cellCorners[j] ) ) return true; + } + if ( lineIntersectsLine2D( polyline[i - 1], polyline[i], cellCorners[nCorners - 1], cellCorners[0] ) ) return true; + } + + return false; +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.h b/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.h index cbf2dbd7b6..28f3f91dc0 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.h +++ b/ApplicationLibCode/ReservoirDataModel/RigCellGeometryTools.h @@ -76,7 +76,14 @@ class RigCellGeometryTools static std::vector unionOfPolygons( const std::vector>& polygons ); + // *** the 2D methods only looks at the X and Y coordinates of the input points *** + static bool pointInsidePolygon2D( const cvf::Vec3d point, const std::vector& polygon ); + static std::pair + lineLineIntersection2D( const cvf::Vec3d a1, const cvf::Vec3d b1, const cvf::Vec3d a2, const cvf::Vec3d b2 ); + static bool lineIntersectsLine2D( const cvf::Vec3d a1, const cvf::Vec3d b1, const cvf::Vec3d a2, const cvf::Vec3d b2 ); + static bool lineIntersectsPolygon2D( const cvf::Vec3d a, const cvf::Vec3d b, const std::vector& polygon ); + static bool polylineIntersectsCellNegK2D( const std::vector& polyline, const std::array& cellCorners ); private: static std::vector ajustPolygonToAvoidIntersectionsAtVertex( const std::vector& polyLine, diff --git a/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.cpp b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.cpp index 9e254cd724..d10442cbd6 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.cpp @@ -445,18 +445,22 @@ void RigEclipseCaseData::computeActiveCellIJKBBox() fractureModelActiveBB.add( i, j, k ); } } - m_activeCellInfo->setIJKBoundingBox( matrixModelActiveBB.m_min, matrixModelActiveBB.m_max ); - m_fractureActiveCellInfo->setIJKBoundingBox( fractureModelActiveBB.m_min, fractureModelActiveBB.m_max ); + m_activeCellInfo->setIjkBoundingBox( matrixModelActiveBB.m_min, matrixModelActiveBB.m_max ); + m_fractureActiveCellInfo->setIjkBoundingBox( fractureModelActiveBB.m_min, fractureModelActiveBB.m_max ); } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigEclipseCaseData::computeActiveCellBoundingBoxes() +void RigEclipseCaseData::computeActiveCellBoundingBoxes( bool useOptimizedVersion ) { computeActiveCellIJKBBox(); - computeActiveCellsGeometryBoundingBox(); + + if ( useOptimizedVersion ) + computeActiveCellsGeometryBoundingBoxOptimized(); + else + computeActiveCellsGeometryBoundingBoxSlow(); } //-------------------------------------------------------------------------------------------------- @@ -627,7 +631,7 @@ bool RigEclipseCaseData::hasFractureResults() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigEclipseCaseData::computeActiveCellsGeometryBoundingBox() +void RigEclipseCaseData::computeActiveCellsGeometryBoundingBoxSlow() { if ( m_activeCellInfo.isNull() || m_fractureActiveCellInfo.isNull() ) { @@ -673,9 +677,75 @@ void RigEclipseCaseData::computeActiveCellsGeometryBoundingBox() activeInfos[acIdx]->setGeometryBoundingBox( bb ); } + // This design choice is unfortunate, as the bounding box of active cells can be computed in different ways. + // Must keep the code to make sure existing projects display 3D model at the same location in the scene. m_mainGrid->setDisplayModelOffset( bb.min() ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigEclipseCaseData::computeActiveCellsGeometryBoundingBoxOptimized() +{ + if ( m_activeCellInfo.isNull() || m_fractureActiveCellInfo.isNull() ) + { + return; + } + + if ( m_mainGrid.isNull() ) + { + cvf::BoundingBox bb; + m_activeCellInfo->setGeometryBoundingBox( bb ); + m_fractureActiveCellInfo->setGeometryBoundingBox( bb ); + return; + } + + RigActiveCellInfo* activeInfos[2]; + activeInfos[0] = m_fractureActiveCellInfo.p(); + activeInfos[1] = m_activeCellInfo.p(); + + cvf::BoundingBox bb; + for ( int acIdx = 0; acIdx < 2; ++acIdx ) + { + bb.reset(); + if ( m_mainGrid->nodes().empty() ) + { + bb.add( cvf::Vec3d::ZERO ); + } + else + { + // Use the top and bottom layer of active cells to compute the bounding box + + auto [minBB, maxBB] = activeInfos[acIdx]->ijkBoundingBox(); + + for ( auto k : { minBB.z(), maxBB.z() } ) + { + for ( size_t i = minBB.x(); i <= maxBB.x(); i++ ) + { + for ( size_t j = minBB.y(); j <= maxBB.y(); j++ ) + { + size_t cellIndex = m_mainGrid->cellIndexFromIJK( i, j, k ); + + std::array hexCorners; + m_mainGrid->cellCornerVertices( cellIndex, hexCorners.data() ); + for ( const auto& corner : hexCorners ) + { + bb.add( corner ); + } + } + } + } + } + + activeInfos[acIdx]->setGeometryBoundingBox( bb ); + } + + auto bbMainGrid = m_mainGrid->boundingBox(); + + // Use center of bounding box as display offset. This point will be stable and independent of the active cell bounding box. + m_mainGrid->setDisplayModelOffset( bbMainGrid.center() ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.h b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.h index 2d42ca067e..63416b16cb 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.h +++ b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseData.h @@ -103,7 +103,7 @@ class RigEclipseCaseData : public cvf::Object const RigWellResultPoint& sourceWellCellResult, const RigWellResultPoint& otherWellCellResult ) const; - void computeActiveCellBoundingBoxes(); + void computeActiveCellBoundingBoxes( bool useOptimizedVersion ); RiaDefines::EclipseUnitSystem unitsType() const { return m_unitsType; } void setUnitsType( RiaDefines::EclipseUnitSystem unitsType ) { m_unitsType = unitsType; } @@ -126,7 +126,8 @@ class RigEclipseCaseData : public cvf::Object private: void computeActiveCellIJKBBox(); void computeWellCellsPrGrid(); - void computeActiveCellsGeometryBoundingBox(); + void computeActiveCellsGeometryBoundingBoxSlow(); + void computeActiveCellsGeometryBoundingBoxOptimized(); const RigFormationNames* activeFormationNames() const; diff --git a/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseDataTools.cpp b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseDataTools.cpp new file mode 100644 index 0000000000..39716b03a9 --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseDataTools.cpp @@ -0,0 +1,48 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RigEclipseCaseDataTools.h" + +#include "RigCaseCellResultsData.h" +#include "RigEclipseCaseData.h" +#include "RigSimWellData.h" + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RigEclipseCaseDataTools::firstProducer( RigEclipseCaseData* eclipseCaseData ) +{ + if ( !eclipseCaseData ) return {}; + + auto caseCellResultsData = eclipseCaseData->results( RiaDefines::PorosityModelType::MATRIX_MODEL ); + if ( !caseCellResultsData ) return {}; + + auto timeStepCount = caseCellResultsData->timeStepDates().size(); + if ( timeStepCount == 0 ) return {}; + + auto simWells = eclipseCaseData->wellResults(); + for ( const auto& well : simWells ) + { + if ( well->wellProductionType( timeStepCount - 1 ) == RiaDefines::WellProductionType::PRODUCER ) + { + return well->m_wellName; + } + } + + return {}; +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseDataTools.h b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseDataTools.h new file mode 100644 index 0000000000..ee13a1752a --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigEclipseCaseDataTools.h @@ -0,0 +1,32 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024 Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "QString" + +class RigEclipseCaseData; + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +class RigEclipseCaseDataTools +{ +public: + static QString firstProducer( RigEclipseCaseData* eclipseCaseData ); +}; diff --git a/ApplicationLibCode/ReservoirDataModel/RigEclipseWellLogExtractor.cpp b/ApplicationLibCode/ReservoirDataModel/RigEclipseWellLogExtractor.cpp index 571e27babe..88d02f9312 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigEclipseWellLogExtractor.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigEclipseWellLogExtractor.cpp @@ -193,9 +193,7 @@ void RigEclipseWellLogExtractor::curveData( const RigResultAccessor* resultAcces //-------------------------------------------------------------------------------------------------- std::vector RigEclipseWellLogExtractor::findCloseCellIndices( const cvf::BoundingBox& bb ) { - std::vector closeCells; - m_caseData->mainGrid()->findIntersectingCells( bb, &closeCells ); - return closeCells; + return m_caseData->mainGrid()->findIntersectingCells( bb ); } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.cpp b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.cpp index e922fa0ece..bf34be9ae8 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.cpp @@ -18,13 +18,14 @@ #include "RigFaultReactivationModel.h" +#include "RigActiveCellInfo.h" +#include "RigEclipseCaseData.h" #include "RigFaultReactivationModelGenerator.h" #include "RigGriddedPart3d.h" -#include "RigPolyLinesData.h" -#include "RimFaultReactivationDataAccess.h" +#include "RimEclipseCase.h" -#include "cafAssert.h" +#include //-------------------------------------------------------------------------------------------------- /// @@ -138,6 +139,15 @@ std::pair RigFaultReactivationModel::modelLocalNormalsXY return m_generator->modelLocalNormalsXY(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Vec3d RigFaultReactivationModel::transformPointIfNeeded( const cvf::Vec3d point ) const +{ + if ( m_generator.get() == nullptr ) return point; + return m_generator->transformPointIfNeeded( point ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -145,8 +155,9 @@ void RigFaultReactivationModel::updateGeometry( size_t startCell, cvf::StructGri { reset(); - auto frontPart = m_3dparts[GridPart::FW]; - auto backPart = m_3dparts[GridPart::HW]; + auto frontPart = m_3dparts[GridPart::FW]; + auto backPart = m_3dparts[GridPart::HW]; + m_normalPointsAt = GridPart::FW; m_generator->generateGeometry( startCell, startFace, frontPart, backPart ); @@ -154,6 +165,7 @@ void RigFaultReactivationModel::updateGeometry( size_t startCell, cvf::StructGri { m_3dparts[GridPart::HW] = frontPart; m_3dparts[GridPart::FW] = backPart; + m_normalPointsAt = GridPart::HW; } auto& frontPoints = m_generator->frontPoints(); @@ -214,10 +226,10 @@ const RigGriddedPart3d* RigFaultReactivationModel::grid( RimFaultReactivation::G //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const cvf::Vec3d RigFaultReactivationModel::faultNormal() const +const cvf::Vec3d RigFaultReactivationModel::modelNormal() const { if ( m_generator.get() == nullptr ) return { 0.0, 0.0, 0.0 }; - return m_generator->normal(); + return m_generator->modelNormal(); } //-------------------------------------------------------------------------------------------------- @@ -228,3 +240,37 @@ const std::pair RigFaultReactivationModel::faultTopBotto if ( m_generator.get() == nullptr ) return std::make_pair( cvf::Vec3d(), cvf::Vec3d() ); return m_generator->faultTopBottomPoints(); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RigFaultReactivationModel::depthTopBottom() const +{ + if ( m_generator.get() == nullptr ) + return std::make_pair( std::numeric_limits::infinity(), std::numeric_limits::infinity() ); + return m_generator->depthTopBottom(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimFaultReactivation::GridPart RigFaultReactivationModel::normalPointsAt() const +{ + return m_normalPointsAt; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigFaultReactivationModel::postProcessElementSets( const RimEclipseCase* eCase ) +{ + if ( eCase->eclipseCaseData() == nullptr ) return; + + auto cellInfo = eCase->eclipseCaseData()->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL ); + + for ( auto part : allGridParts() ) + { + auto gridPart = m_3dparts[part]; + gridPart->postProcessElementSets( eCase->mainGrid(), cellInfo ); + } +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.h b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.h index afd7077a5c..7a6f17fa41 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.h +++ b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModel.h @@ -24,7 +24,6 @@ #include "cvfColor3.h" #include "cvfMatrix4.h" #include "cvfObject.h" -#include "cvfPlane.h" #include "cvfStructGrid.h" #include "cvfTextureImage.h" #include "cvfVector3.h" @@ -36,9 +35,8 @@ #include class RigGriddedPart3d; -class RigMainGrid; -class RimFaultReactivationDataAccess; class RigFaultReactivationModelGenerator; +class RimEclipseCase; class RigFRModelPart { @@ -71,6 +69,7 @@ class RigFaultReactivationModel : public cvf::Object void setGenerator( std::shared_ptr generator ); std::pair modelLocalNormalsXY() const; + cvf::Vec3d transformPointIfNeeded( const cvf::Vec3d point ) const; void updateGeometry( size_t startCell, cvf::StructGridInterface::FaceType startFace ); @@ -82,8 +81,13 @@ class RigFaultReactivationModel : public cvf::Object const RigGriddedPart3d* grid( GridPart part ) const; - const cvf::Vec3d faultNormal() const; + const cvf::Vec3d modelNormal() const; const std::pair faultTopBottom() const; + std::pair depthTopBottom() const; + + RimFaultReactivation::GridPart normalPointsAt() const; + + void postProcessElementSets( const RimEclipseCase* eCase ); private: std::shared_ptr m_generator; @@ -94,4 +98,5 @@ class RigFaultReactivationModel : public cvf::Object bool m_isValid; std::map m_3dparts; + RimFaultReactivation::GridPart m_normalPointsAt; }; diff --git a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.cpp b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.cpp index 3f7142df90..8530dd74b4 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.cpp @@ -21,6 +21,7 @@ #include "RiaApplication.h" #include "RigActiveCellInfo.h" +#include "RigCell.h" #include "RigFault.h" #include "RigGriddedPart3d.h" #include "RigMainGrid.h" @@ -36,21 +37,26 @@ //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RigFaultReactivationModelGenerator::RigFaultReactivationModelGenerator( cvf::Vec3d position, cvf::Vec3d normal ) +RigFaultReactivationModelGenerator::RigFaultReactivationModelGenerator( cvf::Vec3d position, cvf::Vec3d modelNormal, cvf::Vec3d modelDirection ) : m_startPosition( position ) - , m_normal( normal ) + , m_modelNormal( modelNormal ) + , m_modelDirection( modelDirection ) , m_bufferAboveFault( 0.0 ) , m_bufferBelowFault( 0.0 ) , m_startDepth( 0.0 ) + , m_bottomDepth( 0.0 ) , m_depthBelowFault( 100.0 ) , m_horzExtentFromFault( 1000.0 ) , m_modelThickness( 100.0 ) , m_useLocalCoordinates( false ) , m_cellSizeHeightFactor( 1.0 ) , m_cellSizeWidthFactor( 1.0 ) + , m_minCellHeight( 0.5 ) , m_maxCellHeight( 20.0 ) , m_minCellWidth( 20.0 ) + , m_faultZoneCells( 0 ) { + m_modelPlane.setFromPointAndNormal( position, modelNormal ); } //-------------------------------------------------------------------------------------------------- @@ -87,10 +93,11 @@ void RigFaultReactivationModelGenerator::setActiveCellInfo( const RigActiveCellI //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFaultReactivationModelGenerator::setFaultBufferDepth( double aboveFault, double belowFault ) +void RigFaultReactivationModelGenerator::setFaultBufferDepth( double aboveFault, double belowFault, int faultZoneCells ) { m_bufferAboveFault = aboveFault; m_bufferBelowFault = belowFault; + m_faultZoneCells = faultZoneCells; } //-------------------------------------------------------------------------------------------------- @@ -122,11 +129,13 @@ void RigFaultReactivationModelGenerator::setUseLocalCoordinates( bool useLocalCo //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFaultReactivationModelGenerator::setModelGriddingOptions( double maxCellHeight, +void RigFaultReactivationModelGenerator::setModelGriddingOptions( double minCellHeight, + double maxCellHeight, double cellSizeFactorHeight, double minCellWidth, double cellSizeFactorWidth ) { + m_minCellHeight = minCellHeight; m_maxCellHeight = maxCellHeight; m_cellSizeHeightFactor = cellSizeFactorHeight; m_minCellWidth = minCellWidth; @@ -138,10 +147,7 @@ void RigFaultReactivationModelGenerator::setModelGriddingOptions( double maxCell //-------------------------------------------------------------------------------------------------- std::pair RigFaultReactivationModelGenerator::modelLocalNormalsXY() { - cvf::Vec3d xNormal = m_normal ^ cvf::Vec3d::Z_AXIS; - xNormal.z() = 0.0; - xNormal.normalize(); - + cvf::Vec3d xNormal = m_modelDirection; cvf::Vec3d yNormal = xNormal ^ cvf::Vec3d::Z_AXIS; return std::make_pair( xNormal, yNormal ); @@ -161,11 +167,21 @@ void RigFaultReactivationModelGenerator::setupLocalCoordinateTransform() m_localCoordTransform.setTranslation( center ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Vec3d RigFaultReactivationModelGenerator::transformPointIfNeeded( const cvf::Vec3d point ) const +{ + if ( !m_useLocalCoordinates ) return point; + + return point.getTransformedPoint( m_localCoordTransform ); +} + //-------------------------------------------------------------------------------------------------- /// change corner order to be consistent so that index (0,1) and (2,3) gives the lower and upper horz. lines no matter what I or J face we /// have //-------------------------------------------------------------------------------------------------- -const std::array RigFaultReactivationModelGenerator::faceIJCornerIndexes( cvf::StructGridInterface::FaceType face ) +const std::array RigFaultReactivationModelGenerator::faceIJCornerIndexes( FaceType face ) { switch ( face ) { @@ -191,17 +207,7 @@ const std::array RigFaultReactivationModelGenerator::faceIJCornerIndexes //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -cvf::Vec3d RigFaultReactivationModelGenerator::lineIntersect( const cvf::Plane& plane, cvf::Vec3d lineA, cvf::Vec3d lineB ) -{ - double dist = 0.0; - return caf::HexGridIntersectionTools::planeLineIntersectionForMC( plane, lineA, lineB, &dist ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigFaultReactivationModelGenerator::oppositeStartCellIndex( const std::vector cellIndexColumn, - cvf::StructGridInterface::FaceType face ) +size_t RigFaultReactivationModelGenerator::oppositeStartCellIndex( const std::vector cellIndexColumn, FaceType face ) { auto oppositeStartFace = cvf::StructGridInterface::oppositeFace( face ); bool bFoundOppositeCell = false; @@ -234,7 +240,7 @@ size_t RigFaultReactivationModelGenerator::oppositeStartCellIndex( const std::ve //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFaultReactivationModelGenerator::addFilter( QString name, std::vector cells ) +void RigFaultReactivationModelGenerator::updateFilters( std::vector cellsFront, std::vector cellsBack ) { RimEclipseView* view = dynamic_cast( RiaApplication::instance()->activeGridView() ); if ( view == nullptr ) return; @@ -242,9 +248,12 @@ void RigFaultReactivationModelGenerator::addFilter( QString name, std::vectorcellFilterCollection(); if ( cellFilters == nullptr ) return; - auto eCase = cellFilters->firstAncestorOfType(); - auto filter = cellFilters->addNewUserDefinedIndexFilter( eCase, cells ); - filter->setName( name ); + auto eCase = cellFilters->firstAncestorOfType(); + auto frontFilter = cellFilters->addNewUserDefinedIndexFilter( eCase, cellsFront ); + frontFilter->setName( "Front" ); + + auto backFilter = cellFilters->addNewUserDefinedIndexFilter( eCase, cellsBack ); + backFilter->setName( "Back" ); } //-------------------------------------------------------------------------------------------------- @@ -288,17 +297,14 @@ void RigFaultReactivationModelGenerator::generatePointsFrontBack() { std::array points; - auto alongModel = m_normal ^ cvf::Vec3d::Z_AXIS; - alongModel.normalize(); + double top_depth = -m_startDepth; + m_bottomDepth = m_bottomFault.z() - m_depthBelowFault; - double top_depth = -m_startDepth; - double bottom_depth = m_bottomFault.z() - m_depthBelowFault; - - cvf::Vec3d edge_front = m_startPosition - m_horzExtentFromFault * alongModel; - cvf::Vec3d edge_back = m_startPosition + m_horzExtentFromFault * alongModel; + cvf::Vec3d edge_front = m_startPosition - m_horzExtentFromFault * m_modelDirection; + cvf::Vec3d edge_back = m_startPosition + m_horzExtentFromFault * m_modelDirection; points[8] = m_bottomFault; - points[8].z() = bottom_depth; + points[8].z() = m_bottomDepth; points[9] = m_bottomFault; points[10] = m_bottomReservoirBack; @@ -368,143 +374,277 @@ const std::vector RigFaultReactivationModelGenerator::partition( double //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RigFaultReactivationModelGenerator::elementKLayers( const std::vector& cellIndexColumn ) +std::vector + RigFaultReactivationModelGenerator::buildCellColumn( size_t startCellIndex, FaceType startFace, std::map& layers ) { - std::vector kLayers; - size_t i, j, k; - for ( auto idx : cellIndexColumn ) + + m_grid->ijkFromCellIndexUnguarded( startCellIndex, &i, &j, &k ); + + std::vector cellColumn; + + const int k_start = 0; + const size_t k_stop = m_grid->cellCountK(); + + // build list of k indexes to go through, starting at the start cell and going up, then continuing down below the start cell + std::vector k_values; + + for ( int kLayer = (int)k; kLayer >= k_start; kLayer-- ) + { + k_values.push_back( (size_t)kLayer ); + } + for ( size_t kLayer = k + 1; kLayer < k_stop; kLayer++ ) + { + k_values.push_back( kLayer ); + } + + auto [side1, side2] = sideFacesIJ( startFace ); + + bool isGoingUp = true; + + for ( auto kLayer : k_values ) { - m_grid->ijkFromCellIndexUnguarded( idx, &i, &j, &k ); + if ( !m_grid->isCellValid( i, j, kLayer ) ) continue; + const auto cellIdx = m_grid->cellIndexFromIJKUnguarded( i, j, kLayer ); + + RigCell cell = m_grid->cell( cellIdx ); + + std::vector cellRow; + + cellRow.push_back( cell.neighborCell( side1 ) ); + cellRow.push_back( cell ); + cellRow.push_back( cell.neighborCell( side2 ) ); + + cvf::Vec3d intersect1, intersect2; + size_t intersectedCell; - if ( m_activeCellInfo->isActive( idx ) ) + auto ij_pair = findCellWithIntersection( cellRow, startFace, intersectedCell, intersect1, intersect2, isGoingUp ); + + if ( intersect1.z() != intersect2.z() ) { - kLayers.push_back( (int)k ); + cellColumn.push_back( intersectedCell ); + if ( !intersect1.isZero() ) layers[intersect1.z()] = intersect1; + if ( !intersect2.isZero() ) layers[intersect2.z()] = intersect2; } - else + + if ( kLayer == k ) { - kLayers.push_back( -1 * (int)k ); + std::reverse( cellColumn.begin(), cellColumn.end() ); + isGoingUp = false; } - } - std::reverse( kLayers.begin(), kLayers.end() ); + i = ij_pair.first; + j = ij_pair.second; + } - return kLayers; + return cellColumn; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFaultReactivationModelGenerator::generateGeometry( size_t startCellIndex, - cvf::StructGridInterface::FaceType startFace, - RigGriddedPart3d* frontPart, - RigGriddedPart3d* backPart ) +std::pair RigFaultReactivationModelGenerator::findCellWithIntersection( const std::vector& cellRow, + FaceType face, + size_t& cellIndex, + cvf::Vec3d& intersect1, + cvf::Vec3d& intersect2, + bool goingUp ) { - std::vector cellColumnBackSearch; - std::vector cellColumnBack; - std::vector cellColumnFront; - size_t i, j, k; + const auto cornerIndexes = faceIJCornerIndexes( face ); - // build column of cells behind fault - m_grid->ijkFromCellIndexUnguarded( startCellIndex, &i, &j, &k ); - cellColumnBackSearch.push_back( startCellIndex ); // want the user clicked cell to be the first in the search list + size_t i = 0, j = 0, k = 0; - for ( size_t kLayer = 0; kLayer < m_grid->cellCountK(); kLayer++ ) + for ( auto& cell : cellRow ) { - if ( !m_grid->isCellValid( i, j, kLayer ) ) continue; + if ( cell.isInvalid() ) continue; + + auto corners = cell.faceCorners( face ); + + cvf::Vec3d intersect; + double dist = 0.0; + if ( caf::HexGridIntersectionTools::planeLineIntersect( m_modelPlane, + corners[cornerIndexes[0]], + corners[cornerIndexes[1]], + &intersect, + &dist, + 0.001 ) ) + { + intersect1 = intersect; + + if ( !goingUp ) + { + cellIndex = cell.mainGridCellIndex(); + m_grid->ijkFromCellIndexUnguarded( cellIndex, &i, &j, &k ); + } + } - auto cellIdx = m_grid->cellIndexFromIJKUnguarded( i, j, kLayer ); + if ( caf::HexGridIntersectionTools::planeLineIntersect( m_modelPlane, + corners[cornerIndexes[2]], + corners[cornerIndexes[3]], + &intersect, + &dist, + 0.001 ) ) + { + intersect2 = intersect; - if ( cellIdx != startCellIndex ) cellColumnBackSearch.push_back( cellIdx ); - cellColumnBack.push_back( cellIdx ); + if ( goingUp ) + { + cellIndex = cell.mainGridCellIndex(); + m_grid->ijkFromCellIndexUnguarded( cellIndex, &i, &j, &k ); + } + } } - // build cell column of cells in front of fault, opposite to the cell column behind the fault - auto oppositeStartFace = cvf::StructGridInterface::oppositeFace( startFace ); - size_t oppositeCellIdx = oppositeStartCellIndex( cellColumnBackSearch, startFace ); + return { i, j }; +} - m_grid->ijkFromCellIndexUnguarded( oppositeCellIdx, &i, &j, &k ); - for ( size_t kLayer = 0; kLayer < m_grid->cellCountK(); kLayer++ ) +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::array RigFaultReactivationModelGenerator::shiftOrigin( const std::array& points, + const cvf::Vec3d& newOrigin ) +{ + std::array retPoints; + for ( int i = 0; i < (int)points.size(); i++ ) { - if ( !m_grid->isCellValid( i, j, kLayer ) ) continue; + retPoints[i] = points[i] - newOrigin; + } + return retPoints; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigFaultReactivationModelGenerator::generateGeometry( size_t startCellIndex, + FaceType startFace, + RigGriddedPart3d* frontPart, + RigGriddedPart3d* backPart ) +{ + // build column of cells behind fault + + std::map layersBack; + std::vector cellColumnBack = buildCellColumn( startCellIndex, startFace, layersBack ); - auto cellIdx = m_grid->cellIndexFromIJKUnguarded( i, j, kLayer ); + // find start cell and face on the opposite side of the fault, start with the user clicked cell - cellColumnFront.push_back( cellIdx ); + std::vector cellColumnBackSearch = { startCellIndex }; + for ( auto cidx : cellColumnBack ) + { + if ( cidx != startCellIndex ) cellColumnBackSearch.push_back( cidx ); } + auto oppositeStartFace = cvf::StructGridInterface::oppositeFace( startFace ); + size_t oppositeStartCellIdx = oppositeStartCellIndex( cellColumnBackSearch, startFace ); - auto zPositionsBack = elementLayers( startFace, cellColumnBack ); - auto zPositionsFront = elementLayers( oppositeStartFace, cellColumnFront ); - auto kLayersBack = elementKLayers( cellColumnBack ); - auto kLayersFront = elementKLayers( cellColumnFront ); + // build cell column of cells in front of fault, opposite to the cell column behind the fault + + std::map layersFront; + std::vector cellColumnFront = buildCellColumn( oppositeStartCellIdx, oppositeStartFace, layersFront ); // add extra fault buffer below the fault, starting at the deepest bottom-most cell on either side of the fault - double front_bottom = zPositionsFront.begin()->first; - double back_bottom = zPositionsBack.begin()->first; - m_bottomReservoirFront = zPositionsFront.begin()->second; - m_bottomReservoirBack = zPositionsBack.begin()->second; + double front_bottom = layersFront.begin()->first; + double back_bottom = layersBack.begin()->first; + m_bottomReservoirFront = layersFront.begin()->second; + m_bottomReservoirBack = layersBack.begin()->second; cvf::Vec3d bottom_point = m_bottomReservoirFront; if ( front_bottom > back_bottom ) { - bottom_point = extrapolatePoint( ( ++zPositionsBack.begin() )->second, zPositionsBack.begin()->second, m_bufferBelowFault ); + bottom_point = extrapolatePoint( ( ++layersBack.begin() )->second, layersBack.begin()->second, m_bufferBelowFault ); } - else if ( front_bottom < back_bottom ) + else { - bottom_point = extrapolatePoint( ( ++zPositionsFront.begin() )->second, zPositionsFront.begin()->second, m_bufferBelowFault ); + bottom_point = extrapolatePoint( ( ++layersFront.begin() )->second, layersFront.begin()->second, m_bufferBelowFault ); } m_bottomFault = bottom_point; // add extra fault buffer above the fault, starting at the shallowest top-most cell on either side of the fault - double front_top = zPositionsFront.rbegin()->first; - double back_top = zPositionsBack.rbegin()->first; - m_topReservoirFront = zPositionsFront.rbegin()->second; - m_topReservoirBack = zPositionsBack.rbegin()->second; + double front_top = layersFront.rbegin()->first; + double back_top = layersBack.rbegin()->first; + m_topReservoirFront = layersFront.rbegin()->second; + m_topReservoirBack = layersBack.rbegin()->second; cvf::Vec3d top_point = m_topReservoirFront; if ( front_top > back_top ) { - top_point = extrapolatePoint( ( ++zPositionsFront.rbegin() )->second, zPositionsFront.rbegin()->second, m_bufferAboveFault ); + top_point = extrapolatePoint( ( ++layersFront.rbegin() )->second, layersFront.rbegin()->second, m_bufferAboveFault ); } - else if ( front_top < back_top ) + else { - top_point = extrapolatePoint( ( ++zPositionsBack.rbegin() )->second, zPositionsBack.rbegin()->second, m_bufferAboveFault ); + top_point = extrapolatePoint( ( ++layersBack.rbegin() )->second, layersBack.rbegin()->second, m_bufferAboveFault ); } m_topFault = top_point; - splitLargeLayers( zPositionsFront, kLayersFront, m_maxCellHeight ); - splitLargeLayers( zPositionsBack, kLayersBack, m_maxCellHeight ); + // make sure layers aren't too small or too thick + + mergeTinyLayers( layersFront, m_minCellHeight ); + mergeTinyLayers( layersBack, m_minCellHeight ); + + splitLargeLayers( layersFront, m_maxCellHeight ); + splitLargeLayers( layersBack, m_maxCellHeight ); std::vector frontReservoirLayers; - for ( auto& kvp : zPositionsFront ) + for ( auto& kvp : layersFront ) frontReservoirLayers.push_back( kvp.second ); std::vector backReservoirLayers; - for ( auto& kvp : zPositionsBack ) + for ( auto& kvp : layersBack ) backReservoirLayers.push_back( kvp.second ); + // generate the actual front and back grid parts + generatePointsFrontBack(); - frontPart->generateGeometry( m_frontPoints, - frontReservoirLayers, - kLayersFront, + // use temp origin in start position, at zero depth + cvf::Vec3d origin( m_startPosition ); + origin.z() = 0.0; + + cvf::Vec3d tVec = m_modelThickness * m_modelNormal; + std::vector thicknessVectors; + std::vector> faultLines; + const std::vector thicknessFactors = { -1.0, 0.0, 1.0 }; + + for ( int i = 0; i < 3; i++ ) + { + faultLines.push_back( + caf::Line( m_topFault - origin + thicknessFactors[i] * tVec, m_bottomFault - origin + thicknessFactors[i] * tVec ) ); + thicknessVectors.push_back( thicknessFactors[i] * tVec ); + } + + std::array shiftedFrontPoints = shiftOrigin( m_frontPoints, origin ); + std::array shiftedBackPoints = shiftOrigin( m_backPoints, origin ); + + std::vector frontResZ = extractZValues( frontReservoirLayers ); + std::vector backResZ = extractZValues( backReservoirLayers ); + + frontPart->generateGeometry( shiftedFrontPoints, + frontResZ, m_maxCellHeight, m_cellSizeHeightFactor, m_horizontalPartition, - m_modelThickness, - m_topReservoirFront.z() ); - backPart->generateGeometry( m_backPoints, - backReservoirLayers, - kLayersBack, + faultLines, + thicknessVectors, + m_topReservoirFront.z(), + m_faultZoneCells ); + + std::reverse( faultLines.begin(), faultLines.end() ); + std::reverse( thicknessVectors.begin(), thicknessVectors.end() ); + + backPart->generateGeometry( shiftedBackPoints, + backResZ, m_maxCellHeight, m_cellSizeHeightFactor, m_horizontalPartition, - m_modelThickness, - m_topReservoirBack.z() ); + faultLines, + thicknessVectors, + m_topReservoirBack.z(), + m_faultZoneCells ); + + frontPart->shiftNodes( origin ); + backPart->shiftNodes( origin ); frontPart->generateLocalNodes( m_localCoordTransform ); backPart->generateLocalNodes( m_localCoordTransform ); @@ -516,42 +656,27 @@ void RigFaultReactivationModelGenerator::generateGeometry( size_t //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::map RigFaultReactivationModelGenerator::elementLayers( cvf::StructGridInterface::FaceType face, - std::vector& cellIndexColumn ) +std::pair RigFaultReactivationModelGenerator::sideFacesIJ( FaceType face ) { - cvf::Plane modelPlane; - modelPlane.setFromPointAndNormal( m_startPosition, m_normal ); - - auto cornerIndexes = faceIJCornerIndexes( face ); - - std::map zPositions; - - std::vector okCells; - - for ( auto cellIdx : cellIndexColumn ) + switch ( face ) { - RigCell cell = m_grid->cell( cellIdx ); - auto corners = cell.faceCorners( face ); - - cvf::Vec3d intersect1 = lineIntersect( modelPlane, corners[cornerIndexes[0]], corners[cornerIndexes[1]] ); - cvf::Vec3d intersect2 = lineIntersect( modelPlane, corners[cornerIndexes[2]], corners[cornerIndexes[3]] ); + case cvf::StructGridInterface::POS_I: + case cvf::StructGridInterface::NEG_I: + return { cvf::StructGridInterface::NEG_J, cvf::StructGridInterface::POS_J }; - if ( intersect1.z() != intersect2.z() ) - { - zPositions[intersect1.z()] = intersect1; - zPositions[intersect2.z()] = intersect2; - okCells.push_back( cellIdx ); - } - } + case cvf::StructGridInterface::POS_J: + case cvf::StructGridInterface::NEG_J: + return { cvf::StructGridInterface::NEG_I, cvf::StructGridInterface::POS_I }; - // only keep cells that have a valid height at the plane intersection - cellIndexColumn.clear(); - for ( auto idx : okCells ) - { - cellIndexColumn.push_back( idx ); + case cvf::StructGridInterface::POS_K: + case cvf::StructGridInterface::NEG_K: + case cvf::StructGridInterface::NO_FACE: + default: + break; } - return zPositions; + CVF_ASSERT( false ); // not supported for K faces + return { cvf::StructGridInterface::NO_FACE, cvf::StructGridInterface::NO_FACE }; } //-------------------------------------------------------------------------------------------------- @@ -568,54 +693,91 @@ cvf::Vec3d RigFaultReactivationModelGenerator::extrapolatePoint( cvf::Vec3d star //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigFaultReactivationModelGenerator::splitLargeLayers( std::map& layers, std::vector& kLayers, double maxHeight ) +void RigFaultReactivationModelGenerator::mergeTinyLayers( std::map& layers, double minHeight ) { - std::vector additionalPoints; - - std::pair prevLayer; - std::vector newKLayers; - - bool first = true; - int k = 0; + std::vector newLayers; const int nLayers = (int)layers.size(); - int n = 0; + + std::vector keys; + std::vector vals; for ( auto& layer : layers ) { - if ( n++ == ( nLayers - 1 ) ) break; + keys.push_back( layer.first ); + vals.push_back( layer.second ); + } + + // bottom layer must always be included + newLayers.push_back( vals.front() ); - if ( first ) + // remove any layer that is less than minHeight above the previous layer, starting at the bottom + for ( int k = 1; k < nLayers - 1; k++ ) + { + if ( std::abs( keys[k] - keys[k - 1] ) < minHeight ) { - prevLayer = layer; - first = false; - newKLayers.push_back( kLayers[k++] ); continue; } + newLayers.push_back( vals[k] ); + } + // top layer must always be included + newLayers.push_back( vals.back() ); - if ( std::abs( prevLayer.first - layer.first ) > maxHeight ) + // make sure the top two layers aren't too close, if so, remove the second topmost + const int nNewLayers = (int)newLayers.size(); + if ( nNewLayers > 2 ) + { + if ( std::abs( newLayers[nNewLayers - 1].z() - newLayers[nNewLayers - 2].z() ) < minHeight ) { - const auto& points = interpolateExtraPoints( prevLayer.second, layer.second, maxHeight ); - for ( auto& p : points ) - { - additionalPoints.push_back( p ); - newKLayers.push_back( kLayers[k - 1] ); - } + newLayers.pop_back(); + newLayers.pop_back(); + newLayers.push_back( vals.back() ); } - - prevLayer = layer; - newKLayers.push_back( kLayers[k++] ); } - for ( auto& p : additionalPoints ) + layers.clear(); + for ( auto& p : newLayers ) { layers[p.z()] = p; } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigFaultReactivationModelGenerator::splitLargeLayers( std::map& layers, double maxHeight ) +{ + std::vector additionalPoints; + + const int nLayers = (int)layers.size(); + + std::vector keys; + std::vector vals; - kLayers.clear(); - for ( auto k : newKLayers ) + for ( auto& layer : layers ) { - kLayers.push_back( k ); + keys.push_back( layer.first ); + vals.push_back( layer.second ); + } + + for ( int k = 0; k < nLayers; k++ ) + { + if ( k > 0 ) + { + if ( std::abs( keys[k] - keys[k - 1] ) > maxHeight ) + { + const auto& points = interpolateExtraPoints( vals[k - 1], vals[k], maxHeight ); + for ( auto& p : points ) + { + additionalPoints.push_back( p ); + } + } + } + } + + for ( auto& p : additionalPoints ) + { + layers[p.z()] = p; } } @@ -648,9 +810,9 @@ const std::vector RigFaultReactivationModelGenerator::interpolateExt //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const cvf::Vec3d RigFaultReactivationModelGenerator::normal() const +const cvf::Vec3d RigFaultReactivationModelGenerator::modelNormal() const { - return m_normal; + return m_modelNormal; } //-------------------------------------------------------------------------------------------------- @@ -660,3 +822,26 @@ const std::pair RigFaultReactivationModelGenerator::faul { return std::make_pair( m_topFault, m_bottomFault ); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::pair RigFaultReactivationModelGenerator::depthTopBottom() const +{ + return { -m_startDepth, m_bottomDepth }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RigFaultReactivationModelGenerator::extractZValues( const std::vector& points ) +{ + std::vector layers; + + for ( auto& p : points ) + { + layers.push_back( p.z() ); + } + + return layers; +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.h b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.h index b73f5ce417..23fbe91dc4 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.h +++ b/ApplicationLibCode/ReservoirDataModel/RigFaultReactivationModelGenerator.h @@ -33,57 +33,76 @@ class RigFault; class RigMainGrid; class RigGriddedPart3d; class RigActiveCellInfo; +class RigCell; class RigFaultReactivationModelGenerator : cvf::Object { + using FaceType = cvf::StructGridInterface::FaceType; + public: - RigFaultReactivationModelGenerator( cvf::Vec3d position, cvf::Vec3d normal ); - ~RigFaultReactivationModelGenerator(); + RigFaultReactivationModelGenerator( cvf::Vec3d position, cvf::Vec3d modelNormal, cvf::Vec3d direction ); + ~RigFaultReactivationModelGenerator() override; void setFault( const RigFault* fault ); void setGrid( const RigMainGrid* grid ); void setActiveCellInfo( const RigActiveCellInfo* activeCellInfo ); - void setFaultBufferDepth( double aboveFault, double belowFault ); + void setFaultBufferDepth( double aboveFault, double belowFault, int faultZoneCells ); void setModelSize( double startDepth, double depthBelowFault, double horzExtentFromFault ); void setModelThickness( double thickness ); - void setModelGriddingOptions( double maxCellHeight, double cellSizeFactorHeight, double minCellWidth, double cellSizeFactorWidth ); + void setModelGriddingOptions( double minCellHeight, + double maxCellHeight, + double cellSizeFactorHeight, + double minCellWidth, + double cellSizeFactorWidth ); void setUseLocalCoordinates( bool useLocalCoordinates ); void setupLocalCoordinateTransform(); + cvf::Vec3d transformPointIfNeeded( const cvf::Vec3d point ) const; + std::pair modelLocalNormalsXY(); - void generateGeometry( size_t startCellIndex, - cvf::StructGridInterface::FaceType startFace, - RigGriddedPart3d* frontPart, - RigGriddedPart3d* backPart ); + void generateGeometry( size_t startCellIndex, FaceType startFace, RigGriddedPart3d* frontPart, RigGriddedPart3d* backPart ); const std::array& frontPoints() const; const std::array& backPoints() const; - const cvf::Vec3d normal() const; + const cvf::Vec3d modelNormal() const; const std::pair faultTopBottomPoints() const; + std::pair depthTopBottom() const; protected: - static const std::array faceIJCornerIndexes( cvf::StructGridInterface::FaceType face ); + static const std::array faceIJCornerIndexes( FaceType face ); static const std::vector interpolateExtraPoints( cvf::Vec3d from, cvf::Vec3d to, double maxStep ); static const std::vector partition( double distance, double startSize, double sizeFactor ); + static std::pair sideFacesIJ( FaceType face ); - static cvf::Vec3d lineIntersect( const cvf::Plane& plane, cvf::Vec3d lineA, cvf::Vec3d lineB ); - static cvf::Vec3d extrapolatePoint( cvf::Vec3d startPoint, cvf::Vec3d endPoint, double stopDepth ); - static void splitLargeLayers( std::map& layers, std::vector& kLayers, double maxHeight ); + static cvf::Vec3d extrapolatePoint( cvf::Vec3d startPoint, cvf::Vec3d endPoint, double stopDepth ); + static void splitLargeLayers( std::map& layers, double maxHeight ); + static void mergeTinyLayers( std::map& layers, double minHeight ); + static std::vector extractZValues( const std::vector& points ); + static std::array shiftOrigin( const std::array& points, const cvf::Vec3d& newOrigin ); - std::map elementLayers( cvf::StructGridInterface::FaceType face, std::vector& cellIndexColumn ); - std::vector elementKLayers( const std::vector& cellIndexColumn ); + std::vector buildCellColumn( size_t startCell, FaceType startFace, std::map& layers ); - void addFilter( QString name, std::vector cells ); + void updateFilters( std::vector frontCells, std::vector backCells ); - size_t oppositeStartCellIndex( const std::vector cellIndexColumn, cvf::StructGridInterface::FaceType face ); + size_t oppositeStartCellIndex( const std::vector cellIndexColumn, FaceType face ); void generatePointsFrontBack(); + std::pair findCellWithIntersection( const std::vector& cellRow, + FaceType face, + size_t& cellIndex, + cvf::Vec3d& intersect1, + cvf::Vec3d& intersect2, + bool goingUp ); + private: cvf::Vec3d m_startPosition; - cvf::Vec3d m_normal; + cvf::Vec3d m_modelNormal; + cvf::Vec3d m_modelDirection; + + cvf::Plane m_modelPlane; std::array m_frontPoints; std::array m_backPoints; @@ -96,12 +115,15 @@ class RigFaultReactivationModelGenerator : cvf::Object double m_bufferAboveFault; double m_bufferBelowFault; + int m_faultZoneCells; double m_startDepth; + double m_bottomDepth; double m_depthBelowFault; double m_horzExtentFromFault; double m_modelThickness; + double m_minCellHeight; double m_maxCellHeight; double m_cellSizeHeightFactor; double m_minCellWidth; diff --git a/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.cpp b/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.cpp index 96dd3a4a09..86ded27774 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.cpp @@ -36,6 +36,7 @@ #include "RigGeoMechCaseData.h" #include "RigFemAddressDefines.h" +#include "RigWbsParameter.h" #include "RigWellLogExtractionTools.h" #include "RigWellPath.h" #include "RigWellPathGeometryTools.h" @@ -48,6 +49,7 @@ #include #include +#include #include const double RigGeoMechWellLogExtractor::PURE_WATER_DENSITY_GCM3 = 1.0; // g / cm^3 @@ -147,13 +149,21 @@ QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAdd { wellBoreWallCurveData( resAddr, timeStepIndex, frameIndex, values ); // Try to replace invalid values with Shale-values - wellBoreFGShale( timeStepIndex, frameIndex, values ); + wellBoreFGShale( RigWbsParameter::FG_Shale(), timeStepIndex, frameIndex, values ); values->front() = wbsCurveValuesAtMsl(); } else if ( resAddr.fieldName == RiaResultNames::wbsSFGResult().toStdString() ) { wellBoreWallCurveData( resAddr, timeStepIndex, frameIndex, values ); } + else if ( resAddr.fieldName == RiaResultNames::wbsFGMkMinResult().toStdString() ) + { + wellBoreFG_MatthewsKelly( RigWbsParameter::FG_MkMin(), timeStepIndex, frameIndex, values ); + } + else if ( resAddr.fieldName == RiaResultNames::wbsFGMkExpResult().toStdString() ) + { + wellBoreFG_MatthewsKelly( RigWbsParameter::FG_MkExp(), timeStepIndex, frameIndex, values ); + } else if ( resAddr.fieldName == RiaResultNames::wbsPPResult().toStdString() || resAddr.fieldName == RiaResultNames::wbsOBGResult().toStdString() || resAddr.fieldName == RiaResultNames::wbsSHResult().toStdString() ) @@ -166,10 +176,26 @@ QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAdd { wellPathAngles( resAddr, values ); } - else if ( resAddr.fieldName == RiaResultNames::wbsSHMkResult().toStdString() ) + else if ( resAddr.fieldName == RiaResultNames::wbsSHMkResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsSHMkMinResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsSHMkMaxResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsSHMkExpResult().toStdString() ) { - wellBoreSH_MatthewsKelly( timeStepIndex, frameIndex, values ); - values->front() = wbsCurveValuesAtMsl(); + auto mapSHMkToPP = []( const QString& SHMkName ) -> std::pair + { + if ( SHMkName == RiaResultNames::wbsSHMkMinResult() ) + return { RiaResultNames::wbsPPMinResult(), RiaResultNames::wbsPPInitialResult() }; + if ( SHMkName == RiaResultNames::wbsSHMkMaxResult() ) + return { RiaResultNames::wbsPPMaxResult(), RiaResultNames::wbsPPInitialResult() }; + if ( SHMkName == RiaResultNames::wbsSHMkExpResult() ) + return { RiaResultNames::wbsPPExpResult(), RiaResultNames::wbsPPInitialResult() }; + + CAF_ASSERT( SHMkName == RiaResultNames::wbsSHMkResult() ); + return { RiaResultNames::wbsPPResult(), RiaResultNames::wbsPPResult() }; + }; + + auto [ppResultName, pp0ResultName] = mapSHMkToPP( QString::fromStdString( resAddr.fieldName ) ); + wellBoreSH_MatthewsKelly( timeStepIndex, frameIndex, ppResultName, pp0ResultName, values ); } else { @@ -179,7 +205,7 @@ QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAdd { if ( param == RigWbsParameter::FG_Shale() ) { - wellBoreFGShale( timeStepIndex, frameIndex, values ); + wellBoreFGShale( param, timeStepIndex, frameIndex, values ); } else { @@ -200,6 +226,11 @@ QString RigGeoMechWellLogExtractor::curveData( const RigFemResultAddress& resAdd { return RiaWellLogUnitTools::noUnitString(); } + else if ( param == RigWbsParameter::PP_Min() || param == RigWbsParameter::PP_Max() || + param == RigWbsParameter::PP_Exp() || param == RigWbsParameter::PP_Initial() ) + { + return RiaWellLogUnitTools::barUnitString(); + } } } } @@ -565,6 +596,16 @@ std::vector { sources = calculateWbsParameterForAllSegments( RigWbsParameter::OBG(), timeStepIndex, frameIndex, values, true ); } + else if ( resAddr.fieldName == RiaResultNames::wbsPPExpResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsPPMinResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsPPMaxResult().toStdString() ) + { + RigWbsParameter param; + bool ok = RigWbsParameter::findParameter( QString::fromStdString( resAddr.fieldName ), ¶m ); + + CAF_ASSERT( ok ); + sources = calculateWbsParameterForAllSegments( param, timeStepIndex, frameIndex, values, true ); + } else { sources = calculateWbsParameterForAllSegments( RigWbsParameter::SH(), timeStepIndex, frameIndex, values, true ); @@ -583,7 +624,9 @@ void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddres { CVF_ASSERT( values ); CVF_ASSERT( resAddr.fieldName == RiaResultNames::wbsFGResult().toStdString() || - resAddr.fieldName == RiaResultNames::wbsSFGResult().toStdString() ); + resAddr.fieldName == RiaResultNames::wbsSFGResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsFGMkMinResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsFGMkExpResult().toStdString() ); // The result addresses needed RigFemResultAddress stressResAddr( RIG_ELEMENT_NODAL, "ST", "" ); @@ -591,6 +634,15 @@ void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddres RigFemPartResultsCollection* resultCollection = m_caseData->femPartResults(); + auto mapFGResultToPP = []( const QString& fgResultName ) + { + if ( fgResultName == RiaResultNames::wbsFGMkMinResult() ) return RigWbsParameter::PP_Min(); + if ( fgResultName == RiaResultNames::wbsFGMkExpResult() ) return RigWbsParameter::PP_Exp(); + return RigWbsParameter::PP_Reservoir(); + }; + + RigWbsParameter ppParameter = mapFGResultToPP( QString::fromStdString( resAddr.fieldName ) ); + // Load results std::vector vertexStressesFloat = resultCollection->tensors( stressResAddr, m_partId, timeStepIndex, frameIndex ); if ( vertexStressesFloat.empty() ) return; @@ -609,7 +661,7 @@ void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddres std::vector ppSandAllSegments( intersections().size(), std::numeric_limits::infinity() ); std::vector ppSources = - calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(), RigWbsParameter::GRID, frameIndex, &ppSandAllSegments, false ); + calculateWbsParameterForAllSegments( ppParameter, timeStepIndex, frameIndex, &ppSandAllSegments, false ); std::vector poissonAllSegments( intersections().size(), std::numeric_limits::infinity() ); calculateWbsParameterForAllSegments( RigWbsParameter::poissonRatio(), timeStepIndex, frameIndex, &poissonAllSegments, false ); @@ -622,6 +674,12 @@ void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddres { // FG is for sands, SFG for shale. Sands has valid PP, shale does not. bool isFGregion = ppSources[intersectionIdx] == RigWbsParameter::GRID; + if ( resAddr.fieldName == RiaResultNames::wbsFGMkMinResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsFGMkExpResult().toStdString() ) + { + // Assume only FG for entire well log for FG_MK_MIN/EXP. + isFGregion = true; + } double hydroStaticPorePressureBar = hydroStaticPorePressureForSegment( intersectionIdx ); @@ -644,7 +702,9 @@ void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddres RigGeoMechBoreHoleStressCalculator sigmaCalculator( wellPathStressDouble, porePressureBar, poissonRatio, ucsBar, 32 ); double resultValue = std::numeric_limits::infinity(); - if ( resAddr.fieldName == RiaResultNames::wbsFGResult().toStdString() ) + if ( resAddr.fieldName == RiaResultNames::wbsFGResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsFGMkMinResult().toStdString() || + resAddr.fieldName == RiaResultNames::wbsFGMkExpResult().toStdString() ) { if ( isFGregion && validSegmentStress ) { @@ -673,51 +733,140 @@ void RigGeoMechWellLogExtractor::wellBoreWallCurveData( const RigFemResultAddres //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigGeoMechWellLogExtractor::wellBoreFGShale( int timeStepIndex, int frameIndex, std::vector* values ) +void RigGeoMechWellLogExtractor::wellBoreFGShale( const RigWbsParameter& parameter, int timeStepIndex, int frameIndex, std::vector* values ) { if ( values->empty() ) values->resize( intersections().size(), std::numeric_limits::infinity() ); - WbsParameterSource source = m_parameterSources.at( RigWbsParameter::FG_Shale() ); + WbsParameterSource source = m_parameterSources.at( parameter ); if ( source == RigWbsParameter::DERIVED_FROM_K0FG ) { - std::vector PP0; // results - std::vector K0_FG, OBG0; // parameters - - RigFemResultAddress ppAddr( RIG_WELLPATH_DERIVED, RiaResultNames::wbsPPResult().toStdString(), "" ); - wellPathScaledCurveData( ppAddr, 0, 0, &PP0, true ); - - calculateWbsParameterForAllSegments( RigWbsParameter::K0_FG(), timeStepIndex, frameIndex, &K0_FG, true ); - calculateWbsParameterForAllSegments( RigWbsParameter::OBG0(), 0, 0, &OBG0, true ); - + wellBoreFGDerivedFromK0FG( RiaResultNames::wbsPPResult(), timeStepIndex, frameIndex, values, false ); + } + else + { + std::vector SH; + calculateWbsParameterForAllSegments( RigWbsParameter::SH(), timeStepIndex, frameIndex, &SH, true ); + CVF_ASSERT( SH.size() == intersections().size() ); + double multiplier = m_userDefinedValues.at( parameter ); + CVF_ASSERT( multiplier != std::numeric_limits::infinity() ); #pragma omp parallel for for ( int64_t intersectionIdx = 0; intersectionIdx < static_cast( intersections().size() ); ++intersectionIdx ) { if ( !isValid( ( *values )[intersectionIdx] ) ) { - if ( isValid( PP0[intersectionIdx] ) && isValid( OBG0[intersectionIdx] ) && isValid( K0_FG[intersectionIdx] ) ) + if ( isValid( SH[intersectionIdx] ) ) { - ( *values )[intersectionIdx] = - ( K0_FG[intersectionIdx] * ( OBG0[intersectionIdx] - PP0[intersectionIdx] ) + PP0[intersectionIdx] ); + ( *values )[intersectionIdx] = SH[intersectionIdx] * multiplier; } } } } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigGeoMechWellLogExtractor::wellBoreFGDerivedFromK0FG( const QString& ppResult, + int timeStepIndex, + int frameIndex, + std::vector* values, + bool onlyForPPReservoir ) +{ + std::vector PP0; // results + std::vector K0_FG, OBG0; // parameters + + RigFemResultAddress ppAddr( RIG_WELLPATH_DERIVED, ppResult.toStdString(), "" ); + wellPathScaledCurveData( ppAddr, 0, 0, &PP0, true ); + + if ( onlyForPPReservoir ) + { + std::vector PP( intersections().size(), std::numeric_limits::infinity() ); + std::vector ppSources = + calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(), timeStepIndex, frameIndex, &PP, false ); + + // Invalidate PP results from outside the reservoir zone. +#pragma omp parallel for + for ( int64_t intersectionIdx = 0; intersectionIdx < static_cast( intersections().size() ); ++intersectionIdx ) + { + if ( !isValid( PP[intersectionIdx] ) || ppSources[intersectionIdx] != RigWbsParameter::GRID ) + { + PP0[intersectionIdx] = std::numeric_limits::infinity(); + } + } + } + + calculateWbsParameterForAllSegments( RigWbsParameter::K0_FG(), timeStepIndex, frameIndex, &K0_FG, true ); + calculateWbsParameterForAllSegments( RigWbsParameter::OBG0(), 0, 0, &OBG0, true ); + +#pragma omp parallel for + for ( int64_t intersectionIdx = 0; intersectionIdx < static_cast( intersections().size() ); ++intersectionIdx ) + { + if ( !isValid( ( *values )[intersectionIdx] ) ) + { + if ( isValid( PP0[intersectionIdx] ) && isValid( OBG0[intersectionIdx] ) && isValid( K0_FG[intersectionIdx] ) ) + { + ( *values )[intersectionIdx] = + ( K0_FG[intersectionIdx] * ( OBG0[intersectionIdx] - PP0[intersectionIdx] ) + PP0[intersectionIdx] ); + } + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigGeoMechWellLogExtractor::wellBoreFG_MatthewsKelly( const RigWbsParameter& parameter, + int timeStepIndex, + int frameIndex, + std::vector* values ) +{ + values->resize( intersections().size(), std::numeric_limits::infinity() ); + + // Use FG_Shale source to avoid creating more options. + WbsParameterSource source = m_parameterSources.at( RigWbsParameter::FG_Shale() ); + if ( source == RigWbsParameter::DERIVED_FROM_K0FG ) + { + auto mapParameterToPPResult = []( const RigWbsParameter& parameter ) + { + if ( parameter.name() == RiaResultNames::wbsFGMkMinResult() ) return RiaResultNames::wbsPPMinResult(); + if ( parameter.name() == RiaResultNames::wbsFGMkExpResult() ) return RiaResultNames::wbsPPExpResult(); + return RiaResultNames::wbsPPResult(); + }; + + QString ppResultName = mapParameterToPPResult( parameter ); + bool onlyForPPReservoir = true; + wellBoreFGDerivedFromK0FG( ppResultName, timeStepIndex, frameIndex, values, onlyForPPReservoir ); + } else { + auto mapParameterToSHMkResult = []( const RigWbsParameter& parameter ) + { + if ( parameter.name() == RiaResultNames::wbsFGMkMinResult() ) return RiaResultNames::wbsSHMkMinResult(); + if ( parameter.name() == RiaResultNames::wbsFGMkExpResult() ) return RiaResultNames::wbsSHMkExpResult(); + return RiaResultNames::wbsSHMkResult(); + }; + std::vector SH; - calculateWbsParameterForAllSegments( RigWbsParameter::SH(), timeStepIndex, frameIndex, &SH, true ); + QString SHMkResultName = mapParameterToSHMkResult( parameter ); + RigFemResultAddress SHMkAddr( RIG_WELLPATH_DERIVED, SHMkResultName.toStdString(), "" ); + + curveData( SHMkAddr, timeStepIndex, frameIndex, &SH ); + CVF_ASSERT( SH.size() == intersections().size() ); - double multiplier = m_userDefinedValues.at( RigWbsParameter::FG_Shale() ); + + std::vector PP( intersections().size(), std::numeric_limits::infinity() ); + std::vector ppSources = + calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(), timeStepIndex, frameIndex, &PP, false ); + + double multiplier = m_userDefinedValues.at( parameter ); CVF_ASSERT( multiplier != std::numeric_limits::infinity() ); #pragma omp parallel for for ( int64_t intersectionIdx = 0; intersectionIdx < static_cast( intersections().size() ); ++intersectionIdx ) { - if ( !isValid( ( *values )[intersectionIdx] ) ) + if ( !isValid( ( *values )[intersectionIdx] ) && ppSources[intersectionIdx] == RigWbsParameter::GRID && + isValid( PP[intersectionIdx] ) && isValid( SH[intersectionIdx] ) ) { - if ( isValid( SH[intersectionIdx] ) ) - { - ( *values )[intersectionIdx] = SH[intersectionIdx] * multiplier; - } + ( *values )[intersectionIdx] = SH[intersectionIdx] * multiplier; } } } @@ -726,27 +875,41 @@ void RigGeoMechWellLogExtractor::wellBoreFGShale( int timeStepIndex, int frameIn //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigGeoMechWellLogExtractor::wellBoreSH_MatthewsKelly( int timeStepIndex, int frameIndex, std::vector* values ) +void RigGeoMechWellLogExtractor::wellBoreSH_MatthewsKelly( int timeStepIndex, + int frameIndex, + const QString& wbsPPResultName, + const QString& wbsPP0ResultName, + std::vector* values ) { std::vector PP, PP0; // results std::vector K0_SH, OBG0, DF; // parameters - RigFemResultAddress ppAddr( RIG_WELLPATH_DERIVED, RiaResultNames::wbsPPResult().toStdString(), "" ); + RigFemResultAddress ppAddr( RIG_WELLPATH_DERIVED, wbsPPResultName.toStdString(), "" ); + RigFemResultAddress pp0Addr( RIG_WELLPATH_DERIVED, wbsPP0ResultName.toStdString(), "" ); curveData( ppAddr, timeStepIndex, frameIndex, &PP ); - curveData( ppAddr, 0, 0, &PP0 ); + curveData( pp0Addr, 0, 0, &PP0 ); calculateWbsParameterForAllSegments( RigWbsParameter::K0_SH(), timeStepIndex, frameIndex, &K0_SH, true ); calculateWbsParameterForAllSegments( RigWbsParameter::OBG0(), 0, 0, &OBG0, true ); calculateWbsParameterForAllSegments( RigWbsParameter::DF(), timeStepIndex, frameIndex, &DF, true ); + std::vector ppSandAllSegments( intersections().size(), std::numeric_limits::infinity() ); + std::vector ppSources = + calculateWbsParameterForAllSegments( RigWbsParameter::PP_Reservoir(), timeStepIndex, frameIndex, &ppSandAllSegments, false ); + values->resize( intersections().size(), std::numeric_limits::infinity() ); + if ( PP.size() != intersections().size() || PP0.size() != intersections().size() ) return; + + CAF_ASSERT( OBG0.size() == intersections().size() ); + CAF_ASSERT( K0_SH.size() == intersections().size() ); + CAF_ASSERT( DF.size() == intersections().size() ); #pragma omp parallel for for ( int64_t intersectionIdx = 0; intersectionIdx < static_cast( intersections().size() ); ++intersectionIdx ) { - if ( isValid( PP[intersectionIdx] ) && isValid( PP0[intersectionIdx] ) && isValid( OBG0[intersectionIdx] ) && - isValid( K0_SH[intersectionIdx] ) && isValid( DF[intersectionIdx] ) ) + if ( ppSources[intersectionIdx] == RigWbsParameter::GRID && isValid( PP[intersectionIdx] ) && isValid( PP0[intersectionIdx] ) && + isValid( OBG0[intersectionIdx] ) && isValid( K0_SH[intersectionIdx] ) && isValid( DF[intersectionIdx] ) ) { ( *values )[intersectionIdx] = ( K0_SH[intersectionIdx] * ( OBG0[intersectionIdx] - PP0[intersectionIdx] ) + PP0[intersectionIdx] + DF[intersectionIdx] * ( PP[intersectionIdx] - PP0[intersectionIdx] ) ); @@ -791,7 +954,9 @@ void RigGeoMechWellLogExtractor::setWbsUserDefinedValue( RigWbsParameter paramet //-------------------------------------------------------------------------------------------------- QString RigGeoMechWellLogExtractor::parameterInputUnits( const RigWbsParameter& parameter ) { - if ( parameter == RigWbsParameter::PP_NonReservoir() || parameter == RigWbsParameter::PP_Reservoir() || parameter == RigWbsParameter::UCS() ) + if ( parameter == RigWbsParameter::PP_NonReservoir() || parameter == RigWbsParameter::PP_Reservoir() || + parameter == RigWbsParameter::UCS() || parameter == RigWbsParameter::PP_Min() || parameter == RigWbsParameter::PP_Max() || + parameter == RigWbsParameter::PP_Exp() || parameter == RigWbsParameter::PP_Initial() ) { return RiaWellLogUnitTools::barUnitString(); } @@ -874,7 +1039,7 @@ T RigGeoMechWellLogExtractor::interpolateGridResultValue( RigFemResultPosEnum size_t elmIdx = intersectedCellsGlobIdx()[intersectionIdx]; RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType != HEX8 && elmType != HEX8P ) return T(); + if ( !RigFemTypes::is8NodeElement( elmType ) ) return T(); if ( resultPosType == RIG_FORMATION_NAMES ) { @@ -986,7 +1151,7 @@ void RigGeoMechWellLogExtractor::calculateIntersection() for ( size_t ccIdx = 0; ccIdx < closeCells.size(); ++ccIdx ) { RigElementType elmType = femPart->elementType( closeCells[ccIdx] ); - if ( elmType != HEX8 && elmType != HEX8P ) continue; + if ( elmType != RigElementType::HEX8 && elmType != RigElementType::HEX8P ) continue; const int* cornerIndices = femPart->connectivities( closeCells[ccIdx] ); @@ -1025,13 +1190,12 @@ void RigGeoMechWellLogExtractor::calculateIntersection() //-------------------------------------------------------------------------------------------------- std::vector RigGeoMechWellLogExtractor::findCloseCells( const cvf::BoundingBox& bb ) { - std::vector closeCells; - if ( m_caseData->femParts()->partCount() ) { - m_caseData->femParts()->part( m_partId )->findIntersectingElementIndices( bb, &closeCells ); + return m_caseData->femParts()->part( m_partId )->findIntersectingElementIndices( bb ); } - return closeCells; + + return {}; } //-------------------------------------------------------------------------------------------------- @@ -1249,7 +1413,7 @@ std::vector RigGeoMechWellLogExtractor::interpolateInterfaceValues( RigFemRes { size_t elmIdx = intersectedCellsGlobIdx()[intersectionIdx]; RigElementType elmType = femPart->elementType( elmIdx ); - if ( elmType != HEX8 && elmType != HEX8P ) continue; + if ( !RigFemTypes::is8NodeElement( elmType ) ) continue; interpolatedInterfaceValues[intersectionIdx] = interpolateGridResultValue( nativeAddr.resultPosType, unscaledResultValues, intersectionIdx ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.h b/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.h index 9c90cf1c1a..e846bf440d 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.h +++ b/ApplicationLibCode/ReservoirDataModel/RigGeoMechWellLogExtractor.h @@ -124,8 +124,16 @@ class RigGeoMechWellLogExtractor : public RigWellLogExtractor bool forceGridSourceforPPReservoir = false ); void wellBoreWallCurveData( const RigFemResultAddress& resAddr, int timeStepIndex, int frameIndex, std::vector* values ); - void wellBoreFGShale( int timeStepIndex, int frameIndex, std::vector* values ); - void wellBoreSH_MatthewsKelly( int timeStepIndex, int frameIndex, std::vector* values ); + void wellBoreFGShale( const RigWbsParameter& parameter, int timeStepIndex, int frameIndex, std::vector* values ); + void wellBoreSH_MatthewsKelly( int timeStepIndex, + int frameIndex, + const QString& wbsPPResultName, + const QString& wbsPP0ResultName, + std::vector* values ); + + void wellBoreFGDerivedFromK0FG( const QString& ppResult, int timeStepIndex, int frameIndex, std::vector* values, bool onlyForPPReservoir ); + + void wellBoreFG_MatthewsKelly( const RigWbsParameter& parameter, int timeStepIndex, int frameIndex, std::vector* values ); template T interpolateGridResultValue( RigFemResultPosEnum resultPosType, const std::vector& gridResultValues, int64_t intersectionIdx ) const; diff --git a/ApplicationLibCode/ReservoirDataModel/RigGridBase.cpp b/ApplicationLibCode/ReservoirDataModel/RigGridBase.cpp index 728012823a..ac27d61adb 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigGridBase.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigGridBase.cpp @@ -49,6 +49,18 @@ RigGridBase::~RigGridBase() { } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigGridBase::setGridPointDimensions( const cvf::Vec3st& gridDimensions ) +{ + m_gridPointDimensions = gridDimensions; + + m_cellCount.x() = ( m_gridPointDimensions.x() > 0 ? m_gridPointDimensions.x() - 1 : 0 ); + m_cellCount.y() = ( m_gridPointDimensions.y() > 0 ? m_gridPointDimensions.y() - 1 : 0 ); + m_cellCount.z() = ( m_gridPointDimensions.z() > 0 ? m_gridPointDimensions.z() - 1 : 0 ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -173,8 +185,7 @@ size_t RigGridBase::cellIndexFromIJK( size_t i, size_t j, size_t k ) const CVF_TIGHT_ASSERT( i != cvf::UNDEFINED_SIZE_T && j != cvf::UNDEFINED_SIZE_T && k != cvf::UNDEFINED_SIZE_T ); CVF_TIGHT_ASSERT( i < m_gridPointDimensions.x() && j < m_gridPointDimensions.y() && k < m_gridPointDimensions.z() ); - size_t ci = i + j * ( m_gridPointDimensions.x() - 1 ) + k * ( ( m_gridPointDimensions.x() - 1 ) * ( m_gridPointDimensions.y() - 1 ) ); - return ci; + return i + j * cellCountI() + k * cellCountI() * cellCountJ(); } //-------------------------------------------------------------------------------------------------- @@ -182,8 +193,7 @@ size_t RigGridBase::cellIndexFromIJK( size_t i, size_t j, size_t k ) const //-------------------------------------------------------------------------------------------------- size_t RigGridBase::cellIndexFromIJKUnguarded( size_t i, size_t j, size_t k ) const { - size_t ci = i + j * ( m_gridPointDimensions.x() - 1 ) + k * ( ( m_gridPointDimensions.x() - 1 ) * ( m_gridPointDimensions.y() - 1 ) ); - return ci; + return i + j * cellCountI() + k * cellCountI() * cellCountJ(); } //-------------------------------------------------------------------------------------------------- @@ -207,8 +217,8 @@ bool RigGridBase::ijkFromCellIndex( size_t cellIndex, size_t* i, size_t* j, size return false; } - const size_t cellCountI = m_gridPointDimensions[0] - 1u; - const size_t cellCountJ = m_gridPointDimensions[1] - 1u; + const size_t cellCountI = this->cellCountI(); + const size_t cellCountJ = this->cellCountJ(); *i = index % cellCountI; index /= cellCountI; @@ -254,8 +264,8 @@ void RigGridBase::ijkFromCellIndexUnguarded( size_t cellIndex, size_t* i, size_t { size_t index = cellIndex; - const size_t cellCountI = m_gridPointDimensions[0] - 1u; - const size_t cellCountJ = m_gridPointDimensions[1] - 1u; + const size_t cellCountI = this->cellCountI(); + const size_t cellCountJ = this->cellCountJ(); *i = index % cellCountI; index /= cellCountI; @@ -299,30 +309,6 @@ cvf::Vec3d RigGridBase::minCoordinate() const return v; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigGridBase::gridPointCountI() const -{ - return m_gridPointDimensions.x(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigGridBase::gridPointCountJ() const -{ - return m_gridPointDimensions.y(); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t RigGridBase::gridPointCountK() const -{ - return m_gridPointDimensions.z(); -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -512,6 +498,38 @@ cvf::BoundingBox RigGridBase::boundingBox() return m_boundingBox; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigGridBase::cellCountI() const +{ + return m_cellCount.x(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigGridBase::cellCountJ() const +{ + return m_cellCount.y(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigGridBase::cellCountK() const +{ + return m_cellCount.z(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigGridBase::cellCount() const +{ + return cellCountI() * cellCountJ() * cellCountK(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigGridBase.h b/ApplicationLibCode/ReservoirDataModel/RigGridBase.h index 06a1d9c539..72af3574a0 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigGridBase.h +++ b/ApplicationLibCode/ReservoirDataModel/RigGridBase.h @@ -43,10 +43,13 @@ class RigGridBase : public cvf::StructGridInterface explicit RigGridBase( RigMainGrid* mainGrid ); ~RigGridBase() override; - void setGridPointDimensions( const cvf::Vec3st& gridDimensions ) { m_gridPointDimensions = gridDimensions; } - cvf::Vec3st gridPointDimensions() { return m_gridPointDimensions; } + void setGridPointDimensions( const cvf::Vec3st& gridDimensions ); - size_t cellCount() const { return cellCountI() * cellCountJ() * cellCountK(); } + size_t cellCountI() const override; + size_t cellCountJ() const override; + size_t cellCountK() const override; + + size_t cellCount() const; RigCell& cell( size_t gridLocalCellIndex ); const RigCell& cell( size_t gridLocalCellIndex ) const; @@ -84,10 +87,6 @@ class RigGridBase : public cvf::StructGridInterface // Interface implementation public: - size_t gridPointCountI() const override; - size_t gridPointCountJ() const override; - size_t gridPointCountK() const override; - cvf::Vec3d minCoordinate() const override; cvf::Vec3d maxCoordinate() const override; cvf::Vec3d displayModelOffset() const override; @@ -116,6 +115,7 @@ class RigGridBase : public cvf::StructGridInterface private: std::string m_gridName; cvf::Vec3st m_gridPointDimensions; + cvf::Vec3st m_cellCount; size_t m_indexToStartOfCells; ///< Index into the global cell array stored in main-grid where this grids cells starts. size_t m_gridIndex; ///< The LGR index of this grid. Starts with 1. Main grid has index 0. int m_gridId; ///< The LGR id of this grid. Main grid has id 0. diff --git a/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.cpp b/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.cpp index cc7ac64de7..600926c6a6 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.cpp @@ -18,14 +18,18 @@ #include "RigGriddedPart3d.h" +#include "RigActiveCellInfo.h" #include "RigMainGrid.h" #include "RimFaultReactivationDataAccess.h" #include "RimFaultReactivationEnums.h" #include "cvfBoundingBox.h" +#include "cvfPlane.h" #include "cvfTextureImage.h" +#include "cafLine.h" + #include #include @@ -35,6 +39,9 @@ RigGriddedPart3d::RigGriddedPart3d() : m_useLocalCoordinates( false ) , m_topHeight( 0.0 ) + , m_faultSafetyDistance( 1.0 ) + , m_nVertElements( 0 ) + , m_nHorzElements( 0 ) { } @@ -54,12 +61,14 @@ void RigGriddedPart3d::reset() m_boundaryNodes.clear(); m_borderSurfaceElements.clear(); m_nodes.clear(); + m_dataNodes.clear(); m_localNodes.clear(); m_elementIndices.clear(); m_meshLines.clear(); m_elementSets.clear(); - m_elementKLayer.clear(); - m_elementLayers.clear(); + m_nVertElements = 0; + m_nHorzElements = 0; + m_topHeight = 0.0; } //-------------------------------------------------------------------------------------------------- @@ -156,52 +165,6 @@ std::vector RigGriddedPart3d::generateGrowingLayers( double zFrom, doubl return layers; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -std::vector RigGriddedPart3d::extractZValues( std::vector points ) -{ - std::vector layers; - - for ( auto& p : points ) - { - layers.push_back( p.z() ); - } - - return layers; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RigGriddedPart3d::updateReservoirElementLayers( const std::vector& reservoirLayers, const std::vector& kLayers ) -{ - const int nLayers = (int)reservoirLayers.size(); - - if ( nLayers < 2 ) return; - - int prevLayer = kLayers[0]; - double start = reservoirLayers[0].z(); - - for ( int l = 1; l < nLayers; l++ ) - { - auto currentZone = ( prevLayer >= 0 ) ? ElementSets::Reservoir : ElementSets::IntraReservoir; - - if ( l == nLayers - 1 ) - { - m_elementLayers[currentZone].push_back( std::make_pair( start, reservoirLayers[l].z() ) ); - continue; - } - - if ( ( ( prevLayer < 0 ) && ( kLayers[l] >= 0 ) ) || ( ( prevLayer >= 0 ) && ( kLayers[l] < 0 ) ) ) - { - m_elementLayers[currentZone].push_back( std::make_pair( start, reservoirLayers[l].z() ) ); - start = reservoirLayers[l].z(); - } - prevLayer = kLayers[l]; - } -} - //-------------------------------------------------------------------------------------------------- /// Point index in input /// @@ -223,16 +186,16 @@ void RigGriddedPart3d::updateReservoirElementLayers( const std::vector& inputPoints, - const std::vector& reservoirLayers, - const std::vector& kLayers, - const double maxCellHeight, - double cellSizeFactor, - const std::vector& horizontalPartition, - double modelThickness, - double topHeight ) +void RigGriddedPart3d::generateGeometry( const std::array& inputPoints, + const std::vector& reservoirZ, + double maxCellHeight, + double cellSizeFactor, + const std::vector& horizontalPartition, + const std::vector> faultLines, + const std::vector& thicknessVectors, + double topHeight, + int nFaultZoneCells ) { reset(); @@ -242,33 +205,35 @@ void RigGriddedPart3d::generateGeometry( const std::array& input layersPerRegion[Regions::LowerUnderburden] = generateGrowingLayers( inputPoints[1].z(), inputPoints[0].z(), maxCellHeight, cellSizeFactor ); layersPerRegion[Regions::UpperUnderburden] = generateConstantLayers( inputPoints[1].z(), inputPoints[2].z(), maxCellHeight ); - layersPerRegion[Regions::Reservoir] = extractZValues( reservoirLayers ); - layersPerRegion[Regions::LowerOverburden] = generateConstantLayers( inputPoints[3].z(), inputPoints[4].z(), maxCellHeight ); + layersPerRegion[Regions::Reservoir] = reservoirZ; + + layersPerRegion[Regions::LowerOverburden] = generateConstantLayers( inputPoints[3].z(), inputPoints[4].z(), maxCellHeight ); layersPerRegion[Regions::UpperOverburden] = generateGrowingLayers( inputPoints[4].z(), inputPoints[5].z(), maxCellHeight, cellSizeFactor ); layersPerRegion[Regions::LowerUnderburden].pop_back(); // to avoid overlap with bottom of next region layersPerRegion[Regions::Reservoir].pop_back(); // to avoid overlap with bottom of next region - m_elementLayers[ElementSets::OverBurden] = { std::make_pair( inputPoints[3].z(), inputPoints[5].z() ) }; - m_elementLayers[ElementSets::UnderBurden] = { std::make_pair( inputPoints[0].z(), inputPoints[2].z() ) }; - - updateReservoirElementLayers( reservoirLayers, kLayers ); + m_boundaryNodes[Boundary::Bottom] = {}; + m_boundaryNodes[Boundary::FarSide] = {}; + m_boundaryNodes[Boundary::Fault] = {}; + m_boundaryNodes[Boundary::Reservoir] = {}; - size_t nVertCells = 0; - size_t nHorzCells = horizontalPartition.size() - 1; + size_t nVertCells = 0; + const size_t nHorzCells = horizontalPartition.size() - 1; for ( auto region : allRegions() ) { nVertCells += layersPerRegion[region].size(); } - const std::vector m_thicknessFactors = { -1.0, 0.0, 1.0 }; - const int nThicknessCells = 2; - cvf::Vec3d tVec = stepVector( inputPoints[0], inputPoints[6], 1 ) ^ cvf::Vec3d::Z_AXIS; - tVec.normalize(); - tVec *= modelThickness; + const int nThicknessCells = 2; - m_nodes.reserve( ( nVertCells + 1 ) * ( nHorzCells + 1 ) * ( nThicknessCells + 1 ) ); + size_t reserveSize = ( nVertCells + 1 ) * ( nHorzCells + 1 ) * ( nThicknessCells + 1 ); + m_nodes.reserve( reserveSize ); + m_dataNodes.reserve( reserveSize ); + + m_nHorzElements = (int)nHorzCells; + m_nVertElements = (int)nVertCells - 1; unsigned int nodeIndex = 0; unsigned int layer = 0; @@ -325,12 +290,17 @@ void RigGriddedPart3d::generateGeometry( const std::array& input } else if ( region == Regions::Reservoir ) { - toPos = reservoirLayers[v]; - fromPos.z() = toPos.z(); + fromPos.z() = reservoirZ[v]; + cvf::Plane zPlane; + zPlane.setFromPointAndNormal( fromPos, cvf::Vec3d::Z_AXIS ); + zPlane.intersect( faultLines[1].start(), faultLines[1].end(), &toPos ); } cvf::Vec3d stepHorz = toPos - fromPos; cvf::Vec3d p; + cvf::Vec3d safetyOffset = fromPos - toPos; + safetyOffset.normalize(); + safetyOffset *= m_faultSafetyDistance; m_meshLines.push_back( { fromPos, toPos } ); @@ -340,7 +310,29 @@ void RigGriddedPart3d::generateGeometry( const std::array& input for ( int t = 0; t <= nThicknessCells; t++, nodeIndex++ ) { - m_nodes.push_back( p + m_thicknessFactors[t] * tVec ); + auto nodePoint = p + thicknessVectors[t]; + + // adjust points along the fault line inside the reservoir to make sure they end up at the fault + if ( ( h == (int)nHorzCells ) && + ( ( region == Regions::Reservoir ) || region == Regions::LowerOverburden || region == Regions::UpperUnderburden ) ) + { + cvf::Plane zPlane; + zPlane.setFromPointAndNormal( p, cvf::Vec3d::Z_AXIS ); + zPlane.intersect( faultLines[t].start(), faultLines[t].end(), &nodePoint ); + } + + m_nodes.push_back( nodePoint ); + + // move nodes at fault used for data extraction a bit away from the fault + if ( h == (int)nHorzCells ) + { + m_dataNodes.push_back( p + safetyOffset ); + } + else + { + m_dataNodes.push_back( p ); + } + if ( layer == 0 ) { m_boundaryNodes[Boundary::Bottom].push_back( nodeIndex ); @@ -349,6 +341,15 @@ void RigGriddedPart3d::generateGeometry( const std::array& input { m_boundaryNodes[Boundary::FarSide].push_back( nodeIndex ); } + else if ( h == (int)nHorzCells ) + { + m_boundaryNodes[Boundary::Fault].push_back( nodeIndex ); + + if ( region == Regions::Reservoir ) + { + m_boundaryNodes[Boundary::Reservoir].push_back( nodeIndex ); + } + } } } @@ -363,7 +364,6 @@ void RigGriddedPart3d::generateGeometry( const std::array& input // ** generate elements of type hex8 m_elementIndices.resize( (size_t)( ( nVertCells - 1 ) * nHorzCells * nThicknessCells ) ); - m_elementKLayer.resize( (size_t)( ( nVertCells - 1 ) * nHorzCells * nThicknessCells ) ); m_borderSurfaceElements[RimFaultReactivation::BorderSurface::Seabed] = {}; m_borderSurfaceElements[RimFaultReactivation::BorderSurface::UpperSurface] = {}; @@ -374,53 +374,48 @@ void RigGriddedPart3d::generateGeometry( const std::array& input m_elementSets[ElementSets::Reservoir] = {}; m_elementSets[ElementSets::IntraReservoir] = {}; m_elementSets[ElementSets::UnderBurden] = {}; + m_elementSets[ElementSets::FaultZone] = {}; m_boundaryElements[Boundary::Bottom] = {}; m_boundaryElements[Boundary::FarSide] = {}; + m_boundaryElements[Boundary::Fault] = {}; int layerIndexOffset = 0; int elementIdx = 0; layer = 0; - int kLayer = 0; const int nVertCellsLower = (int)layersPerRegion[Regions::LowerUnderburden].size(); const int nVertCellsFault = (int)( layersPerRegion[Regions::UpperUnderburden].size() + layersPerRegion[Regions::Reservoir].size() + layersPerRegion[Regions::LowerOverburden].size() ); - const int nVertCellsUnderburden = - (int)( layersPerRegion[Regions::LowerUnderburden].size() + layersPerRegion[Regions::UpperUnderburden].size() ); - const int nVertCellsReservoir = nVertCellsUnderburden + (int)( layersPerRegion[Regions::Reservoir].size() ); - RimFaultReactivation::BorderSurface currentSurfaceRegion = RimFaultReactivation::BorderSurface::LowerSurface; - RimFaultReactivation::ElementSets currentElementSet = RimFaultReactivation::ElementSets::UnderBurden; const int nextLayerIdxOff = ( (int)nHorzCells + 1 ) * ( nThicknessCells + 1 ); const int nThicknessOff = nThicknessCells + 1; const int seaBedLayer = (int)( nVertCells - 2 ); + const int nFaultZoneStart = (int)nHorzCells - nFaultZoneCells - 1; + for ( int v = 0; v < (int)nVertCells - 1; v++ ) { if ( v >= nVertCellsLower ) currentSurfaceRegion = RimFaultReactivation::BorderSurface::FaultSurface; if ( v >= nVertCellsLower + nVertCellsFault ) currentSurfaceRegion = RimFaultReactivation::BorderSurface::UpperSurface; - if ( v >= nVertCellsUnderburden ) currentElementSet = RimFaultReactivation::ElementSets::Reservoir; - if ( v >= nVertCellsReservoir ) currentElementSet = RimFaultReactivation::ElementSets::OverBurden; - int i = layerIndexOffset; for ( int h = 0; h < (int)nHorzCells; h++ ) { for ( int t = 0; t < nThicknessCells; t++, elementIdx++ ) { - m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i ); - m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i + nThicknessOff ); - m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i + nThicknessOff + 1 ); - m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i + 1 ); - m_elementIndices[elementIdx].push_back( t + i ); - m_elementIndices[elementIdx].push_back( t + i + nThicknessOff ); - m_elementIndices[elementIdx].push_back( t + i + nThicknessOff + 1 ); m_elementIndices[elementIdx].push_back( t + i + 1 ); + m_elementIndices[elementIdx].push_back( t + i + nThicknessOff + 1 ); + m_elementIndices[elementIdx].push_back( t + i + nThicknessOff ); + + m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i ); + m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i + 1 ); + m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i + nThicknessOff + 1 ); + m_elementIndices[elementIdx].push_back( t + nextLayerIdxOff + i + nThicknessOff ); if ( v == 0 ) { @@ -435,23 +430,9 @@ void RigGriddedPart3d::generateGeometry( const std::array& input m_boundaryElements[Boundary::FarSide].push_back( elementIdx ); } - if ( currentElementSet == RimFaultReactivation::ElementSets::Reservoir ) - { - m_elementKLayer[elementIdx] = kLayers[kLayer]; - if ( kLayers[kLayer] < 0 ) - { - m_elementSets[RimFaultReactivation::ElementSets::IntraReservoir].push_back( elementIdx ); - } - else - { - m_elementSets[currentElementSet].push_back( elementIdx ); - } - } - else - { - m_elementSets[currentElementSet].push_back( elementIdx ); - m_elementKLayer[elementIdx] = -2000; - } + bool inFaultZone = ( currentSurfaceRegion == RimFaultReactivation::BorderSurface::FaultSurface ) && ( h > nFaultZoneStart ); + + if ( inFaultZone ) m_elementSets[RimFaultReactivation::ElementSets::FaultZone].push_back( elementIdx ); } i += nThicknessOff; } @@ -460,11 +441,6 @@ void RigGriddedPart3d::generateGeometry( const std::array& input m_borderSurfaceElements[currentSurfaceRegion].push_back( elementIdx - 2 ); m_borderSurfaceElements[currentSurfaceRegion].push_back( elementIdx - 1 ); - if ( currentElementSet == RimFaultReactivation::ElementSets::Reservoir ) - { - kLayer++; - } - layerIndexOffset += nextLayerIdxOff; } @@ -520,6 +496,16 @@ const std::vector& RigGriddedPart3d::globalNodes() const return m_nodes; } +//-------------------------------------------------------------------------------------------------- +/// Returns nodes in global coordinates, adjusted to always extract data as if the model has no +/// thickness. Additionally, nodes closest to the fault are moved away from the fault +/// to make sure data results come from the correct side of the fault. +//-------------------------------------------------------------------------------------------------- +const std::vector& RigGriddedPart3d::dataNodes() const +{ + return m_dataNodes; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -544,6 +530,22 @@ double RigGriddedPart3d::topHeight() const return m_topHeight; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigGriddedPart3d::setFaultSafetyDistance( double distance ) +{ + m_faultSafetyDistance = distance; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RigGriddedPart3d::faultSafetyDistance() const +{ + return m_faultSafetyDistance; +} + //-------------------------------------------------------------------------------------------------- /// Output elements will be of type HEX8 /// @@ -567,14 +569,40 @@ const std::vector>& RigGriddedPart3d::elementIndices() //-------------------------------------------------------------------------------------------------- const std::vector RigGriddedPart3d::elementCorners( size_t elementIndex ) const { - if ( elementIndex >= m_elementIndices.size() ) return {}; + return extractCornersForElement( m_elementIndices, m_nodes, elementIndex ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +const std::vector RigGriddedPart3d::elementDataCorners( size_t elementIndex ) const +{ + return extractCornersForElement( m_elementIndices, m_dataNodes, elementIndex ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +const std::pair RigGriddedPart3d::elementCountHorzVert() const +{ + return { m_nHorzElements, m_nVertElements }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RigGriddedPart3d::extractCornersForElement( const std::vector>& elementIndices, + const std::vector& nodes, + size_t elementIndex ) +{ + if ( elementIndex >= elementIndices.size() ) return {}; std::vector corners; - for ( auto nodeIdx : m_elementIndices[elementIndex] ) + for ( auto nodeIdx : elementIndices[elementIndex] ) { - if ( nodeIdx >= m_nodes.size() ) continue; - corners.push_back( m_nodes[nodeIdx] ); + if ( nodeIdx >= nodes.size() ) continue; + corners.push_back( nodes[nodeIdx] ); } return corners; @@ -599,53 +627,170 @@ const std::vector>& RigGriddedPart3d::meshLines() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const std::vector RigGriddedPart3d::elementKLayer() const +const std::map>& RigGriddedPart3d::boundaryElements() const { - return m_elementKLayer; + return m_boundaryElements; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const std::vector> RigGriddedPart3d::layers( RigGriddedPart3d::ElementSets elementSet ) const +const std::map>& RigGriddedPart3d::boundaryNodes() const { - if ( m_elementLayers.count( elementSet ) == 0 ) return {}; - return m_elementLayers.at( elementSet ); + return m_boundaryNodes; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const std::map>& RigGriddedPart3d::boundaryElements() const +const std::map>& RigGriddedPart3d::elementSets() const { - return m_boundaryElements; + return m_elementSets; } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const std::map>& RigGriddedPart3d::boundaryNodes() const +void RigGriddedPart3d::generateLocalNodes( const cvf::Mat4d transform ) { - return m_boundaryNodes; + m_localNodes.clear(); + + // need to flip the Y axis for the element corners to be in an acceptable order for abaqus and the IJK numbering algorithm in resinsight + cvf::Vec3d xAxis = { 1.0, 0.0, 0.0 }; + cvf::Vec3d yAxis = { 0.0, -1.0, 0.0 }; + cvf::Vec3d zAxis = { 0.0, 0.0, 1.0 }; + cvf::Mat4d flipY = cvf::Mat4d::fromCoordSystemAxes( &xAxis, &yAxis, &zAxis ); + + for ( auto& node : m_nodes ) + { + auto tn = node.getTransformedPoint( transform ); + m_localNodes.push_back( tn.getTransformedPoint( flipY ) ); + } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const std::map>& RigGriddedPart3d::elementSets() const +void RigGriddedPart3d::shiftNodes( const cvf::Vec3d offset ) { - return m_elementSets; + for ( int i = 0; i < (int)m_nodes.size(); i++ ) + { + m_nodes[i] += offset; + m_dataNodes[i] += offset; + } + + for ( int i = 0; i < (int)m_meshLines.size(); i++ ) + { + for ( int j = 0; j < (int)m_meshLines[i].size(); j++ ) + { + m_meshLines[i][j] += offset; + } + } } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigGriddedPart3d::generateLocalNodes( const cvf::Mat4d transform ) +void RigGriddedPart3d::postProcessElementSets( const RigMainGrid* mainGrid, const RigActiveCellInfo* cellInfo ) { - m_localNodes.clear(); + std::set usedElements; - for ( auto& node : m_nodes ) + // fault zone elements are already assigned + for ( auto elIdx : m_elementSets[ElementSets::FaultZone] ) { - m_localNodes.push_back( node.getTransformedPoint( transform ) ); + usedElements.insert( elIdx ); + } + + // look for overburden, starting at top going down + updateElementSet( ElementSets::OverBurden, usedElements, mainGrid, cellInfo, m_nVertElements - 1, -1, -1 ); + + // look for underburden, starting at bottom going up + updateElementSet( ElementSets::UnderBurden, usedElements, mainGrid, cellInfo, 0, m_nVertElements, 1 ); + + // remaining elements are in the reservoir + m_elementSets[ElementSets::IntraReservoir] = {}; + m_elementSets[ElementSets::Reservoir] = {}; + + for ( unsigned int element = 0; element < m_elementIndices.size(); element++ ) + { + if ( usedElements.contains( element ) ) continue; + + auto corners = elementDataCorners( element ); + bool bActive = false; + + size_t cellIdx = 0; + for ( const auto& p : corners ) + { + cellIdx = mainGrid->findReservoirCellIndexFromPoint( p ); + + bActive = ( cellIdx != cvf::UNDEFINED_SIZE_T ) && ( cellInfo->isActive( cellIdx ) ); + if ( bActive ) break; + } + + if ( bActive ) + { + m_elementSets[ElementSets::Reservoir].push_back( element ); + } + else + { + m_elementSets[ElementSets::IntraReservoir].push_back( element ); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigGriddedPart3d::updateElementSet( ElementSets elSet, + std::set& usedElements, + const RigMainGrid* mainGrid, + const RigActiveCellInfo* cellInfo, + int rowStart, + int rowEnd, + int rowInc ) +{ + for ( int col = 0; col < m_nHorzElements; col++ ) + { + for ( int row = rowStart; row != rowEnd; row += rowInc ) + { + const unsigned int elIdx = (unsigned int)( 2 * ( ( row * m_nHorzElements ) + col ) ); + + bool bStop = false; + + for ( unsigned int t = 0; t < 2; t++ ) + { + if ( usedElements.contains( elIdx + t ) ) + { + bStop = true; + break; + } + + auto corners = elementDataCorners( elIdx + t ); + + size_t cellIdx = 0; + for ( const auto& p : corners ) + { + cellIdx = mainGrid->findReservoirCellIndexFromPoint( p ); + + if ( ( cellIdx != cvf::UNDEFINED_SIZE_T ) && ( cellInfo->isActive( cellIdx ) ) ) + { + bStop = true; + break; + } + } + } + + if ( bStop ) + { + break; + } + else + { + m_elementSets[elSet].push_back( elIdx ); + m_elementSets[elSet].push_back( elIdx + 1 ); + usedElements.insert( elIdx ); + usedElements.insert( elIdx + 1 ); + } + } } } diff --git a/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.h b/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.h index 410bbccab7..13167d21f8 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.h +++ b/ApplicationLibCode/ReservoirDataModel/RigGriddedPart3d.h @@ -24,10 +24,16 @@ #include "cvfObject.h" #include "cvfVector3.h" +#include "cafLine.h" + #include #include +#include #include +class RigMainGrid; +class RigActiveCellInfo; + //================================================================================================== /// /// @@ -43,23 +49,31 @@ class RigGriddedPart3d : public cvf::Object void reset(); - void generateGeometry( const std::array& inputPoints, - const std::vector& reservoirLayers, - const std::vector& kLayers, - double maxCellHeight, - double cellSizeFactor, - const std::vector& horizontalPartition, - double modelThickness, - double topHeight ); - + void generateGeometry( const std::array& inputPoints, + const std::vector& reservoirZ, + double maxCellHeight, + double cellSizeFactor, + const std::vector& horizontalPartition, + const std::vector> faultLines, + const std::vector& thicknessVectors, + double topHeight, + int nFaultZoneCells ); + + void shiftNodes( const cvf::Vec3d offset ); void generateLocalNodes( const cvf::Mat4d transform ); void setUseLocalCoordinates( bool useLocalCoordinates ); + void postProcessElementSets( const RigMainGrid* mainGrid, const RigActiveCellInfo* cellInfo ); + bool useLocalCoordinates() const; double topHeight() const; + void setFaultSafetyDistance( double distance ); + double faultSafetyDistance() const; + const std::vector& nodes() const; const std::vector& globalNodes() const; + const std::vector& dataNodes() const; const std::vector>& elementIndices() const; const std::map>& borderSurfaceElements() const; @@ -68,18 +82,24 @@ class RigGriddedPart3d : public cvf::Object const std::map>& boundaryElements() const; const std::map>& boundaryNodes() const; const std::map>& elementSets() const; - const std::vector elementKLayer() const; const std::vector elementCorners( size_t elementIndex ) const; - const std::vector> layers( ElementSets elementSet ) const; + const std::vector elementDataCorners( size_t elementIndex ) const; + const std::pair elementCountHorzVert() const; protected: static cvf::Vec3d stepVector( cvf::Vec3d start, cvf::Vec3d stop, int nSteps ); static std::vector generateConstantLayers( double zFrom, double zTo, double maxSize ); static std::vector generateGrowingLayers( double zFrom, double zTo, double maxSize, double growfactor ); - static std::vector extractZValues( std::vector ); void generateVerticalMeshlines( const std::vector& cornerPoints, const std::vector& horzPartition ); - void updateReservoirElementLayers( const std::vector& reservoirLayers, const std::vector& kLayers ); + + void updateElementSet( ElementSets elSet, + std::set& usedElements, + const RigMainGrid* mainGrid, + const RigActiveCellInfo* cellInfo, + int rowStart, + int rowEnd, + int rowInc ); private: enum class Regions @@ -91,21 +111,27 @@ class RigGriddedPart3d : public cvf::Object UpperOverburden }; - static std::vector allRegions(); + static std::vector allRegions(); + static std::vector extractCornersForElement( const std::vector>& elementIndices, + const std::vector& nodes, + size_t elementIndex ); private: bool m_useLocalCoordinates; double m_topHeight; + double m_faultSafetyDistance; + + int m_nVertElements; + int m_nHorzElements; std::vector m_nodes; + std::vector m_dataNodes; std::vector m_localNodes; std::vector> m_elementIndices; - std::vector m_elementKLayer; std::map> m_borderSurfaceElements; std::vector> m_meshLines; std::map> m_boundaryElements; std::map> m_boundaryNodes; std::map> m_elementSets; - std::map>> m_elementLayers; }; diff --git a/ApplicationLibCode/ReservoirDataModel/RigMainGrid.cpp b/ApplicationLibCode/ReservoirDataModel/RigMainGrid.cpp index b3cfba5026..71fab84de7 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigMainGrid.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigMainGrid.cpp @@ -151,8 +151,7 @@ size_t RigMainGrid::findReservoirCellIndexFromPoint( const cvf::Vec3d& point ) c cvf::BoundingBox pointBBox; pointBBox.add( point ); - std::vector cellIndices; - m_mainGrid->findIntersectingCells( pointBBox, &cellIndices ); + std::vector cellIndices = m_mainGrid->findIntersectingCells( pointBBox ); cvf::Vec3d hexCorners[8]; for ( size_t cellIndex : cellIndices ) @@ -289,6 +288,8 @@ void RigMainGrid::computeCachedData( std::string* aabbTreeInfo ) *aabbTreeInfo += "Cells per bounding box : " + std::to_string( cellsPerBoundingBox ) + "\n"; *aabbTreeInfo += m_cellSearchTree->info(); } + + computeBoundingBox(); } //-------------------------------------------------------------------------------------------------- @@ -434,6 +435,35 @@ bool RigMainGrid::hasFaultWithName( const QString& name ) const return false; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigMainGrid::computeBoundingBox() +{ + m_boundingBox.reset(); + + const int numberOfThreads = RiaOpenMPTools::availableThreadCount(); + + std::vector threadBoundingBoxes( numberOfThreads ); + +#pragma omp parallel + { + int myThread = RiaOpenMPTools::currentThreadIndex(); + + // NB! We are inside a parallel section, do not use "parallel for" here +#pragma omp for + for ( long i = 0; i < static_cast( m_nodes.size() ); i++ ) + { + threadBoundingBoxes[myThread].add( m_nodes[i] ); + } + } + + for ( int i = 0; i < numberOfThreads; i++ ) + { + m_boundingBox.add( threadBoundingBoxes[i] ); + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -781,11 +811,12 @@ const RigFault* RigMainGrid::findFaultFromCellIndexAndCellFace( size_t reservoir //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void RigMainGrid::findIntersectingCells( const cvf::BoundingBox& inputBB, std::vector* cellIndices ) const +std::vector RigMainGrid::findIntersectingCells( const cvf::BoundingBox& inputBB ) const { CVF_ASSERT( m_cellSearchTree.notNull() ); - - m_cellSearchTree->findIntersections( inputBB, cellIndices ); + std::vector cellIndices; + m_cellSearchTree->findIntersections( inputBB, &cellIndices ); + return cellIndices; } //-------------------------------------------------------------------------------------------------- @@ -943,13 +974,6 @@ void RigMainGrid::buildCellSearchTreeOptimized( size_t cellsPerBoundingBox ) //-------------------------------------------------------------------------------------------------- cvf::BoundingBox RigMainGrid::boundingBox() const { - if ( m_boundingBox.isValid() ) return m_boundingBox; - - for ( const auto& node : m_nodes ) - { - m_boundingBox.add( node ); - } - return m_boundingBox; } diff --git a/ApplicationLibCode/ReservoirDataModel/RigMainGrid.h b/ApplicationLibCode/ReservoirDataModel/RigMainGrid.h index bc38322b7b..536a2a2d12 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigMainGrid.h +++ b/ApplicationLibCode/ReservoirDataModel/RigMainGrid.h @@ -94,8 +94,8 @@ class RigMainGrid : public RigGridBase cvf::Vec3d displayModelOffset() const override; void setDisplayModelOffset( cvf::Vec3d offset ); - void setFlipAxis( bool flipXAxis, bool flipYAxis ); - void findIntersectingCells( const cvf::BoundingBox& inputBB, std::vector* cellIndices ) const; + void setFlipAxis( bool flipXAxis, bool flipYAxis ); + std::vector findIntersectingCells( const cvf::BoundingBox& inputBB ) const; cvf::BoundingBox boundingBox() const; @@ -118,6 +118,7 @@ class RigMainGrid : public RigGridBase void buildCellSearchTree(); void buildCellSearchTreeOptimized( size_t cellsPerBoundingBox ); bool hasFaultWithName( const QString& name ) const; + void computeBoundingBox(); static std::array defaultMapAxes(); @@ -133,7 +134,7 @@ class RigMainGrid : public RigGridBase cvf::Vec3d m_displayModelOffset; cvf::ref m_cellSearchTree; - mutable cvf::BoundingBox m_boundingBox; + cvf::BoundingBox m_boundingBox; bool m_flipXAxis; bool m_flipYAxis; diff --git a/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.cpp b/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.cpp index 120f93912e..b5bc81933c 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.cpp @@ -28,6 +28,7 @@ #include "RigWellResultFrame.h" #include "RimEclipseCase.h" +#include "RimEclipseResultCase.h" #include "RimEclipseView.h" #include "RimSimWellInView.h" #include "RimSimWellInViewCollection.h" @@ -37,7 +38,7 @@ //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RigMswCenterLineCalculator::calculateMswWellPipeGeometry( RimSimWellInView* rimWell ) +std::vector RigMswCenterLineCalculator::calculateMswWellPipeGeometry( const RimSimWellInView* rimWell ) { CVF_ASSERT( rimWell ); @@ -50,7 +51,13 @@ std::vector RigMswCenterLineCalculator::calculateMswWe auto eclipseCaseData = eclipseView->eclipseCase()->eclipseCaseData(); int timeStepIndex = eclipseView->currentTimeStep(); - return calculateMswWellPipeGeometryForTimeStep( eclipseCaseData, simWellData, timeStepIndex ); + int shortBranchMergeThreshold = 4; + if ( auto eclipseResultCase = dynamic_cast( eclipseView->eclipseCase() ) ) + { + shortBranchMergeThreshold = eclipseResultCase->mswMergeThreshold(); + } + + return calculateMswWellPipeGeometryForTimeStep( eclipseCaseData, simWellData, timeStepIndex, shortBranchMergeThreshold ); } return {}; @@ -62,10 +69,9 @@ std::vector RigMswCenterLineCalculator::calculateMswWe std::vector RigMswCenterLineCalculator::calculateMswWellPipeGeometryForTimeStep( const RigEclipseCaseData* eclipseCaseData, const RigSimWellData* wellResults, - int timeStepIndex ) + int timeStepIndex, + int shortBranchMergeThreshold ) { - if ( timeStepIndex >= 0 && !wellResults->hasAnyValidCells( timeStepIndex ) ) return {}; - const RigWellResultFrame* wellFramePtr = nullptr; if ( timeStepIndex < 0 ) @@ -80,7 +86,7 @@ std::vector const RigWellResultFrame& wellFrame = *wellFramePtr; const std::vector resultBranches = wellFrame.wellResultBranches(); - std::vector wellBranches = mergeShortBranchesIntoLongBranches( resultBranches ); + std::vector wellBranches = mergeShortBranchesIntoLongBranches( resultBranches, shortBranchMergeThreshold ); // Connect outlet segment of branches to parent branch @@ -290,7 +296,8 @@ SimulationWellCellBranch /// //-------------------------------------------------------------------------------------------------- std::vector - RigMswCenterLineCalculator::mergeShortBranchesIntoLongBranches( const std::vector& resBranches ) + RigMswCenterLineCalculator::mergeShortBranchesIntoLongBranches( const std::vector& resBranches, + int shortBranchMergeThreshold ) { std::vector longWellBranches; std::vector shortWellBranches; @@ -314,8 +321,7 @@ std::vector } } - const int resultPointThreshold = 3; - if ( resultBranch.branchResultPoints().size() > resultPointThreshold ) + if ( static_cast( resultBranch.branchResultPoints().size() ) > shortBranchMergeThreshold ) { longWellBranches.push_back( branch ); } diff --git a/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.h b/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.h index 345b0ceb46..747fdd5da6 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.h +++ b/ApplicationLibCode/ReservoirDataModel/RigMswCenterLineCalculator.h @@ -35,7 +35,7 @@ class RigSimWellData; class RigMswCenterLineCalculator { public: - static std::vector calculateMswWellPipeGeometry( RimSimWellInView* rimWell ); + static std::vector calculateMswWellPipeGeometry( const RimSimWellInView* rimWell ); private: struct OutputSegment @@ -69,11 +69,13 @@ class RigMswCenterLineCalculator private: static std::vector calculateMswWellPipeGeometryForTimeStep( const RigEclipseCaseData* eclipseCaseData, const RigSimWellData* simWellData, - int timeStepIndex ); + int timeStepIndex, + int shortBranchMergeThreshold ); static SimulationWellCellBranch addCoordsAtCellFaceIntersectionsAndCreateBranch( const std::vector branchCoords, const std::vector& resultPoints, const RigEclipseCaseData* eclipseCaseData ); - static std::vector mergeShortBranchesIntoLongBranches( const std::vector& resBranches ); + static std::vector mergeShortBranchesIntoLongBranches( const std::vector& resBranches, + int shortBranchMergeThreshold ); }; diff --git a/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.cpp b/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.cpp index 88318e1ec5..7a282e3a85 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.cpp @@ -44,11 +44,37 @@ RigPolyLinesData::~RigPolyLinesData() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -const std::vector>& RigPolyLinesData::polyLines() const +const std::vector>& RigPolyLinesData::rawPolyLines() const { return m_polylines; } +//-------------------------------------------------------------------------------------------------- +/// Returns the polylines with the last point equal to the first point if the polyline is closed +//-------------------------------------------------------------------------------------------------- +const std::vector> RigPolyLinesData::completePolyLines() const +{ + if ( !m_closePolyline ) return m_polylines; + + std::vector> completeLines; + for ( const auto& polyline : m_polylines ) + { + auto completePolyline = polyline; + if ( !polyline.empty() ) + { + const double epsilon = 1e-6; + + if ( polyline.front().pointDistance( polyline.back() ) > epsilon ) + { + completePolyline.push_back( polyline.front() ); + } + } + completeLines.push_back( completePolyline ); + } + + return completeLines; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.h b/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.h index 5e0fcf176b..f11c92dc27 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.h +++ b/ApplicationLibCode/ReservoirDataModel/RigPolyLinesData.h @@ -34,7 +34,8 @@ class RigPolyLinesData : public cvf::Object RigPolyLinesData(); ~RigPolyLinesData() override; - const std::vector>& polyLines() const; + const std::vector>& rawPolyLines() const; + const std::vector> completePolyLines() const; void setPolyLines( const std::vector>& polyLines ); void setPolyLine( const std::vector& polyline ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilder.cpp b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilder.cpp new file mode 100644 index 0000000000..0fa052bb9e --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilder.cpp @@ -0,0 +1,288 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RigReservoirBuilder.h" + +#include "RigActiveCellInfo.h" +#include "RigCell.h" +#include "RigEclipseCaseData.h" +#include "RigMainGrid.h" + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigReservoirBuilder::RigReservoirBuilder() + : m_minWorldCoordinate( 0.0, 0.0, 0.0 ) + , m_maxWorldCoordinate( 0.0, 0.0, 0.0 ) + , m_gridPointDimensions( 0, 0, 0 ) +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::setWorldCoordinates( cvf::Vec3d minWorldCoordinate, cvf::Vec3d maxWorldCoordinate ) +{ + m_minWorldCoordinate = minWorldCoordinate; + m_maxWorldCoordinate = maxWorldCoordinate; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::setIJKCount( const cvf::Vec3st& ijkCount ) +{ + m_gridPointDimensions = { ijkCount.x() + 1, ijkCount.y() + 1, ijkCount.z() + 1 }; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::addLocalGridRefinement( const cvf::Vec3st& minCellPosition, + const cvf::Vec3st& maxCellPosition, + const cvf::Vec3st& singleCellRefinementFactors ) +{ + m_localGridRefinements.push_back( LocalGridRefinement( minCellPosition, maxCellPosition, singleCellRefinementFactors ) ); +} + +//-------------------------------------------------------------------------------------------------- +/// Build the geometry for a grids and cells +/// - create 8 nodes for each cell +/// - create cells by referencing the nodes +/// - optionally create and add LGR grids +/// - set all cells to active +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::createGridsAndCells( RigEclipseCaseData* eclipseCase ) +{ + std::vector& mainGridNodes = eclipseCase->mainGrid()->nodes(); + appendNodes( m_minWorldCoordinate, m_maxWorldCoordinate, ijkCount(), mainGridNodes ); + size_t mainGridNodeCount = mainGridNodes.size(); + size_t mainGridCellCount = mainGridNodeCount / 8; + + // Must create cells in main grid here, as this information is used when creating LGRs + appendCells( 0, mainGridCellCount, eclipseCase->mainGrid(), eclipseCase->mainGrid()->globalCellArray() ); + + size_t totalCellCount = mainGridCellCount; + + size_t lgrIdx; + for ( lgrIdx = 0; lgrIdx < m_localGridRefinements.size(); lgrIdx++ ) + { + LocalGridRefinement& lgr = m_localGridRefinements[lgrIdx]; + + // Compute all global cell indices to be replaced by local grid refinement + std::vector mainGridIndicesWithSubGrid; + { + size_t i; + for ( i = lgr.m_mainGridMinCellPosition.x(); i <= lgr.m_mainGridMaxCellPosition.x(); i++ ) + { + size_t j; + for ( j = lgr.m_mainGridMinCellPosition.y(); j <= lgr.m_mainGridMaxCellPosition.y(); j++ ) + { + size_t k; + for ( k = lgr.m_mainGridMinCellPosition.z(); k <= lgr.m_mainGridMaxCellPosition.z(); k++ ) + { + mainGridIndicesWithSubGrid.push_back( cellIndexFromIJK( i, j, k ) ); + } + } + } + } + + // Create local grid and set local grid dimensions + RigLocalGrid* localGrid = new RigLocalGrid( eclipseCase->mainGrid() ); + localGrid->setGridId( 1 ); + localGrid->setGridName( "LGR_1" ); + eclipseCase->mainGrid()->addLocalGrid( localGrid ); + localGrid->setParentGrid( eclipseCase->mainGrid() ); + + localGrid->setIndexToStartOfCells( mainGridNodes.size() / 8 ); + cvf::Vec3st gridPointDimensions( lgr.m_singleCellRefinementFactors.x() * + ( lgr.m_mainGridMaxCellPosition.x() - lgr.m_mainGridMinCellPosition.x() + 1 ) + + 1, + lgr.m_singleCellRefinementFactors.y() * + ( lgr.m_mainGridMaxCellPosition.y() - lgr.m_mainGridMinCellPosition.y() + 1 ) + + 1, + lgr.m_singleCellRefinementFactors.z() * + ( lgr.m_mainGridMaxCellPosition.z() - lgr.m_mainGridMinCellPosition.z() + 1 ) + + 1 ); + localGrid->setGridPointDimensions( gridPointDimensions ); + + cvf::BoundingBox bb; + size_t cellIdx; + for ( cellIdx = 0; cellIdx < mainGridIndicesWithSubGrid.size(); cellIdx++ ) + { + RigCell& cell = eclipseCase->mainGrid()->globalCellArray()[mainGridIndicesWithSubGrid[cellIdx]]; + + std::array& indices = cell.cornerIndices(); + int nodeIdx; + for ( nodeIdx = 0; nodeIdx < 8; nodeIdx++ ) + { + bb.add( eclipseCase->mainGrid()->nodes()[indices[nodeIdx]] ); + } + // Deactivate cell in main grid + cell.setSubGrid( localGrid ); + } + + cvf::Vec3st lgrCellDimensions = gridPointDimensions - cvf::Vec3st( 1, 1, 1 ); + appendNodes( bb.min(), bb.max(), lgrCellDimensions, mainGridNodes ); + + size_t subGridCellCount = ( mainGridNodes.size() / 8 ) - totalCellCount; + appendCells( totalCellCount * 8, subGridCellCount, localGrid, eclipseCase->mainGrid()->globalCellArray() ); + totalCellCount += subGridCellCount; + } + + eclipseCase->mainGrid()->setGridPointDimensions( m_gridPointDimensions ); + + // Set all cells active + RigActiveCellInfo* activeCellInfo = eclipseCase->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL ); + activeCellInfo->setReservoirCellCount( eclipseCase->mainGrid()->globalCellArray().size() ); + for ( size_t i = 0; i < eclipseCase->mainGrid()->globalCellArray().size(); i++ ) + { + activeCellInfo->setCellResultIndex( i, i ); + } + + activeCellInfo->setGridCount( 1 ); + activeCellInfo->setGridActiveCellCounts( 0, eclipseCase->mainGrid()->globalCellArray().size() ); + activeCellInfo->computeDerivedData(); + + bool useOptimizedVersion = false; // workaround, optimized version causes assert in debug builds + eclipseCase->computeActiveCellBoundingBoxes( useOptimizedVersion ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::appendCells( size_t nodeStartIndex, size_t cellCount, RigGridBase* hostGrid, std::vector& cells ) +{ + size_t cellIndexStart = cells.size(); + cells.resize( cells.size() + cellCount ); + +#pragma omp parallel for + for ( long long i = 0; i < static_cast( cellCount ); i++ ) + { + RigCell& riCell = cells[cellIndexStart + i]; + + riCell.setHostGrid( hostGrid ); + riCell.setGridLocalCellIndex( i ); + + riCell.cornerIndices()[0] = nodeStartIndex + i * 8 + 0; + riCell.cornerIndices()[1] = nodeStartIndex + i * 8 + 1; + riCell.cornerIndices()[2] = nodeStartIndex + i * 8 + 2; + riCell.cornerIndices()[3] = nodeStartIndex + i * 8 + 3; + riCell.cornerIndices()[4] = nodeStartIndex + i * 8 + 4; + riCell.cornerIndices()[5] = nodeStartIndex + i * 8 + 5; + riCell.cornerIndices()[6] = nodeStartIndex + i * 8 + 6; + riCell.cornerIndices()[7] = nodeStartIndex + i * 8 + 7; + + riCell.setParentCellIndex( 0 ); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::appendNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, const cvf::Vec3st& cubeDimension, std::vector& nodes ) +{ + double dx = ( max.x() - min.x() ) / static_cast( cubeDimension.x() ); + double dy = ( max.y() - min.y() ) / static_cast( cubeDimension.y() ); + double dz = ( max.z() - min.z() ) / static_cast( cubeDimension.z() ); + + double zPos = min.z(); + + size_t k; + for ( k = 0; k < cubeDimension.z(); k++ ) + { + double yPos = min.y(); + + size_t j; + for ( j = 0; j < cubeDimension.y(); j++ ) + { + double xPos = min.x(); + + size_t i; + for ( i = 0; i < cubeDimension.x(); i++ ) + { + cvf::Vec3d cornerA( xPos, yPos, zPos ); + cvf::Vec3d cornerB( xPos + dx, yPos + dy, zPos + dz ); + + appendCubeNodes( cornerA, cornerB, nodes ); + + xPos += dx; + } + + yPos += dy; + } + + zPos += dz; + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigReservoirBuilder::appendCubeNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, std::vector& nodes ) +{ + // + // 7---------6 Faces: + // /| /| |k 0 bottom 0, 3, 2, 1 + // / | / | | /j 1 top 4, 5, 6, 7 + // 4---------5 | |/ 2 front 0, 1, 5, 4 + // | 3------|--2 *---i 3 right 1, 2, 6, 5 + // | / | / 4 back 3, 7, 6, 2 + // |/ |/ 5 left 0, 4, 7, 3 + // 0---------1 + + cvf::Vec3d v0( min.x(), min.y(), min.z() ); + cvf::Vec3d v1( max.x(), min.y(), min.z() ); + cvf::Vec3d v2( max.x(), max.y(), min.z() ); + cvf::Vec3d v3( min.x(), max.y(), min.z() ); + + cvf::Vec3d v4( min.x(), min.y(), max.z() ); + cvf::Vec3d v5( max.x(), min.y(), max.z() ); + cvf::Vec3d v6( max.x(), max.y(), max.z() ); + cvf::Vec3d v7( min.x(), max.y(), max.z() ); + + nodes.push_back( v0 ); + nodes.push_back( v1 ); + nodes.push_back( v2 ); + nodes.push_back( v3 ); + nodes.push_back( v4 ); + nodes.push_back( v5 ); + nodes.push_back( v6 ); + nodes.push_back( v7 ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RigReservoirBuilder::cellIndexFromIJK( size_t i, size_t j, size_t k ) const +{ + CVF_TIGHT_ASSERT( i < ( m_gridPointDimensions.x() - 1 ) ); + CVF_TIGHT_ASSERT( j < ( m_gridPointDimensions.y() - 1 ) ); + CVF_TIGHT_ASSERT( k < ( m_gridPointDimensions.z() - 1 ) ); + + size_t ci = i + j * ( m_gridPointDimensions.x() - 1 ) + k * ( ( m_gridPointDimensions.x() - 1 ) * ( m_gridPointDimensions.y() - 1 ) ); + return ci; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Vec3st RigReservoirBuilder::ijkCount() const +{ + return cvf::Vec3st( m_gridPointDimensions.x() - 1, m_gridPointDimensions.y() - 1, m_gridPointDimensions.z() - 1 ); +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilder.h b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilder.h new file mode 100644 index 0000000000..54ad686f38 --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilder.h @@ -0,0 +1,73 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2023- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "cvfVector3.h" + +#include + +class RigGridBase; +class RigCell; +class RigEclipseCaseData; + +class LocalGridRefinement +{ +public: + LocalGridRefinement( const cvf::Vec3st& mainGridMin, const cvf::Vec3st& mainGridMax, const cvf::Vec3st& singleCellRefinementFactors ) + { + m_mainGridMinCellPosition = mainGridMin; + m_mainGridMaxCellPosition = mainGridMax; + m_singleCellRefinementFactors = singleCellRefinementFactors; + } + + cvf::Vec3st m_mainGridMinCellPosition; + cvf::Vec3st m_mainGridMaxCellPosition; + cvf::Vec3st m_singleCellRefinementFactors; +}; + +class RigReservoirBuilder +{ +public: + RigReservoirBuilder(); + + void setWorldCoordinates( cvf::Vec3d minWorldCoordinate, cvf::Vec3d maxWorldCoordinate ); + + void setIJKCount( const cvf::Vec3st& ijkCount ); + cvf::Vec3st ijkCount() const; + + void addLocalGridRefinement( const cvf::Vec3st& minCellPosition, + const cvf::Vec3st& maxCellPosition, + const cvf::Vec3st& singleCellRefinementFactors ); + + void createGridsAndCells( RigEclipseCaseData* eclipseCase ); + +private: + static void appendCells( size_t nodeStartIndex, size_t cellCount, RigGridBase* hostGrid, std::vector& cells ); + static void appendNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, const cvf::Vec3st& cubeDimension, std::vector& nodes ); + static void appendCubeNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, std::vector& nodes ); + + size_t cellIndexFromIJK( size_t i, size_t j, size_t k ) const; + +private: + cvf::Vec3d m_minWorldCoordinate; + cvf::Vec3d m_maxWorldCoordinate; + cvf::Vec3st m_gridPointDimensions; + + std::vector m_localGridRefinements; +}; diff --git a/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.cpp b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.cpp index a5e8b5b866..e7886c8df8 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.cpp @@ -39,10 +39,9 @@ //-------------------------------------------------------------------------------------------------- RigReservoirBuilderMock::RigReservoirBuilderMock() { - m_resultCount = 0; - m_timeStepCount = 0; - m_gridPointDimensions = cvf::Vec3st::ZERO; - m_enableWellData = true; + m_resultCount = 0; + m_timeStepCount = 0; + m_enableWellData = true; } //-------------------------------------------------------------------------------------------------- @@ -50,7 +49,7 @@ RigReservoirBuilderMock::RigReservoirBuilderMock() //-------------------------------------------------------------------------------------------------- void RigReservoirBuilderMock::setGridPointDimensions( const cvf::Vec3st& gridPointDimensions ) { - m_gridPointDimensions = gridPointDimensions; + m_reservoirBuilder.setIJKCount( { gridPointDimensions.x() - 1, gridPointDimensions.y() - 1, gridPointDimensions.z() - 1 } ); } //-------------------------------------------------------------------------------------------------- @@ -62,194 +61,12 @@ void RigReservoirBuilderMock::setResultInfo( size_t resultCount, size_t timeStep m_timeStepCount = timeStepCount; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RigReservoirBuilderMock::appendNodes( const cvf::Vec3d& min, - const cvf::Vec3d& max, - const cvf::Vec3st& cubeDimension, - std::vector& nodes ) -{ - double dx = ( max.x() - min.x() ) / static_cast( cubeDimension.x() ); - double dy = ( max.y() - min.y() ) / static_cast( cubeDimension.y() ); - double dz = ( max.z() - min.z() ) / static_cast( cubeDimension.z() ); - - double zPos = min.z(); - - size_t k; - for ( k = 0; k < cubeDimension.z(); k++ ) - { - double yPos = min.y(); - - size_t j; - for ( j = 0; j < cubeDimension.y(); j++ ) - { - double xPos = min.x(); - - size_t i; - for ( i = 0; i < cubeDimension.x(); i++ ) - { - cvf::Vec3d cornerA( xPos, yPos, zPos ); - cvf::Vec3d cornerB( xPos + dx, yPos + dy, zPos + dz ); - - appendCubeNodes( cornerA, cornerB, nodes ); - - xPos += dx; - } - - yPos += dy; - } - - zPos += dz; - } -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RigReservoirBuilderMock::appendCubeNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, std::vector& nodes ) -{ - // - // 7---------6 Faces: - // /| /| |k 0 bottom 0, 3, 2, 1 - // / | / | | /j 1 top 4, 5, 6, 7 - // 4---------5 | |/ 2 front 0, 1, 5, 4 - // | 3------|--2 *---i 3 right 1, 2, 6, 5 - // | / | / 4 back 3, 7, 6, 2 - // |/ |/ 5 left 0, 4, 7, 3 - // 0---------1 - - cvf::Vec3d v0( min.x(), min.y(), min.z() ); - cvf::Vec3d v1( max.x(), min.y(), min.z() ); - cvf::Vec3d v2( max.x(), max.y(), min.z() ); - cvf::Vec3d v3( min.x(), max.y(), min.z() ); - - cvf::Vec3d v4( min.x(), min.y(), max.z() ); - cvf::Vec3d v5( max.x(), min.y(), max.z() ); - cvf::Vec3d v6( max.x(), max.y(), max.z() ); - cvf::Vec3d v7( min.x(), max.y(), max.z() ); - - nodes.push_back( v0 ); - nodes.push_back( v1 ); - nodes.push_back( v2 ); - nodes.push_back( v3 ); - nodes.push_back( v4 ); - nodes.push_back( v5 ); - nodes.push_back( v6 ); - nodes.push_back( v7 ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void RigReservoirBuilderMock::appendCells( size_t nodeStartIndex, size_t cellCount, RigGridBase* hostGrid, std::vector& cells ) -{ - size_t cellIndexStart = cells.size(); - cells.resize( cells.size() + cellCount ); - -#pragma omp parallel for - for ( long long i = 0; i < static_cast( cellCount ); i++ ) - { - RigCell& riCell = cells[cellIndexStart + i]; - - riCell.setHostGrid( hostGrid ); - riCell.setGridLocalCellIndex( i ); - - riCell.cornerIndices()[0] = nodeStartIndex + i * 8 + 0; - riCell.cornerIndices()[1] = nodeStartIndex + i * 8 + 1; - riCell.cornerIndices()[2] = nodeStartIndex + i * 8 + 2; - riCell.cornerIndices()[3] = nodeStartIndex + i * 8 + 3; - riCell.cornerIndices()[4] = nodeStartIndex + i * 8 + 4; - riCell.cornerIndices()[5] = nodeStartIndex + i * 8 + 5; - riCell.cornerIndices()[6] = nodeStartIndex + i * 8 + 6; - riCell.cornerIndices()[7] = nodeStartIndex + i * 8 + 7; - - riCell.setParentCellIndex( 0 ); - } -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void RigReservoirBuilderMock::populateReservoir( RigEclipseCaseData* eclipseCase ) { - std::vector& mainGridNodes = eclipseCase->mainGrid()->nodes(); - appendNodes( m_minWorldCoordinate, m_maxWorldCoordinate, cellDimension(), mainGridNodes ); - size_t mainGridNodeCount = mainGridNodes.size(); - size_t mainGridCellCount = mainGridNodeCount / 8; - - // Must create cells in main grid here, as this information is used when creating LGRs - appendCells( 0, mainGridCellCount, eclipseCase->mainGrid(), eclipseCase->mainGrid()->globalCellArray() ); - - size_t totalCellCount = mainGridCellCount; - - size_t lgrIdx; - for ( lgrIdx = 0; lgrIdx < m_localGridRefinements.size(); lgrIdx++ ) - { - LocalGridRefinement& lgr = m_localGridRefinements[lgrIdx]; - - // Compute all global cell indices to be replaced by local grid refinement - std::vector mainGridIndicesWithSubGrid; - { - size_t i; - for ( i = lgr.m_mainGridMinCellPosition.x(); i <= lgr.m_mainGridMaxCellPosition.x(); i++ ) - { - size_t j; - for ( j = lgr.m_mainGridMinCellPosition.y(); j <= lgr.m_mainGridMaxCellPosition.y(); j++ ) - { - size_t k; - for ( k = lgr.m_mainGridMinCellPosition.z(); k <= lgr.m_mainGridMaxCellPosition.z(); k++ ) - { - mainGridIndicesWithSubGrid.push_back( cellIndexFromIJK( i, j, k ) ); - } - } - } - } - - // Create local grid and set local grid dimensions - RigLocalGrid* localGrid = new RigLocalGrid( eclipseCase->mainGrid() ); - localGrid->setGridId( 1 ); - localGrid->setGridName( "LGR_1" ); - eclipseCase->mainGrid()->addLocalGrid( localGrid ); - localGrid->setParentGrid( eclipseCase->mainGrid() ); - - localGrid->setIndexToStartOfCells( mainGridNodes.size() / 8 ); - cvf::Vec3st gridPointDimensions( lgr.m_singleCellRefinementFactors.x() * - ( lgr.m_mainGridMaxCellPosition.x() - lgr.m_mainGridMinCellPosition.x() + 1 ) + - 1, - lgr.m_singleCellRefinementFactors.y() * - ( lgr.m_mainGridMaxCellPosition.y() - lgr.m_mainGridMinCellPosition.y() + 1 ) + - 1, - lgr.m_singleCellRefinementFactors.z() * - ( lgr.m_mainGridMaxCellPosition.z() - lgr.m_mainGridMinCellPosition.z() + 1 ) + - 1 ); - localGrid->setGridPointDimensions( gridPointDimensions ); - - cvf::BoundingBox bb; - size_t cellIdx; - for ( cellIdx = 0; cellIdx < mainGridIndicesWithSubGrid.size(); cellIdx++ ) - { - RigCell& cell = eclipseCase->mainGrid()->globalCellArray()[mainGridIndicesWithSubGrid[cellIdx]]; - - std::array& indices = cell.cornerIndices(); - int nodeIdx; - for ( nodeIdx = 0; nodeIdx < 8; nodeIdx++ ) - { - bb.add( eclipseCase->mainGrid()->nodes()[indices[nodeIdx]] ); - } - // Deactivate cell in main grid - cell.setSubGrid( localGrid ); - } - - cvf::Vec3st lgrCellDimensions = gridPointDimensions - cvf::Vec3st( 1, 1, 1 ); - appendNodes( bb.min(), bb.max(), lgrCellDimensions, mainGridNodes ); - - size_t subGridCellCount = ( mainGridNodes.size() / 8 ) - totalCellCount; - appendCells( totalCellCount * 8, subGridCellCount, localGrid, eclipseCase->mainGrid()->globalCellArray() ); - totalCellCount += subGridCellCount; - } - - eclipseCase->mainGrid()->setGridPointDimensions( m_gridPointDimensions ); + m_reservoirBuilder.createGridsAndCells( eclipseCase ); if ( m_enableWellData ) { @@ -258,24 +75,12 @@ void RigReservoirBuilderMock::populateReservoir( RigEclipseCaseData* eclipseCase addFaults( eclipseCase ); - // Set all cells active - RigActiveCellInfo* activeCellInfo = eclipseCase->activeCellInfo( RiaDefines::PorosityModelType::MATRIX_MODEL ); - activeCellInfo->setReservoirCellCount( eclipseCase->mainGrid()->globalCellArray().size() ); - for ( size_t i = 0; i < eclipseCase->mainGrid()->globalCellArray().size(); i++ ) - { - activeCellInfo->setCellResultIndex( i, i ); - } - - activeCellInfo->setGridCount( 1 ); - activeCellInfo->setGridActiveCellCounts( 0, eclipseCase->mainGrid()->globalCellArray().size() ); - activeCellInfo->computeDerivedData(); - // Add grid coarsening for main grid - if ( cellDimension().x() > 4 && cellDimension().y() > 5 && cellDimension().z() > 6 ) - { - eclipseCase->mainGrid()->addCoarseningBox( 1, 2, 1, 3, 1, 4 ); - eclipseCase->mainGrid()->addCoarseningBox( 3, 4, 4, 5, 5, 6 ); - } + // if ( cellDimension().x() > 4 && cellDimension().y() > 5 && cellDimension().z() > 6 ) + // { + // eclipseCase->mainGrid()->addCoarseningBox( 1, 2, 1, 3, 1, 4 ); + // eclipseCase->mainGrid()->addCoarseningBox( 3, 4, 4, 5, 5, 6 ); + // } } //-------------------------------------------------------------------------------------------------- @@ -285,7 +90,7 @@ void RigReservoirBuilderMock::addLocalGridRefinement( const cvf::Vec3st& mainGri const cvf::Vec3st& mainGridEnd, const cvf::Vec3st& refinementFactors ) { - m_localGridRefinements.push_back( LocalGridRefinement( mainGridStart, mainGridEnd, refinementFactors ) ); + m_reservoirBuilder.addLocalGridRefinement( mainGridStart, mainGridEnd, refinementFactors ); } //-------------------------------------------------------------------------------------------------- @@ -293,8 +98,7 @@ void RigReservoirBuilderMock::addLocalGridRefinement( const cvf::Vec3st& mainGri //-------------------------------------------------------------------------------------------------- void RigReservoirBuilderMock::setWorldCoordinates( cvf::Vec3d minWorldCoordinate, cvf::Vec3d maxWorldCoordinate ) { - m_minWorldCoordinate = minWorldCoordinate; - m_maxWorldCoordinate = maxWorldCoordinate; + m_reservoirBuilder.setWorldCoordinates( minWorldCoordinate, maxWorldCoordinate ); } //-------------------------------------------------------------------------------------------------- @@ -377,7 +181,8 @@ void RigReservoirBuilderMock::addWellData( RigEclipseCaseData* eclipseCase, RigG CVF_ASSERT( eclipseCase ); CVF_ASSERT( grid ); - cvf::Vec3st dim = grid->gridPointDimensions(); + auto cellCountJ = grid->cellCountJ(); + auto cellCountK = grid->cellCountK(); cvf::Collection wells; @@ -404,7 +209,7 @@ void RigReservoirBuilderMock::addWellData( RigEclipseCaseData* eclipseCase, RigG // Connections // int connectionCount = std::min(dim.x(), std::min(dim.y(), dim.z())) - 2; - size_t connectionCount = dim.z() - 2; + size_t connectionCount = cellCountK - 2; if ( connectionCount > 0 ) { // Only main grid supported by now. Must be taken care of when LGRs are supported @@ -420,10 +225,10 @@ void RigReservoirBuilderMock::addWellData( RigEclipseCaseData* eclipseCase, RigG RigWellResultPoint data; data.setGridIndex( 0 ); - if ( connIdx < dim.y() - 2 ) + if ( connIdx < cellCountJ - 2 ) data.setGridCellIndex( grid->cellIndexFromIJK( 1, 1 + connIdx, 1 + connIdx ) ); else - data.setGridCellIndex( grid->cellIndexFromIJK( 1, dim.y() - 2, 1 + connIdx ) ); + data.setGridCellIndex( grid->cellIndexFromIJK( 1, cellCountJ - 2, 1 + connIdx ) ); if ( connIdx < connectionCount / 2 ) { @@ -458,7 +263,7 @@ void RigReservoirBuilderMock::addWellData( RigEclipseCaseData* eclipseCase, RigG } } - if ( connIdx < dim.y() - 2 ) + if ( connIdx < cellCountJ - 2 ) { data.setGridCellIndex( grid->cellIndexFromIJK( 1, 1 + connIdx, 2 + connIdx ) ); @@ -500,23 +305,25 @@ void RigReservoirBuilderMock::addFaults( RigEclipseCaseData* eclipseCase ) cvf::Collection faults; + auto cellDimension = m_reservoirBuilder.ijkCount(); + { cvf::ref fault = new RigFault; fault->setName( "Fault A" ); cvf::Vec3st min = cvf::Vec3st::ZERO; - cvf::Vec3st max( 0, 0, cellDimension().z() - 2 ); + cvf::Vec3st max( 0, 0, cellDimension.z() - 2 ); - if ( cellDimension().x() > 5 ) + if ( cellDimension.x() > 5 ) { - min.x() = cellDimension().x() / 2; + min.x() = cellDimension.x() / 2; max.x() = min.x() + 2; } - if ( cellDimension().y() > 5 ) + if ( cellDimension.y() > 5 ) { - min.y() = cellDimension().y() / 2; - max.y() = cellDimension().y() / 2; + min.y() = cellDimension.y() / 2; + max.y() = cellDimension.y() / 2; } cvf::CellRange cellRange( min, max ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.h b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.h index c793e532dd..c38269df48 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.h +++ b/ApplicationLibCode/ReservoirDataModel/RigReservoirBuilderMock.h @@ -21,13 +21,12 @@ #pragma once #include "RigNncConnection.h" +#include "RigReservoirBuilder.h" #include "cvfArray.h" #include "cvfObject.h" #include "cvfVector3.h" -#include - class RigEclipseCaseData; class RigMainGrid; class RigGridBase; @@ -35,21 +34,6 @@ class RigCell; class QString; -class LocalGridRefinement -{ -public: - LocalGridRefinement( const cvf::Vec3st& mainGridMin, const cvf::Vec3st& mainGridMax, const cvf::Vec3st& singleCellRefinementFactors ) - { - m_mainGridMinCellPosition = mainGridMin; - m_mainGridMaxCellPosition = mainGridMax; - m_singleCellRefinementFactors = singleCellRefinementFactors; - } - - cvf::Vec3st m_mainGridMinCellPosition; - cvf::Vec3st m_mainGridMaxCellPosition; - cvf::Vec3st m_singleCellRefinementFactors; -}; - class RigReservoirBuilderMock { public: @@ -60,9 +44,8 @@ class RigReservoirBuilderMock void setResultInfo( size_t resultCount, size_t timeStepCount ); void enableWellData( bool enableWellData ); - size_t resultCount() const { return m_resultCount; } - size_t timeStepCount() const { return m_timeStepCount; } - cvf::Vec3st gridPointDimensions() const { return m_gridPointDimensions; } + size_t resultCount() const { return m_resultCount; } + size_t timeStepCount() const { return m_timeStepCount; } void addLocalGridRefinement( const cvf::Vec3st& minCellPosition, const cvf::Vec3st& maxCellPosition, @@ -79,34 +62,12 @@ class RigReservoirBuilderMock static void addNnc( RigMainGrid* grid, size_t i1, size_t j1, size_t k1, size_t i2, size_t j2, size_t k2, RigConnectionContainer& nncConnections ); - void addWellData( RigEclipseCaseData* eclipseCase, RigGridBase* grid ); - static void appendCells( size_t nodeStartIndex, size_t cellCount, RigGridBase* hostGrid, std::vector& cells ); - - static void appendNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, const cvf::Vec3st& cubeDimension, std::vector& nodes ); - static void appendCubeNodes( const cvf::Vec3d& min, const cvf::Vec3d& max, std::vector& nodes ); - - size_t cellIndexFromIJK( size_t i, size_t j, size_t k ) const - { - CVF_TIGHT_ASSERT( i < ( m_gridPointDimensions.x() - 1 ) ); - CVF_TIGHT_ASSERT( j < ( m_gridPointDimensions.y() - 1 ) ); - CVF_TIGHT_ASSERT( k < ( m_gridPointDimensions.z() - 1 ) ); - - size_t ci = i + j * ( m_gridPointDimensions.x() - 1 ) + k * ( ( m_gridPointDimensions.x() - 1 ) * ( m_gridPointDimensions.y() - 1 ) ); - return ci; - } - - cvf::Vec3st cellDimension() - { - return cvf::Vec3st( m_gridPointDimensions.x() - 1, m_gridPointDimensions.y() - 1, m_gridPointDimensions.z() - 1 ); - } + void addWellData( RigEclipseCaseData* eclipseCase, RigGridBase* grid ); private: - cvf::Vec3d m_minWorldCoordinate; - cvf::Vec3d m_maxWorldCoordinate; - cvf::Vec3st m_gridPointDimensions; - size_t m_resultCount; - size_t m_timeStepCount; - bool m_enableWellData; + size_t m_resultCount; + size_t m_timeStepCount; + bool m_enableWellData; - std::vector m_localGridRefinements; + RigReservoirBuilder m_reservoirBuilder; }; diff --git a/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.cpp b/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.cpp index ee3cbadb8b..014a96d9ef 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.cpp @@ -43,7 +43,7 @@ //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -std::vector RigSimulationWellCenterLineCalculator::calculateWellPipeStaticCenterline( RimSimWellInView* rimWell ) +std::vector RigSimulationWellCenterLineCalculator::calculateWellPipeStaticCenterline( const RimSimWellInView* rimWell ) { std::vector> pipeBranchesCLCoords; std::vector> pipeBranchesCellIds; @@ -118,7 +118,7 @@ std::pair>, std::vector>& pipeBranchesCLCoords, std::vector>& pipeBranchesCellIds ) { diff --git a/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.h b/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.h index 347edc2d45..d2b8257634 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.h +++ b/ApplicationLibCode/ReservoirDataModel/RigSimulationWellCenterLineCalculator.h @@ -37,7 +37,7 @@ class RigWellResultFrame; class RigSimulationWellCenterLineCalculator { public: - static std::vector calculateWellPipeStaticCenterline( RimSimWellInView* rimWell ); + static std::vector calculateWellPipeStaticCenterline( const RimSimWellInView* rimWell ); static std::vector calculateWellPipeCenterlineForTimeStep( const RigEclipseCaseData* eclipseCaseData, const RigSimWellData* simWellData, @@ -49,7 +49,7 @@ class RigSimulationWellCenterLineCalculator extractBranchData( const std::vector simulationBranch ); private: - static void calculateWellPipeStaticCenterline( RimSimWellInView* rimWell, + static void calculateWellPipeStaticCenterline( const RimSimWellInView* rimWell, std::vector>& pipeBranchesCLCoords, std::vector>& pipeBranchesCellIds ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigStimPlanModelTools.cpp b/ApplicationLibCode/ReservoirDataModel/RigStimPlanModelTools.cpp index 47c6eb515f..5c3f423a5b 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigStimPlanModelTools.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigStimPlanModelTools.cpp @@ -54,8 +54,7 @@ cvf::Vec3d RigStimPlanModelTools::calculateTSTDirection( RigEclipseCaseData* ecl // Find upper face of cells close to the anchor point cvf::BoundingBox boundingBox( anchorPosition - boundingBoxSize, anchorPosition + boundingBoxSize ); - std::vector closeCells; - mainGrid->findIntersectingCells( boundingBox, &closeCells ); + std::vector closeCells = mainGrid->findIntersectingCells( boundingBox ); // The stratigraphic thickness is the averge of normals of the top face cvf::Vec3d direction = cvf::Vec3d::ZERO; diff --git a/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.cpp b/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.cpp index 5d0cc11aff..e010a3d6ab 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.cpp @@ -17,6 +17,7 @@ ///////////////////////////////////////////////////////////////////////////////// #include "RigWbsParameter.h" +#include "RiaResultNames.h" #include "RiaWellLogUnitTools.h" #include "RigFemAddressDefines.h" @@ -259,6 +260,47 @@ RigWbsParameter RigWbsParameter::PP_NonReservoir() return RigWbsParameter( "PP_Non-Reservoir", true, sources ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWbsParameter RigWbsParameter::PP_Min() +{ + SourceVector sources = { { LAS_FILE, SourceAddress( RiaResultNames::wbsPPMinResult(), "", RiaWellLogUnitTools::barUnitString() ) } }; + + return RigWbsParameter( "PP_MIN", true, sources ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWbsParameter RigWbsParameter::PP_Max() +{ + SourceVector sources = { { LAS_FILE, SourceAddress( RiaResultNames::wbsPPMaxResult(), "", RiaWellLogUnitTools::barUnitString() ) } }; + + return RigWbsParameter( "PP_MAX", true, sources ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWbsParameter RigWbsParameter::PP_Exp() +{ + SourceVector sources = { { LAS_FILE, SourceAddress( RiaResultNames::wbsPPExpResult(), "", RiaWellLogUnitTools::barUnitString() ) } }; + + return RigWbsParameter( "PP_EXP", true, sources ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWbsParameter RigWbsParameter::PP_Initial() +{ + SourceVector sources = { + { LAS_FILE, SourceAddress( RiaResultNames::wbsPPInitialResult(), "", RiaWellLogUnitTools::barUnitString() ) } }; + + return RigWbsParameter( "PP_INIT", true, sources ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -365,6 +407,26 @@ RigWbsParameter RigWbsParameter::FG_Shale() return param; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWbsParameter RigWbsParameter::FG_MkMin() +{ + RigWbsParameter param( "FG_MK_MIN", false, { { DERIVED_FROM_K0FG, SourceAddress() }, { PROPORTIONAL_TO_SH, SourceAddress() } } ); + param.setOptionsExclusive( true ); + return param; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWbsParameter RigWbsParameter::FG_MkExp() +{ + RigWbsParameter param( "FG_MK_EXP", false, { { DERIVED_FROM_K0FG, SourceAddress() }, { PROPORTIONAL_TO_SH, SourceAddress() } } ); + param.setOptionsExclusive( true ); + return param; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -376,12 +438,30 @@ RigWbsParameter RigWbsParameter::waterDensity() { LAS_FILE, SourceAddress( "RHO_INP", "", RiaWellLogUnitTools::gPerCm3UnitString() ) } } ); return param; } + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- std::set RigWbsParameter::allParameters() { - return { PP_Reservoir(), PP_NonReservoir(), poissonRatio(), UCS(), OBG(), OBG0(), SH(), DF(), K0_FG(), K0_SH(), FG_Shale(), waterDensity() }; + return { PP_Reservoir(), + PP_NonReservoir(), + PP_Min(), + PP_Max(), + PP_Exp(), + PP_Initial(), + poissonRatio(), + UCS(), + OBG(), + OBG0(), + SH(), + DF(), + K0_FG(), + K0_SH(), + FG_Shale(), + FG_MkMin(), + FG_MkExp(), + waterDensity() }; } //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.h b/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.h index 34186d862a..5e8bd726d3 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.h +++ b/ApplicationLibCode/ReservoirDataModel/RigWbsParameter.h @@ -74,6 +74,11 @@ class RigWbsParameter static RigWbsParameter PP_Reservoir(); static RigWbsParameter PP_NonReservoir(); + static RigWbsParameter PP_Min(); + static RigWbsParameter PP_Max(); + static RigWbsParameter PP_Exp(); + static RigWbsParameter PP_Initial(); + static RigWbsParameter poissonRatio(); static RigWbsParameter UCS(); static RigWbsParameter OBG(); @@ -83,6 +88,9 @@ class RigWbsParameter static RigWbsParameter K0_FG(); static RigWbsParameter K0_SH(); static RigWbsParameter FG_Shale(); + static RigWbsParameter FG_MkMin(); + static RigWbsParameter FG_MkExp(); + static RigWbsParameter waterDensity(); static std::set allParameters(); diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogCsvFile.cpp b/ApplicationLibCode/ReservoirDataModel/RigWellLogCsvFile.cpp new file mode 100644 index 0000000000..849a32c29f --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogCsvFile.cpp @@ -0,0 +1,231 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RigWellLogCsvFile.h" + +#include "RiaInterpolationTools.h" +#include "RifCsvUserDataParser.h" +#include "RigWellLogCurveData.h" +#include "RigWellPathGeometryTools.h" + +#include "SummaryPlotCommands/RicPasteAsciiDataToSummaryPlotFeatureUi.h" + +#include "RiaLogging.h" +#include "RiaStringEncodingTools.h" + +#include "RimWellLogCurve.h" +#include "RimWellPath.h" + +#include +#include + +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWellLogCsvFile::RigWellLogCsvFile() + : RigWellLogFile() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWellLogCsvFile::~RigWellLogCsvFile() +{ + close(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RigWellLogCsvFile::open( const QString& fileName, RigWellPath* wellPath, QString* errorMessage ) +{ + m_wellLogChannelNames.clear(); + + RifCsvUserDataFileParser parser( fileName, errorMessage ); + + AsciiDataParseOptions parseOptions; + parseOptions.useCustomDateTimeFormat = true; + parseOptions.dateTimeFormat = "dd.MM.yyyy hh:mm:ss"; + parseOptions.fallbackDateTimeFormat = "dd.MM.yyyy"; + parseOptions.cellSeparator = ";"; + parseOptions.decimalSeparator = ","; + + if ( !parser.parse( parseOptions ) ) + { + return false; + } + + std::map> readValues; + + for ( auto s : parser.tableData().columnInfos() ) + { + if ( s.dataType != Column::NUMERIC ) continue; + QString columnName = QString::fromStdString( s.columnName() ); + m_wellLogChannelNames.append( columnName ); + readValues[columnName] = s.values; + m_units[columnName] = QString::fromStdString( s.unitName ); + + if ( columnName.toUpper() == "TVDMSL" || columnName.toUpper().contains( "TVD" ) ) + { + m_tvdMslLogName = columnName; + } + } + + if ( m_tvdMslLogName.isEmpty() ) + { + QString message = "CSV file does not have TVD values."; + RiaLogging::error( message ); + if ( errorMessage ) *errorMessage = message; + return false; + } + + std::vector readTvds = readValues[m_tvdMslLogName]; + + for ( auto [channelName, readValues] : readValues ) + { + if ( channelName == m_tvdMslLogName ) + { + // Use TVD from well path. + m_values[m_tvdMslLogName] = wellPath->trueVerticalDepths(); + } + else + { + CAF_ASSERT( readValues.size() == readTvds.size() ); + + auto wellPathMds = wellPath->measuredDepths(); + auto wellPathTvds = wellPath->trueVerticalDepths(); + + // Interpolate values for the well path depths (from TVD). + // Assumes that the well channel values is dependent on TVD only (MD is not considered). + std::vector values; + for ( auto tvd : wellPathTvds ) + { + double value = RiaInterpolationTools::linear( readTvds, readValues, tvd, RiaInterpolationTools::ExtrapolationMode::TREND ); + values.push_back( value ); + } + + m_values[channelName] = values; + } + } + + // Use MD from well path. + m_depthLogName = "DEPTH"; + m_values[m_depthLogName] = wellPath->measuredDepths(); + + return true; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RigWellLogCsvFile::close() +{ + m_wellLogChannelNames.clear(); + m_depthLogName.clear(); + m_values.clear(); + m_units.clear(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QStringList RigWellLogCsvFile::wellLogChannelNames() const +{ + return m_wellLogChannelNames; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RigWellLogCsvFile::depthValues() const +{ + return values( m_depthLogName ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RigWellLogCsvFile::tvdMslValues() const +{ + return values( m_tvdMslLogName ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RigWellLogCsvFile::tvdRkbValues() const +{ + // Not supported. + return std::vector(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector RigWellLogCsvFile::values( const QString& name ) const +{ + if ( auto it = m_values.find( name ); it != m_values.end() ) return it->second; + return std::vector(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RigWellLogCsvFile::depthUnitString() const +{ + return wellLogChannelUnitString( m_tvdMslLogName ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RigWellLogCsvFile::wellLogChannelUnitString( const QString& wellLogChannelName ) const +{ + auto unit = m_units.find( wellLogChannelName ); + if ( unit != m_units.end() ) + return unit->second; + else + return ""; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RigWellLogCsvFile::hasTvdMslChannel() const +{ + return !m_tvdMslLogName.isEmpty(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool RigWellLogCsvFile::hasTvdRkbChannel() const +{ + return !m_tvdRkbLogName.isEmpty(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +double RigWellLogCsvFile::getMissingValue() const +{ + return std::numeric_limits::infinity(); +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogCsvFile.h b/ApplicationLibCode/ReservoirDataModel/RigWellLogCsvFile.h new file mode 100644 index 0000000000..78857d8779 --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogCsvFile.h @@ -0,0 +1,69 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RigWellLogFile.h" + +#include "RiaDefines.h" + +#include + +#include +#include + +class RigWellPath; + +//================================================================================================== +/// +//================================================================================================== +class RigWellLogCsvFile : public RigWellLogFile +{ +public: + RigWellLogCsvFile(); + ~RigWellLogCsvFile() override; + + bool open( const QString& fileName, RigWellPath* wellPath, QString* errorMessage ); + + QStringList wellLogChannelNames() const override; + + std::vector depthValues() const override; + std::vector tvdMslValues() const override; + std::vector tvdRkbValues() const override; + + std::vector values( const QString& name ) const override; + + QString wellLogChannelUnitString( const QString& wellLogChannelName ) const override; + RiaDefines::DepthUnitType depthUnit() const; + + bool hasTvdMslChannel() const override; + bool hasTvdRkbChannel() const override; + + double getMissingValue() const override; + +private: + void close(); + QString depthUnitString() const override; + + QStringList m_wellLogChannelNames; + QString m_depthLogName; + QString m_tvdMslLogName; + QString m_tvdRkbLogName; + std::map> m_values; + std::map m_units; +}; diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogCurveData.cpp b/ApplicationLibCode/ReservoirDataModel/RigWellLogCurveData.cpp index c090d07001..f5239ed7ba 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigWellLogCurveData.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogCurveData.cpp @@ -251,6 +251,7 @@ std::vector RigWellLogCurveData::depthValuesByIntervals( RiaDefines::Dep RiaDefines::DepthUnitType destinationDepthUnit ) const { const std::vector depthValues = RigWellLogCurveData::depthsForDepthUnit( depths( depthType ), m_depthUnit, destinationDepthUnit ); + if ( depthValues.empty() ) return depthValues; std::vector filteredValues; RiaCurveDataTools::getValuesByIntervals( depthValues, m_intervalsOfContinousValidValues, &filteredValues ); diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogFile.cpp b/ApplicationLibCode/ReservoirDataModel/RigWellLogFile.cpp new file mode 100644 index 0000000000..50f720d8ae --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogFile.cpp @@ -0,0 +1,80 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2015- Statoil ASA +// Copyright (C) 2015- Ceetron Solutions AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "RigWellLogFile.h" + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWellLogFile::RigWellLogFile() + : cvf::Object() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RigWellLogFile::~RigWellLogFile() +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RiaDefines::DepthUnitType RigWellLogFile::depthUnit() const +{ + RiaDefines::DepthUnitType unitType = RiaDefines::DepthUnitType::UNIT_METER; + + if ( depthUnitString().toUpper() == "F" || depthUnitString().toUpper() == "FT" ) + { + unitType = RiaDefines::DepthUnitType::UNIT_FEET; + } + + return unitType; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QString RigWellLogFile::convertedWellLogChannelUnitString( const QString& wellLogChannelName, RiaDefines::DepthUnitType displayDepthUnit ) const +{ + QString unit = wellLogChannelUnitString( wellLogChannelName ); + + if ( unit == depthUnitString() ) + { + if ( displayDepthUnit != depthUnit() ) + { + if ( displayDepthUnit == RiaDefines::DepthUnitType::UNIT_METER ) + { + return "M"; + } + else if ( displayDepthUnit == RiaDefines::DepthUnitType::UNIT_FEET ) + { + return "FT"; + } + else if ( displayDepthUnit == RiaDefines::DepthUnitType::UNIT_NONE ) + { + CVF_ASSERT( false ); + return ""; + } + } + } + + return unit; +} diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogFile.h b/ApplicationLibCode/ReservoirDataModel/RigWellLogFile.h new file mode 100644 index 0000000000..ed91a3f5f5 --- /dev/null +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogFile.h @@ -0,0 +1,58 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2015- Statoil ASA +// Copyright (C) 2015- Ceetron Solutions AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "RiaDefines.h" + +#include "cvfObject.h" + +#include +#include + +class RimWellLogCurve; + +//================================================================================================== +/// +//================================================================================================== +class RigWellLogFile : public cvf::Object +{ +public: + RigWellLogFile(); + ~RigWellLogFile() override; + + virtual QStringList wellLogChannelNames() const = 0; + + virtual std::vector depthValues() const = 0; + virtual std::vector tvdMslValues() const = 0; + virtual std::vector tvdRkbValues() const = 0; + + virtual std::vector values( const QString& name ) const = 0; + + virtual QString wellLogChannelUnitString( const QString& wellLogChannelName ) const = 0; + virtual QString depthUnitString() const = 0; + + QString convertedWellLogChannelUnitString( const QString& wellLogChannelName, RiaDefines::DepthUnitType displayDepthUnit ) const; + RiaDefines::DepthUnitType depthUnit() const; + + virtual bool hasTvdMslChannel() const = 0; + virtual bool hasTvdRkbChannel() const = 0; + + virtual double getMissingValue() const = 0; +}; diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.cpp b/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.cpp index 743ebf357a..661ea3110f 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.cpp +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.cpp @@ -38,7 +38,7 @@ /// //-------------------------------------------------------------------------------------------------- RigWellLogLasFile::RigWellLogLasFile() - : cvf::Object() + : RigWellLogFile() { m_wellLogFile = nullptr; } @@ -223,42 +223,6 @@ QString RigWellLogLasFile::depthUnitString() const return unit; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QString RigWellLogLasFile::wellLogChannelUnitString( const QString& wellLogChannelName, RiaDefines::DepthUnitType displayDepthUnit ) const -{ - QString unit; - - NRLib::LasWell* lasWell = dynamic_cast( m_wellLogFile ); - if ( lasWell ) - { - unit = QString::fromStdString( lasWell->unitName( wellLogChannelName.toStdString() ) ); - } - - if ( unit == depthUnitString() ) - { - if ( displayDepthUnit != depthUnit() ) - { - if ( displayDepthUnit == RiaDefines::DepthUnitType::UNIT_METER ) - { - return "M"; - } - else if ( displayDepthUnit == RiaDefines::DepthUnitType::UNIT_FEET ) - { - return "FT"; - } - else if ( displayDepthUnit == RiaDefines::DepthUnitType::UNIT_NONE ) - { - CVF_ASSERT( false ); - return ""; - } - } - } - - return unit; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -297,18 +261,3 @@ double RigWellLogLasFile::getMissingValue() const { return m_wellLogFile->GetContMissing(); } - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RiaDefines::DepthUnitType RigWellLogLasFile::depthUnit() const -{ - RiaDefines::DepthUnitType unitType = RiaDefines::DepthUnitType::UNIT_METER; - - if ( depthUnitString().toUpper() == "F" || depthUnitString().toUpper() == "FT" ) - { - unitType = RiaDefines::DepthUnitType::UNIT_FEET; - } - - return unitType; -} diff --git a/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.h b/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.h index 8e473f37f1..1be8f381ff 100644 --- a/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.h +++ b/ApplicationLibCode/ReservoirDataModel/RigWellLogLasFile.h @@ -19,9 +19,9 @@ #pragma once -#include "RiaDefines.h" +#include "RigWellLogFile.h" -#include "cvfObject.h" +#include "RiaDefines.h" #include #include @@ -36,7 +36,7 @@ class RimWellLogCurve; //================================================================================================== /// //================================================================================================== -class RigWellLogLasFile : public cvf::Object +class RigWellLogLasFile : public RigWellLogFile { public: RigWellLogLasFile(); @@ -46,26 +46,24 @@ class RigWellLogLasFile : public cvf::Object QString wellName() const; QString date() const; - QStringList wellLogChannelNames() const; + QStringList wellLogChannelNames() const override; - std::vector depthValues() const; - std::vector tvdMslValues() const; - std::vector tvdRkbValues() const; + std::vector depthValues() const override; + std::vector tvdMslValues() const override; + std::vector tvdRkbValues() const override; - std::vector values( const QString& name ) const; + std::vector values( const QString& name ) const override; - QString wellLogChannelUnitString( const QString& wellLogChannelName, RiaDefines::DepthUnitType displayDepthUnit ) const; - QString wellLogChannelUnitString( const QString& wellLogChannelName ) const; - RiaDefines::DepthUnitType depthUnit() const; + QString wellLogChannelUnitString( const QString& wellLogChannelName ) const override; - bool hasTvdMslChannel() const; - bool hasTvdRkbChannel() const; + bool hasTvdMslChannel() const override; + bool hasTvdRkbChannel() const override; - double getMissingValue() const; + double getMissingValue() const override; private: void close(); - QString depthUnitString() const; + QString depthUnitString() const override; NRLib::Well* m_wellLogFile; QStringList m_wellLogChannelNames; diff --git a/ApplicationLibCode/SocketInterface/CMakeLists_files.cmake b/ApplicationLibCode/SocketInterface/CMakeLists_files.cmake new file mode 100644 index 0000000000..9c8472dbef --- /dev/null +++ b/ApplicationLibCode/SocketInterface/CMakeLists_files.cmake @@ -0,0 +1,25 @@ +set(SOURCE_GROUP_HEADER_FILES + ${CMAKE_CURRENT_LIST_DIR}/RifTextDataTableFormatter.h +) + +set(SOURCE_GROUP_SOURCE_FILES + ${CMAKE_CURRENT_LIST_DIR}/RiaSocketServer.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaProjectInfoCommands.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaCaseInfoCommands.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaGeometryCommands.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaNNCCommands.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaPropertyDataCommands.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaWellDataCommands.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaSocketTools.cpp + ${CMAKE_CURRENT_LIST_DIR}/RiaSocketDataTransfer.cpp +) + +list(APPEND CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) + +list(APPEND CODE_SOURCE_FILES ${SOURCE_GROUP_SOURCE_FILES}) + +source_group( + "SocketInterface" + FILES ${SOURCE_GROUP_HEADER_FILES} ${SOURCE_GROUP_SOURCE_FILES} + ${CMAKE_CURRENT_LIST_DIR}/CMakeLists_files.cmake +) diff --git a/ApplicationLibCode/UnitTests/CMakeLists_files.cmake b/ApplicationLibCode/UnitTests/CMakeLists.txt similarity index 66% rename from ApplicationLibCode/UnitTests/CMakeLists_files.cmake rename to ApplicationLibCode/UnitTests/CMakeLists.txt index aa33ac608d..d25c8bd5c9 100644 --- a/ApplicationLibCode/UnitTests/CMakeLists_files.cmake +++ b/ApplicationLibCode/UnitTests/CMakeLists.txt @@ -1,11 +1,11 @@ -configure_file( - ${CMAKE_CURRENT_LIST_DIR}/RiaTestDataDirectory.h.cmake - ${CMAKE_BINARY_DIR}/Generated/RiaTestDataDirectory.h -) +# ResInsight unit tests -set(SOURCE_GROUP_HEADER_FILES) +if(MSVC) + # TARGET_RUNTIME_DLLS requires 3.21 + cmake_minimum_required(VERSION 3.21) +endif(MSVC) -set(SOURCE_GROUP_SOURCE_FILES +set(SOURCE_UNITTEST_FILES ${CMAKE_CURRENT_LIST_DIR}/cvfGeometryTools-Test.cpp ${CMAKE_CURRENT_LIST_DIR}/Ert-Test.cpp ${CMAKE_CURRENT_LIST_DIR}/RifcCommandCore-Test.cpp @@ -100,20 +100,118 @@ set(SOURCE_GROUP_SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/RifInpExportTools-Test.cpp ${CMAKE_CURRENT_LIST_DIR}/RifGridCalculationIO-Test.cpp ${CMAKE_CURRENT_LIST_DIR}/RifSummaryCalculationIO-Test.cpp + ${CMAKE_CURRENT_LIST_DIR}/RimEmReader-Test.cpp + ${CMAKE_CURRENT_LIST_DIR}/RifPolygonReader-Test.cpp ) if(RESINSIGHT_ENABLE_GRPC) - list(APPEND GPRC_UNIT_TEST_SOURCE_FILES + list(APPEND SOURCE_UNITTEST_FILES ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcInterface-Test.cpp ) - list(APPEND SOURCE_GROUP_SOURCE_FILES ${GRPC_UNIT_TEST_SOURCE_FILES}) endif(RESINSIGHT_ENABLE_GRPC) -list(APPEND CODE_HEADER_FILES ${SOURCE_GROUP_HEADER_FILES}) +# Obsolete test +if(RESINSIGHT_USE_ODB_API_OBSOLETE) + list(APPEND SOURCE_UNITTEST_FILES + ${CMAKE_CURRENT_LIST_DIR}/RifOdbReader-Test.cpp + ) +endif(RESINSIGHT_USE_ODB_API_OBSOLETE) + +include(FetchContent) +FetchContent_Declare( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.11.0 +) + +FetchContent_MakeAvailable(googletest) + +# ############################################################################## +# Copy required Dll/.so to output folder +# ############################################################################## + +# create an empty library target that will be used to copy files to the build +# folder +add_library(ResInsightDummyTestTarget EXCLUDE_FROM_ALL empty.cpp) +set_property( + TARGET ResInsightDummyTestTarget PROPERTY FOLDER "FileCopyTargetsTest" +) + +# create a custom target that copies the files to the build folder +foreach(riFileName ${RI_FILENAMES}) + list( + APPEND + copyCommands + COMMAND + ${CMAKE_COMMAND} + -E + copy_if_different + ${riFileName} + $ + ) +endforeach() +add_custom_target(PreBuildFileCopyTest ${copyCommands}) +set_property(TARGET PreBuildFileCopyTest PROPERTY FOLDER "FileCopyTargetsTest") + +add_executable(ResInsight-tests ${SOURCE_UNITTEST_FILES} main.cpp) + +# Make ResInsight-tests depend on the prebuild target. +add_dependencies(ResInsight-tests PreBuildFileCopyTest) + +configure_file( + ${CMAKE_CURRENT_LIST_DIR}/RiaTestDataDirectory.h.cmake + ${CMAKE_BINARY_DIR}/Generated/RiaTestDataDirectory.h +) + +target_include_directories( + ResInsight-tests + PUBLIC ${CMAKE_BINARY_DIR}/Generated + "$" + ${RI_PRIVATE_INCLUDES} ${PROJECT_SOURCE_DIR}/Commands +) + +target_compile_features(ResInsight-tests PRIVATE cxx_std_20) + +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) -list(APPEND CODE_SOURCE_FILES ${SOURCE_GROUP_SOURCE_FILES}) +if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") + list(APPEND THIRD_PARTY_LIBRARIES rt atomic) +endif() -source_group( - "UnitTests" FILES ${SOURCE_GROUP_HEADER_FILES} ${SOURCE_GROUP_SOURCE_FILES} - ${CMAKE_CURRENT_LIST_DIR}/CMakeLists_files.cmake +set(LINK_LIBRARIES + ${THIRD_PARTY_LIBRARIES} + ${OPENGL_LIBRARIES} + ${QT_LIBRARIES} + ${OPM_LIBRARIES} + ${APP_FWK_LIBRARIES} + ${VIZ_FWK_LIBRARIES} + ApplicationLibCode + Commands + RigGeoMechDataModel + RifGeoMechFileInterface ) + +if(RESINSIGHT_ENABLE_GRPC) + list(APPEND LINK_LIBRARIES GrpcInterface) +endif() + +if(RESINSIGHT_USE_ODB_API) + list(APPEND LINK_LIBRARIES RifOdbReader) +endif() + +target_link_libraries(ResInsight-tests PUBLIC ${LINK_LIBRARIES} GTest::gtest) + +if(MSVC) + add_custom_command( + TARGET ResInsight-tests + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy $ + $ + COMMAND_EXPAND_LISTS + ) + + set_target_properties(ResInsight-tests PROPERTIES COMPILE_FLAGS "/wd4190") +endif(MSVC) + +add_test(NAME ResInsight-tests COMMAND ResInsight-tests) diff --git a/ApplicationLibCode/UnitTests/RiaFilePathTools-Test.cpp b/ApplicationLibCode/UnitTests/RiaFilePathTools-Test.cpp index 0b311c00da..96654aeb0b 100644 --- a/ApplicationLibCode/UnitTests/RiaFilePathTools-Test.cpp +++ b/ApplicationLibCode/UnitTests/RiaFilePathTools-Test.cpp @@ -1,5 +1,6 @@ #include "gtest/gtest.h" +#include "RiaEnsembleNameTools.h" #include "RiaFilePathTools.h" #include @@ -112,3 +113,90 @@ TEST( RiaFilePathTools, removeDuplicatePathSeparators ) EXPECT_STRCASEEQ( expectedPath.toLatin1(), resultRootPath.toLatin1() ); } } + +//-------------------------------------------------------------------------------------------------- +TEST( RiaFilePathTools, splitIntoComponets ) +{ + { + QString testPath( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-0/iter-3/eclipse/model/DROGON-0.SMSPEC" ); + + auto words = RiaFilePathTools::splitPathIntoComponents( testPath ); + + EXPECT_EQ( 8, words.size() ); + + EXPECT_EQ( QString( "models" ), words[0] ); + EXPECT_EQ( QString( "from_equinor_sftp" ), words[1] ); + EXPECT_EQ( QString( "drogon3d_ahm" ), words[2] ); + EXPECT_EQ( QString( "realization-0" ), words[3] ); + EXPECT_EQ( QString( "iter-3" ), words[4] ); + EXPECT_EQ( QString( "eclipse" ), words[5] ); + EXPECT_EQ( QString( "model" ), words[6] ); + EXPECT_EQ( QString( "DROGON-0.SMSPEC" ), words[7] ); + } + + { + QString testPath( "/home/builder/models/realization-0/iter-3/eclipse/model/DROGON-0.SMSPEC" ); + + auto words = RiaFilePathTools::splitPathIntoComponents( testPath ); + + EXPECT_EQ( 8, words.size() ); + + EXPECT_EQ( QString( "home" ), words[0] ); + EXPECT_EQ( QString( "builder" ), words[1] ); + EXPECT_EQ( QString( "models" ), words[2] ); + EXPECT_EQ( QString( "realization-0" ), words[3] ); + EXPECT_EQ( QString( "iter-3" ), words[4] ); + EXPECT_EQ( QString( "eclipse" ), words[5] ); + EXPECT_EQ( QString( "model" ), words[6] ); + EXPECT_EQ( QString( "DROGON-0.SMSPEC" ), words[7] ); + } +} + +//-------------------------------------------------------------------------------------------------- +TEST( RiaFilePathTools, EnsembleName ) +{ + { + QString testPath1( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-0/iter-3/eclipse/model/DROGON-0.SMSPEC" ); + QString testPath2( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-1/iter-3/eclipse/model/DROGON-1.SMSPEC" ); + QStringList allPaths = { testPath1, testPath2 }; + + auto ensembleName = + RiaEnsembleNameTools::findSuitableEnsembleName( allPaths, RiaEnsembleNameTools::EnsembleGroupingMode::FMU_FOLDER_STRUCTURE ); + + EXPECT_EQ( QString( "iter-3" ), ensembleName ); + } +} + +//-------------------------------------------------------------------------------------------------- +TEST( RiaFilePathTools, RealizationName ) +{ + { + QString testPath0( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-0/iter-3/eclipse/model/DROGON-0.SMSPEC" ); + QString testPath1( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-1/iter-3/eclipse/model/DROGON-1.SMSPEC" ); + QStringList allPaths = { testPath0, testPath1 }; + + QString fileName = "DROGON-0.SMSPEC"; + + auto name = RiaEnsembleNameTools::uniqueShortName( testPath1, allPaths, fileName ); + + EXPECT_EQ( QString( "real-1" ), name ); + } +} + +//-------------------------------------------------------------------------------------------------- +TEST( RiaFilePathTools, keyPathComponentsForEachFilePath ) +{ + { + QString testPath0( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-0/iter-3/eclipse/model/DROGON-0.SMSPEC" ); + QString testPath1( "e:/models/from_equinor_sftp/drogon3d_ahm/realization-1/iter-3/eclipse/model/DROGON-1.SMSPEC" ); + QStringList allPaths = { testPath0, testPath1 }; + + auto keyComponents = RiaFilePathTools::keyPathComponentsForEachFilePath( allPaths ); + + auto test0 = keyComponents[testPath0]; + EXPECT_EQ( QString( "realization-0" ), test0.front() ); + + auto test1 = keyComponents[testPath1]; + EXPECT_EQ( QString( "realization-1" ), test1.front() ); + } +} diff --git a/ApplicationLibCode/UnitTests/RiaStdStringTools-Test.cpp b/ApplicationLibCode/UnitTests/RiaStdStringTools-Test.cpp index 543a221909..c419e2476b 100644 --- a/ApplicationLibCode/UnitTests/RiaStdStringTools-Test.cpp +++ b/ApplicationLibCode/UnitTests/RiaStdStringTools-Test.cpp @@ -202,3 +202,58 @@ TEST( RiaStdStringToolsTest, DISABLED_PerformanceConversion ) std::cout << "std::from_chars " << std::setw( 9 ) << diff.count() << " s\n"; } } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RiaStdStringToolsTest, ValuesFromRangeSelection ) +{ + std::string testString = "1,2,5-10,15"; + std::set expectedValues = { 1, 2, 5, 6, 7, 8, 9, 10, 15 }; + + auto actualValues = RiaStdStringTools::valuesFromRangeSelection( testString ); + + ASSERT_EQ( expectedValues, actualValues ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RiaStdStringToolsTest, ValuesFromRangeSelectionMinMax ) +{ + std::string testString = "-3, 5, 6-8, 10, 15-"; + int minimumValue = 1; + int maximumValue = 20; + std::set expectedValues = { 1, 2, 3, 5, 6, 7, 8, 10, 15, 16, 17, 18, 19, 20 }; + + auto actualValues = RiaStdStringTools::valuesFromRangeSelection( testString, minimumValue, maximumValue ); + + ASSERT_EQ( expectedValues, actualValues ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RiaStdStringToolsTest, TestInvalidRangeStrings ) +{ + int minimumValue = 1; + int maximumValue = 20; + + { + // Handle blank space and inverted from/to + std::string testString = "5, -3, 9-8"; + std::set expectedValues = { 1, 2, 3, 5, 8, 9 }; + auto actualValues = RiaStdStringTools::valuesFromRangeSelection( testString, minimumValue, maximumValue ); + + ASSERT_EQ( expectedValues, actualValues ); + } + + { + // If the range is invalid, the result should be an empty set + std::string testString = "5, a"; + std::set expectedValues = {}; + auto actualValues = RiaStdStringTools::valuesFromRangeSelection( testString, minimumValue, maximumValue ); + + ASSERT_EQ( expectedValues, actualValues ); + } +} diff --git a/ApplicationLibCode/GeoMech/OdbReader_UnitTests/RifOdbReader-Test.cpp b/ApplicationLibCode/UnitTests/RifOdbReader-Test.cpp similarity index 100% rename from ApplicationLibCode/GeoMech/OdbReader_UnitTests/RifOdbReader-Test.cpp rename to ApplicationLibCode/UnitTests/RifOdbReader-Test.cpp diff --git a/ApplicationLibCode/UnitTests/RifPolygonReader-Test.cpp b/ApplicationLibCode/UnitTests/RifPolygonReader-Test.cpp new file mode 100644 index 0000000000..f556ba332e --- /dev/null +++ b/ApplicationLibCode/UnitTests/RifPolygonReader-Test.cpp @@ -0,0 +1,99 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2024- Equinor ASA +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#include "gtest/gtest.h" + +#include "RifPolygonReader.h" + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RifPolygonReader, MultiplePolygonsInSameFile ) +{ + std::string fileContent = R"( +# This is a comment +# This is a comment +58177.76 732.7 1643.6 +58260.83 732.8 1596.6 +57985.66 732.7 1542.0 +59601.45 732.4 3639.0 +59422.01 732.2 3639.0 +59793.41 732.2 3639.0 +999 999 999 +# starting polyline 2 +58260.83 732.8 1596.6 +57985.66 732.7 1542.0 +59601.45 732.4 3639.0 )"; + + QString fileContentAsQString = QString::fromStdString( fileContent ); + QString errorMessage; + + auto polygons = RifPolygonReader::parseText( fileContentAsQString, &errorMessage ); + EXPECT_TRUE( polygons.size() == 2 ); + + auto firstPolygon = polygons.front(); + EXPECT_TRUE( firstPolygon.size() == 6 ); + EXPECT_DOUBLE_EQ( firstPolygon.front().x(), 58177.76 ); + + auto secondPolygon = polygons.back(); + EXPECT_TRUE( secondPolygon.size() == 3 ); + EXPECT_DOUBLE_EQ( secondPolygon.back().x(), 59601.45 ); +} + +TEST( RifPolygonReader, CsvImport ) +{ + std::string fileContent = R"( +X_UTME,Y_UTMN,Z_TVDSS,POLY_ID +460536.5500488281,5934613.072753906,1652.97265625,0 +460535.4345703125,5934678.220581055,1652.8203125,0 +460534.3497314453,5934741.589111328,1652.672119140625,0 +460534.5389404297,5934747.926269531,1652.6595458984375,0 +460530.44287109375,5934829.321044922,1652.448974609375,0 +460530.20642089844,5934842.320922852,1652.6920166015625,0 +460535.5516357422,5934890.617675781,1653.71240234375,0 +460548.05139160156,5935007.113769531,1656.166259765625,0 +460550.3292236328,5935027.826538086,1656.641845703125,0 +)"; + + QString fileContentAsQString = QString::fromStdString( fileContent ); + QString errorMessage; + + auto polygons = RifPolygonReader::parseTextCsv( fileContentAsQString, &errorMessage ); + EXPECT_TRUE( polygons.size() == 1 ); + + auto firstPolygon = polygons.front(); + EXPECT_TRUE( firstPolygon.second.size() == 9 ); + EXPECT_DOUBLE_EQ( firstPolygon.second.back().z(), -1656.641845703125 ); +} + +TEST( RifPolygonReader, CsvImportNoHeader ) +{ + std::string fileContent = R"( +460536.5500488281,5934613.072753906,1652.97265625,0 +460535.4345703125,5934678.220581055,1652.8203125,0 +)"; + + QString fileContentAsQString = QString::fromStdString( fileContent ); + QString errorMessage; + + auto polygons = RifPolygonReader::parseTextCsv( fileContentAsQString, &errorMessage ); + EXPECT_TRUE( polygons.size() == 1 ); + + auto firstPolygon = polygons.front(); + EXPECT_TRUE( firstPolygon.second.size() == 2 ); +} diff --git a/ApplicationLibCode/UnitTests/RifPressureDepthTextFileReader-Test.cpp b/ApplicationLibCode/UnitTests/RifPressureDepthTextFileReader-Test.cpp index b202978972..f06b2acd84 100644 --- a/ApplicationLibCode/UnitTests/RifPressureDepthTextFileReader-Test.cpp +++ b/ApplicationLibCode/UnitTests/RifPressureDepthTextFileReader-Test.cpp @@ -62,3 +62,33 @@ TEST( RifPressureDepthTextFileReaderTest, LoadFileNonExistingFiles ) EXPECT_FALSE( errorMessage.isEmpty() ); EXPECT_EQ( 0u, items.size() ); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RifPressureDepthTextFileReaderTest, FieldUnitData ) +{ + auto content = R"( +--TVDMSL +RFT +-- +WELLNAME 'A1' +DATE 18-NOV-2018 +PRESSURE DEPTH +PSIA FEET +12008.00 22640.66 +12020.40 22674.44 +\n)"; + + auto [items, errorMessage] = RifPressureDepthTextFileReader::parse( content ); + + EXPECT_TRUE( errorMessage.isEmpty() ); + ASSERT_EQ( 1u, items.size() ); + + EXPECT_EQ( "A1", items[0].wellName().toStdString() ); + std::vector> values0 = items[0].getPressureDepthValues(); + EXPECT_EQ( 2u, values0.size() ); + double delta = 0.001; + EXPECT_NEAR( 12008.0, values0[0].first, delta ); + EXPECT_NEAR( 22640.66, values0[0].second, delta ); +} diff --git a/ApplicationLibCode/UnitTests/RigCellGeometryTools-Test.cpp b/ApplicationLibCode/UnitTests/RigCellGeometryTools-Test.cpp index 714774fa6d..9a88034e67 100644 --- a/ApplicationLibCode/UnitTests/RigCellGeometryTools-Test.cpp +++ b/ApplicationLibCode/UnitTests/RigCellGeometryTools-Test.cpp @@ -284,6 +284,55 @@ TEST( RigCellGeometryTools, lengthCalcTestTriangle ) EXPECT_LT( length, 1.8 ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RigCellGeometryTools, lineIntersectsLine2DTest ) +{ + cvf::Vec3d a1( 0, 0, 0 ); + cvf::Vec3d b1( 1, 1, 1 ); + + cvf::Vec3d a2( 0, 1, 500 ); + cvf::Vec3d b2( 1, 0, 7000 ); + + cvf::Vec3d a3( -10, -10, 0 ); + cvf::Vec3d b3( -4, -1, 0 ); + + EXPECT_TRUE( RigCellGeometryTools::lineIntersectsLine2D( a1, b1, a2, b2 ) ); + EXPECT_FALSE( RigCellGeometryTools::lineIntersectsLine2D( a1, b1, a3, b3 ) ); + + auto [intersect, point] = RigCellGeometryTools::lineLineIntersection2D( a1, b1, a2, b2 ); + EXPECT_TRUE( intersect ); + EXPECT_DOUBLE_EQ( 0.5, point.x() ); + EXPECT_DOUBLE_EQ( 0.5, point.y() ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RigCellGeometryTools, lineIntersectsPolygon2DTest ) +{ + cvf::Vec3d a1( 0, 0, 0 ); + cvf::Vec3d b1( 1, 1, 1 ); + + cvf::Vec3d a2( 5, -5, 0 ); + cvf::Vec3d b2( 15, 25, 0 ); + + cvf::Vec3d p1( 10, 10, 0 ); + cvf::Vec3d p2( 11, 20, 1000 ); + cvf::Vec3d p3( 20, 7, -20 ); + cvf::Vec3d p4( 21, -1, 55 ); + + std::vector polygon; + polygon.push_back( p1 ); + polygon.push_back( p2 ); + polygon.push_back( p3 ); + polygon.push_back( p4 ); + + EXPECT_FALSE( RigCellGeometryTools::lineIntersectsPolygon2D( a1, b1, polygon ) ); + EXPECT_TRUE( RigCellGeometryTools::lineIntersectsPolygon2D( a2, b2, polygon ) ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/UnitTests/RimEmReader-Test.cpp b/ApplicationLibCode/UnitTests/RimEmReader-Test.cpp new file mode 100644 index 0000000000..e5247f0c34 --- /dev/null +++ b/ApplicationLibCode/UnitTests/RimEmReader-Test.cpp @@ -0,0 +1,106 @@ +///////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) Ceetron Solutions AS +// +// ResInsight 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 3 of the License, or +// (at your option) any later version. +// +// ResInsight 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 at +// for more details. +// +///////////////////////////////////////////////////////////////////////////////// + +#ifdef USE_HDF5 + +#include "gtest/gtest.h" + +#include "RigEclipseCaseData.h" + +#include "RimEmCase.h" + +#include +#include + +#include "H5Cpp.h" +#include +#include + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST( RigReservoirTest, DISABLED_TestImportGrid ) +{ + QString fileName( "f:/Models/emgs/BrickvilleProject/Horizons/test.h5grid" ); + + std::array originNED; + std::array originMesh; + std::array cellSizes; + std::array numCells; + std::map> resultData; + + try + { + H5::Exception::dontPrint(); // Turn off auto-printing of failures to handle the errors appropriately + + H5::H5File mainFile( fileName.toStdString().c_str(), + H5F_ACC_RDONLY ); // initial date part is an attribute of SourSimRL main file + + { + auto attr = mainFile.openAttribute( "description::OriginNED" ); + H5::DataType type = attr.getDataType(); + attr.read( type, originNED.data() ); + } + + { + H5::Group group = mainFile.openGroup( "Mesh" ); + + { + auto attr = group.openAttribute( "cell_sizes" ); + H5::DataType type = attr.getDataType(); + attr.read( type, cellSizes.data() ); + } + { + auto attr = group.openAttribute( "num_cells" ); + H5::DataType type = attr.getDataType(); + attr.read( type, numCells.data() ); + } + { + auto attr = group.openAttribute( "origin" ); + H5::DataType type = attr.getDataType(); + attr.read( type, originMesh.data() ); + } + } + + H5::Group group = mainFile.openGroup( "Data" ); + auto numObj = group.getNumObjs(); + for ( size_t i = 0; i < numObj; i++ ) + { + auto objName = group.getObjnameByIdx( i ); + auto objType = group.getObjTypeByIdx( i ); + qDebug() << "objName " << QString::fromStdString( objName ) << " objType " << objType; + + std::vector resultValues; + H5::DataSet dataset = H5::DataSet( group.openDataSet( objName ) ); + + hsize_t dims[3]; + H5::DataSpace dataspace = dataset.getSpace(); + dataspace.getSimpleExtentDims( dims, nullptr ); + + resultValues.resize( dims[0] * dims[1] * dims[2] ); + dataset.read( resultValues.data(), H5::PredType::NATIVE_DOUBLE ); + + resultData[objName] = resultValues; + } + } + catch ( ... ) + { + } +} + +#endif // USE_HDF5 diff --git a/ApplicationLibCode/UnitTests/empty.cpp b/ApplicationLibCode/UnitTests/empty.cpp new file mode 100644 index 0000000000..580fdff75d --- /dev/null +++ b/ApplicationLibCode/UnitTests/empty.cpp @@ -0,0 +1,10 @@ +// +// This empty file is used by ResInsightDummyTarget +// +// Creating a dummy target with an empty file is used to have a different target than ResInsight. +// This target is used to find the full path to the build folder. +// +// $ +// +// If we use the ResInsight target ($), we get a circular dependency. +// diff --git a/ApplicationLibCode/GeoMech/OdbReader_UnitTests/main.cpp b/ApplicationLibCode/UnitTests/main.cpp similarity index 78% rename from ApplicationLibCode/GeoMech/OdbReader_UnitTests/main.cpp rename to ApplicationLibCode/UnitTests/main.cpp index 2659fa2c69..b6b01932b5 100644 --- a/ApplicationLibCode/GeoMech/OdbReader_UnitTests/main.cpp +++ b/ApplicationLibCode/UnitTests/main.cpp @@ -1,7 +1,6 @@ ///////////////////////////////////////////////////////////////////////////////// // -// Copyright (C) 2015 - Statoil ASA -// Copyright (C) 2015 - Ceetron Solutions AS +// Copyright (C) 2024 Equinor ASA // // ResInsight is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by @@ -18,23 +17,23 @@ ///////////////////////////////////////////////////////////////////////////////// #include "gtest/gtest.h" -#include -#include "cvfTrace.h" +#include "RiaConsoleApplication.h" + +#include //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- int main( int argc, char** argv ) { - cvf::Assert::setReportMode( cvf::Assert::CONSOLE ); + RiaApplication* app = new RiaConsoleApplication( argc, argv ); + app->initialize(); - testing::InitGoogleTest( &argc, argv ); + QLocale::setDefault( QLocale( QLocale::English, QLocale::UnitedStates ) ); + setlocale( LC_NUMERIC, "C" ); + testing::InitGoogleTest( &argc, argv ); int result = RUN_ALL_TESTS(); - - std::cout << "Please press to close the window."; - std::cin.get(); - return result; } diff --git a/ApplicationLibCode/UserInterface/RiuComparisonViewMover.cpp b/ApplicationLibCode/UserInterface/RiuComparisonViewMover.cpp index ea0419ff9a..dd0d385e9a 100644 --- a/ApplicationLibCode/UserInterface/RiuComparisonViewMover.cpp +++ b/ApplicationLibCode/UserInterface/RiuComparisonViewMover.cpp @@ -61,7 +61,7 @@ bool RiuComparisonViewMover::eventFilter( QObject* watched, QEvent* event ) if ( m_dragState == LEFT_EDGE ) { - QPointF mousePos = mEv->windowPos(); + QPointF mousePos = mEv->localPos(); QPointF normMousePos = { mousePos.x() / m_viewer->width(), mousePos.y() / m_viewer->height() }; cvf::Rectf orgCompViewWindow = m_viewer->comparisonViewVisibleNormalizedRect(); diff --git a/ApplicationLibCode/UserInterface/RiuFemResultTextBuilder.cpp b/ApplicationLibCode/UserInterface/RiuFemResultTextBuilder.cpp index 8ef22bbfbe..329b3ba39c 100644 --- a/ApplicationLibCode/UserInterface/RiuFemResultTextBuilder.cpp +++ b/ApplicationLibCode/UserInterface/RiuFemResultTextBuilder.cpp @@ -135,7 +135,8 @@ QString RiuFemResultTextBuilder::geometrySelectionText( QString itemSeparator ) int elementId = femPart->elmId( m_cellIndex ); auto elementType = femPart->elementType( m_cellIndex ); - text += QString( "Element : Id[%1], Type[%2]" ).arg( elementId ).arg( RigFemTypes::elementTypeText( elementType ) ); + text += + QString( "Element : Id[%1], Type[%2]" ).arg( elementId ).arg( QString::fromStdString( RigFemTypes::elementTypeText( elementType ) ) ); size_t i = 0; size_t j = 0; @@ -280,16 +281,16 @@ void RiuFemResultTextBuilder::appendTextFromResultColors( RigGeoMechCaseData* if ( resultDefinition->hasResult() ) { - const std::vector& scalarResults = - geomData->femPartResults()->resultValues( resultDefinition->resultAddress(), gridIndex, timeStepIndex, frameIndex ); + auto address = RigFemAddressDefines::getResultLookupAddress( resultDefinition->resultAddress() ); + const std::vector& scalarResults = geomData->femPartResults()->resultValues( address, gridIndex, timeStepIndex, frameIndex ); if ( !scalarResults.empty() ) { - caf::AppEnum resPosAppEnum = resultDefinition->resultPositionType(); + caf::AppEnum resPosAppEnum = address.resultPosType; resultInfoText->append( resPosAppEnum.uiText() + ", " ); resultInfoText->append( resultDefinition->resultFieldUiName() + ", " ); resultInfoText->append( resultDefinition->resultComponentUiName() + ":\n" ); - if ( resultDefinition->resultPositionType() != RIG_ELEMENT_NODAL_FACE ) + if ( address.resultPosType != RIG_ELEMENT_NODAL_FACE ) { RigFemPart* femPart = geomData->femParts()->part( gridIndex ); RigElementType elmType = femPart->elementType( cellIndex ); @@ -301,8 +302,8 @@ void RiuFemResultTextBuilder::appendTextFromResultColors( RigGeoMechCaseData* { float scalarValue = std::numeric_limits::infinity(); int nodeIdx = elementConn[lNodeIdx]; - if ( resultDefinition->resultPositionType() == RIG_NODAL || - ( resultDefinition->resultPositionType() == RIG_DIFFERENTIALS && + if ( address.resultPosType == RIG_NODAL || + ( address.resultPosType == RIG_DIFFERENTIALS && resultDefinition->resultFieldName() == QString::fromStdString( RigFemAddressDefines::porBar() ) ) ) { scalarValue = scalarResults[nodeIdx]; @@ -406,13 +407,15 @@ QString RiuFemResultTextBuilder::closestNodeResultText( RimGeoMechResultDefiniti RigGeoMechCaseData* geomData = m_geomResDef->geoMechCase()->geoMechData(); + auto address = RigFemAddressDefines::getResultLookupAddress( resultColors->resultAddress() ); + const std::vector& scalarResults = - geomData->femPartResults()->resultValues( resultColors->resultAddress(), m_gridIndex, m_timeStepIndex, m_frameIndex ); + geomData->femPartResults()->resultValues( address, m_gridIndex, m_timeStepIndex, m_frameIndex ); if ( !scalarResults.empty() && m_displayCoordView ) { RigFemPart* femPart = geomData->femParts()->part( m_gridIndex ); - RigFemResultPosEnum activeResultPosition = resultColors->resultPositionType(); + RigFemResultPosEnum activeResultPosition = address.resultPosType; cvf::Vec3d intersectionPointInDomain = m_displayCoordView->displayCoordTransform()->translateToDomainCoord( m_intersectionPointInDisplay ); @@ -442,11 +445,7 @@ QString RiuFemResultTextBuilder::closestNodeResultText( RimGeoMechResultDefiniti } else if ( m_isIntersectionTriangleSet && activeResultPosition == RIG_ELEMENT_NODAL_FACE ) { - RiuGeoMechXfTensorResultAccessor tensAccessor( geomData->femPartResults(), - resultColors->resultAddress(), - m_gridIndex, - m_timeStepIndex, - m_frameIndex ); + RiuGeoMechXfTensorResultAccessor tensAccessor( geomData->femPartResults(), address, m_gridIndex, m_timeStepIndex, m_frameIndex ); float tensValue = tensAccessor.calculateElmNodeValue( m_intersectionTriangle, closestElmNodResIdx ); text.append( QString( "Closest result: N[%1], in Element[%2] transformed onto intersection: %3 \n" ) diff --git a/ApplicationLibCode/UserInterface/RiuMainWindow.cpp b/ApplicationLibCode/UserInterface/RiuMainWindow.cpp index a85ff2d0aa..01ef0bb120 100644 --- a/ApplicationLibCode/UserInterface/RiuMainWindow.cpp +++ b/ApplicationLibCode/UserInterface/RiuMainWindow.cpp @@ -516,7 +516,6 @@ void RiuMainWindow::createMenus() testMenu->addSeparator(); testMenu->addAction( m_showRegressionTestDialog ); testMenu->addAction( m_executePaintEventPerformanceTest ); - testMenu->addAction( cmdFeatureMgr->action( "RicLaunchUnitTestsFeature" ) ); testMenu->addAction( cmdFeatureMgr->action( "RicRunCommandFileFeature" ) ); testMenu->addAction( cmdFeatureMgr->action( "RicExportObjectAndFieldKeywordsFeature" ) ); testMenu->addAction( cmdFeatureMgr->action( "RicSaveProjectNoGlobalPathsFeature" ) ); @@ -571,15 +570,14 @@ void RiuMainWindow::createToolBars() toolbar->addAction( cmdFeatureMgr->action( "RicImportEnsembleFeature" ) ); toolbar->hide(); } + { -#ifdef USE_ODB_API QToolBar* toolbar = addToolBar( tr( "Import GeoMech" ) ); toolbar->setObjectName( toolbar->windowTitle() ); toolbar->addAction( cmdFeatureMgr->action( "RicImportGeoMechCaseFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicImportGeoMechCaseTimeStepFilterFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicImportElementPropertyFeature" ) ); toolbar->hide(); -#endif } { @@ -666,13 +664,13 @@ void RiuMainWindow::createToolBars() { QToolBar* toolbar = addToolBar( tr( "Test" ) ); toolbar->setObjectName( toolbar->windowTitle() ); - toolbar->addAction( cmdFeatureMgr->action( "RicLaunchUnitTestsFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicLaunchRegressionTestsFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicLaunchRegressionTestDialogFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicShowClassNamesFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicRunCommandFileFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicExecuteLastUsedScriptFeature" ) ); toolbar->addAction( cmdFeatureMgr->action( "RicExportCompletionsForVisibleWellPathsFeature" ) ); + toolbar->addAction( cmdFeatureMgr->action( "RicShowMemoryReportFeature" ) ); } // Create animation toolbar @@ -1766,7 +1764,6 @@ void RiuMainWindow::updateMemoryUsage() QColor okColor( 0, 150, 0 ); QColor warningColor( 200, 0, 0 ); - QColor criticalColor( 255, 100, 0 ); float currentUsageFraction = 0.0f; float availVirtualFraction = 1.0f; diff --git a/ApplicationLibCode/UserInterface/RiuMainWindowBase.cpp b/ApplicationLibCode/UserInterface/RiuMainWindowBase.cpp index 8f32f714f2..adfcd08106 100644 --- a/ApplicationLibCode/UserInterface/RiuMainWindowBase.cpp +++ b/ApplicationLibCode/UserInterface/RiuMainWindowBase.cpp @@ -43,6 +43,7 @@ #include "DockWidget.h" #include +#include #include #include #include diff --git a/ApplicationLibCode/UserInterface/RiuMdiArea.cpp b/ApplicationLibCode/UserInterface/RiuMdiArea.cpp index 4e7742a32a..ade46e5e57 100644 --- a/ApplicationLibCode/UserInterface/RiuMdiArea.cpp +++ b/ApplicationLibCode/UserInterface/RiuMdiArea.cpp @@ -112,6 +112,9 @@ std::list RiuMdiArea::subWindowListSortedByVerticalPosition() //-------------------------------------------------------------------------------------------------- void RiuMdiArea::tileWindowsHorizontally() { + // Make sure that all windows are windowed and not maximized + tileSubWindows(); + QPoint position( 0, 0 ); for ( auto* window : subWindowListSortedByPosition() ) @@ -129,6 +132,9 @@ void RiuMdiArea::tileWindowsHorizontally() //-------------------------------------------------------------------------------------------------- void RiuMdiArea::tileWindowsVertically() { + // Make sure that all windows are windowed and not maximized + tileSubWindows(); + auto windowList = subWindowListSortedByVerticalPosition(); QPoint position( 0, 0 ); diff --git a/ApplicationLibCode/UserInterface/RiuMenuBarBuildTools.cpp b/ApplicationLibCode/UserInterface/RiuMenuBarBuildTools.cpp index c62a3786c4..9e48e1a273 100644 --- a/ApplicationLibCode/UserInterface/RiuMenuBarBuildTools.cpp +++ b/ApplicationLibCode/UserInterface/RiuMenuBarBuildTools.cpp @@ -129,13 +129,11 @@ void RiuMenuBarBuildTools::addImportMenuWithActions( QObject* parent, QMenu* men importSummaryMenu->addAction( cmdFeatureMgr->action( "RicImportSummaryGroupFeature" ) ); importSummaryMenu->addAction( cmdFeatureMgr->action( "RicImportEnsembleFeature" ) ); -#ifdef USE_ODB_API importMenu->addSeparator(); QMenu* importGeoMechMenu = importMenu->addMenu( QIcon( ":/GeoMechCase24x24.png" ), "Geo Mechanical Cases" ); importGeoMechMenu->addAction( cmdFeatureMgr->action( "RicImportGeoMechCaseFeature" ) ); importGeoMechMenu->addAction( cmdFeatureMgr->action( "RicImportGeoMechCaseTimeStepFilterFeature" ) ); importGeoMechMenu->addAction( cmdFeatureMgr->action( "RicImportElementPropertyFeature" ) ); -#endif importMenu->addSeparator(); QMenu* importWellMenu = importMenu->addMenu( QIcon( ":/Well.svg" ), "Well Data" ); diff --git a/ApplicationLibCode/UserInterface/RiuMohrsCirclePlot.cpp b/ApplicationLibCode/UserInterface/RiuMohrsCirclePlot.cpp index a4daa17ed7..bf7fbbb581 100644 --- a/ApplicationLibCode/UserInterface/RiuMohrsCirclePlot.cpp +++ b/ApplicationLibCode/UserInterface/RiuMohrsCirclePlot.cpp @@ -371,7 +371,7 @@ bool RiuMohrsCirclePlot::addOrUpdateCurves( const RimGeoMechResultDefinition* ge { RigFemPart* femPart = geomResDef->ownerCaseData()->femParts()->part( gridIndex ); - if ( femPart->elementType( elmIndex ) != HEX8P ) return false; + if ( femPart->elementType( elmIndex ) != RigElementType::HEX8P ) return false; RigFemPartResultsCollection* resultCollection = geomResDef->geoMechCase()->geoMechData()->femPartResults(); diff --git a/ApplicationLibCode/UserInterface/RiuPlotMainWindow.cpp b/ApplicationLibCode/UserInterface/RiuPlotMainWindow.cpp index 7219ffe40d..191e99e855 100644 --- a/ApplicationLibCode/UserInterface/RiuPlotMainWindow.cpp +++ b/ApplicationLibCode/UserInterface/RiuPlotMainWindow.cpp @@ -174,6 +174,9 @@ void RiuPlotMainWindow::initializeGuiNewProjectLoaded() setPdmRoot( RimProject::current() ); restoreTreeViewState(); + RimMainPlotCollection* mainPlotColl = RimMainPlotCollection::current(); + mainPlotColl->ensureDefaultFlowPlotsAreCreated(); + auto sumPlotManager = dynamic_cast( m_summaryPlotManager.get() ); if ( sumPlotManager ) { diff --git a/ApplicationLibCode/UserInterface/RiuPlotMainWindowTools.cpp b/ApplicationLibCode/UserInterface/RiuPlotMainWindowTools.cpp index d81d95ab43..1910726831 100644 --- a/ApplicationLibCode/UserInterface/RiuPlotMainWindowTools.cpp +++ b/ApplicationLibCode/UserInterface/RiuPlotMainWindowTools.cpp @@ -20,6 +20,8 @@ #include "RiaGuiApplication.h" #include "RiuPlotMainWindow.h" +#include "cafPdmObject.h" + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/UserInterface/RiuPlotObjectPicker.cpp b/ApplicationLibCode/UserInterface/RiuPlotObjectPicker.cpp index e189c13961..c3c844050f 100644 --- a/ApplicationLibCode/UserInterface/RiuPlotObjectPicker.cpp +++ b/ApplicationLibCode/UserInterface/RiuPlotObjectPicker.cpp @@ -21,6 +21,8 @@ #include "RiaGuiApplication.h" #include "RiuPlotMainWindow.h" +#include "cafPdmObject.h" + #include //-------------------------------------------------------------------------------------------------- diff --git a/ApplicationLibCode/UserInterface/RiuSummaryPlot.cpp b/ApplicationLibCode/UserInterface/RiuSummaryPlot.cpp index 5e0de6acfc..9cd95d1fda 100644 --- a/ApplicationLibCode/UserInterface/RiuSummaryPlot.cpp +++ b/ApplicationLibCode/UserInterface/RiuSummaryPlot.cpp @@ -32,6 +32,7 @@ #include "cafCmdFeatureMenuBuilder.h" +#include #include #include diff --git a/ApplicationLibCode/UserInterface/RiuSummaryQuantityNameInfoProvider.cpp b/ApplicationLibCode/UserInterface/RiuSummaryQuantityNameInfoProvider.cpp index c272f63464..b30d7e3e70 100644 --- a/ApplicationLibCode/UserInterface/RiuSummaryQuantityNameInfoProvider.cpp +++ b/ApplicationLibCode/UserInterface/RiuSummaryQuantityNameInfoProvider.cpp @@ -326,6 +326,7 @@ std::unordered_mapmargins = QMargins( 8, 8, 8, 8 ); layout->tickTextLeadSpace = 5; } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiuTextContentFrame::updateFontSize() +{ + if ( m_fontPixelSize != -1 ) + { + QFont font = this->font(); + font.setPixelSize( m_fontPixelSize ); + setFont( font ); + } + else + { + RiuAbstractOverlayContentFrame::updateFontSize(); + } +} diff --git a/ApplicationLibCode/UserInterface/RiuTextContentFrame.h b/ApplicationLibCode/UserInterface/RiuTextContentFrame.h index d5f4d211ac..df3f078280 100644 --- a/ApplicationLibCode/UserInterface/RiuTextContentFrame.h +++ b/ApplicationLibCode/UserInterface/RiuTextContentFrame.h @@ -27,14 +27,14 @@ class RiuTextContentFrame : public RiuAbstractOverlayContentFrame Q_OBJECT public: - RiuTextContentFrame( QWidget* parent, const QString& title, const QString& text ); + RiuTextContentFrame( QWidget* parent, const QString& title, const QString& text, int fontPixeSize ); QSize sizeHint() const override; QSize minimumSizeHint() const override; void renderTo( QPainter* painter, const QRect& targetRect ) override; -protected: +private: struct LayoutInfo { LayoutInfo( const QSize& size ) @@ -60,7 +60,10 @@ class RiuTextContentFrame : public RiuAbstractOverlayContentFrame private: virtual void layoutInfo( LayoutInfo* layout ) const; -protected: + void updateFontSize(); + +private: QString m_title; QString m_text; + int m_fontPixelSize; }; diff --git a/ApplicationLibCode/UserInterface/RiuViewer.cpp b/ApplicationLibCode/UserInterface/RiuViewer.cpp index 4bd9455a06..c929010946 100644 --- a/ApplicationLibCode/UserInterface/RiuViewer.cpp +++ b/ApplicationLibCode/UserInterface/RiuViewer.cpp @@ -27,10 +27,8 @@ #include "RiaPreferences.h" #include "RiaRegressionTestRunner.h" +#include "Rim3dView.h" #include "RimCase.h" -#include "RimGridView.h" -#include "RimProject.h" -#include "RimViewController.h" #include "RimViewLinker.h" #include "RivGridBoxGenerator.h" @@ -60,20 +58,15 @@ #include "cvfCamera.h" #include "cvfFont.h" -#include "cvfOpenGLResourceManager.h" #include "cvfOverlayAxisCross.h" #include "cvfOverlayItem.h" -#include "cvfPartRenderHintCollection.h" -#include "cvfRenderQueueSorter.h" -#include "cvfRenderSequence.h" #include "cvfRendering.h" #include "cvfScene.h" -#include -#include - #include +#include + using cvf::ManipulatorTrackball; const double RI_MIN_NEARPLANE_DISTANCE = 0.1; @@ -92,8 +85,8 @@ std::unique_ptr RiuViewer::s_hoverCursor; //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -RiuViewer::RiuViewer( const QGLFormat& format, QWidget* parent ) - : caf::Viewer( format, parent ) +RiuViewer::RiuViewer( QWidget* parent ) + : caf::Viewer( parent ) , m_isNavigationRotationEnabled( true ) , m_zScale( 1.0 ) { @@ -489,17 +482,20 @@ void RiuViewer::paintOverlayItems( QPainter* painter ) { Rim3dView* view = dynamic_cast( m_rimView.p() ); - QString stepName = view->timeStepName( view->currentTimeStep() ); + if ( view ) + { + QString stepName = view->timeStepName( view->currentTimeStep() ); - m_animationProgress->setFormat( "Time Step: %v/%m " + stepName ); - m_animationProgress->setMinimum( 0 ); - m_animationProgress->setMaximum( static_cast( view->timeStepCount() ) - 1 ); - m_animationProgress->setValue( view->currentTimeStep() ); + m_animationProgress->setFormat( "Time Step: %v/%m " + stepName ); + m_animationProgress->setMinimum( 0 ); + m_animationProgress->setMaximum( static_cast( view->timeStepCount() ) - 1 ); + m_animationProgress->setValue( view->currentTimeStep() ); - m_animationProgress->resize( columnWidth, m_animationProgress->sizeHint().height() ); - m_animationProgress->render( painter, QPoint( columnPos, yPos ) ); + m_animationProgress->resize( columnWidth, m_animationProgress->sizeHint().height() ); + m_animationProgress->render( painter, QPoint( columnPos, yPos ) ); - yPos += m_animationProgress->height() + margin; + yPos += m_animationProgress->height() + margin; + } } if ( m_showInfoText && !isComparisonViewActive() ) @@ -687,6 +683,21 @@ void RiuViewer::mousePressEvent( QMouseEvent* event ) m_lastMousePressPosition = event->pos(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void RiuViewer::mouseDoubleClickEvent( QMouseEvent* event ) +{ + if ( auto view = dynamic_cast( m_rimView.p() ) ) + { + view->zoomAll(); + + return; + } + + caf::Viewer::mouseDoubleClickEvent( event ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -1029,6 +1040,8 @@ RimViewWindow* RiuViewer::ownerViewWindow() const //-------------------------------------------------------------------------------------------------- void RiuViewer::optimizeClippingPlanes() { + if ( m_rimView == nullptr ) return; + if ( m_showWindowEdgeAxes ) { m_windowEdgeAxisOverlay->setDisplayCoordTransform( m_rimView->displayCoordTransform().p() ); diff --git a/ApplicationLibCode/UserInterface/RiuViewer.h b/ApplicationLibCode/UserInterface/RiuViewer.h index c22fc0cfd2..e25aa6c378 100644 --- a/ApplicationLibCode/UserInterface/RiuViewer.h +++ b/ApplicationLibCode/UserInterface/RiuViewer.h @@ -23,15 +23,9 @@ #include "RiuInterfaceToViewWindow.h" #include "RiuViewerToViewInterface.h" -#include "cafFontTools.h" -#include "cafMouseState.h" #include "cafPdmInterfacePointer.h" -#include "cafPdmObject.h" -#include "cafPdmPointer.h" #include "cafViewer.h" -#include "cvfStructGrid.h" - #include class RicCommandFeature; @@ -73,7 +67,7 @@ class RiuViewer : public caf::Viewer, public RiuInterfaceToViewWindow Q_OBJECT public: - RiuViewer( const QGLFormat& format, QWidget* parent ); + RiuViewer( QWidget* parent ); ~RiuViewer() override; RiuViewer( const RiuViewer& ) = delete; @@ -166,6 +160,7 @@ public slots: void mouseReleaseEvent( QMouseEvent* event ) override; void mousePressEvent( QMouseEvent* event ) override; + void mouseDoubleClickEvent( QMouseEvent* event ) override; private: QLabel* m_infoLabel; diff --git a/ApplicationLibCode/UserInterface/RiuViewerCommands.cpp b/ApplicationLibCode/UserInterface/RiuViewerCommands.cpp index 37833f816a..1fb9b04446 100644 --- a/ApplicationLibCode/UserInterface/RiuViewerCommands.cpp +++ b/ApplicationLibCode/UserInterface/RiuViewerCommands.cpp @@ -393,6 +393,7 @@ void RiuViewerCommands::displayContextMenu( QMouseEvent* event ) } menuBuilder << "RicNewPolygonFilter3dviewFeature"; + menuBuilder.addCmdFeature( "RicCreatePolygonFeature", "Polygon" ); menuBuilder << "RicEclipsePropertyFilterNewInViewFeature"; menuBuilder << "RicGeoMechPropertyFilterNewInViewFeature"; diff --git a/ApplicationLibCode/UserInterface/RiuWellAllocationPlot.cpp b/ApplicationLibCode/UserInterface/RiuWellAllocationPlot.cpp index 8717cd2210..e922448f72 100644 --- a/ApplicationLibCode/UserInterface/RiuWellAllocationPlot.cpp +++ b/ApplicationLibCode/UserInterface/RiuWellAllocationPlot.cpp @@ -74,27 +74,34 @@ RiuWellAllocationPlot::RiuWellAllocationPlot( RimWellAllocationPlot* plotDefinit mainLayout->addLayout( plotWidgetsLayout ); plotWidgetsLayout->addLayout( leftColumnLayout ); - m_legendWidget = new RiuNightchartsWidget( this ); - new RiuPlotObjectPicker( m_legendWidget, m_plotDefinition->plotLegend() ); - caf::CmdFeatureMenuBuilder menuForSubWidgets; menuForSubWidgets << "RicShowTotalAllocationDataFeature"; - new RiuContextMenuLauncher( m_legendWidget, menuForSubWidgets ); - leftColumnLayout->addWidget( m_legendWidget ); - m_legendWidget->showPie( false ); + { + QWidget* totalFlowAllocationWidget = m_plotDefinition->totalWellFlowPlot()->createViewWidget( this ); + new RiuPlotObjectPicker( totalFlowAllocationWidget, m_plotDefinition->totalWellFlowPlot() ); + new RiuContextMenuLauncher( totalFlowAllocationWidget, menuForSubWidgets ); + + leftColumnLayout->addWidget( totalFlowAllocationWidget, Qt::AlignTop ); + } + + { + m_legendWidget = new RiuNightchartsWidget( this ); + new RiuPlotObjectPicker( m_legendWidget, m_plotDefinition->plotLegend() ); + + new RiuContextMenuLauncher( m_legendWidget, menuForSubWidgets ); - QWidget* totalFlowAllocationWidget = m_plotDefinition->totalWellFlowPlot()->createViewWidget( this ); - new RiuPlotObjectPicker( totalFlowAllocationWidget, m_plotDefinition->totalWellFlowPlot() ); - new RiuContextMenuLauncher( totalFlowAllocationWidget, menuForSubWidgets ); + leftColumnLayout->addWidget( m_legendWidget ); + m_legendWidget->showPie( false ); + } - leftColumnLayout->addWidget( totalFlowAllocationWidget, Qt::AlignTop ); leftColumnLayout->addWidget( m_plotDefinition->tofAccumulatedPhaseFractionsPlot()->createViewWidget( this ), Qt::AlignTop ); leftColumnLayout->addStretch(); QWidget* wellFlowWidget = m_plotDefinition->accumulatedWellFlowPlot()->createPlotWidget(); plotWidgetsLayout->addWidget( wellFlowWidget ); + plotWidgetsLayout->addSpacing( 10 ); { caf::CmdFeatureMenuBuilder menuBuilder; diff --git a/ApplicationLibCode/UserInterface/RiuWellLogPlot.cpp b/ApplicationLibCode/UserInterface/RiuWellLogPlot.cpp index 466fb8a6c2..dd6f3bff3b 100644 --- a/ApplicationLibCode/UserInterface/RiuWellLogPlot.cpp +++ b/ApplicationLibCode/UserInterface/RiuWellLogPlot.cpp @@ -132,15 +132,32 @@ void RiuWellLogPlot::reinsertScrollbar() int colCount = m_gridLayout->columnCount(); int rowCount = m_gridLayout->rowCount(); + bool showScrollBar = !plotWidgets.empty(); + + if ( depthTrackPlot() ) + { + double minVisible, maxVisible; + double minAvailable, maxAvailable; + + depthTrackPlot()->visibleDepthRange( &minVisible, &maxVisible ); + depthTrackPlot()->availableDepthRange( &minAvailable, &maxAvailable ); + + // Hide scrollbar if the visible range covers the complete available range + if ( minVisible <= minAvailable && maxVisible >= maxAvailable ) + { + showScrollBar = false; + } + } + if ( depthTrackPlot() && depthTrackPlot()->depthOrientation() == RiaDefines::Orientation::HORIZONTAL ) { m_gridLayout->addLayout( m_horizontalTrackScrollBarLayout, rowCount, 0, 1, colCount ); - m_horizontalTrackScrollBar->setVisible( !plotWidgets.empty() ); + m_horizontalTrackScrollBar->setVisible( showScrollBar ); } else { m_gridLayout->addLayout( m_verticalTrackScrollBarLayout, 2, colCount, 1, 1 ); - m_verticalTrackScrollBar->setVisible( !plotWidgets.empty() ); + m_verticalTrackScrollBar->setVisible( showScrollBar ); m_gridLayout->setColumnStretch( colCount, 0 ); } } diff --git a/CMakeLists.txt b/CMakeLists.txt index 3ebbd8dfc3..be662dc9da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -324,6 +324,12 @@ set(CMAKE_CXX_COMPILER_LAUNCHER ${TEMP_CMAKE_CXX_COMPILER_LAUNCHER}) # ############################################################################## find_package(Git QUIET) if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git") + execute_process( + COMMAND git log -1 --pretty=format:%h + OUTPUT_VARIABLE RESINSIGHT_GIT_HASH + OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET + ) + # Update submodules as needed option(RESINSIGHT_UPDATE_SUBMODULES "Check submodules during build" ON) mark_as_advanced(RESINSIGHT_UPDATE_SUBMODULES) @@ -546,7 +552,7 @@ list(APPEND THIRD_PARTY_LIBRARIES qwt) # ############################################################################## # Qt Advanced Docking System # ############################################################################## -set(ADS_VERSION "4.0.3") +set(ADS_VERSION "4.2.1") add_subdirectory(ThirdParty/qtadvanceddocking EXCLUDE_FROM_ALL) @@ -623,11 +629,84 @@ set_property( add_subdirectory(ThirdParty/tomlplusplus) +# ############################################################################## +# spdlog +# ############################################################################## + +add_subdirectory(ThirdParty/spdlog) +list(APPEND THIRD_PARTY_LIBRARIES spdlog) + # ############################################################################## # Thirdparty libraries are put in ThirdParty solution folder # ############################################################################## set_property(TARGET ${THIRD_PARTY_LIBRARIES} PROPERTY FOLDER "Thirdparty") +# ############################################################################## +# Build list of DLLs needed for executables +# ############################################################################## +if(MSVC) + + if(NOT ${RESINSIGHT_ODB_API_DIR} EQUAL "") + set(RESINSIGHT_USE_ODB_API 1) + endif() + + # Odb Dlls + if(RESINSIGHT_USE_ODB_API) + # Find all the dlls + file(GLOB RI_ALL_ODB_DLLS ${RESINSIGHT_ODB_API_DIR}/lib/*.dll) + + # Strip off the path + foreach(aDLL ${RI_ALL_ODB_DLLS}) + get_filename_component(filenameWithExt ${aDLL} NAME) + list(APPEND RI_ODB_DLLS ${filenameWithExt}) + endforeach(aDLL) + + foreach(aDLL ${RI_ODB_DLLS}) + list(APPEND RI_FILENAMES ${RESINSIGHT_ODB_API_DIR}/lib/${aDLL}) + endforeach() + endif() + + # OpenVDS Dlls + set(OPENVDS_DLL_NAMES openvds segyutils) + foreach(OPENVDS_DLL_NAME ${OPENVDS_DLL_NAMES}) + list(APPEND RI_FILENAMES + ${RESINSIGHT_OPENVDS_API_DIR}/bin/msvc_141/${OPENVDS_DLL_NAME}.dll + ) + endforeach(OPENVDS_DLL_NAME) + list(APPEND RI_FILENAMES + ${RESINSIGHT_OPENVDS_API_DIR}/bin/msvc_141/SEGYImport.exe + ) + + # HDF5 Dlls + if(RESINSIGHT_FOUND_HDF5) + set(HDF5_DLL_NAMES hdf5 hdf5_cpp szip zlib) + foreach(HDF5_DLL_NAME ${HDF5_DLL_NAMES}) + list(APPEND RI_FILENAMES ${RESINSIGHT_HDF5_DIR}/bin/${HDF5_DLL_NAME}.dll) + endforeach(HDF5_DLL_NAME) + endif() + +else() + # Linux + + # OpenVDS lib files + list(APPEND RI_FILENAMES ${RESINSIGHT_OPENVDS_API_DIR}/bin/SEGYImport) + + set(OPENVDS_LIB_NAMES + libopenvds.so + libopenvds.so.3 + libopenvds.so.3.2.7 + libopenvds-e1541338.so.3.2.7 + libsegyutils.so + libsegyutils.so.3 + libsegyutils.so.3.2.7 + ) + foreach(OPENVDS_LIB_NAME ${OPENVDS_LIB_NAMES}) + list(APPEND RI_FILENAMES + ${RESINSIGHT_OPENVDS_API_DIR}/lib64/${OPENVDS_LIB_NAME} + ) + endforeach(OPENVDS_LIB_NAME) +endif(MSVC) + # ############################################################################## # Unity Build # ############################################################################## @@ -674,6 +753,14 @@ if(CMAKE_COMPILER_IS_GNUCC) endif() +# !!! For now, we force Qt to version 5 +message(STATUS "Forcing setting of CEE_USE_QT5 to ON") +set(CEE_USE_QT5 + ON + CACHE BOOL "Force usage of Qt5" FORCE +) +message(STATUS "CEE_USE_QT5=${CEE_USE_QT5}") + add_subdirectory(${VIZ_MODULES_FOLDER_NAME}/LibCore) add_subdirectory(${VIZ_MODULES_FOLDER_NAME}/LibGeometry) add_subdirectory(${VIZ_MODULES_FOLDER_NAME}/LibRender) @@ -702,6 +789,9 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") endif() set_property(TARGET ${VIZ_FWK_LIBRARIES} PROPERTY FOLDER "VizFwk") +if(WIN32) + set_property(TARGET run_Glsl2Include PROPERTY FOLDER "VizFwk") +endif() # ############################################################################## # Application Framework @@ -907,6 +997,7 @@ add_subdirectory(ApplicationLibCode) add_subdirectory(ApplicationLibCode/Commands) add_subdirectory(ApplicationLibCode/ResultStatisticsCache) add_subdirectory(ApplicationLibCode/GeoMech/GeoMechDataModel) +add_subdirectory(ApplicationLibCode/GeoMech/GeoMechFileInterface) if(RESINSIGHT_USE_ODB_API) add_subdirectory(ApplicationLibCode/GeoMech/OdbReader) endif() @@ -941,8 +1032,13 @@ if(MSVC AND RESINSIGHT_ENABLE_STATIC_ANALYSIS) ) set(TARGETS_FOR_STATIC_ANALYSIS - ${APP_FWK_LIBRARIES} ${APP_FWK_TEST_PROJECTS} ApplicationLibCode Commands - ResultStatisticsCache RigGeoMechDataModel + ${APP_FWK_LIBRARIES} + ${APP_FWK_TEST_PROJECTS} + ApplicationLibCode + Commands + ResultStatisticsCache + RigGeoMechDataModel + RifGeoMechFileInterface ) foreach(TARGET_PROJECT ${TARGETS_FOR_STATIC_ANALYSIS}) diff --git a/Fwk/AppFwk/CMakeLists.txt b/Fwk/AppFwk/CMakeLists.txt index 09c9867301..b7f3c7f0e0 100644 --- a/Fwk/AppFwk/CMakeLists.txt +++ b/Fwk/AppFwk/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8.12) +cmake_minimum_required(VERSION 3.15) project(CeeApp) @@ -11,27 +11,6 @@ if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) ) endif() -# Qt -if(NOT DEFINED (CEE_USE_QT5)) - option(CEE_USE_QT5 "Use Qt5" ON) -endif(NOT DEFINED (CEE_USE_QT5)) - -if(CEE_USE_QT5) - find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui OpenGL Widgets - ) - set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::OpenGL Qt5::Widgets) -else() - find_package( - Qt4 - COMPONENTS QtCore QtGui QtMain QtOpenGl - REQUIRED - ) - include(${QT_USE_FILE}) -endif(CEE_USE_QT5) - set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) @@ -40,6 +19,15 @@ if(MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") endif() +# Qt +if(NOT DEFINED (CEE_USE_QT5)) + option(CEE_USE_QT5 "Use Qt5" ON) +endif(NOT DEFINED (CEE_USE_QT5)) + +if(NOT DEFINED (CEE_USE_QT6)) + option(CEE_USE_QT6 "Use Qt6" OFF) +endif(NOT DEFINED (CEE_USE_QT6)) + # CeeViz is not available here, exclude it from the build set(CAF_EXCLUDE_CVF ON) diff --git a/Fwk/AppFwk/CommonCode/CMakeLists.txt b/Fwk/AppFwk/CommonCode/CMakeLists.txt index 9a78a8b941..0bf5a214e8 100644 --- a/Fwk/AppFwk/CommonCode/CMakeLists.txt +++ b/Fwk/AppFwk/CommonCode/CMakeLists.txt @@ -14,13 +14,23 @@ find_package(OpenGL) # These headers need to go through Qt's MOC compiler set(MOC_HEADER_FILES cafMessagePanel.h) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets OpenGL -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGL) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() add_library( ${PROJECT_NAME} diff --git a/Fwk/AppFwk/CommonCode/cafEffectGenerator.cpp b/Fwk/AppFwk/CommonCode/cafEffectGenerator.cpp index 80cd9b9255..04d246afa1 100644 --- a/Fwk/AppFwk/CommonCode/cafEffectGenerator.cpp +++ b/Fwk/AppFwk/CommonCode/cafEffectGenerator.cpp @@ -58,8 +58,6 @@ #include "cvfTextureImage.h" #include "cvfUniform.h" -#include - namespace caf { //############################################################################################################################# diff --git a/Fwk/AppFwk/CommonCode/cafUtils.cpp b/Fwk/AppFwk/CommonCode/cafUtils.cpp index a987273457..07afa25f7f 100644 --- a/Fwk/AppFwk/CommonCode/cafUtils.cpp +++ b/Fwk/AppFwk/CommonCode/cafUtils.cpp @@ -40,8 +40,7 @@ #include #include - -#include +#include #include #include @@ -153,7 +152,7 @@ QString Utils::makeValidFileBasename( const QString& fileBasenameCandidate ) cleanBasename.replace( "\n", "_" ); cleanBasename.replace( "#", "_" ); - cleanBasename.replace( QRegExp( "_+" ), "_" ); + cleanBasename.replace( QRegularExpression( "_+" ), "_" ); return cleanBasename; } @@ -283,8 +282,12 @@ bool Utils::isStringMatch( const QString& filterString, const QString& value ) return false; } - QRegExp searcher( filterString, Qt::CaseInsensitive, QRegExp::WildcardUnix ); - return searcher.exactMatch( value ); + auto regExpString = QRegularExpression::wildcardToRegularExpression( filterString ); + QRegularExpression regExp( regExpString ); + regExp.setPatternOptions( QRegularExpression::CaseInsensitiveOption ); + auto match = regExp.match( value ); + + return match.hasMatch(); } //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/CommonCode/cafUtils.h b/Fwk/AppFwk/CommonCode/cafUtils.h index da265dd334..d681c6427a 100644 --- a/Fwk/AppFwk/CommonCode/cafUtils.h +++ b/Fwk/AppFwk/CommonCode/cafUtils.h @@ -38,9 +38,10 @@ #include +#include + class QLineEdit; class QString; -class QStringList; namespace caf { diff --git a/Fwk/AppFwk/CommonCode/cvfStructGrid.cpp b/Fwk/AppFwk/CommonCode/cvfStructGrid.cpp index ff9923fa26..d3f653021a 100644 --- a/Fwk/AppFwk/CommonCode/cvfStructGrid.cpp +++ b/Fwk/AppFwk/CommonCode/cvfStructGrid.cpp @@ -67,36 +67,6 @@ StructGridInterface::StructGridInterface() m_characteristicCellSizeK = cvf::UNDEFINED_DOUBLE; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t StructGridInterface::cellCountI() const -{ - if ( gridPointCountI() == 0 ) return 0; - - return gridPointCountI() - 1; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t StructGridInterface::cellCountJ() const -{ - if ( gridPointCountJ() == 0 ) return 0; - - return gridPointCountJ() - 1; -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -size_t StructGridInterface::cellCountK() const -{ - if ( gridPointCountK() == 0 ) return 0; - - return gridPointCountK() - 1; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -367,6 +337,8 @@ bool StructGridInterface::hasValidCharacteristicCellSizes() const //-------------------------------------------------------------------------------------------------- void StructGridInterface::computeCharacteristicCellSize( const std::vector& globalCellIndices ) const { + if ( globalCellIndices.empty() ) return; + ubyte faceConnPosI[4]; cellFaceVertexIndices( StructGridInterface::POS_I, faceConnPosI ); diff --git a/Fwk/AppFwk/CommonCode/cvfStructGrid.h b/Fwk/AppFwk/CommonCode/cvfStructGrid.h index 6407b93e96..7275be352a 100644 --- a/Fwk/AppFwk/CommonCode/cvfStructGrid.h +++ b/Fwk/AppFwk/CommonCode/cvfStructGrid.h @@ -77,13 +77,9 @@ class StructGridInterface : public Object public: StructGridInterface(); - virtual size_t gridPointCountI() const = 0; - virtual size_t gridPointCountJ() const = 0; - virtual size_t gridPointCountK() const = 0; - - size_t cellCountI() const; - size_t cellCountJ() const; - size_t cellCountK() const; + virtual size_t cellCountI() const = 0; + virtual size_t cellCountJ() const = 0; + virtual size_t cellCountK() const = 0; virtual bool isCellValid( size_t i, size_t j, size_t k ) const = 0; diff --git a/Fwk/AppFwk/cafCommand/CMakeLists.txt b/Fwk/AppFwk/cafCommand/CMakeLists.txt index fa20397a09..f6900a07ab 100644 --- a/Fwk/AppFwk/cafCommand/CMakeLists.txt +++ b/Fwk/AppFwk/cafCommand/CMakeLists.txt @@ -10,13 +10,23 @@ endif() set(MOC_HEADER_FILES cafCmdFeature.h cafCmdFeatureManager.h) # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() set(PROJECT_FILES cafCmdExecCommandManager.cpp @@ -46,7 +56,7 @@ target_link_libraries(${PROJECT_NAME} cafProjectDataModel ${QT_LIBRARIES}) if(MSVC) set_target_properties( - ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127" + ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127 /wd4996" ) endif() diff --git a/Fwk/AppFwk/cafCommand/cafCmdFeature.cpp b/Fwk/AppFwk/cafCommand/cafCmdFeature.cpp index 0c23f0f54e..51eb884f16 100644 --- a/Fwk/AppFwk/cafCommand/cafCmdFeature.cpp +++ b/Fwk/AppFwk/cafCommand/cafCmdFeature.cpp @@ -163,11 +163,9 @@ void CmdFeature::applyShortcutWithHintToAction( QAction* action, const QKeySeque { action->setShortcut( keySequence ); -#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 ) ) // Qt made keyboard shortcuts in context menus platform dependent in Qt 5.10 // With no global way of removing it. action->setShortcutVisibleInContextMenu( true ); -#endif } //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafCommand/cafCmdFeatureManager.h b/Fwk/AppFwk/cafCommand/cafCmdFeatureManager.h index 518dbab7ca..49f869d9b2 100644 --- a/Fwk/AppFwk/cafCommand/cafCmdFeatureManager.h +++ b/Fwk/AppFwk/cafCommand/cafCmdFeatureManager.h @@ -43,10 +43,10 @@ #include #include #include +#include class QAction; class QKeySequence; -class QWidget; namespace caf { diff --git a/Fwk/AppFwk/cafCommand/cafCmdFeatureMenuBuilder.cpp b/Fwk/AppFwk/cafCommand/cafCmdFeatureMenuBuilder.cpp index 6ee608ad6f..5b5702c0ee 100644 --- a/Fwk/AppFwk/cafCommand/cafCmdFeatureMenuBuilder.cpp +++ b/Fwk/AppFwk/cafCommand/cafCmdFeatureMenuBuilder.cpp @@ -204,7 +204,7 @@ void CmdFeatureMenuBuilder::appendToMenu( QMenu* menu ) } else { - act = commandManager->action( m_items[i].itemName ); + act = commandManager->action( m_items[i].itemName, m_items[i].uiText ); } CAF_ASSERT( act ); diff --git a/Fwk/AppFwk/cafCommand/cafCmdFieldChangeExec.cpp b/Fwk/AppFwk/cafCommand/cafCmdFieldChangeExec.cpp index 3cf7280206..827e3d2966 100644 --- a/Fwk/AppFwk/cafCommand/cafCmdFieldChangeExec.cpp +++ b/Fwk/AppFwk/cafCommand/cafCmdFieldChangeExec.cpp @@ -38,6 +38,7 @@ #include "cafNotificationCenter.h" #include "cafPdmReferenceHelper.h" +#include "cafPdmUiOrdering.h" namespace caf { diff --git a/Fwk/AppFwk/cafCommand/cafCmdUiCommandSystemImpl.cpp b/Fwk/AppFwk/cafCommand/cafCmdUiCommandSystemImpl.cpp index 3c555155b7..49d8c4c78f 100644 --- a/Fwk/AppFwk/cafCommand/cafCmdUiCommandSystemImpl.cpp +++ b/Fwk/AppFwk/cafCommand/cafCmdUiCommandSystemImpl.cpp @@ -43,8 +43,7 @@ #include "cafPdmChildArrayField.h" #include "cafPdmFieldHandle.h" #include "cafPdmObjectHandle.h" -#include "cafPdmUiObjectHandle.h" -#include "cafPdmXmlFieldHandle.h" +#include "cafPdmReferenceHelper.h" #include "cafSelectionManager.h" #include diff --git a/Fwk/AppFwk/cafCommandFeatures/CMakeLists.txt b/Fwk/AppFwk/cafCommandFeatures/CMakeLists.txt index d335bb5e28..090e820da6 100644 --- a/Fwk/AppFwk/cafCommandFeatures/CMakeLists.txt +++ b/Fwk/AppFwk/cafCommandFeatures/CMakeLists.txt @@ -10,13 +10,23 @@ endif() set(MOC_HEADER_FILES) # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() set(PROJECT_FILES # Default features @@ -63,34 +73,16 @@ set(QRC_FILES # https://gitlab.kitware.com/cmake/community/wikis/doc/tutorials/Object-Library # and # https://cmake.org/cmake/help/v3.15/command/add_library.html?highlight=add_library#object-libraries + add_library(${PROJECT_NAME} OBJECT ${PROJECT_FILES} ${MOC_SOURCE_FILES}) -target_include_directories( - ${PROJECT_NAME} - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} - $ # Needed for cmake version - # < 3.12. Remove when we - # can use - # target_link_libraries - $ # Needed for cmake - # version < 3.12. - # Remove when we can - # use - # target_link_libraries +target_link_libraries( + ${PROJECT_NAME} cafCommand cafUserInterface ${QT_LIBRARIES} ) -# Before cmake 3.12 OBJECT libraries could not use the target_link_libraries -# command, So we need to set the POSITION_INDEPENDENT_CODE option manually - -set_property(TARGET ${PROJECT_NAME} PROPERTY POSITION_INDEPENDENT_CODE ON) - -# Not to be used until we can use cmake 3.12 or above target_link_libraries ( -# ${PROJECT_NAME} cafCommand cafUserInterface ${QT_LIBRARIES} ) - if(MSVC) set_target_properties( - ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127" + ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127 /wd4996" ) endif() diff --git a/Fwk/AppFwk/cafCommandFeatures/ToggleCommands/cafToggleItemsFeatureImpl.cpp b/Fwk/AppFwk/cafCommandFeatures/ToggleCommands/cafToggleItemsFeatureImpl.cpp index 4a91543dd8..7994eb173d 100644 --- a/Fwk/AppFwk/cafCommandFeatures/ToggleCommands/cafToggleItemsFeatureImpl.cpp +++ b/Fwk/AppFwk/cafCommandFeatures/ToggleCommands/cafToggleItemsFeatureImpl.cpp @@ -36,11 +36,8 @@ #include "cafToggleItemsFeatureImpl.h" -//#include "RiaFeatureCommandContext.h" -//#include "RiaGuiApplication.h" -//#include "RiuMainWindow.h" -//#include "RiuPlotMainWindow.h" - +#include "cafCmdFeatureManager.h" +#include "cafPdmField.h" #include "cafPdmUiFieldHandle.h" #include "cafPdmUiItem.h" #include "cafPdmUiObjectHandle.h" @@ -50,7 +47,6 @@ #include -#include "cafCmdFeatureManager.h" #include namespace caf diff --git a/Fwk/AppFwk/cafHexInterpolator/cafHexInterpolator_UnitTest/CMakeLists.txt b/Fwk/AppFwk/cafHexInterpolator/cafHexInterpolator_UnitTest/CMakeLists.txt index ecba3ce456..1aefcb39b3 100644 --- a/Fwk/AppFwk/cafHexInterpolator/cafHexInterpolator_UnitTest/CMakeLists.txt +++ b/Fwk/AppFwk/cafHexInterpolator/cafHexInterpolator_UnitTest/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8.12) - project(cafHexInterpolator_UnitTests) if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) diff --git a/Fwk/AppFwk/cafPdmCvf/CMakeLists.txt b/Fwk/AppFwk/cafPdmCvf/CMakeLists.txt index 12d5ce7861..61c2954cdc 100644 --- a/Fwk/AppFwk/cafPdmCvf/CMakeLists.txt +++ b/Fwk/AppFwk/cafPdmCvf/CMakeLists.txt @@ -6,16 +6,23 @@ if(CAF_ENABLE_UNITY_BUILD) set(CMAKE_UNITY_BUILD true) endif() -# Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) - -add_definitions(-DCVF_USING_CMAKE) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets) +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) + qt5_add_resources(QRC_FILES_CPP ${QRC_FILES}) +endif() add_library( ${PROJECT_NAME} diff --git a/Fwk/AppFwk/cafPdmCvf/cafPdmCvf_UnitTests/CMakeLists.txt b/Fwk/AppFwk/cafPdmCvf/cafPdmCvf_UnitTests/CMakeLists.txt index 5de8dc5906..acc5691ffa 100644 --- a/Fwk/AppFwk/cafPdmCvf/cafPdmCvf_UnitTests/CMakeLists.txt +++ b/Fwk/AppFwk/cafPdmCvf/cafPdmCvf_UnitTests/CMakeLists.txt @@ -1,16 +1,20 @@ -cmake_minimum_required(VERSION 2.8.12) - -find_package(Qt5 CONFIG COMPONENTS Core) -if(Qt5Core_FOUND) - find_package(Qt5 CONFIG REQUIRED Core) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core + ) + set(QT_LIBRARIES Qt6::Core) else() find_package( - Qt4 - COMPONENTS QtCore - REQUIRED + Qt5 + COMPONENTS + REQUIRED Core ) - include(${QT_USE_FILE}) -endif(Qt5Core_FOUND) + set(QT_LIBRARIES Qt5::Core) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) + qt5_add_resources(QRC_FILES_CPP ${QRC_FILES}) +endif() project(cafPdmCvf_UnitTests) diff --git a/Fwk/AppFwk/cafPdmCvf/cafPdmXmlColor3f.cpp b/Fwk/AppFwk/cafPdmCvf/cafPdmXmlColor3f.cpp index 113aaefef1..d8f232b31c 100644 --- a/Fwk/AppFwk/cafPdmCvf/cafPdmXmlColor3f.cpp +++ b/Fwk/AppFwk/cafPdmCvf/cafPdmXmlColor3f.cpp @@ -36,6 +36,7 @@ #include "cafPdmXmlColor3f.h" +#include #include QTextStream& operator>>( QTextStream& str, cvf::Color3f& value ) diff --git a/Fwk/AppFwk/cafPdmCvf/cafPdmXmlVec3d.cpp b/Fwk/AppFwk/cafPdmCvf/cafPdmXmlVec3d.cpp index c504f477a2..1e320341e3 100644 --- a/Fwk/AppFwk/cafPdmCvf/cafPdmXmlVec3d.cpp +++ b/Fwk/AppFwk/cafPdmCvf/cafPdmXmlVec3d.cpp @@ -36,6 +36,7 @@ #include "cafPdmXmlVec3d.h" +#include #include QTextStream& operator>>( QTextStream& str, cvf::Vec3d& value ) diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmAbstractFieldScriptingCapability.h b/Fwk/AppFwk/cafPdmScripting/cafPdmAbstractFieldScriptingCapability.h index 67ebc98a19..72595fd452 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmAbstractFieldScriptingCapability.h +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmAbstractFieldScriptingCapability.h @@ -39,7 +39,6 @@ #include class QTextStream; -class QStringList; namespace caf { diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.cpp b/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.cpp index a591633756..7d193465c1 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.cpp +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.cpp @@ -67,7 +67,7 @@ void PdmFieldScriptingCapabilityIOHandler::writeToField( QString& while ( !inputStream.atEnd() ) { currentChar = errorMessageContainer->readCharWithLineNumberCount( inputStream ); - if ( currentChar > 1 && currentChar != QChar( '\\' ) ) + if ( !currentChar.isNull() && currentChar != QChar( '\\' ) ) { if ( currentChar == QChar( '"' ) ) // End Quote { diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.h b/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.h index c1abd5803f..0440d0c237 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.h +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmFieldScriptingCapability.h @@ -44,11 +44,7 @@ #include "cafPdmPtrField.h" #include "cafPdmScriptIOMessages.h" -#include -#include -#include - -#include +#include #define CAF_PDM_InitScriptableField( field, keyword, default, uiName, ... ) \ { \ diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h index 210340ddec..0458006556 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectMethod.h @@ -37,9 +37,7 @@ #include "cafAssert.h" #include "cafPdmObject.h" -#include "cafPdmObjectFactory.h" #include "cafPdmPointer.h" -#include "cafPdmScriptResponse.h" /// CAF_PDM_OBJECT_METHOD_SOURCE_INIT associates the self class keyword and the method keyword with the method factory /// Place this in the cpp file, preferably above the constructor diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectScriptingCapability.h b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectScriptingCapability.h index 37d7c037b0..bff28f0eac 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmObjectScriptingCapability.h +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmObjectScriptingCapability.h @@ -35,15 +35,9 @@ //################################################################################################## #pragma once -#include "cafPdmChildArrayField.h" #include "cafPdmObjectCapability.h" -#include "cafPdmObjectMethod.h" #include "cafPdmObjectScriptingCapabilityRegister.h" -#include - -#include -#include #include class QTextStream; diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmScriptResponse.h b/Fwk/AppFwk/cafPdmScripting/cafPdmScriptResponse.h index 482a586435..c8983d6e8d 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmScriptResponse.h +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmScriptResponse.h @@ -36,7 +36,6 @@ #pragma once #include "cafPdmObject.h" -#include "cafPdmPointer.h" #include #include diff --git a/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/CMakeLists.txt b/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/CMakeLists.txt index a6c3d2892d..3af7bad1c3 100644 --- a/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/CMakeLists.txt +++ b/Fwk/AppFwk/cafPdmScripting/cafPdmScripting_UnitTests/CMakeLists.txt @@ -1,11 +1,20 @@ project(cafPdmScripting_UnitTests) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Xml Gui -) -set(QT_LIBRARIES Qt5::Core Qt5::Xml Qt5::Gui Qt5::Widgets) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets + ) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Xml Gui + ) + set(QT_LIBRARIES Qt5::Core Qt5::Xml Qt5::Gui) +endif() if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) # VS 2017 : Disable warnings from from gtest code, using deprecated code @@ -16,12 +25,16 @@ endif() include_directories(${CMAKE_CURRENT_SOURCE_DIR} # required for gtest-all.cpp ) -# add the executable -add_executable( - ${PROJECT_NAME} cafPdmScripting_UnitTests.cpp gtest/gtest-all.cpp +set(PROJECT_FILES cafPdmScripting_UnitTests.cpp gtest/gtest-all.cpp cafPdmScriptingBasicTest.cpp cafPdmFieldSerializationTest.cpp ) +if(CEE_USE_QT6) + qt_add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +else() + add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +endif(CEE_USE_QT6) + if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") target_compile_options( cafPdmScripting_UnitTests PRIVATE -Wno-delete-abstract-non-virtual-dtor @@ -29,7 +42,7 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") endif() target_link_libraries( - ${PROJECT_NAME} cafPdmScripting ${QT_LIBRARIES} ${THREAD_LIBRARY} + ${PROJECT_NAME} PRIVATE cafPdmScripting ${QT_LIBRARIES} ${THREAD_LIBRARY} ) source_group("" FILES ${PROJECT_FILES}) @@ -45,3 +58,18 @@ if(Qt5Core_FOUND) ) endforeach(qtlib) endif(Qt5Core_FOUND) + +# Install +install( + TARGETS ${PROJECT_NAME} + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(CEE_USE_QT6) + qt_generate_deploy_app_script( + TARGET ${PROJECT_NAME} OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR NO_TRANSLATIONS + ) + install(SCRIPT ${deploy_script}) +endif(CEE_USE_QT6) diff --git a/Fwk/AppFwk/cafProjectDataModel/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/CMakeLists.txt index cd1c8b3cca..42100ff574 100644 --- a/Fwk/AppFwk/cafProjectDataModel/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/CMakeLists.txt @@ -7,12 +7,22 @@ if(CAF_ENABLE_UNITY_BUILD) endif() # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) +endif() set(PROJECT_FILES cafFactory.h @@ -33,7 +43,7 @@ target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) if(MSVC) set_target_properties( - ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127" + ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127 /wd4996" ) endif() diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/CMakeLists.txt index b072b4b1b2..b33de76ebe 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/CMakeLists.txt @@ -6,12 +6,22 @@ if(CAF_ENABLE_UNITY_BUILD) set(CMAKE_UNITY_BUILD true) endif() -find_package( - Qt5 - COMPONENTS - REQUIRED Core -) -set(QT_LIBRARIES Qt5::Core) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core + ) + set(QT_LIBRARIES Qt6::Core) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core + ) + set(QT_LIBRARIES Qt5::Core) +endif() set(PROJECT_FILES cafAssert.h diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmBase.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmBase.h index 503fbe84af..23b540257e 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmBase.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmBase.h @@ -1,8 +1,5 @@ #pragma once -// Brings in size_t and definition of NULL -#include - // Macro to disable the copy constructor and assignment operator // Should be used in the private section of a class #define PDM_DISABLE_COPY_AND_ASSIGN( CLASS_NAME ) \ diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests/CMakeLists.txt index 6ec68fc642..0b6a4b059b 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmCore_UnitTests/CMakeLists.txt @@ -3,12 +3,21 @@ cmake_minimum_required(VERSION 3.15) project(cafPdmCore_UnitTests) # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Widgets Qt5::Gui) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Widgets Gui + ) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Widgets Qt5::Gui) +endif() if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) # VS 2017 : Disable warnings from from gtest code, using deprecated code @@ -34,8 +43,11 @@ set(PROJECT_FILES TestObj.h ) -# add the executable -add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +if(CEE_USE_QT6) + qt_add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +else() + add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +endif(CEE_USE_QT6) if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") @@ -52,7 +64,7 @@ if(Qt5Core_FOUND) endif() target_link_libraries( - ${PROJECT_NAME} cafPdmCore ${QT_LIBRARIES} ${THREAD_LIBRARY} + ${PROJECT_NAME} PRIVATE cafPdmCore ${QT_LIBRARIES} ${THREAD_LIBRARY} ) # Copy Qt Dlls @@ -64,3 +76,18 @@ foreach(qtlib ${QT_LIBRARIES}) $ ) endforeach(qtlib) + +# Install +install( + TARGETS ${PROJECT_NAME} + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(CEE_USE_QT6) + qt_generate_deploy_app_script( + TARGET ${PROJECT_NAME} OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR NO_TRANSLATIONS + ) + install(SCRIPT ${deploy_script}) +endif(CEE_USE_QT6) diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmFieldCapability.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmFieldCapability.h index 26b7067b1d..a0624847aa 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmFieldCapability.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmFieldCapability.h @@ -2,7 +2,7 @@ #include -class QString; +#include namespace caf { diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.cpp index e58bbf63fe..1b5f0d9f58 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.cpp @@ -39,7 +39,7 @@ #include "cafAssert.h" #include "cafPdmFieldHandle.h" -#include +#include #include @@ -328,7 +328,13 @@ PdmObjectHandle* PdmReferenceHelper::objectFromFieldReference( PdmFieldHandle* f if ( reference.isEmpty() ) return nullptr; if ( reference.trimmed().isEmpty() ) return nullptr; - QStringList decodedReference = reference.split( QRegExp( "\\s+" ), QString::SkipEmptyParts ); +#if ( QT_VERSION < QT_VERSION_CHECK( 5, 14, 0 ) ) + auto SkipEmptyParts = QString::SkipEmptyParts; +#else + auto SkipEmptyParts = Qt::SkipEmptyParts; +#endif + + QStringList decodedReference = reference.split( QRegularExpression( "\\s+" ), SkipEmptyParts ); PdmObjectHandle* lastCommonAnchestor = fromField->ownerObject(); CAF_ASSERT( lastCommonAnchestor ); diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.h index 474bf78718..50ce298a44 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafPdmReferenceHelper.h @@ -37,9 +37,6 @@ #pragma once #include "cafPdmObjectHandle.h" -#include "cafPdmPointer.h" - -class QStringList; namespace caf { diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafSignal.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafSignal.h index 32b0122df8..4b3ba669d6 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafSignal.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmCore/cafSignal.h @@ -40,7 +40,6 @@ #include #include #include -#include #include namespace caf diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmDocument.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmDocument.h index 23c54ab357..21164263a2 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmDocument.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmDocument.h @@ -35,9 +35,9 @@ //################################################################################################## #pragma once + #include "cafPdmField.h" #include "cafPdmObject.h" -#include "cafPdmPointer.h" namespace caf { diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.cpp index 1c3d8c8a65..968ff651ad 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.cpp @@ -1,5 +1,7 @@ #include "cafPdmObject.h" +#include "cafPdmUiFieldHandle.h" + using namespace caf; CAF_PDM_ABSTRACT_SOURCE_INIT( PdmObject, "PdmObjectBase" ); @@ -15,6 +17,20 @@ caf::PdmObject::PdmObject() CAF_PDM_InitObject( "Base PDM Object", "", "", "The Abstract Base Class for the Project Data Model" ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void PdmObject::addFieldUiNoDefault( PdmFieldHandle* field, const QString& keyword, PdmUiItemInfo* fieldDescription ) +{ + addField( field, keyword ); + + PdmUiFieldHandle* uiFieldHandle = field->uiCapability(); + if ( uiFieldHandle ) + { + uiFieldHandle->setUiItemInfo( fieldDescription ); + } +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.h index 1616b01cd9..4f4c8fb71c 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmObject.h @@ -38,27 +38,16 @@ #include "cafPdmObjectHandle.h" -#include "cafPdmPointer.h" -#include "cafPdmUiOrdering.h" - -#include - class QXmlStreamReader; class QXmlStreamWriter; +#include "cafInternalPdmUiFieldCapability.h" #include "cafPdmObjectCapability.h" - #include "cafPdmUiObjectHandle.h" +#include "cafPdmUiOrdering.h" #include "cafPdmXmlObjectHandle.h" #include "cafPdmXmlObjectHandleMacros.h" -#include "cafInternalPdmUiFieldCapability.h" -#include "cafInternalPdmXmlFieldCapability.h" -#include "cafPdmFieldHandle.h" - -#include "cafIconProvider.h" -#include "cafPdmUiFieldSpecialization.h" - namespace caf { class PdmFieldHandle; @@ -183,16 +172,7 @@ class PdmObject : public PdmObjectHandle, public PdmXmlObjectHandle, public PdmU /// Does the same as the above method, but omits the default value. /// Consider this method private. Please use the CAF_PDM_InitFieldNoDefault() macro instead. - void addFieldUiNoDefault( PdmFieldHandle* field, const QString& keyword, PdmUiItemInfo* fieldDescription ) - { - addField( field, keyword ); - - PdmUiFieldHandle* uiFieldHandle = field->uiCapability(); - if ( uiFieldHandle ) - { - uiFieldHandle->setUiItemInfo( fieldDescription ); - } - } + void addFieldUiNoDefault( PdmFieldHandle* field, const QString& keyword, PdmUiItemInfo* fieldDescription ); /// Returns _this_ if _this_ has requested class keyword /// Traverses parents recursively and returns first parent of the requested diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/CMakeLists.txt index a803743e42..c686570d1f 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/CMakeLists.txt @@ -12,15 +12,23 @@ set(MOC_HEADER_FILES cafPdmUiEditorHandle.h cafPdmUiFieldEditorHandle.h ) # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) - -add_definitions(-DCVF_USING_CMAKE) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() set(PROJECT_FILES cafInternalPdmFieldTypeSpecializations.h diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafFontTools.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafFontTools.cpp index 01830ef6f9..12e8d251de 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafFontTools.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafFontTools.cpp @@ -40,7 +40,10 @@ #include "cafPdmUiItem.h" #include + +#if ( QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 ) ) #include +#endif #include @@ -92,6 +95,7 @@ int FontTools::absolutePointSize( FontSize normalPointSize, RelativeSize relativ //-------------------------------------------------------------------------------------------------- int FontTools::pointSizeToPixelSize( int pointSize ) { +#if ( QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 ) ) auto app = dynamic_cast( QCoreApplication::instance() ); if ( app ) { @@ -99,6 +103,7 @@ int FontTools::pointSizeToPixelSize( int pointSize ) double inches = pointSize / 72.0; return static_cast( std::ceil( inches * dpi ) ); } +#endif return pointSize; } @@ -115,6 +120,7 @@ int FontTools::pointSizeToPixelSize( FontSize pointSize ) //-------------------------------------------------------------------------------------------------- int FontTools::pixelSizeToPointSize( int pixelSize ) { +#if ( QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 ) ) auto app = dynamic_cast( QCoreApplication::instance() ); if ( app ) { @@ -122,6 +128,7 @@ int FontTools::pixelSizeToPointSize( int pixelSize ) double inches = pixelSize / dpi; return static_cast( std::ceil( inches * 72.0 ) ); } +#endif return pixelSize; } diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmFieldTypeSpecializations.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmFieldTypeSpecializations.h index b07a0da80b..4486578654 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmFieldTypeSpecializations.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmFieldTypeSpecializations.h @@ -4,10 +4,6 @@ #include "cafPdmObjectHandle.h" #include "cafPdmPointer.h" -#include - -#include - namespace caf { template diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmUiFieldCapability.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmUiFieldCapability.h index 121612c990..47ffa2ce5f 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmUiFieldCapability.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafInternalPdmUiFieldCapability.h @@ -1,5 +1,7 @@ #pragma once +#include "cafPdmChildArrayField.h" +#include "cafPdmChildField.h" #include "cafPdmUiFieldHandle.h" namespace caf @@ -43,6 +45,10 @@ class PdmFieldUiCap> : public PdmUiFieldHandle PdmFieldUiCap( FieldType* field, bool giveOwnership ) : PdmUiFieldHandle( field, giveOwnership ) { + // In almost all use cases, we want to hide the visual appearance of the child field. + // The object contained in the child field will be visible in the project tree as a child of the + // parent object. + setUiTreeHidden( true ); } // Gui generalized interface @@ -66,6 +72,11 @@ class PdmFieldUiCap> : public PdmUiFieldHandle PdmFieldUiCap( FieldType* field, bool giveOwnership ) : PdmUiFieldHandle( field, giveOwnership ) { + // In almost all use cases, we want to hide the visual appearance of the child array field. + // They are usually members of a collection object, and this object is usually visible in the project tree + // The objects contained in the child array field will be visible in the project tree as children of the + // collection object + setUiTreeHidden( true ); } // Gui generalized interface diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiEditorHandle.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiEditorHandle.h index f6200ceaa1..2378d5527f 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiEditorHandle.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiEditorHandle.h @@ -43,7 +43,6 @@ namespace caf { -class PdmUiItem; //================================================================================================== /// Abstract class to handle editors. Inherits QObject to be able to use signals and slots diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.cpp index 09d985f71f..7c2cb1ca0d 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.cpp @@ -42,9 +42,7 @@ #include "cafPdmUiObjectHandle.h" #include -#include #include -#include namespace caf { @@ -137,6 +135,30 @@ void PdmUiFieldEditorHandle::createWidgets( QWidget* parent ) } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QWidget* PdmUiFieldEditorHandle::combinedWidget() +{ + return m_combinedWidget; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QWidget* PdmUiFieldEditorHandle::editorWidget() +{ + return m_editorWidget; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QWidget* PdmUiFieldEditorHandle::labelWidget() +{ + return m_labelWidget; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -153,6 +175,30 @@ int PdmUiFieldEditorHandle::rowStretchFactor() const return isMultiRowEditor() ? 1 : 0; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QWidget* PdmUiFieldEditorHandle::createCombinedWidget( QWidget* parent ) +{ + return nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QWidget* PdmUiFieldEditorHandle::createEditorWidget( QWidget* parent ) +{ + return nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QWidget* PdmUiFieldEditorHandle::createLabelWidget( QWidget* parent ) +{ + return nullptr; +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.h index 11a3c464cc..5587792a66 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiFieldEditorHandle.h @@ -40,14 +40,6 @@ #include "cafPdmUiEditorHandle.h" #include "cafQShortenedLabel.h" -#include - -#include -#include -#include - -class QLabel; - namespace caf { //================================================================================================== @@ -99,9 +91,9 @@ class PdmUiFieldEditorHandle : public PdmUiEditorHandle void setUiField( PdmUiFieldHandle* uiFieldHandle ); void createWidgets( QWidget* parent ); - QWidget* combinedWidget() { return m_combinedWidget; } - QWidget* editorWidget() { return m_editorWidget; } - QWidget* labelWidget() { return m_labelWidget; } + QWidget* combinedWidget(); + QWidget* editorWidget(); + QWidget* labelWidget(); QMargins labelContentMargins() const; int rowStretchFactor() const; @@ -109,9 +101,9 @@ class PdmUiFieldEditorHandle : public PdmUiEditorHandle /// Implement one of these, or both editor and label. The widgets will be used in the parent layout according to /// being "Label" Editor" or a single combined widget. - virtual QWidget* createCombinedWidget( QWidget* parent ) { return nullptr; } - virtual QWidget* createEditorWidget( QWidget* parent ) { return nullptr; } - virtual QWidget* createLabelWidget( QWidget* parent ) { return nullptr; } + virtual QWidget* createCombinedWidget( QWidget* parent ); + virtual QWidget* createEditorWidget( QWidget* parent ); + virtual QWidget* createLabelWidget( QWidget* parent ); void setValueToField( const QVariant& value ); diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.cpp index 37829e1e03..e5b4d1b88b 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.cpp @@ -35,7 +35,6 @@ //################################################################################################## #include "cafPdmUiItem.h" -#include "cafPdmPtrField.h" #include "cafPdmUiEditorHandle.h" #include "cafPdmUiObjectEditorHandle.h" diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.h index 947b9ce0c7..07d757ceab 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiItem.h @@ -39,10 +39,6 @@ #include "cafIconProvider.h" #include "cafPdmUiFieldSpecialization.h" -#include -#include -#include -#include #include #include diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectEditorHandle.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectEditorHandle.h index 05f043c4aa..23074f25f0 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectEditorHandle.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectEditorHandle.h @@ -37,7 +37,6 @@ #pragma once -#include "cafPdmPointer.h" #include "cafPdmUiEditorHandle.h" #include diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectHandle.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectHandle.h index ee395297a1..c17447eb65 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectHandle.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiObjectHandle.h @@ -13,6 +13,7 @@ class PdmObjectHandle; class PdmUiOrdering; class PdmFieldHandle; class PdmUiEditorAttribute; +class CmdFeatureMenuBuilder; class PdmUiObjectHandle : public PdmUiItem, public PdmObjectCapability { @@ -44,6 +45,9 @@ class PdmUiObjectHandle : public PdmUiItem, public PdmObjectCapability void updateUiIconFromToggleField(); + /// Append actions to menu builder + virtual void appendMenuItems( caf::CmdFeatureMenuBuilder& menuBuilder ) const {} + // Virtual interface to override in subclasses to support special behaviour if needed public: // Virtual virtual caf::PdmFieldHandle* userDescriptionField() { return nullptr; } @@ -87,13 +91,6 @@ class PdmUiObjectHandle : public PdmUiItem, public PdmObjectCapability { } - /// Override to provide tree editor specific attributes for the field and uiConfigName - virtual void defineTreeEditorAttribute( const caf::PdmFieldHandle* field, - QString uiConfigName, - caf::PdmUiEditorAttribute* attribute ) - { - } - /// Override to provide editor specific data for the uiConfigName for the object virtual void defineObjectEditorAttribute( QString uiConfigName, caf::PdmUiEditorAttribute* attribute ) {} diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiOrdering.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiOrdering.cpp index 74c0b73f95..eacaf1bd3e 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiOrdering.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiOrdering.cpp @@ -36,7 +36,6 @@ #include "cafPdmUiOrdering.h" -#include "cafPdmDataValueField.h" #include "cafPdmObjectHandle.h" #include "cafPdmUiFieldHandle.h" #include "cafPdmUiObjectHandle.h" diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.cpp index 4ac222882c..656ff92704 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.cpp @@ -37,7 +37,6 @@ #include "cafPdmUiTreeOrdering.h" #include "cafAssert.h" -#include "cafPdmDataValueField.h" #include "cafPdmObjectHandle.h" #include "cafPdmUiEditorHandle.h" #include "cafPdmUiFieldHandle.h" diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.h index f531cc8d37..9bc32f4ff1 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafPdmUiTreeOrdering.h @@ -41,8 +41,6 @@ #include #include -#include - namespace caf { class PdmFieldHandle; diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafQShortenedLabel.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafQShortenedLabel.cpp index 305e81d1ed..9230fae456 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafQShortenedLabel.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafQShortenedLabel.cpp @@ -36,9 +36,7 @@ #include "cafQShortenedLabel.h" #include -#include #include -#include using namespace caf; diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafSelectionManager.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafSelectionManager.h index b48433fee5..96acde4c0f 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafSelectionManager.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafSelectionManager.h @@ -37,7 +37,6 @@ #include "cafSelectionChangedReceiver.h" -#include "cafPdmField.h" #include "cafPdmObjectHandle.h" #include "cafPdmPointer.h" #include "cafPdmUiItem.h" diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafUiTreeItem.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafUiTreeItem.h index cd2d7c8ee6..1d0b04abe3 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafUiTreeItem.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmUiCore/cafUiTreeItem.h @@ -36,7 +36,6 @@ #pragma once -//#include #include #include diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/CMakeLists.txt index 2ef313e3dd..de12c881f7 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/CMakeLists.txt @@ -7,12 +7,22 @@ if(CAF_ENABLE_UNITY_BUILD) endif() # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Xml -) -set(QT_LIBRARIES Qt5::Core Qt5::Xml) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Xml + ) + set(QT_LIBRARIES Qt6::Core Qt6::Xml) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Xml + ) + set(QT_LIBRARIES Qt5::Core Qt5::Xml) +endif() set(PROJECT_FILES cafInternalPdmFieldIoHelper.cpp diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.cpp index c56a326c86..d326cefcb8 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.cpp @@ -1,3 +1,4 @@ +#include #include //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.h index 024c67b269..8983658a4b 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmStreamOperators.h @@ -79,6 +79,22 @@ QTextStream& operator<<( QTextStream& str, const std::pair& sobj ) template QTextStream& operator>>( QTextStream& str, std::pair& sobj ) +{ + T first; + U second; + + str >> first >> second; + + sobj = std::make_pair( first, second ); + + return str; +} + +//================================================================================================== +/// Explicit specialization for std::pair, as the string can contain spaces +//================================================================================================== +template +QTextStream& operator>>( QTextStream& str, std::pair& sobj ) { T first; @@ -100,10 +116,7 @@ QTextStream& operator>>( QTextStream& str, std::pair& sobj ) } } - QVariant v = restOfString; - U second = v.value(); - - sobj = std::make_pair( first, second ); + sobj = std::make_pair( first, restOfString ); return str; } diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldCapability.inl b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldCapability.inl index 85b9ecd63f..7027f4a642 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldCapability.inl +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldCapability.inl @@ -2,6 +2,8 @@ #include "cafAssert.h" #include "cafInternalPdmFieldIoHelper.h" #include "cafPdmObjectFactory.h" +#include "cafPdmObjectHandle.h" +#include "cafPdmReferenceHelper.h" #include "cafPdmXmlObjectHandle.h" #include diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldReaderWriter.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldReaderWriter.h index fa72d6cc19..0712c393f5 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldReaderWriter.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafInternalPdmXmlFieldReaderWriter.h @@ -7,7 +7,6 @@ #include "cafInternalPdmFieldIoHelper.h" #include "cafInternalPdmFilePathStreamOperators.h" #include "cafInternalPdmStreamOperators.h" -#include "cafPdmReferenceHelper.h" namespace caf { @@ -71,56 +70,4 @@ void PdmFieldReader::readFieldData( DataType& fieldValue, QXmlStreamRe template <> void PdmFieldReader::readFieldData( QString& field, QXmlStreamReader& xmlStream, PdmObjectFactory* objectFactory ); -#if 0 -//-------------------------------------------------------------------------------------------------- -/// Specialized IO for PdmPointer -//-------------------------------------------------------------------------------------------------- -template -struct PdmFieldWriter< PdmPointer > -{ - static void writeFieldData(const PdmPointer & fieldValue, QXmlStreamWriter& xmlStream, PdmReferenceHelper* referenceHelper) - { - QString dataString; - - CAF_ASSERT(referenceHelper); - - if (fieldValue.isNull()) - { - dataString = "NULL"; - } - else - { - dataString = referenceHelper->referenceFromRootToObject(fieldValue.p()); - } - - xmlStream.writeCharacters(dataString); - } -}; - -template -struct PdmFieldReader< PdmPointer > -{ - static void readFieldData(PdmPointer & fieldValue, QXmlStreamReader& xmlStream, PdmObjectFactory*, PdmReferenceHelper* referenceHelper) - { - PdmFieldIOHelper::skipComments(xmlStream); - if (!xmlStream.isCharacters()) return; - - QString dataString = xmlStream.text().toString(); - - // Make stream point to end of element - QXmlStreamReader::TokenType type = xmlStream.readNext(); - Q_UNUSED(type); - PdmFieldIOHelper::skipCharactersAndComments(xmlStream); - - if (dataString != "NULL") - { - CAF_ASSERT(referenceHelper); - - PdmObjectHandle* objHandle = referenceHelper->objectFromReference(dataString); - fieldValue.setRawPtr(objHandle); - } - } -}; - -#endif } // End of namespace caf diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.cpp index 2f1d1dd423..6ac0284ada 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.cpp @@ -35,10 +35,12 @@ //################################################################################################## #include "cafPdmSettings.h" - -#include "cafPdmField.h" +#include "cafPdmObjectHandle.h" +#include "cafPdmValueField.h" #include "cafPdmXmlObjectHandle.h" +#include + namespace caf { //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.h index d9d7689197..6da23c60c7 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmSettings.h @@ -36,7 +36,7 @@ #pragma once -#include +#include namespace caf { diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlFieldHandle.h b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlFieldHandle.h index b158215453..63741d0874 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlFieldHandle.h +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlFieldHandle.h @@ -2,7 +2,6 @@ #include "cafPdmFieldCapability.h" #include -#include class QXmlStreamReader; class QXmlStreamWriter; diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlObjectHandle.cpp b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlObjectHandle.cpp index 8bf84556d3..a464538386 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlObjectHandle.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXmlObjectHandle.cpp @@ -10,6 +10,7 @@ #include #include +#include #include namespace caf diff --git a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests/CMakeLists.txt index 4a44bcfcbe..974509c4ef 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/cafPdmXml/cafPdmXml_UnitTests/CMakeLists.txt @@ -2,12 +2,22 @@ cmake_minimum_required(VERSION 3.15) project(cafPdmXml_UnitTests) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Xml -) -set(QT_LIBRARIES Qt5::Core Qt5::Xml) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Xml + ) + set(QT_LIBRARIES Qt6::Core Qt6::Xml) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Xml + ) + set(QT_LIBRARIES Qt5::Core Qt5::Xml) +endif() if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) # VS 2017 : Disable warnings from from gtest code, using deprecated code @@ -18,23 +28,24 @@ endif() include_directories(${CMAKE_CURRENT_SOURCE_DIR} # required for gtest-all.cpp ) -# add the executable -add_executable( - ${PROJECT_NAME} - cafPdmXml_UnitTests.cpp gtest/gtest-all.cpp cafPdmXmlBasicTest.cpp - cafPdmAdvancedTemplateTest.cpp cafPdmXmlNumberTest.cpp cafPdmPtrArrayTest.cpp +set(PROJECT_FILES + cafPdmXml_UnitTests.cpp gtest/gtest-all.cpp cafPdmXmlBasicTest.cpp + cafPdmAdvancedTemplateTest.cpp cafPdmXmlNumberTest.cpp + cafPdmPtrArrayTest.cpp ) -if(Qt5Core_FOUND) - set(QT_LIBRARIES Qt5::Core Qt5::Xml) -endif() +if(CEE_USE_QT6) + qt_add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +else() + add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +endif(CEE_USE_QT6) + +source_group("" FILES ${PROJECT_FILES}) target_link_libraries( - ${PROJECT_NAME} cafPdmXml ${QT_LIBRARIES} ${THREAD_LIBRARY} + ${PROJECT_NAME} PRIVATE cafPdmXml ${QT_LIBRARIES} ${THREAD_LIBRARY} ) -source_group("" FILES ${PROJECT_FILES}) - # Copy Qt Dlls if(Qt5Core_FOUND) foreach(qtlib ${QT_LIBRARIES}) @@ -46,3 +57,18 @@ if(Qt5Core_FOUND) ) endforeach(qtlib) endif(Qt5Core_FOUND) + +# Install +install( + TARGETS ${PROJECT_NAME} + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(CEE_USE_QT6) + qt_generate_deploy_app_script( + TARGET ${PROJECT_NAME} OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR NO_TRANSLATIONS + ) + install(SCRIPT ${deploy_script}) +endif(CEE_USE_QT6) diff --git a/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/AggregatedTypesInField.cpp b/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/AggregatedTypesInField.cpp index 31032b898b..4d00b3067c 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/AggregatedTypesInField.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/AggregatedTypesInField.cpp @@ -52,11 +52,15 @@ class AggregatedTypes : public caf::PdmObject auto pair = std::make_pair( false, 12.0 ); CAF_PDM_InitField( &m_checkableDouble, "CheckableDouble", pair, "label text" ); + + auto strPair = std::make_pair( false, QString( "msj" ) ); + CAF_PDM_InitField( &m_checkableString, "CheckableString", strPair, "label text" ); } ~AggregatedTypes() {} - caf::PdmField> m_checkableDouble; + caf::PdmField> m_checkableDouble; + caf::PdmField> m_checkableString; }; CAF_PDM_SOURCE_INIT( AggregatedTypes, "AggregatedTypes" ); @@ -79,14 +83,19 @@ TEST( AggregatedTypeTest, MyTest ) QXmlStreamWriter xmlStream( &xml ); xmlStream.setAutoFormatting( true ); - const double testValue = 0.0012; + const double testValue = 0.0012; + const QString testString = "string with spaces"; { AggregatedTypes myObj; auto testPair = std::make_pair( true, testValue ); myObj.m_checkableDouble = testPair; - xml = myObj.writeObjectToXmlString(); + + auto testStrPair = std::make_pair( true, testString ); + myObj.m_checkableString = testStrPair; + + xml = myObj.writeObjectToXmlString(); } { @@ -95,8 +104,10 @@ TEST( AggregatedTypeTest, MyTest ) myObj.readObjectFromXmlString( xml, caf::PdmDefaultObjectFactory::instance() ); auto fieldValue = myObj.m_checkableDouble(); - ASSERT_TRUE( fieldValue.first ); ASSERT_DOUBLE_EQ( testValue, fieldValue.second ); + + auto fieldStrValue = myObj.m_checkableString(); + ASSERT_STREQ( testString.toStdString().data(), fieldStrValue.second.toStdString().data() ); } } diff --git a/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/CMakeLists.txt b/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/CMakeLists.txt index 8ebab1d009..768ca2b7c1 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/CMakeLists.txt +++ b/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/CMakeLists.txt @@ -3,12 +3,21 @@ cmake_minimum_required(VERSION 3.15) project(cafProjectDataModel_UnitTests) # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Xml Gui -) -set(QT_LIBRARIES Qt5::Core Qt5::Xml Qt5::Gui Qt5::Widgets) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Widgets + ) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Xml Gui + ) + set(QT_LIBRARIES Qt5::Core Qt5::Xml Qt5::Gui) +endif() if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) # VS 2017 : Disable warnings from from gtest code, using deprecated code @@ -19,12 +28,21 @@ endif() include_directories(${CMAKE_CURRENT_SOURCE_DIR} # required for gtest-all.cpp ) -set(PROJECT_FILES cafPdmBasicTest.cpp cafProjectDataModel_UnitTests.cpp - Child.cpp Parent.cpp TestObj.cpp AggregatedTypesInField.cpp +set(PROJECT_FILES + cafPdmBasicTest.cpp + cafProjectDataModel_UnitTests.cpp + Child.cpp + Parent.cpp + TestObj.cpp + AggregatedTypesInField.cpp + gtest/gtest-all.cpp ) -# add the executable -add_executable(${PROJECT_NAME} ${PROJECT_FILES} gtest/gtest-all.cpp) +if(CEE_USE_QT6) + qt_add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +else() + add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +endif(CEE_USE_QT6) if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") target_compile_options( @@ -34,7 +52,7 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") endif() target_link_libraries( - ${PROJECT_NAME} cafProjectDataModel ${QT_LIBRARIES} ${THREAD_LIBRARY} + ${PROJECT_NAME} PRIVATE cafProjectDataModel ${QT_LIBRARIES} ${THREAD_LIBRARY} ) source_group("" FILES ${PROJECT_FILES}) @@ -48,3 +66,18 @@ foreach(qtlib ${QT_LIBRARIES}) $ ) endforeach(qtlib) + +# Install +install( + TARGETS ${PROJECT_NAME} + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(CEE_USE_QT6) + qt_generate_deploy_app_script( + TARGET ${PROJECT_NAME} OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR NO_TRANSLATIONS + ) + install(SCRIPT ${deploy_script}) +endif(CEE_USE_QT6) diff --git a/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/cafPdmBasicTest.cpp b/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/cafPdmBasicTest.cpp index 725fd859d5..d128f321af 100644 --- a/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/cafPdmBasicTest.cpp +++ b/Fwk/AppFwk/cafProjectDataModel/cafProjectDataModel_UnitTests/cafPdmBasicTest.cpp @@ -261,7 +261,7 @@ TEST( BaseTest, Start ) SimpleObj s; s.m_dir = 10000; sp = &s; - a->m_textField = "Hei og hå"; + a->m_textField = "Hei"; //*s2 = s; a->m_simpleObjPtrField = s2; diff --git a/Fwk/AppFwk/cafTests/cafTestApplication/CMakeLists.txt b/Fwk/AppFwk/cafTests/cafTestApplication/CMakeLists.txt index 92f8557dd6..328c2d4218 100644 --- a/Fwk/AppFwk/cafTests/cafTestApplication/CMakeLists.txt +++ b/Fwk/AppFwk/cafTests/cafTestApplication/CMakeLists.txt @@ -15,14 +15,24 @@ set(MOC_HEADER_FILES MainWindow.h WidgetLayoutTest.h CustomObjectEditor.h # Resource file set(QRC_FILES ${QRC_FILES} textedit.qrc) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets OpenGL Svg -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL Qt5::Svg) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) -qt5_add_resources(QRC_FILES_CPP ${QRC_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL Svg + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGL Qt6::Svg) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) + qt5_add_resources(QRC_FILES_CPP ${QRC_FILES}) +endif() option(USE_COMMAND_FRAMEWORK "Use Caf Command Framework" ON) @@ -49,16 +59,28 @@ set(PROJECT_FILES LineEditAndPushButtons.cpp ) -# add the executable -add_executable( - ${PROJECT_NAME} - ${PROJECT_FILES} - ${MOC_SOURCE_FILES} - ${QRC_FILES_CPP} - $ # Needed for cmake version < 3.12. Remove - # when we can use target_link_libraries - # with OBJECT libraries -) +if(CEE_USE_QT6) + qt_add_executable( + ${PROJECT_NAME} + ${PROJECT_FILES} + ${MOC_SOURCE_FILES} + ${QRC_FILES_CPP} + $ # Needed for cmake version < 3.12. + # Remove + # when we can use target_link_libraries with OBJECT libraries + ) +else() + add_executable( + ${PROJECT_NAME} + ${PROJECT_FILES} + ${MOC_SOURCE_FILES} + ${QRC_FILES_CPP} + $ # Needed for cmake version < 3.12. + # Remove when we can use + # target_link_libraries with OBJECT + # libraries + ) +endif(CEE_USE_QT6) set(TAP_LINK_LIBRARIES cafUserInterface) @@ -77,8 +99,8 @@ if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") endif() target_link_libraries( - ${PROJECT_NAME} ${TAP_LINK_LIBRARIES} ${QT_LIBRARIES} - ${EXTERNAL_LINK_LIBRARIES} + ${PROJECT_NAME} PRIVATE ${TAP_LINK_LIBRARIES} ${QT_LIBRARIES} + ${EXTERNAL_LINK_LIBRARIES} ) source_group("" FILES ${PROJECT_FILES}) @@ -91,3 +113,27 @@ foreach(qtlib ${QT_LIBRARIES}) $ ) endforeach(qtlib) + +# Install +install( + TARGETS ${PROJECT_NAME} + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(CEE_USE_QT6) + qt_generate_deploy_app_script( + TARGET ${PROJECT_NAME} OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR NO_TRANSLATIONS + ) + install(SCRIPT ${deploy_script}) + + if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") + set(CPACK_GENERATOR TGZ) + elseif(${CMAKE_SYSTEM_NAME} MATCHES "Windows") + set(CPACK_GENERATOR ZIP) + endif() + + include(CPack) + +endif(CEE_USE_QT6) diff --git a/Fwk/AppFwk/cafTests/cafTestApplication/LineEditAndPushButtons.cpp b/Fwk/AppFwk/cafTests/cafTestApplication/LineEditAndPushButtons.cpp index ab4e0dac6a..18b9bc4c01 100644 --- a/Fwk/AppFwk/cafTests/cafTestApplication/LineEditAndPushButtons.cpp +++ b/Fwk/AppFwk/cafTests/cafTestApplication/LineEditAndPushButtons.cpp @@ -7,6 +7,8 @@ #include "cafPdmUiPushButtonEditor.h" #include "cafPdmUiTreeSelectionEditor.h" +#include + CAF_PDM_SOURCE_INIT( LineEditAndPushButtons, "LineEditAndPushButtons" ); //-------------------------------------------------------------------------------------------------- @@ -35,20 +37,16 @@ LineEditAndPushButtons::LineEditAndPushButtons() m_textListField.uiCapability()->setUiEditorTypeName( caf::PdmUiListEditor::uiEditorTypeName() ); CAF_PDM_InitFieldNoDefault( &m_pushButton_a, "PushButtonA", "Rotate", "", "", "" ); - m_pushButton_a.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButton_a.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButton_a ); CAF_PDM_InitFieldNoDefault( &m_pushButtonReplace, "PushButtonB", "Replace (CTRL + Enter)", "", "", "" ); - m_pushButtonReplace.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButtonReplace.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonReplace ); CAF_PDM_InitFieldNoDefault( &m_pushButtonClear, "PushButtonC", "Clear (Alt + Enter)", "", "", "" ); - m_pushButtonClear.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButtonClear.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonClear ); CAF_PDM_InitFieldNoDefault( &m_pushButtonAppend, "PushButtonD", "Append (Shift + Enter)", "", "", "" ); - m_pushButtonAppend.uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - m_pushButtonAppend.uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); + caf::PdmUiPushButtonEditor::configureEditorLabelHidden( &m_pushButtonAppend ); std::vector items; items.push_back( "sldkfj" ); diff --git a/Fwk/AppFwk/cafTests/cafTestApplication/Main.cpp b/Fwk/AppFwk/cafTests/cafTestApplication/Main.cpp index 21f518e93c..9f11496b07 100644 --- a/Fwk/AppFwk/cafTests/cafTestApplication/Main.cpp +++ b/Fwk/AppFwk/cafTests/cafTestApplication/Main.cpp @@ -18,6 +18,8 @@ int main( int argc, char* argv[] ) { QApplication app( argc, argv ); + caf::CmdFeatureManager::createSingleton(); + MainWindow window; window.setWindowTitle( "Ceetron Application Framework Test Application" ); window.resize( 1000, 810 ); diff --git a/Fwk/AppFwk/cafTests/cafTestApplication/MainWindow.cpp b/Fwk/AppFwk/cafTests/cafTestApplication/MainWindow.cpp index 4d87f66a0c..3e0bdee720 100644 --- a/Fwk/AppFwk/cafTests/cafTestApplication/MainWindow.cpp +++ b/Fwk/AppFwk/cafTests/cafTestApplication/MainWindow.cpp @@ -33,7 +33,6 @@ #include "cafPdmUiFilePathEditor.h" #include "cafPdmUiItem.h" #include "cafPdmUiListEditor.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUiPropertyView.h" #include "cafPdmUiPushButtonEditor.h" #include "cafPdmUiTableView.h" diff --git a/Fwk/AppFwk/cafTests/cafTestCvfApplication/CMakeLists.txt b/Fwk/AppFwk/cafTests/cafTestCvfApplication/CMakeLists.txt index a1fe491d03..48ca8821f1 100644 --- a/Fwk/AppFwk/cafTests/cafTestCvfApplication/CMakeLists.txt +++ b/Fwk/AppFwk/cafTests/cafTestCvfApplication/CMakeLists.txt @@ -8,14 +8,23 @@ set(MOC_HEADER_FILES MainWindow.h WidgetLayoutTest.h) # Resource file set(QRC_FILES textedit.qrc) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets OpenGL Svg -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL Qt5::Svg) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) -qt5_add_resources(QRC_FILES_CPP ${QRC_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL Svg + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGL Qt6::Svg) +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) + qt5_add_resources(QRC_FILES_CPP ${QRC_FILES}) +endif() option(USE_COMMAND_FRAMEWORK "Use Caf Command Framework" ON) diff --git a/Fwk/AppFwk/cafTests/cafTestCvfApplication/WidgetLayoutTest.h b/Fwk/AppFwk/cafTests/cafTestCvfApplication/WidgetLayoutTest.h index 4fa363e940..af09ba6782 100644 --- a/Fwk/AppFwk/cafTests/cafTestCvfApplication/WidgetLayoutTest.h +++ b/Fwk/AppFwk/cafTests/cafTestCvfApplication/WidgetLayoutTest.h @@ -10,7 +10,7 @@ class WidgetLayoutTest : public QWidget Q_OBJECT public: - WidgetLayoutTest( QWidget* parent = 0, Qt::WindowFlags f = 0 ); + WidgetLayoutTest( QWidget* parent = 0, Qt::WindowFlags f = Qt::WindowFlags() ); ~WidgetLayoutTest(); private: diff --git a/Fwk/AppFwk/cafUserInterface/CMakeLists.txt b/Fwk/AppFwk/cafUserInterface/CMakeLists.txt index 81bc726a87..06453f27ec 100644 --- a/Fwk/AppFwk/cafUserInterface/CMakeLists.txt +++ b/Fwk/AppFwk/cafUserInterface/CMakeLists.txt @@ -55,13 +55,23 @@ set(MOC_HEADER_FILES cafPdmUiValueRangeEditor.h ) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets Svg + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::Svg) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets Svg + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Svg) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() set(PROJECT_FILES # field editors @@ -172,6 +182,7 @@ set(PROJECT_FILES cafPdmUiTreeViewItemDelegate.h cafPdmUiTreeViewItemDelegate.cpp cafPdmUiTreeAttributes.h + cafPdmUiTreeAttributes.cpp cafUiAppearanceSettings.cpp cafUiIconFactory.cpp cafPdmUiSliderTools.h @@ -184,7 +195,7 @@ add_library( if(MSVC) set_target_properties( - ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127" + ${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/W4 /wd4100 /wd4127 /wd4996" ) endif() diff --git a/Fwk/AppFwk/cafUserInterface/QMinimizePanel.cpp b/Fwk/AppFwk/cafUserInterface/QMinimizePanel.cpp index d4df416646..a9635a7e92 100644 --- a/Fwk/AppFwk/cafUserInterface/QMinimizePanel.cpp +++ b/Fwk/AppFwk/cafUserInterface/QMinimizePanel.cpp @@ -403,7 +403,6 @@ void QMinimizePanel::initialize( const QString& title ) { m_titleLabel = new QLabel( title ); QPalette titleLabelPalette = m_titleLabel->palette(); - titleLabelPalette.setBrush( QPalette::WindowText, titleLabelPalette.windowText() ); m_titleLabel->setPalette( titleLabelPalette ); titleLayout->addWidget( m_titleLabel, 1, Qt::AlignLeft ); } diff --git a/Fwk/AppFwk/cafUserInterface/cafAboutDialog.cpp b/Fwk/AppFwk/cafUserInterface/cafAboutDialog.cpp index d301cef741..982b0e3de3 100644 --- a/Fwk/AppFwk/cafUserInterface/cafAboutDialog.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafAboutDialog.cpp @@ -41,7 +41,10 @@ #include #include #include + +#if ( QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 ) ) #include +#endif namespace caf { @@ -299,6 +302,7 @@ QString AboutDialog::versionStringForcurrentOpenGLContext() { QString versionString( "OpenGL " ); +#if ( QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 ) ) QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags(); if ( flags & QGLFormat::OpenGL_Version_4_0 ) @@ -339,7 +343,7 @@ QString AboutDialog::versionStringForcurrentOpenGLContext() versionString += "None"; else versionString += "Unknown"; - +#endif return versionString; } diff --git a/Fwk/AppFwk/cafUserInterface/cafMemoryInspector.cpp b/Fwk/AppFwk/cafUserInterface/cafMemoryInspector.cpp index 9148783929..686a75e0c0 100644 --- a/Fwk/AppFwk/cafUserInterface/cafMemoryInspector.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafMemoryInspector.cpp @@ -3,9 +3,9 @@ #include "cafMemoryInspector.h" #include -#include #include #include +#include #ifdef _WIN32 // Define this one to tell windows.h to not define min() and max() as macros @@ -24,6 +24,13 @@ #define MIB_DIV 1048576 #ifdef __linux__ + +#if ( QT_VERSION < QT_VERSION_CHECK( 5, 14, 0 ) ) + auto SkipEmptyParts = QString::SkipEmptyParts; +#else + auto SkipEmptyParts = Qt::SkipEmptyParts; +#endif + //-------------------------------------------------------------------------------------------------- /// Read bytes of memory of different types for current process from /proc/self/statm /// See: http://man7.org/linux/man-pages/man5/proc.5.html @@ -40,7 +47,7 @@ std::map readProcessBytesLinux() if (procSelfStatus.open(QIODevice::ReadOnly | QIODevice::Text)) { QString line(procSelfStatus.readLine(256)); - QStringList lineWords = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); + QStringList lineWords = line.split(QRegularExpression("\\s+"), SkipEmptyParts); quantities["VmSize"] = static_cast(lineWords[0].toLongLong() * pageSize); quantities["RSS"] = static_cast(lineWords[1].toLongLong() * pageSize); quantities["Shared"] = static_cast(lineWords[2].toLongLong() * pageSize); @@ -68,7 +75,7 @@ std::map readMemInfoLinuxMiB() if (lineLength > 0) { QString line = QString::fromLatin1(buf, lineLength); - QStringList words = line.split(QRegExp(":*\\s+"), QString::SkipEmptyParts); + QStringList words = line.split(QRegularExpression(":*\\s+"), SkipEmptyParts); if (words.size() > 1) { bool ok = true; diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiActionPushButtonEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiActionPushButtonEditor.cpp index df19a94742..2b692f5e32 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiActionPushButtonEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiActionPushButtonEditor.cpp @@ -41,7 +41,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" #include "cafFactory.h" @@ -117,7 +116,7 @@ QWidget* PdmUiActionPushButtonEditor::createEditorWidget( QWidget* parent ) m_buttonLayout = new QHBoxLayout( containerWidget ); m_buttonLayout->addWidget( m_pushButton ); - m_buttonLayout->setMargin( 0 ); + m_buttonLayout->setContentsMargins( 0, 0, 0, 0 ); m_buttonLayout->setSpacing( 0 ); containerWidget->setLayout( m_buttonLayout ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxAndTextEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxAndTextEditor.cpp index 51aae11d98..4092b50f8c 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxAndTextEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxAndTextEditor.cpp @@ -41,8 +41,6 @@ #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" #include "cafPdmUiLineEditor.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include #include @@ -110,7 +108,7 @@ QWidget* PdmUiCheckBoxAndTextEditor::createEditorWidget( QWidget* parent ) layout->addWidget( m_checkBox ); layout->addWidget( m_lineEdit ); - layout->setMargin( 0 ); + layout->setContentsMargins( 0, 0, 0, 0 ); containerWidget->setLayout( layout ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxEditor.cpp index d52dd26fe9..48cf6ff17b 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxEditor.cpp @@ -41,8 +41,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include "cafFactory.h" diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxTristateEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxTristateEditor.cpp index 7e621d99ea..fd3749b7d9 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxTristateEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiCheckBoxTristateEditor.cpp @@ -7,8 +7,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include "cafFactory.h" #include "cafTristate.h" diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiColorEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiColorEditor.cpp index da19e6d17a..f8adaf40b0 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiColorEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiColorEditor.cpp @@ -41,8 +41,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include "cafFactory.h" diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiComboBoxEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiComboBoxEditor.cpp index e0a9db744b..428674510e 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiComboBoxEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiComboBoxEditor.cpp @@ -40,7 +40,6 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafQShortenedLabel.h" #include "cafUiAppearanceSettings.h" #include "cafUiIconFactory.h" diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiDateEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiDateEditor.cpp index 50f0e32ba8..8d1a1d4c2b 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiDateEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiDateEditor.cpp @@ -41,8 +41,6 @@ #include "cafPdmObject.h" #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include "cafSelectionManager.h" #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleSliderEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleSliderEditor.cpp index 890e8a7005..78573a8605 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleSliderEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleSliderEditor.cpp @@ -39,7 +39,6 @@ #include "cafPdmField.h" #include "cafPdmUiFieldHandle.h" #include "cafPdmUiObjectHandle.h" -#include "cafQShortenedLabel.h" #include #include @@ -107,7 +106,7 @@ QWidget* PdmUiDoubleSliderEditor::createEditorWidget( QWidget* parent ) QWidget* containerWidget = new QWidget( parent ); QHBoxLayout* layout = new QHBoxLayout(); - layout->setMargin( 0 ); + layout->setContentsMargins( 0, 0, 0, 0 ); containerWidget->setLayout( layout ); m_lineEdit = new QLineEdit( containerWidget ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleValueEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleValueEditor.cpp index e668bf9298..cf0607a388 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleValueEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiDoubleValueEditor.cpp @@ -42,7 +42,6 @@ #include "cafPdmUiFieldEditorHandle.h" #include "cafFactory.h" -#include "cafQShortenedLabel.h" #include #include @@ -116,7 +115,7 @@ QWidget* PdmUiDoubleValueEditor::createEditorWidget( QWidget* parent ) QWidget* containerWidget = new QWidget( parent ); QHBoxLayout* layout = new QHBoxLayout(); - layout->setMargin( 0 ); + layout->setContentsMargins( 0, 0, 0, 0 ); containerWidget->setLayout( layout ); m_lineEdit = new QLineEdit( containerWidget ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiFilePathEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiFilePathEditor.cpp index 07ab2c0be1..b2acbd40dc 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiFilePathEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiFilePathEditor.cpp @@ -42,9 +42,8 @@ #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" #include "cafPdmUiLineEditor.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" +#include #include #include #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiFormLayoutObjectEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiFormLayoutObjectEditor.h index 054ca7b941..4c49a76172 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiFormLayoutObjectEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiFormLayoutObjectEditor.h @@ -36,7 +36,6 @@ #pragma once -#include "cafPdmUiOrdering.h" #include "cafPdmUiWidgetObjectEditorHandle.h" #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.cpp index 0534669644..15ab06d5b8 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.cpp @@ -41,9 +41,7 @@ #include "cafPdmObject.h" #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" #include "cafPdmUniqueIdValidator.h" -#include "cafQShortenedLabel.h" #include "cafSelectionManager.h" #include "cafUiAppearanceSettings.h" #include "cafUiIconFactory.h" @@ -254,22 +252,7 @@ void PdmUiLineEditor::configureAndUpdateUi( const QString& uiConfigName ) QString displayString; if ( displayStringAttrib.m_displayString.isEmpty() ) { -#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 ) && QT_VERSION < QT_VERSION_CHECK( 5, 9, 0 ) ) - bool valueOk = false; - double value = uiField()->uiValue().toDouble( &valueOk ); - if ( valueOk ) - { - // Workaround for issue seen on Qt 5.6.1 on Linux - int precision = 8; - displayString = QString::number( value, 'g', precision ); - } - else - { - displayString = uiField()->uiValue().toString(); - } -#else displayString = uiField()->uiValue().toString(); -#endif } else { diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.h index 0dccd8c03c..5f9c8811b5 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiLineEditor.h @@ -43,13 +43,13 @@ #include #include #include +#include #include #include #include class QGridLayout; class QCompleter; -class QStringListModel; namespace caf { diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.cpp index e77b6d1616..c9bb4147d9 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.cpp @@ -41,9 +41,6 @@ #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafFactory.h" -#include "cafQShortenedLabel.h" - #include #include #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.h index 744922fdc6..d343c106e4 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiListEditor.h @@ -38,12 +38,12 @@ #include "cafPdmUiFieldEditorHandle.h" +#include + class QItemSelection; class QLabel; class QListViewHeightHint; class QModelIndex; -class QStringList; -class QStringListModel; namespace caf { diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.cpp index 6248680233..9667434ab4 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.cpp @@ -41,10 +41,8 @@ #include "cafPdmField.h" #include "cafPdmObject.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" #include "cafFactory.h" -#include "cafQShortenedLabel.h" #include @@ -114,19 +112,39 @@ void PdmUiPushButtonEditor::configureAndUpdateUi( const QString& uiConfigName ) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void PdmUiPushButtonEditor::configureEditorForField( PdmFieldHandle* fieldHandle ) +void PdmUiPushButtonEditor::configureEditorLabelLeft( PdmFieldHandle* fieldHandle ) { if ( fieldHandle ) { - if ( fieldHandle->xmlCapability() ) + if ( auto xmlCap = fieldHandle->xmlCapability() ) { - fieldHandle->xmlCapability()->disableIO(); + xmlCap->disableIO(); } - if ( fieldHandle->uiCapability() ) + if ( auto uiCap = fieldHandle->uiCapability() ) { - fieldHandle->uiCapability()->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); - fieldHandle->uiCapability()->setUiLabelPosition( caf::PdmUiItemInfo::LEFT ); + uiCap->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + uiCap->setUiLabelPosition( caf::PdmUiItemInfo::LEFT ); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void PdmUiPushButtonEditor::configureEditorLabelHidden( PdmFieldHandle* fieldHandle ) +{ + if ( fieldHandle ) + { + if ( auto xmlCap = fieldHandle->xmlCapability() ) + { + xmlCap->disableIO(); + } + + if ( auto uiCap = fieldHandle->uiCapability() ) + { + uiCap->setUiEditorTypeName( caf::PdmUiPushButtonEditor::uiEditorTypeName() ); + uiCap->setUiLabelPosition( caf::PdmUiItemInfo::HIDDEN ); } } } @@ -143,7 +161,7 @@ QWidget* PdmUiPushButtonEditor::createEditorWidget( QWidget* parent ) m_buttonLayout = new QHBoxLayout( containerWidget ); m_buttonLayout->addWidget( m_pushButton ); - m_buttonLayout->setMargin( 0 ); + m_buttonLayout->setContentsMargins( 0, 0, 0, 0 ); m_buttonLayout->setSpacing( 0 ); containerWidget->setLayout( m_buttonLayout ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.h index 00c1eb6a7e..269c80a97a 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiPushButtonEditor.h @@ -35,12 +35,14 @@ //################################################################################################## #pragma once + #include "cafPdmUiFieldEditorHandle.h" #include #include #include #include + class QHBoxLayout; namespace caf @@ -67,7 +69,8 @@ class PdmUiPushButtonEditor : public PdmUiFieldEditorHandle PdmUiPushButtonEditor() {} ~PdmUiPushButtonEditor() override {} - static void configureEditorForField( PdmFieldHandle* fieldHandle ); + static void configureEditorLabelLeft( PdmFieldHandle* fieldHandle ); + static void configureEditorLabelHidden( PdmFieldHandle* fieldHandle ); protected: QWidget* createEditorWidget( QWidget* parent ) override; diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.cpp index 1caf05af05..f3140d4518 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.cpp @@ -42,7 +42,6 @@ #include "cafPdmUiFieldEditorHandle.h" #include "cafFactory.h" -#include "cafQShortenedLabel.h" #include #include @@ -104,7 +103,7 @@ QWidget* PdmUiSliderEditor::createEditorWidget( QWidget* parent ) QWidget* containerWidget = new QWidget( parent ); QHBoxLayout* layout = new QHBoxLayout(); - layout->setMargin( 0 ); + layout->setContentsMargins( 0, 0, 0, 0 ); containerWidget->setLayout( layout ); m_spinBox = new QSpinBox( containerWidget ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.h index 9ff9e53fc4..8f76eb660d 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiSliderEditor.h @@ -35,6 +35,7 @@ //################################################################################################## #pragma once + #include "cafPdmUiFieldEditorHandle.h" #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTabbedPropertyViewDialog.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiTabbedPropertyViewDialog.h index f67986502e..e0a13976d6 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTabbedPropertyViewDialog.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTabbedPropertyViewDialog.h @@ -11,7 +11,6 @@ class PdmUiPropertyView; class QDialogButtonBox; class QWidget; class QString; -class QStringList; namespace caf { @@ -35,4 +34,4 @@ class PdmUiTabbedPropertyViewDialog : public QDialog QDialogButtonBox* m_dialogButtonBox; }; -} // namespace caf \ No newline at end of file +} // namespace caf diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableRowEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableRowEditor.cpp index 7162f75bf6..fe7ec29c91 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableRowEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableRowEditor.cpp @@ -36,9 +36,8 @@ #include "cafPdmUiTableRowEditor.h" -#include "cafPdmField.h" -#include "cafPdmObject.h" -#include "cafPdmUiEditorHandle.h" +#include "cafPdmUiObjectHandle.h" +#include "cafPdmUiOrdering.h" #include "cafPdmUiTableViewQModel.h" namespace caf diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.cpp index c369dbf64b..55adc2893c 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.cpp @@ -42,7 +42,6 @@ #include "cafPdmUiEditorHandle.h" #include "cafPdmUiTableViewDelegate.h" #include "cafPdmUiTableViewQModel.h" -#include "cafQShortenedLabel.h" #include "cafSelectionManager.h" #include @@ -160,7 +159,7 @@ QWidget* PdmUiTableViewEditor::createLabelWidget( QWidget* parent ) } QHBoxLayout* layoutForIconLabel = new QHBoxLayout(); - layoutForIconLabel->setMargin( 0 ); + layoutForIconLabel->setContentsMargins( 0, 0, 0, 0 ); layoutForIconLabel->addWidget( m_tableHeadingIcon ); layoutForIconLabel->addSpacing( 3 ); layoutForIconLabel->addWidget( m_tableHeading ); @@ -193,9 +192,25 @@ void PdmUiTableViewEditor::configureAndUpdateUi( const QString& uiConfigName ) this->setRowSelectionLevel( editorAttrib.rowSelectionLevel ); this->enableHeaderText( editorAttrib.enableHeaderText ); - QPalette myPalette( m_tableView->palette() ); - myPalette.setColor( QPalette::Base, editorAttrib.baseColor ); - m_tableView->setPalette( myPalette ); + QString styleSheetTable; + QString styleSheetHeader; + + if ( editorAttrib.baseColor.isValid() ) + { + // Configure style sheet to set the background color of the table and headers, including the corner button + + styleSheetTable = QString( "QTableView QTableCornerButton::section { background: %1 } QTableView { " + "background-color : %1 } " ) + .arg( editorAttrib.baseColor.name() ); + + styleSheetHeader = + QString( "QHeaderView { background-color: %1 } QHeaderView::section { background-color: %1 }" ) + .arg( editorAttrib.baseColor.name() ); + } + + m_tableView->setStyleSheet( styleSheetTable ); + m_tableView->horizontalHeader()->setStyleSheet( styleSheetHeader ); + m_tableView->verticalHeader()->setStyleSheet( styleSheetHeader ); // Drop target settings m_tableView->setAcceptDrops( editorAttrib.enableDropTarget ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.h index f66fe42eb6..b95cab8712 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewEditor.h @@ -36,11 +36,11 @@ #pragma once -#include "cafPdmDocument.h" #include "cafPdmUiFieldEditorHandle.h" #include "cafSelectionChangedReceiver.h" #include +#include #include #include #include @@ -107,11 +107,8 @@ class PdmUiTableViewEditorAttribute : public PdmUiEditorAttribute , resizePolicy( NO_AUTOMATIC_RESIZE ) , enableDropTarget( false ) { - QPalette myPalette; - baseColor = myPalette.color( QPalette::Active, QPalette::Base ); } - int selectionLevel; int tableSelectionLevel; int rowSelectionLevel; bool enableHeaderText; diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewQModel.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewQModel.cpp index 4add98a298..0814e67c08 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewQModel.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTableViewQModel.cpp @@ -37,18 +37,13 @@ #include "cafPdmUiTableViewQModel.h" #include "cafPdmChildArrayField.h" -#include "cafPdmField.h" -#include "cafPdmObject.h" -#include "cafPdmUiComboBoxEditor.h" #include "cafPdmUiCommandSystemProxy.h" #include "cafPdmUiDateEditor.h" #include "cafPdmUiFieldEditorHelper.h" #include "cafPdmUiLineEditor.h" +#include "cafPdmUiObjectHandle.h" +#include "cafPdmUiOrdering.h" #include "cafPdmUiTableRowEditor.h" -#include "cafPdmUiTableView.h" -#include "cafSelectionManager.h" - -#include namespace caf { diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.cpp index 781dce3f9b..d87f427d1a 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.cpp @@ -40,8 +40,6 @@ #include "cafPdmObject.h" #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include #include @@ -184,7 +182,7 @@ QWidget* PdmUiTextEditor::createEditorWidget( QWidget* parent ) QVBoxLayout* layout = new QVBoxLayout; layout->addWidget( m_textEdit ); - layout->setMargin( 0 ); + layout->setContentsMargins( 0, 0, 0, 0 ); QHBoxLayout* buttonLayout = new QHBoxLayout; buttonLayout->insertStretch( 0, 10 ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.h index eaccdd07a2..e68caf2526 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTextEditor.h @@ -35,7 +35,9 @@ //################################################################################################## #pragma once + #include "cafPdmUiFieldEditorHandle.h" + #include #include #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.cpp index c5a1ad4fcd..6b68545df1 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.cpp @@ -41,8 +41,6 @@ #include "cafPdmObject.h" #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include "cafSelectionManager.h" #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.h index 109057a4b8..41f9a6b18a 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTimeEditor.h @@ -38,7 +38,6 @@ #include "cafPdmUiFieldEditorHandle.h" -#include #include #include #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiToolBarEditor.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiToolBarEditor.h index be53429233..9bc187bfdd 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiToolBarEditor.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiToolBarEditor.h @@ -45,6 +45,7 @@ class QToolBar; class QMainWindow; +class QAction; namespace caf { diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.cpp new file mode 100644 index 0000000000..56fc50f440 --- /dev/null +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.cpp @@ -0,0 +1,85 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cafPdmUiTreeAttributes.h" + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::unique_ptr caf::PdmUiTreeViewItemAttribute::createTag() +{ + return std::make_unique(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::unique_ptr + caf::PdmUiTreeViewItemAttribute::createTag( const QColor& color, const QColor& backgroundColor, const QString& text ) +{ + auto tag = createTag(); + + auto weight1 = 100; + double transparency = 0.3; + int weight2 = std::max( 1, static_cast( weight1 * 10 * transparency ) ); + + int weightsum = weight1 + weight2; + + auto blendedColor = QColor( ( color.red() * weight1 + backgroundColor.red() * weight2 ) / weightsum, + ( color.green() * weight1 + backgroundColor.green() * weight2 ) / weightsum, + ( color.blue() * weight1 + backgroundColor.blue() * weight2 ) / weightsum ); + + tag->bgColor = blendedColor; + tag->fgColor = color; + tag->text = text; + + return tag; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void caf::PdmUiTreeViewItemAttribute::appendTagToTreeViewItemAttribute( caf::PdmUiEditorAttribute* attribute, + const QString& iconResourceString ) +{ + if ( auto* treeItemAttribute = dynamic_cast( attribute ) ) + { + auto tag = caf::PdmUiTreeViewItemAttribute::createTag(); + tag->icon = caf::IconProvider( iconResourceString ); + + treeItemAttribute->tags.push_back( std::move( tag ) ); + } +} diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.h b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.h index de171f7000..b5e6442be1 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.h +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeAttributes.h @@ -1,5 +1,3 @@ - - //################################################################################################## // // Custom Visualization Core library @@ -73,12 +71,14 @@ class PdmUiTreeViewItemAttribute : public PdmUiEditorAttribute caf::Signal clicked; - static std::unique_ptr create() { return std::make_unique(); } - private: Tag& operator=( const Tag& rhs ) { return *this; } }; + static std::unique_ptr createTag(); + static std::unique_ptr createTag( const QColor& color, const QColor& backgroundColor, const QString& text ); + static void appendTagToTreeViewItemAttribute( caf::PdmUiEditorAttribute* attribute, const QString& iconString ); + std::vector> tags; }; diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeSelectionEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeSelectionEditor.cpp index 712d771d22..8f64b77103 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeSelectionEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeSelectionEditor.cpp @@ -39,7 +39,6 @@ #include "cafPdmObject.h" #include "cafPdmUiCommandSystemProxy.h" #include "cafPdmUiTreeSelectionQModel.h" -#include "cafQShortenedLabel.h" #include #include @@ -683,17 +682,10 @@ void PdmUiTreeSelectionEditor::slotTextFilterChanged() return; } - QString searchString = m_textFilterLineEdit->text(); - searchString += "*"; - - // Escape the characters '[' and ']' as these have special meaning for a search string - // To be able to search for vector names in brackets, these must be escaped - // See "Wildcard Matching" in Qt documentation - searchString.replace( "[", "\\[" ); - searchString.replace( "]", "\\]" ); - - QRegExp searcher( searchString, Qt::CaseInsensitive, QRegExp::WildcardUnix ); - m_proxyModel->setFilterRegExp( searcher ); + auto regExpString = m_textFilterLineEdit->text() + ".*"; + QRegularExpression regExp( regExpString ); + regExp.setPatternOptions( QRegularExpression::CaseInsensitiveOption ); + m_proxyModel->setFilterRegularExpression( regExp ); updateUi(); } diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeView.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeView.cpp index 0b95535da2..0db23db475 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeView.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeView.cpp @@ -80,10 +80,8 @@ PdmUiTreeView::PdmUiTreeView( QWidget* parent, Qt::WindowFlags f ) connect( m_clearAction, &QAction::triggered, this, &PdmUiTreeView::slotOnClearSearchBox ); m_clearAction->setVisible( false ); -#if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 ) m_layout->addLayout( searchLayout ); connect( m_searchBox, SIGNAL( textChanged( QString ) ), SLOT( slotOnSearchTextChanged() ) ); -#endif m_treeViewEditor = new PdmUiTreeViewEditor(); QWidget* treewidget = m_treeViewEditor->getOrCreateWidget( this ); diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewEditor.cpp index d5f7fbfd22..1701b29442 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewEditor.cpp @@ -49,6 +49,7 @@ #include "cafPdmUiTreeViewQModel.h" #include "cafSelectionManager.h" +#include #include #include #include @@ -194,10 +195,7 @@ QWidget* PdmUiTreeViewEditor::createWidget( QWidget* parent ) m_filterModel = new QSortFilterProxyModel( this ); m_filterModel->setFilterKeyColumn( 0 ); m_filterModel->setFilterCaseSensitivity( Qt::CaseInsensitive ); - -#if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 ) m_filterModel->setRecursiveFilteringEnabled( true ); -#endif m_filterModel->setSourceModel( m_treeViewModel ); m_treeView = new PdmUiTreeViewWidget( m_mainWidget ); @@ -618,7 +616,7 @@ void PdmUiTreeViewEditor::updateItemDelegateForSubTree( const QModelIndex& subRo { size_t indexInParentField = reorderability->indexOf( pdmObject ); { - auto tag = PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = PdmUiTreeViewItemAttribute::createTag(); tag->icon = caf::IconProvider( ":/caf/Up16x16.png" ); tag->selectedOnly = true; if ( reorderability->canItemBeMovedUp( indexInParentField ) ) @@ -633,7 +631,7 @@ void PdmUiTreeViewEditor::updateItemDelegateForSubTree( const QModelIndex& subRo m_delegate->addTag( filterIndex, std::move( tag ) ); } { - auto tag = PdmUiTreeViewItemAttribute::Tag::create(); + auto tag = PdmUiTreeViewItemAttribute::createTag(); tag->icon = IconProvider( ":/caf/Down16x16.png" ); tag->selectedOnly = true; if ( reorderability->canItemBeMovedDown( indexInParentField ) ) diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewItemDelegate.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewItemDelegate.cpp index c0b4fa5d7a..0f093e01ae 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewItemDelegate.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewItemDelegate.cpp @@ -49,6 +49,7 @@ #include "cafPdmUiTreeViewQModel.h" #include "cafSelectionManager.h" +#include #include #include #include diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewQModel.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewQModel.cpp index ec28ec433a..8f2e093828 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewQModel.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiTreeViewQModel.cpp @@ -36,10 +36,11 @@ #include "cafPdmUiTreeViewQModel.h" -#include "cafPdmField.h" -#include "cafPdmObject.h" +#include "cafPdmReferenceHelper.h" #include "cafPdmUiCommandSystemProxy.h" #include "cafPdmUiDragDropInterface.h" +#include "cafPdmUiFieldHandle.h" +#include "cafPdmUiObjectHandle.h" #include "cafPdmUiTreeItemEditor.h" #include "cafPdmUiTreeOrdering.h" #include "cafPdmUiTreeViewEditor.h" diff --git a/Fwk/AppFwk/cafUserInterface/cafPdmUiValueRangeEditor.cpp b/Fwk/AppFwk/cafUserInterface/cafPdmUiValueRangeEditor.cpp index bf3743ff6b..8c86f63aad 100644 --- a/Fwk/AppFwk/cafUserInterface/cafPdmUiValueRangeEditor.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafPdmUiValueRangeEditor.cpp @@ -41,8 +41,6 @@ #include "cafPdmUiDefaultObjectEditor.h" #include "cafPdmUiFieldEditorHandle.h" #include "cafPdmUiLineEditor.h" -#include "cafPdmUiOrdering.h" -#include "cafQShortenedLabel.h" #include #include @@ -259,7 +257,7 @@ QWidget* PdmUiValueRangeEditor::createEditorWidget( QWidget* parent ) auto containerWidget = new QWidget( parent ); auto layout = new QGridLayout(); - layout->setMargin( 0 ); + layout->setContentsMargins( 0, 0, 0, 0 ); containerWidget->setLayout( layout ); m_lineEditMin = new QLineEdit( containerWidget ); diff --git a/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/CMakeLists.txt b/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/CMakeLists.txt index 22bbc636fa..352c64f868 100644 --- a/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/CMakeLists.txt +++ b/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/CMakeLists.txt @@ -2,12 +2,22 @@ cmake_minimum_required(VERSION 3.15) project(cafUserInterface_UnitTests) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets Svg -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL Qt5::Svg) +# Qt +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets Svg + ) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::OpenGL) +endif() include_directories(${CMAKE_CURRENT_SOURCE_DIR} # required for gtest-all.cpp ) @@ -16,13 +26,16 @@ set(PROJECT_FILES cafUserInterface_UnitTests.cpp cafPdmUiTreeViewModelTest.cpp cafPdmUiTreeSelectionQModelTest.cpp gtest/gtest-all.cpp ) -# add the executable -add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +if(CEE_USE_QT6) + qt_add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +else() + add_executable(${PROJECT_NAME} ${PROJECT_FILES}) +endif(CEE_USE_QT6) source_group("" FILES ${PROJECT_FILES}) target_link_libraries( - ${PROJECT_NAME} cafUserInterface ${QT_LIBRARIES} ${THREAD_LIBRARY} + ${PROJECT_NAME} PRIVATE cafUserInterface ${QT_LIBRARIES} ${THREAD_LIBRARY} ) # Copy Qt Dlls @@ -34,3 +47,18 @@ foreach(qtlib ${QT_LIBRARIES}) $ ) endforeach(qtlib) + +# Install +install( + TARGETS ${PROJECT_NAME} + BUNDLE DESTINATION . + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(CEE_USE_QT6) + qt_generate_deploy_app_script( + TARGET ${PROJECT_NAME} OUTPUT_SCRIPT deploy_script + NO_UNSUPPORTED_PLATFORM_ERROR NO_TRANSLATIONS + ) + install(SCRIPT ${deploy_script}) +endif(CEE_USE_QT6) diff --git a/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/cafPdmUiTreeViewModelTest.cpp b/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/cafPdmUiTreeViewModelTest.cpp index 805eaba8e7..1f60b7e568 100644 --- a/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/cafPdmUiTreeViewModelTest.cpp +++ b/Fwk/AppFwk/cafUserInterface/cafUserInterface_UnitTests/cafPdmUiTreeViewModelTest.cpp @@ -34,6 +34,7 @@ class DemoPdmObject : public caf::PdmObject CAF_PDM_InitObject( "DemoPdmObject", "", "Tooltip DemoPdmObject", "WhatsThis DemoPdmObject" ); CAF_PDM_InitFieldNoDefault( &m_simpleObjPtrField, "SimpleObjPtrField", "SimpleObjPtrField", "", "Tooltip", "WhatsThis" ); + m_simpleObjPtrField.uiCapability()->setUiTreeHidden( false ); } ~DemoPdmObject() { m_simpleObjPtrField.deleteChildren(); } diff --git a/Fwk/AppFwk/cafViewer/CMakeLists.txt b/Fwk/AppFwk/cafViewer/CMakeLists.txt index 3563c7b006..33411039bf 100644 --- a/Fwk/AppFwk/cafViewer/CMakeLists.txt +++ b/Fwk/AppFwk/cafViewer/CMakeLists.txt @@ -11,13 +11,23 @@ endif() # These headers need to go through Qt's MOC compiler set(MOC_HEADER_FILES cafViewer.h) -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets OpenGL -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGL) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() add_library( ${PROJECT_NAME} diff --git a/Fwk/AppFwk/cafViewer/cafCadNavigation.cpp b/Fwk/AppFwk/cafViewer/cafCadNavigation.cpp index 483e9fd5ec..416e13ea97 100644 --- a/Fwk/AppFwk/cafViewer/cafCadNavigation.cpp +++ b/Fwk/AppFwk/cafViewer/cafCadNavigation.cpp @@ -144,16 +144,22 @@ bool caf::CadNavigation::handleInputEvent( QInputEvent* inputEvent ) { QWheelEvent* we = static_cast( inputEvent ); - updatePointOfInterestDuringZoomIfNecessary( we->x(), we->y() ); +#if ( QT_VERSION < QT_VERSION_CHECK( 5, 15, 0 ) ) + QPoint cursorPosition = we->pos(); +#else + QPoint cursorPosition = we->position().toPoint(); +#endif + + updatePointOfInterestDuringZoomIfNecessary( cursorPosition.x(), cursorPosition.y() ); if ( m_isRotCenterInitialized ) { int translatedMousePosX, translatedMousePosY; - cvfEventPos( we->x(), we->y(), &translatedMousePosX, &translatedMousePosY ); + cvfEventPos( cursorPosition.x(), cursorPosition.y(), &translatedMousePosX, &translatedMousePosY ); cvf::ref ray = createZoomRay( translatedMousePosX, translatedMousePosY ); - zoomAlongRay( ray.p(), -we->delta() ); + zoomAlongRay( ray.p(), -we->angleDelta().y() ); } isEventHandled = true; } diff --git a/Fwk/AppFwk/cafViewer/cafCeetronNavigation.cpp b/Fwk/AppFwk/cafViewer/cafCeetronNavigation.cpp index bdd52b41be..e511934184 100644 --- a/Fwk/AppFwk/cafViewer/cafCeetronNavigation.cpp +++ b/Fwk/AppFwk/cafViewer/cafCeetronNavigation.cpp @@ -200,13 +200,18 @@ void caf::CeetronNavigation::wheelEvent( QWheelEvent* event ) if ( vpHeight <= 0 ) return; int navDelta = vpHeight / 5; - if ( event->delta() < 0 ) navDelta *= -1; + if ( event->angleDelta().y() < 0 ) navDelta *= -1; - int posY = m_viewer->height() - event->y(); +#if ( QT_VERSION < QT_VERSION_CHECK( 5, 15, 0 ) ) + QPoint cursorPosition = event->pos(); +#else + QPoint cursorPosition = event->position().toPoint(); +#endif + int posY = m_viewer->height() - cursorPosition.y(); - m_trackball->startNavigation( ManipulatorTrackball::WALK, event->x(), posY ); + m_trackball->startNavigation( ManipulatorTrackball::WALK, cursorPosition.x(), posY ); - m_trackball->updateNavigation( event->x(), posY + navDelta ); + m_trackball->updateNavigation( cursorPosition.x(), posY + navDelta ); m_trackball->endNavigation(); m_viewer->updateParallelProjectionHeightFromMoveZoom( m_pointOfInterest ); diff --git a/Fwk/AppFwk/cafViewer/cafCeetronPlusNavigation.cpp b/Fwk/AppFwk/cafViewer/cafCeetronPlusNavigation.cpp index e6df70a6d0..b55c1f72de 100644 --- a/Fwk/AppFwk/cafViewer/cafCeetronPlusNavigation.cpp +++ b/Fwk/AppFwk/cafViewer/cafCeetronPlusNavigation.cpp @@ -185,16 +185,22 @@ bool caf::CeetronPlusNavigation::handleInputEvent( QInputEvent* inputEvent ) { QWheelEvent* we = static_cast( inputEvent ); - updatePointOfInterestDuringZoomIfNecessary( we->x(), we->y() ); +#if ( QT_VERSION < QT_VERSION_CHECK( 5, 15, 0 ) ) + QPoint cursorPosition = we->pos(); +#else + QPoint cursorPosition = we->position().toPoint(); +#endif + + updatePointOfInterestDuringZoomIfNecessary( cursorPosition.x(), cursorPosition.y() ); if ( m_isRotCenterInitialized ) { int translatedMousePosX, translatedMousePosY; - cvfEventPos( we->x(), we->y(), &translatedMousePosX, &translatedMousePosY ); + cvfEventPos( cursorPosition.x(), cursorPosition.y(), &translatedMousePosX, &translatedMousePosY ); cvf::ref ray = createZoomRay( translatedMousePosX, translatedMousePosY ); - zoomAlongRay( ray.p(), we->delta() ); + zoomAlongRay( ray.p(), we->angleDelta().y() ); } isEventHandled = true; } diff --git a/Fwk/AppFwk/cafViewer/cafOpenGLWidget.cpp b/Fwk/AppFwk/cafViewer/cafOpenGLWidget.cpp index c343eccc69..9105fae538 100644 --- a/Fwk/AppFwk/cafViewer/cafOpenGLWidget.cpp +++ b/Fwk/AppFwk/cafViewer/cafOpenGLWidget.cpp @@ -37,7 +37,7 @@ #include "cafOpenGLWidget.h" #include "cvfBase.h" #include "cvfOpenGLContextGroup.h" -#include "cvfqtCvfBoundQGLContext.h" +#include "cvfqtCvfBoundQGLContext_deprecated.h" namespace caf { @@ -58,22 +58,25 @@ OpenGLWidget::OpenGLWidget( cvf::OpenGLContextGroup* contextGroup, QWidget* parent, OpenGLWidget* shareWidget, Qt::WindowFlags f ) - : QGLWidget( new cvfqt::CvfBoundQGLContext( contextGroup, format ), parent, shareWidget, f ) + : QGLWidget( new cvfqt::CvfBoundQGLContext_deprecated( contextGroup, format ), parent, shareWidget, f ) { if ( isValid() ) { cvf::ref myContext = cvfOpenGLContext(); if ( myContext.notNull() ) { + cvf::OpenGLContextGroup* myOwnerContextGroup = myContext->group(); + if ( shareWidget ) { // We need to check if we actually got a context that shares resources with shareWidget. cvf::ref shareContext = shareWidget->cvfOpenGLContext(); + CVF_ASSERT( myOwnerContextGroup == shareContext->group() ); if ( isSharing() ) { - CVF_ASSERT( myContext->group() == shareContext->group() ); - myContext->initializeContext(); + makeCurrent(); + myOwnerContextGroup->initializeContextGroup( myContext.p() ); } else { @@ -81,13 +84,14 @@ OpenGLWidget::OpenGLWidget( cvf::OpenGLContextGroup* contextGroup, // since the construction process above has already optimistically added the new context to the // existing group. In this case, the newly context is basically defunct so we just shut it down // (which will also remove it from the group) - myContext->shutdownContext(); + myOwnerContextGroup->contextAboutToBeShutdown( myContext.p() ); CVF_ASSERT( myContext->group() == nullptr ); } } else { - myContext->initializeContext(); + makeCurrent(); + contextGroup->initializeContextGroup( myContext.p() ); } } } @@ -106,7 +110,7 @@ OpenGLWidget::OpenGLWidget( cvf::OpenGLContextGroup* contextGroup, /// If the context is not valid, sharing failed and the newly created widget/context be discarded. //-------------------------------------------------------------------------------------------------- OpenGLWidget::OpenGLWidget( OpenGLWidget* shareWidget, QWidget* parent, Qt::WindowFlags f ) - : QGLWidget( new cvfqt::CvfBoundQGLContext( shareWidget->cvfOpenGLContext()->group(), shareWidget->format() ), + : QGLWidget( new cvfqt::CvfBoundQGLContext_deprecated( shareWidget->cvfOpenGLContext()->group(), shareWidget->format() ), parent, shareWidget, f ) @@ -118,13 +122,16 @@ OpenGLWidget::OpenGLWidget( OpenGLWidget* shareWidget, QWidget* parent, Qt::Wind cvf::ref myContext = cvfOpenGLContext(); if ( myContext.notNull() ) { + cvf::OpenGLContextGroup* myOwnerContextGroup = myContext->group(); + // We need to check if we actually got a context that shares resources with shareWidget. if ( isSharing() ) { if ( isValid() ) { CVF_ASSERT( myContext->group() == shareContext->group() ); - myContext->initializeContext(); + makeCurrent(); + myOwnerContextGroup->initializeContextGroup( myContext.p() ); } } else @@ -133,7 +140,7 @@ OpenGLWidget::OpenGLWidget( OpenGLWidget* shareWidget, QWidget* parent, Qt::Wind // the construction process above has already optimistically added the new context to the existing group. // In this case, the newly context is basically defunct so we just shut it down (which will also remove it // from the group) - myContext->shutdownContext(); + myOwnerContextGroup->contextAboutToBeShutdown( myContext.p() ); CVF_ASSERT( myContext->group() == nullptr ); } } @@ -144,8 +151,9 @@ OpenGLWidget::OpenGLWidget( OpenGLWidget* shareWidget, QWidget* parent, Qt::Wind //-------------------------------------------------------------------------------------------------- cvf::OpenGLContext* OpenGLWidget::cvfOpenGLContext() const { - const QGLContext* qglContext = context(); - const cvfqt::CvfBoundQGLContext* contextBinding = dynamic_cast( qglContext ); + const QGLContext* qglContext = context(); + const cvfqt::CvfBoundQGLContext_deprecated* contextBinding = + dynamic_cast( qglContext ); CVF_ASSERT( contextBinding ); return contextBinding->cvfOpenGLContext(); @@ -161,7 +169,14 @@ void OpenGLWidget::cvfShutdownOpenGLContext() cvf::ref myContext = cvfOpenGLContext(); if ( myContext.notNull() ) { - myContext->shutdownContext(); + cvf::OpenGLContextGroup* myOwnerContextGroup = myContext->group(); + + // If shutdown has already been called, the context is no longer member of any group + if ( myOwnerContextGroup ) + { + makeCurrent(); + myOwnerContextGroup->contextAboutToBeShutdown( myContext.p() ); + } } } diff --git a/Fwk/AppFwk/cafViewer/cafViewer.cpp b/Fwk/AppFwk/cafViewer/cafViewer.cpp index d4bd7f2a27..1652b9b7c1 100644 --- a/Fwk/AppFwk/cafViewer/cafViewer.cpp +++ b/Fwk/AppFwk/cafViewer/cafViewer.cpp @@ -42,16 +42,13 @@ #include "cafPointOfInterestVisualizer.h" #include "cvfCamera.h" -#include "cvfDebugTimer.h" #include "cvfDrawable.h" -#include "cvfDrawableGeo.h" #include "cvfDynamicUniformSet.h" #include "cvfFramebufferObject.h" #include "cvfHitItemCollection.h" -#include "cvfManipulatorTrackball.h" #include "cvfModel.h" #include "cvfOpenGLCapabilities.h" -#include "cvfOpenGLResourceManager.h" +#include "cvfOpenGLUtils.h" #include "cvfOverlayImage.h" #include "cvfPart.h" #include "cvfRay.h" @@ -65,17 +62,18 @@ #include "cvfShaderSourceProvider.h" #include "cvfSingleQuadRenderingGenerator.h" #include "cvfTextureImage.h" -#include "cvfTransform.h" #include "cvfUniform.h" #include "cvfUniformSet.h" -#include "cvfqtOpenGLContext.h" +#include "cvfqtOpenGLWidget.h" #include "cvfqtPerformanceInfoHud.h" #include "cvfqtUtils.h" #include #include #include +#include +#include #include @@ -108,14 +106,13 @@ class GlobalViewerDynUniformSet : public cvf::DynamicUniformSet } // namespace caf -std::list caf::Viewer::sm_viewers; cvf::ref caf::Viewer::sm_openGLContextGroup; //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -caf::Viewer::Viewer( const QGLFormat& format, QWidget* parent ) - : caf::OpenGLWidget( contextGroup(), format, nullptr, sharedWidget() ) +caf::Viewer::Viewer( QWidget* parent ) + : cvfqt::OpenGLWidget( contextGroup(), parent ) , m_navigationPolicy( nullptr ) , m_navigationPolicyEnabled( true ) , m_defaultPerspectiveNearPlaneDistance( 0.05 ) @@ -176,12 +173,7 @@ caf::Viewer::Viewer( const QGLFormat& format, QWidget* parent ) m_overlayImage->setBlending( cvf::OverlayImage::TEXTURE_ALPHA ); m_overlayImage->setLayoutFixedPosition( cvf::Vec2i( 0, 0 ) ); - setupMainRendering(); - setupRenderingSequence(); - m_showPerfInfoHud = false; - - sm_viewers.push_back( this ); } //-------------------------------------------------------------------------------------------------- @@ -189,10 +181,6 @@ caf::Viewer::Viewer( const QGLFormat& format, QWidget* parent ) //-------------------------------------------------------------------------------------------------- caf::Viewer::~Viewer() { - this->cvfShutdownOpenGLContext(); - sm_viewers.remove( this ); - - // To delete the layout widget if ( m_layoutWidget ) m_layoutWidget->deleteLater(); } @@ -214,14 +202,6 @@ void caf::Viewer::setupMainRendering() m_mainRendering->addGlobalDynamicUniformSet( m_globalUniformSet.p() ); m_comparisonMainRendering->addGlobalDynamicUniformSet( m_globalUniformSet.p() ); - // Set fixed function rendering if QGLFormat does not support directRendering - if ( !this->format().directRendering() ) - { - m_mainRendering->renderEngine()->enableForcedImmediateMode( true ); - m_comparisonMainRendering->renderEngine()->enableForcedImmediateMode( true ); - m_overlayItemsRendering->renderEngine()->enableForcedImmediateMode( true ); - } - if ( contextGroup()->capabilities() && contextGroup()->capabilities()->hasCapability( cvf::OpenGLCapabilities::FRAMEBUFFER_OBJECT ) ) { @@ -278,14 +258,19 @@ void caf::Viewer::setupRenderingSequence() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -caf::Viewer* caf::Viewer::sharedWidget() +void caf::Viewer::deleteFboOpenGLResources() { - if ( !sm_viewers.empty() ) + // The OpenGL resources can be deleted at any time. CeeViz does not delete resources for FBOs, so delete them manually + + if ( m_offscreenFbo.notNull() ) { - return *( sm_viewers.begin() ); - } + if ( auto context = cvfOpenGLContext() ) + { + context->makeCurrent(); - return nullptr; + m_offscreenFbo->deleteOrReleaseOpenGLResources( context ); + } + } } //-------------------------------------------------------------------------------------------------- @@ -589,21 +574,6 @@ bool caf::Viewer::calculateNearFarPlanes( const cvf::Rendering* rendering, //-------------------------------------------------------------------------------------------------- bool caf::Viewer::event( QEvent* e ) { - // The most reliable way we have found of detecting when an OpenGL context is about to be destroyed is - // hooking into the QEvent::PlatformSurface event and checking for the SurfaceAboutToBeDestroyed event type. - // From the Qt doc: - // The underlying native surface will be destroyed immediately after this event. - // The SurfaceAboutToBeDestroyed event type is useful as a means of stopping rendering to a platform window before - // it is destroyed. - if ( e->type() == QEvent::PlatformSurface ) - { - QPlatformSurfaceEvent* platformSurfaceEvent = static_cast( e ); - if ( platformSurfaceEvent->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed ) - { - cvfShutdownOpenGLContext(); - } - } - if ( e && m_navigationPolicy.notNull() && m_navigationPolicyEnabled ) { switch ( e->type() ) @@ -625,18 +595,14 @@ bool caf::Viewer::event( QEvent* e ) case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: - if ( m_navigationPolicy->handleInputEvent( static_cast( e ) ) ) - return true; - else - return QGLWidget::event( e ); + if ( m_navigationPolicy->handleInputEvent( static_cast( e ) ) ) return true; break; default: - return QGLWidget::event( e ); break; } } - else - return QGLWidget::event( e ); + + return cvfqt::OpenGLWidget::event( e ); } //-------------------------------------------------------------------------------------------------- @@ -783,10 +749,8 @@ bool caf::Viewer::isPerfInfoHudEnabled() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void caf::Viewer::paintEvent( QPaintEvent* event ) +void caf::Viewer::paintGL() { - makeCurrent(); - cvf::ref myOglContext = cvfOpenGLContext(); CVF_CHECK_OGL( myOglContext.p() ); CVF_ASSERT( myOglContext->isContextValid() ); @@ -850,7 +814,7 @@ void caf::Viewer::paintEvent( QPaintEvent* event ) if ( isShadersSupported() ) { - cvfqt::OpenGLContext::saveOpenGLState( myOglContext.p() ); + cvf::OpenGLUtils::pushOpenGLState( myOglContext.p() ); } optimizeClippingPlanes(); @@ -880,12 +844,28 @@ void caf::Viewer::paintEvent( QPaintEvent* event ) if ( isShadersSupported() ) { - cvfqt::OpenGLContext::restoreOpenGLState( myOglContext.p() ); + cvf::OpenGLUtils::popOpenGLState( myOglContext.p() ); } painter.endNativePainting(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void caf::Viewer::onWidgetOpenGLReady() +{ + setupMainRendering(); + setupRenderingSequence(); + + QOpenGLContext* myQtOpenGLContext = context(); + CVF_ASSERT( myQtOpenGLContext ); + CVF_ASSERT( myQtOpenGLContext->isValid() ); + + // Connect to signal so we get notified when Qt's OpenGL context is about to be destroyed + connect( myQtOpenGLContext, &QOpenGLContext::aboutToBeDestroyed, this, &Viewer::deleteFboOpenGLResources ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -1176,15 +1156,7 @@ void caf::Viewer::updateCachedValuesInScene() //-------------------------------------------------------------------------------------------------- bool caf::Viewer::isShadersSupported() { - QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags(); - bool hasOpenGL_2_0 = QGLFormat::OpenGL_Version_2_0 & flags; - - if ( hasOpenGL_2_0 ) - { - return true; - } - - return false; + return true; } //-------------------------------------------------------------------------------------------------- @@ -1192,55 +1164,10 @@ bool caf::Viewer::isShadersSupported() //-------------------------------------------------------------------------------------------------- QImage caf::Viewer::snapshotImage() { - // Qt5 : Call paintEvent() manually to make sure invisible widgets are rendered properly - // If this call is skipped, we get an assert in cvf::FramebufferObject::bind() - paintEvent( nullptr ); - - QImage image; - if ( m_offscreenFbo.notNull() && m_offscreenViewportWidth > 0 && m_offscreenViewportHeight > 0 ) - { - cvf::ref myOglContext = cvfOpenGLContext(); - - m_offscreenFbo->bind( myOglContext.p() ); + auto image = grabFramebuffer(); - GLint iOldPackAlignment = 0; - glGetIntegerv( GL_PACK_ALIGNMENT, &iOldPackAlignment ); - glPixelStorei( GL_PACK_ALIGNMENT, 1 ); - CVF_CHECK_OGL( myOglContext.p() ); - - cvf::UByteArray arr( 3 * m_offscreenViewportWidth * m_offscreenViewportHeight ); - - glReadPixels( 0, - 0, - static_cast( m_offscreenViewportWidth ), - static_cast( m_offscreenViewportHeight ), - GL_RGB, - GL_UNSIGNED_BYTE, - arr.ptr() ); - CVF_CHECK_OGL( myOglContext.p() ); - - glPixelStorei( GL_PACK_ALIGNMENT, iOldPackAlignment ); - CVF_CHECK_OGL( myOglContext.p() ); - - cvf::FramebufferObject::useDefaultWindowFramebuffer( myOglContext.p() ); - - cvf::TextureImage texImage; - texImage.setFromRgb( arr.ptr(), m_offscreenViewportWidth, m_offscreenViewportHeight ); - - image = cvfqt::Utils::toQImage( texImage ); - } - else - { - // Code moved from RimView::snapshotWindowContent() - - GLint currentReadBuffer; - glGetIntegerv( GL_READ_BUFFER, ¤tReadBuffer ); - - glReadBuffer( GL_FRONT ); - image = this->grabFrameBuffer(); - - glReadBuffer( currentReadBuffer ); - } + // Convert to RGB32 format to avoid visual artifacts related to alpha channel + image.reinterpretAsFormat( QImage::Format_RGB32 ); return image; } diff --git a/Fwk/AppFwk/cafViewer/cafViewer.h b/Fwk/AppFwk/cafViewer/cafViewer.h index 981745cc4f..36d624f0d0 100644 --- a/Fwk/AppFwk/cafViewer/cafViewer.h +++ b/Fwk/AppFwk/cafViewer/cafViewer.h @@ -36,16 +36,13 @@ #pragma once -#include "cvfAssert.h" -#include "cvfBase.h" #include "cvfCollection.h" #include "cvfObject.h" #include "cvfOpenGL.h" #include "cvfRect.h" -#include "cvfRenderingScissor.h" #include "cvfVector3.h" -#include "cafOpenGLWidget.h" +#include "cvfqtOpenGLWidget.h" namespace cvf { @@ -61,6 +58,7 @@ class Scene; class Texture; class TextureImage; class RayIntersectSpec; +class RenderingScissor; } // namespace cvf namespace caf @@ -79,11 +77,11 @@ namespace caf class GlobalViewerDynUniformSet; class ScissorChanger; -class Viewer : public caf::OpenGLWidget +class Viewer : public cvfqt::OpenGLWidget { Q_OBJECT public: - Viewer( const QGLFormat& format, QWidget* parent ); + Viewer( QWidget* parent ); ~Viewer() override; QWidget* layoutWidget() { return m_layoutWidget; } // Use this when putting it into something @@ -194,6 +192,8 @@ public slots: // Method to override if painting directly on the OpenGl Canvas is needed. virtual void paintOverlayItems( QPainter* painter ){}; + void onWidgetOpenGLReady() override; + // Overridable methods to setup the render system virtual void optimizeClippingPlanes(); @@ -204,7 +204,7 @@ public slots: // Standard overrides. Not for overriding void resizeGL( int width, int height ) override; - void paintEvent( QPaintEvent* event ) override; + void paintGL() override; // Support the navigation policy concept bool event( QEvent* e ) override; @@ -234,6 +234,7 @@ public slots: void updateCamera( int width, int height ); void releaseOGlResourcesForCurrentFrame(); void debugShowRenderingSequencePartNames(); + void deleteFboOpenGLResources(); int clampFrameIndex( int frameIndex ) const; @@ -249,10 +250,8 @@ public slots: void updateOverlayImagePresence(); // System to make sure we share OpenGL resources - static Viewer* sharedWidget(); static cvf::OpenGLContextGroup* contextGroup(); - static std::list sm_viewers; static cvf::ref sm_openGLContextGroup; caf::FrameAnimationControl* m_animationControl; diff --git a/Fwk/AppFwk/cafVizExtensions/CMakeLists.txt b/Fwk/AppFwk/cafVizExtensions/CMakeLists.txt index 464207036f..bc552e2022 100644 --- a/Fwk/AppFwk/cafVizExtensions/CMakeLists.txt +++ b/Fwk/AppFwk/cafVizExtensions/CMakeLists.txt @@ -10,13 +10,26 @@ endif() find_package(OpenGL) # Qt -find_package( - Qt5 - COMPONENTS - REQUIRED Core Gui Widgets OpenGL -) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) -qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGL) + qt_standard_project_setup() + set_property( + SOURCE cafTransparentWBRenderConfiguration.cpp PROPERTY SKIP_AUTOMOC ON + ) +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui Widgets OpenGL + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() add_library( ${PROJECT_NAME} diff --git a/Fwk/AppFwk/cafVizExtensions/cafHexGridIntersectionTools/cafHexGridIntersectionTools_UnitTest/CMakeLists.txt b/Fwk/AppFwk/cafVizExtensions/cafHexGridIntersectionTools/cafHexGridIntersectionTools_UnitTest/CMakeLists.txt index 4838dcce1d..21a538b759 100644 --- a/Fwk/AppFwk/cafVizExtensions/cafHexGridIntersectionTools/cafHexGridIntersectionTools_UnitTest/CMakeLists.txt +++ b/Fwk/AppFwk/cafVizExtensions/cafHexGridIntersectionTools/cafHexGridIntersectionTools_UnitTest/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8.12) - project(cafHexGridIntersectionTools_UnitTests) if(MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) diff --git a/Fwk/AppFwk/cafVizExtensions/cafLine.h b/Fwk/AppFwk/cafVizExtensions/cafLine.h index 2c549a2361..272c0548e5 100644 --- a/Fwk/AppFwk/cafVizExtensions/cafLine.h +++ b/Fwk/AppFwk/cafVizExtensions/cafLine.h @@ -56,6 +56,8 @@ class Line Line findLineBetweenNearestPoints( const Line& otherLine, bool* withinLineSegments = nullptr ); + cvf::Vector3 closestPointOnLine( const cvf::Vector3& point ) const; + private: cvf::Vector3 m_start; cvf::Vector3 m_end; diff --git a/Fwk/AppFwk/cafVizExtensions/cafLine.inl b/Fwk/AppFwk/cafVizExtensions/cafLine.inl index a0795abc07..02c110d431 100644 --- a/Fwk/AppFwk/cafVizExtensions/cafLine.inl +++ b/Fwk/AppFwk/cafVizExtensions/cafLine.inl @@ -105,3 +105,27 @@ caf::Line caf::Line::findLineBetweenNearestPoints( const Line& otherLine, } return Line( start() + s * d1, otherLine.start() + t * d2 ); } + +//-------------------------------------------------------------------------------------------------- +/// Returns the closest point on the line segment to the given point +/// From https://paulbourke.net/geometry/pointlineplane/ +//-------------------------------------------------------------------------------------------------- +template +cvf::Vector3 caf::Line::closestPointOnLine( const cvf::Vector3& point ) const +{ + S distance = vector().length(); + + const double u = ( ( ( point.x() - start().x() ) * ( end().x() - start().x() ) ) + + ( ( point.y() - start().y() ) * ( end().y() - start().y() ) ) + + ( ( point.z() - start().z() ) * ( end().z() - start().z() ) ) ) / + ( distance * distance ); + + if ( u < 0.0 ) return start(); + if ( u > 1.0 ) return end(); + + cvf::Vector3 projectedPoint( ( start().x() + u * ( end().x() - start().x() ) ), + ( start().y() + u * ( end().y() - start().y() ) ), + ( start().z() + u * ( end().z() - start().z() ) ) ); + + return projectedPoint; +} diff --git a/Fwk/CMakeLists.txt b/Fwk/CMakeLists.txt index ebc03e7082..14cf32a91e 100644 --- a/Fwk/CMakeLists.txt +++ b/Fwk/CMakeLists.txt @@ -32,9 +32,22 @@ if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNO_DEBUG") endif() - -find_package(Qt5 COMPONENTS REQUIRED Core Gui OpenGL Widgets) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::OpenGL Qt5::Widgets) +if(CEE_USE_QT6) + find_package( + Qt6 + COMPONENTS + REQUIRED Core Gui OpenGL Widgets + ) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::OpenGL Qt6::Widgets) + qt_standard_project_setup() +else() + find_package( + Qt5 + COMPONENTS + REQUIRED Core Gui OpenGL Widgets + ) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::OpenGL Qt5::Widgets) +endif() # Libraries add_subdirectory(AppFwk/cafProjectDataModel/cafPdmCore) diff --git a/Fwk/VizFwk/CMake/!CMake.vcxproj b/Fwk/VizFwk/CMake/!CMake.vcxproj deleted file mode 100644 index bba6ee8521..0000000000 --- a/Fwk/VizFwk/CMake/!CMake.vcxproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - - NotBuildable - Win32 - - - - {FB015304-89D5-4093-B01A-0E7F642971DC} - CMake - - - - Utility - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/CMake/!CMake.vcxproj.filters b/Fwk/VizFwk/CMake/!CMake.vcxproj.filters deleted file mode 100644 index ee51bd897c..0000000000 --- a/Fwk/VizFwk/CMake/!CMake.vcxproj.filters +++ /dev/null @@ -1,25 +0,0 @@ - - - - - for CeeViz - - - for UnitTests - - - Utils - - - - - {3e72b0a1-06b6-459f-9607-d9fa896d7f8c} - - - {51e511a3-e51f-4744-bff6-f658fccf0863} - - - {8764f605-13cc-4037-9f2b-fcae94e99ae9} - - - \ No newline at end of file diff --git a/Fwk/VizFwk/CMakeLists.txt b/Fwk/VizFwk/CMakeLists.txt index f977e4e8f1..dd046624ac 100644 --- a/Fwk/VizFwk/CMakeLists.txt +++ b/Fwk/VizFwk/CMakeLists.txt @@ -1,8 +1,15 @@ -cmake_minimum_required(VERSION 2.8.12) +cmake_minimum_required(VERSION 3.15) project(VizFramework) +if (CEE_CEEVIZ_ROOT) + message(STATUS "CEE_CEEVIZ_ROOT: ${CEE_CEEVIZ_ROOT}") +else() + set(CEE_CEEVIZ_ROOT ${PROJECT_SOURCE_DIR}) + message(STATUS "Setting CEE_CEEVIZ_ROOT to ${CEE_CEEVIZ_ROOT}") +endif() + # Determine if we're being run stand-alone or invoked from some other project set(CEE_STAND_ALONE ON) if (PROJECT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) @@ -20,6 +27,8 @@ if (CEE_STAND_ALONE) endif() include(CMake/Utils/ceeDetermineCompilerFlags.cmake) + + set(CMAKE_CXX_STANDARD 17) endif() @@ -44,32 +53,46 @@ add_subdirectory(ThirdParty/FreeType) add_subdirectory(LibUtilities) - option(CEE_BUILD_GUI_QT "Build GUI library for Qt" ON) if (CEE_BUILD_GUI_QT) + option(CEE_USE_QT6 "Use Qt6" OFF) option(CEE_USE_QT5 "Use Qt5" OFF) add_subdirectory(LibGuiQt) endif() if (CEE_STAND_ALONE) - option(CEE_BUILD_UNIT_TESTS "Build unit tests" ON) - if (CEE_BUILD_UNIT_TESTS) - add_subdirectory(Tests) - endif() + option(CEE_BUILD_TEST_APPS "Build test apps" ON) +endif() +if (CEE_BUILD_UNIT_TESTS OR CEE_BUILD_TEST_APPS) + # Add CeeViz's root source dir as a preprocessor directive so unit tests and test apps can determine where to find the resources they want. + add_definitions(-DCVF_CEEVIZ_ROOT_SOURCE_DIR="${CEE_CEEVIZ_ROOT}") +endif() - option(CEE_BUILD_TEST_APPS "Build test apps" ON) - if (CEE_BUILD_TEST_APPS) - if (CEE_BUILD_GUI_QT) - # For now, build the snippet libs here - add_subdirectory(Tests/SnippetsBasis) - - add_subdirectory(TestApps/Qt/QtMinimal) - add_subdirectory(TestApps/Qt/QtMultiView) - add_subdirectory(TestApps/Qt/QtSnippetRunner) +if (CEE_BUILD_UNIT_TESTS) + add_subdirectory(Tests) +endif() + +if (CEE_BUILD_TEST_APPS) + # For now, build the snippet libs here + add_subdirectory(Tests/SnippetsBasis) + + if (CEE_BUILD_GUI_QT) + add_subdirectory(TestApps/Qt/QtMinimal) + add_subdirectory(TestApps/Qt/QtMultiView) + add_subdirectory(TestApps/Qt/QtTestBenchOpenGLWidget) + add_subdirectory(TestApps/Qt/QtSnippetRunner) + + if (CEE_USE_QT5) + add_subdirectory(TestApps/Qt/QtMinimal_GLWidget) + add_subdirectory(TestApps/Qt/QtMinimal_deprecated) + add_subdirectory(TestApps/Qt/QtMultiView_deprecated) endif() endif() + if (WIN32) + add_subdirectory(TestApps/Win32/Win32SnippetRunner) + endif() endif() diff --git a/Fwk/VizFwk/Doxygen/!Doxygen.vcxproj b/Fwk/VizFwk/Doxygen/!Doxygen.vcxproj deleted file mode 100644 index c4b85e9faa..0000000000 --- a/Fwk/VizFwk/Doxygen/!Doxygen.vcxproj +++ /dev/null @@ -1,44 +0,0 @@ - - - - - Doxygen - Win32 - - - - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03} - Doxygen - - - - Utility - - - - - - - $(ProjectDir)\html\ - - - $(ProjectDir)\html\ - - - *.html;*.css;*.map;*.md5;*.dot;*.png;*.gif;*.js;installdox - - - - - - Document - RunDoxygen.bat - Running Doxygen... - html/ToForceRebuildEveryTime.html - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Doxygen/!Doxygen.vcxproj.filters b/Fwk/VizFwk/Doxygen/!Doxygen.vcxproj.filters deleted file mode 100644 index c8bc3a518d..0000000000 --- a/Fwk/VizFwk/Doxygen/!Doxygen.vcxproj.filters +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibCore/CMakeLists.txt b/Fwk/VizFwk/LibCore/CMakeLists.txt index b08f9f82bf..517acbf9e9 100644 --- a/Fwk/VizFwk/LibCore/CMakeLists.txt +++ b/Fwk/VizFwk/LibCore/CMakeLists.txt @@ -112,5 +112,11 @@ target_include_directories(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR} ) +if (UNIX AND NOT APPLE) + # Our core library has dependencies on librt and libpthread for timers and mutex. + target_link_libraries(${PROJECT_NAME} -lrt -lpthread) +endif() + + set(PROJECT_FILES ${CEE_HEADER_FILES} ${CEE_SOURCE_FILES}) source_group("" FILES ${PROJECT_FILES}) diff --git a/Fwk/VizFwk/LibCore/LibCore.vcxproj b/Fwk/VizFwk/LibCore/LibCore.vcxproj deleted file mode 100644 index 2e5f67e714..0000000000 --- a/Fwk/VizFwk/LibCore/LibCore.vcxproj +++ /dev/null @@ -1,326 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {A9C7A239-B761-A892-BF34-5AECA0D9EE88} - LibCore - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibCore/LibCore.vcxproj.filters b/Fwk/VizFwk/LibCore/LibCore.vcxproj.filters deleted file mode 100644 index 5d549ba813..0000000000 --- a/Fwk/VizFwk/LibCore/LibCore.vcxproj.filters +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibCore/cvfBase.h b/Fwk/VizFwk/LibCore/cvfBase.h index 6b6e8bf6e6..9944b8380e 100644 --- a/Fwk/VizFwk/LibCore/cvfBase.h +++ b/Fwk/VizFwk/LibCore/cvfBase.h @@ -68,7 +68,7 @@ // Makes it easier to check on the current GCC version #ifdef __GNUC__ // 40302 means version 4.3.2. -# define CVF_GCC_VER (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) +#define CVF_GCC_VER (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // Helper macro to disable (ignore) compiler warnings on GCC @@ -80,6 +80,15 @@ #define CVF_GCC_DIAGNOSTIC_IGNORE(OPTION_STRING) #endif +// Helper macros for push/pop of GCC diagnostics, available from GCC 4.6.x +#if defined(__GNUC__) && (CVF_GCC_VER >= 40600) +#define CVF_GCC_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") +#define CVF_GCC_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#else +#define CVF_GCC_DIAGNOSTIC_PUSH +#define CVF_GCC_DIAGNOSTIC_POP +#endif + #if defined(CVF_LINUX) || defined(CVF_IOS) || defined(CVF_OSX) || defined(CVF_ANDROID) // Used by int64_t on *nix below @@ -123,6 +132,13 @@ typedef __int64 int64; typedef int64_t int64; #endif +// 64bit unsigned integer support via the int64 type +#ifdef WIN32 +typedef unsigned __int64 uint64; +#elif defined(CVF_LINUX) || defined(CVF_IOS) || defined(CVF_OSX) || defined(CVF_ANDROID) +typedef uint64_t uint64; +#endif + } #include "cvfConfigCore.h" diff --git a/Fwk/VizFwk/LibCore/cvfLibCore.h b/Fwk/VizFwk/LibCore/cvfLibCore.h index 88238dfa22..850ba4f7c4 100644 --- a/Fwk/VizFwk/LibCore/cvfLibCore.h +++ b/Fwk/VizFwk/LibCore/cvfLibCore.h @@ -57,6 +57,7 @@ #include "cvfFlags.h" #include "cvfFunctorRange.h" #include "cvfLogger.h" +#include "cvfLogManager.h" #include "cvfMath.h" #include "cvfMatrix4.h" #include "cvfObject.h" diff --git a/Fwk/VizFwk/LibFreeType/CMakeLists.txt b/Fwk/VizFwk/LibFreeType/CMakeLists.txt index 59eb8dc8aa..bbd8e6523d 100644 --- a/Fwk/VizFwk/LibFreeType/CMakeLists.txt +++ b/Fwk/VizFwk/LibFreeType/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibFreeType) diff --git a/Fwk/VizFwk/LibFreeType/LibFreeType.vcxproj b/Fwk/VizFwk/LibFreeType/LibFreeType.vcxproj deleted file mode 100644 index a9a9f47287..0000000000 --- a/Fwk/VizFwk/LibFreeType/LibFreeType.vcxproj +++ /dev/null @@ -1,244 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {2667AC1D-CA80-42F8-8644-DDB58D342FF2} - LibFreeType - LibFreeType - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - - - - - Level4 - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - - - - - Level4 - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - - - - - Level4 - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - - - - - Level4 - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibIo;../LibRender;../LibUtilities;../ThirdParty/FreeType/include - - - true - true - true - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibFreeType/LibFreeType.vcxproj.filters b/Fwk/VizFwk/LibFreeType/LibFreeType.vcxproj.filters deleted file mode 100644 index 4add469679..0000000000 --- a/Fwk/VizFwk/LibFreeType/LibFreeType.vcxproj.filters +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibGeometry/CMakeLists.txt b/Fwk/VizFwk/LibGeometry/CMakeLists.txt index 00c9018dd8..dd6a5b49aa 100644 --- a/Fwk/VizFwk/LibGeometry/CMakeLists.txt +++ b/Fwk/VizFwk/LibGeometry/CMakeLists.txt @@ -9,6 +9,11 @@ endif() # Use our strict compile flags set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STRICT_CXX_FLAGS}") +# For now, disable warning about unknown pragmas locally here (due to usage of OpenMP) +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-pragmas") +endif() + set(CEE_HEADER_FILES cvfArrowGenerator.h diff --git a/Fwk/VizFwk/LibGeometry/LibGeometry.vcxproj b/Fwk/VizFwk/LibGeometry/LibGeometry.vcxproj deleted file mode 100644 index fdea6f8510..0000000000 --- a/Fwk/VizFwk/LibGeometry/LibGeometry.vcxproj +++ /dev/null @@ -1,287 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90} - LibGeometry - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibGeometry/LibGeometry.vcxproj.filters b/Fwk/VizFwk/LibGeometry/LibGeometry.vcxproj.filters deleted file mode 100644 index c5b73ae9b8..0000000000 --- a/Fwk/VizFwk/LibGeometry/LibGeometry.vcxproj.filters +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibGeometry/cvfBoundingBoxTree.cpp b/Fwk/VizFwk/LibGeometry/cvfBoundingBoxTree.cpp index 54666fd83a..d38c9c83d8 100644 --- a/Fwk/VizFwk/LibGeometry/cvfBoundingBoxTree.cpp +++ b/Fwk/VizFwk/LibGeometry/cvfBoundingBoxTree.cpp @@ -716,6 +716,7 @@ std::string AABBTree::treeInfo() const { size_t treeSizeInMB = treeSize() / (1024u *1024u); auto text = "Tree size : " + std::to_string(treeSizeInMB) + "[MB] \n"; + if (treeSize() == 0) return text; text += "Num leaves: " + std::to_string(leavesCount()) + "\n"; diff --git a/Fwk/VizFwk/LibGuiQt/CMakeLists.txt b/Fwk/VizFwk/LibGuiQt/CMakeLists.txt index f0c5385f35..dfe208df6f 100644 --- a/Fwk/VizFwk/LibGuiQt/CMakeLists.txt +++ b/Fwk/VizFwk/LibGuiQt/CMakeLists.txt @@ -10,19 +10,31 @@ endif() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_BASE_CXX_FLAGS}") if (CMAKE_COMPILER_IS_GNUCXX) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") + # Due to usage of OpenMP, disable warning about unknown pragmas + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long -Wno-unknown-pragmas") endif() find_package(OpenGL) -find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) -set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + +message(STATUS "In LibGuiQt, CEE_USE_QT6=${CEE_USE_QT6}") +message(STATUS "In LibGuiQt, CEE_USE_QT5=${CEE_USE_QT5}") +if (CEE_USE_QT6) + find_package(Qt6 COMPONENTS REQUIRED Core Gui Widgets OpenGLWidgets) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGLWidgets ) +elseif (CEE_USE_QT5) + find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + + + set(CEE_HEADER_FILES cvfqtBasicAboutDialog.h -cvfqtCvfBoundQGLContext.h cvfqtMouseState.h -cvfqtOpenGLContext.h cvfqtOpenGLWidget.h cvfqtPerformanceInfoHud.h cvfqtUtils.h @@ -30,14 +42,21 @@ cvfqtUtils.h set(CEE_SOURCE_FILES cvfqtBasicAboutDialog.cpp -cvfqtCvfBoundQGLContext.cpp cvfqtMouseState.cpp -cvfqtOpenGLContext.cpp cvfqtOpenGLWidget.cpp cvfqtPerformanceInfoHud.cpp cvfqtUtils.cpp ) +if (CEE_USE_QT5) + set(CEE_HEADER_FILES ${CEE_HEADER_FILES} cvfqtGLWidget.h) + set(CEE_SOURCE_FILES ${CEE_SOURCE_FILES} cvfqtGLWidget.cpp) + set(CEE_HEADER_FILES ${CEE_HEADER_FILES} cvfqtCvfBoundQGLContext_deprecated.h) + set(CEE_SOURCE_FILES ${CEE_SOURCE_FILES} cvfqtCvfBoundQGLContext_deprecated.cpp) + set(CEE_HEADER_FILES ${CEE_HEADER_FILES} cvfqtGLWidget_deprecated.h) + set(CEE_SOURCE_FILES ${CEE_SOURCE_FILES} cvfqtGLWidget_deprecated.cpp) +endif() + add_library(${PROJECT_NAME} ${CEE_HEADER_FILES} ${CEE_SOURCE_FILES}) target_include_directories(${PROJECT_NAME} @@ -58,6 +77,5 @@ source_group("" FILES ${PROJECT_FILES}) # Unity Build if (CMAKE_UNITY_BUILD) - set_source_files_properties (cvfqtOpenGLWidget.cpp PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE) - set_source_files_properties (cvfqtOpenGLContext.cpp PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE) + set_source_files_properties (cvfqtGLWidget_deprecated.cpp PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE) endif() diff --git a/Fwk/VizFwk/LibGuiQt/LibGuiQt.vcxproj b/Fwk/VizFwk/LibGuiQt/LibGuiQt.vcxproj deleted file mode 100644 index 2eee0aacb8..0000000000 --- a/Fwk/VizFwk/LibGuiQt/LibGuiQt.vcxproj +++ /dev/null @@ -1,146 +0,0 @@ - - - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {FBFAC173-30FE-2C09-3F2E-D54477B433DE} - LibGuiQt - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level3 - WIN32;_DEBUG;QT_THREAD_SUPPORT;QT_CORE_LIB;QT_GUI_LIB;QT_OPENGL_LIB;%(PreprocessorDefinitions) - $(QTDIR)/include;$(QTDIR)/include/QtCore;$(QTDIR)/include/QtGui;$(QTDIR)/include/QtOpenGL;../LibCore;../LibGeometry;../LibRender;../LibViewing - - - true - - - - - Level3 - WIN32;_DEBUG;QT_THREAD_SUPPORT;QT_CORE_LIB;QT_GUI_LIB;QT_OPENGL_LIB;%(PreprocessorDefinitions) - $(QTDIR)/include;$(QTDIR)/include/QtCore;$(QTDIR)/include/QtGui;$(QTDIR)/include/QtOpenGL;../LibCore;../LibGeometry;../LibRender;../LibViewing - - - true - - - - - Level3 - WIN32;NDEBUG;QT_NO_DEBUG;QT_THREAD_SUPPORT;QT_CORE_LIB;QT_GUI_LIB;QT_OPENGL_LIB;%(PreprocessorDefinitions) - $(QTDIR)/include;$(QTDIR)/include/QtCore;$(QTDIR)/include/QtGui;$(QTDIR)/include/QtOpenGL;../LibCore;../LibGeometry;../LibRender;../LibViewing - - - true - true - true - - - - - Level3 - WIN32;NDEBUG;QT_NO_DEBUG;QT_THREAD_SUPPORT;QT_CORE_LIB;QT_GUI_LIB;QT_OPENGL_LIB;%(PreprocessorDefinitions) - $(QTDIR)/include;$(QTDIR)/include/QtCore;$(QTDIR)/include/QtGui;$(QTDIR)/include/QtOpenGL;../LibCore;../LibGeometry;../LibRender;../LibViewing - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibGuiQt/LibGuiQt.vcxproj.filters b/Fwk/VizFwk/LibGuiQt/LibGuiQt.vcxproj.filters deleted file mode 100644 index 9b59b15a2c..0000000000 --- a/Fwk/VizFwk/LibGuiQt/LibGuiQt.vcxproj.filters +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.cpp index 3ded50b295..21d9ee74da 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.cpp +++ b/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.cpp @@ -40,12 +40,12 @@ #include "cvfqtBasicAboutDialog.h" -#include -#include - +#include +#include #include #include #include + namespace cvfqt { @@ -255,8 +255,7 @@ void BasicAboutDialog::create() // Library version if (m_showLibraryVersion) { - QString ver; - ver.sprintf("%s.%s%s-%s", CVF_MAJOR_VERSION, CVF_MINOR_VERSION, CVF_SPECIAL_BUILD, CVF_BUILD_NUMBER); + QString ver = QString("%1.%2%3-%4").arg(CVF_MAJOR_VERSION).arg(CVF_MINOR_VERSION).arg(CVF_SPECIAL_BUILD).arg(CVF_BUILD_NUMBER); addStringPairToVerInfoLayout("Library ver.: ", ver, verInfoLayout, insertRow++); } diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.h b/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.h index 49569ecb83..deff8f7cf0 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.h +++ b/Fwk/VizFwk/LibGuiQt/cvfqtBasicAboutDialog.h @@ -37,7 +37,7 @@ #pragma once -#include +#include #include class QGridLayout; diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext_deprecated.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext_deprecated.cpp new file mode 100644 index 0000000000..78a67e2fac --- /dev/null +++ b/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext_deprecated.cpp @@ -0,0 +1,150 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfBase.h" +#include "cvfOpenGLCapabilities.h" +#include "cvfqtCvfBoundQGLContext_deprecated.h" + +namespace cvfqt { + + + +//================================================================================================== +/// +/// \class cvfqt::OpenGLContext_QGLContextAdapter_deprecated +/// \ingroup GuiQt +/// +/// Derived OpenGLContext that adapts a Qt QGLContext +/// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +OpenGLContext_QGLContextAdapter_deprecated::OpenGLContext_QGLContextAdapter_deprecated(cvf::OpenGLContextGroup* contextGroup, QGLContext* backingQGLContext) +: cvf::OpenGLContext(contextGroup) +{ + m_qtGLContext = backingQGLContext; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +OpenGLContext_QGLContextAdapter_deprecated::~OpenGLContext_QGLContextAdapter_deprecated() +{ + m_qtGLContext = NULL; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void OpenGLContext_QGLContextAdapter_deprecated::makeCurrent() +{ + CVF_ASSERT(m_qtGLContext); + m_qtGLContext->makeCurrent(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool OpenGLContext_QGLContextAdapter_deprecated::isCurrent() const +{ + if (m_qtGLContext) + { + if (QGLContext::currentContext() == m_qtGLContext) + { + return true; + } + } + + return false; +} + + + + +//================================================================================================== +/// +/// \class cvfqt::CvfBoundQGLContext_deprecated +/// \ingroup GuiQt +/// +/// +/// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +CvfBoundQGLContext_deprecated::CvfBoundQGLContext_deprecated(cvf::OpenGLContextGroup* contextGroup, const QGLFormat & format) +: QGLContext(format) +{ + m_cvfGLContext = new OpenGLContext_QGLContextAdapter_deprecated(contextGroup, this); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +CvfBoundQGLContext_deprecated::~CvfBoundQGLContext_deprecated() +{ + if (m_cvfGLContext.notNull()) + { + // TODO + // Need to resolve the case where the Qt QGLcontext (that we're deriving from) is deleted + // and we are still holding a reference to one or more OpenGLContext objects + // By the time we get here we expect that we're holding the only reference + CVF_ASSERT(m_cvfGLContext->refCount() == 1); + m_cvfGLContext = NULL; + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* CvfBoundQGLContext_deprecated::cvfOpenGLContext() const +{ + return const_cast(m_cvfGLContext.p()); +} + + +} // namespace cvfqt + + diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext_deprecated.h b/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext_deprecated.h new file mode 100644 index 0000000000..7bc173973a --- /dev/null +++ b/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext_deprecated.h @@ -0,0 +1,84 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +#include "cvfOpenGLContext.h" + +#include + +namespace cvfqt { + + +//================================================================================================== +// +// Derived OpenGLContext that adapts a Qt QGLContext +// +//================================================================================================== +class OpenGLContext_QGLContextAdapter_deprecated : public cvf::OpenGLContext +{ +public: + OpenGLContext_QGLContextAdapter_deprecated(cvf::OpenGLContextGroup* contextGroup, QGLContext* backingQGLContext); + virtual ~OpenGLContext_QGLContextAdapter_deprecated(); + + virtual void makeCurrent(); + virtual bool isCurrent() const; + +private: + QGLContext* m_qtGLContext; +}; + + + +//================================================================================================== +// +// Utility class used to piggyback OpenGLContext onto Qt's QGLContext +// +//================================================================================================== +class CvfBoundQGLContext_deprecated : public QGLContext +{ +public: + CvfBoundQGLContext_deprecated(cvf::OpenGLContextGroup* contextGroup, const QGLFormat & format); + virtual ~CvfBoundQGLContext_deprecated(); + + cvf::OpenGLContext* cvfOpenGLContext() const; + +private: + cvf::ref m_cvfGLContext; +}; + +} diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget.cpp new file mode 100644 index 0000000000..cc211f921f --- /dev/null +++ b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget.cpp @@ -0,0 +1,518 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfqtGLWidget.h" + +#include "cvfOpenGLContextGroup.h" +#include "cvfOpenGLContext.h" +#include "cvfLogManager.h" +#include "cvfTrace.h" + +#include +#include +#include +#include + +namespace cvfqt { + + + +//================================================================================================== +// +// +// +//================================================================================================== +class ForwardingOpenGLContext_GLWidget : public cvf::OpenGLContext +{ +public: + ForwardingOpenGLContext_GLWidget(cvf::OpenGLContextGroup* contextGroup, QGLWidget* ownerQtGLWidget) + : cvf::OpenGLContext(contextGroup), + m_ownerQtGLWidget(ownerQtGLWidget) + { + CVF_ASSERT(contextGroup); + + // In our current usage pattern the owner widget (and its contained Qt OpenGL context) must already be initialized/created + CVF_ASSERT(m_ownerQtGLWidget); + CVF_ASSERT(m_ownerQtGLWidget->isValid()); + CVF_ASSERT(m_ownerQtGLWidget->context()); + CVF_ASSERT(m_ownerQtGLWidget->context()->isValid()); + } + + virtual void makeCurrent() + { + if (m_ownerQtGLWidget) + { + m_ownerQtGLWidget->makeCurrent(); + } + } + + virtual bool isCurrent() const + { + const QGLContext* ownersQGLContext = m_ownerQtGLWidget ? m_ownerQtGLWidget->context() : NULL; + if (ownersQGLContext && QGLContext::currentContext() == ownersQGLContext) + { + return true; + } + + return false; + } + + virtual cvf::OglId defaultFramebufferObject() const + { + if (m_ownerQtGLWidget) + { + const QGLContext* ownersQGLContext = m_ownerQtGLWidget->context(); + const QOpenGLContext* ownersQOpenGLContext = ownersQGLContext ? ownersQGLContext->contextHandle() : NULL; + return ownersQOpenGLContext ? ownersQOpenGLContext->defaultFramebufferObject() : 0; + } + + return 0; + } + +private: + QPointer m_ownerQtGLWidget; +}; + + + + +//================================================================================================== +/// +/// \class cvfqt::GLWidget +/// \ingroup GuiQt +/// +/// +/// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// Constructor, use this for the first or only widget in your application. +//-------------------------------------------------------------------------------------------------- +GLWidget::GLWidget(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent, Qt::WindowFlags f) +: QGLWidget(format, parent, NULL, f), + m_cvfOpenGLContextGroup(contextGroup), + m_logger(CVF_GET_LOGGER("cee.cvf.qt")) +{ + // Must pass a context group + CVF_ASSERT(m_cvfOpenGLContextGroup.notNull()); + + // Only the first widget in a context group can be created using this constructor + // All following widgets must be created using the constructor overload that takes a shareWidget + CVF_ASSERT(m_cvfOpenGLContextGroup->contextCount() == 0); + + // The isValid() call will return true if the widget has a valid GL rendering context; otherwise returns false. + // The widget will be invalid if the system has no OpenGL support. + if (!isValid()) + { + CVF_LOG_ERROR(m_logger, "Widget creation failed, the system has no OpenGL support"); + return; + } + + + // The Qt docs for QGLWidget and all previous experience indicates that it is OK to do OpenGL related + // initialization in QGLWidget's constructor (contrary to QOpenGLWidget). + // Note that the Qt docs still hint that initialization should be deferred to initializeGL(). If we ever + // experience problems related to doing initialization here, we should probably move the initialization. + + // Since we're in the constructor we must ensure this widget's context is current before initialization + makeCurrent(); + + const QGLContext* myQtGLContext = context(); + CVF_ASSERT(myQtGLContext); + CVF_ASSERT(myQtGLContext->isValid()); + CVF_ASSERT(QGLContext::currentContext() == myQtGLContext); + + m_cvfForwardingOpenGLContext = new ForwardingOpenGLContext_GLWidget(m_cvfOpenGLContextGroup.p(), this); + + if (!m_cvfOpenGLContextGroup->initializeContextGroup(m_cvfForwardingOpenGLContext.p())) + { + CVF_LOG_ERROR(m_logger, "Error initializing context group"); + } + + + // Install our event filter + installEventFilter(this); + + // If we're using Qt5 or above, we can get hold of a QOpenGLContext from our QGLContext + // Connect to QOpenGLContext's aboutToBeDestroyed signal so we get notified when Qt's OpenGL context is about to be destroyed + connect(myQtGLContext->contextHandle(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::qtOpenGLContextAboutToBeDestroyed); +} + + +//-------------------------------------------------------------------------------------------------- +/// Constructor, creates a widget sharing the OpenGL resources with the specified widget. +//-------------------------------------------------------------------------------------------------- +GLWidget::GLWidget(GLWidget* shareWidget, QWidget* parent , Qt::WindowFlags f) +: QGLWidget(shareWidget->context()->requestedFormat(), parent, shareWidget, f), + m_logger(CVF_GET_LOGGER("cee.cvf.qt")) +{ + // Note that when calling QGLWidget's constructor in the initializer list above, we *must* use the + // constructor overload that takes a format as its first parameter. If we do not do this, the default QGLFormat + // will be used, and it may not be compatible with the format of the shareWidget. + // We grab hold of the format from the shareWidget, but note that we do that by calling requestedFormat() + // instead of just format() to ensure that the format being requested here is the same as the one that was actually used + // in the "first widget constructor" and not whatever format the first widget ended up with after construction. + + // Requires that a share widget is passed in as parameter + CVF_ASSERT(shareWidget); + + // If the share widget doesn't have a CVF OpenGL context something went wrong when it was created and we cannot continue + cvf::ref shareContext = shareWidget->cvfOpenGLContext(); + CVF_ASSERT(shareContext.notNull()); + + if (!isValid()) + { + CVF_LOG_ERROR(m_logger, "Widget creation failed, the system has no OpenGL support"); + return; + } + + // We need to check if we actually got a context that shares resources with the passed shareWidget. + if (!isSharing()) + { + CVF_LOG_ERROR(m_logger, "Widget creation failed, unable to create a shared OpenGL context"); + return; + } + + + // Since we're in the constructor we must ensure this widget's context is current before initialization + makeCurrent(); + + const QGLContext* myQtGLContext = context(); + CVF_ASSERT(myQtGLContext); + CVF_ASSERT(myQtGLContext->isValid()); + CVF_ASSERT(QGLContext::currentContext() == myQtGLContext); + + m_cvfOpenGLContextGroup = shareContext->group(); + CVF_ASSERT(m_cvfOpenGLContextGroup.notNull()); + + m_cvfForwardingOpenGLContext = new ForwardingOpenGLContext_GLWidget(m_cvfOpenGLContextGroup.p(), this); + + // Normally, the context group should already be initialized when the first widget in the group was created. + // Still, for good measure do an initialization here. It will amount to a no-op if context group is already initialized + if (!m_cvfOpenGLContextGroup->initializeContextGroup(m_cvfForwardingOpenGLContext.p())) + { + CVF_LOG_ERROR(m_logger, "Error initializing context group using sharing widget"); + } + + + // Install our event filter + installEventFilter(this); + + // If we're using Qt5 or above, we can get hold of a QOpenGLContext from our QGLContext + // Connect to QOpenGLContext's aboutToBeDestroyed signal so we get notified when Qt's OpenGL context is about to be destroyed + connect(myQtGLContext->contextHandle(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::qtOpenGLContextAboutToBeDestroyed); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +GLWidget::~GLWidget() +{ + cvf::Trace::show("GLWidget::~GLWidget()"); + + // Make sure we disconnect from the aboutToBeDestroyed signal since after this destructor has been + // called, out object is dangling and the call to the slot will cause a crash + const QGLContext* myQtGLContext = context(); + const QOpenGLContext* myQtOpenGLContext = myQtGLContext ? myQtGLContext->contextHandle() : NULL; + if (myQtOpenGLContext) + { + disconnect(myQtOpenGLContext, &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::qtOpenGLContextAboutToBeDestroyed); + } + + // For Qt5, our testing indicates that once we hit the widget's destructor it may be too late + // to try and do any cleanup of OpenGL resources. Most of the time it works, but typically it will fail when + // we're shutting down the application by closing the main window. In such cases it seems that the OpenGL + // context cannot be made current anymore. + // + // One solution to this is to do an explicit shutdown of the context while before the system + // start shutting down. One traditional way of doing this is to iterate over all GLWidgets and call + // the cvfShutdownOpenGLContext() explicitly, eg from QMainWindow::closeEvent() + // + // In our quest to get a notification just before the QGLContext dies we have also tried to go via + // QGLContext's QOpenGLContext and connect to the aboutToBeDestroyed signal. This signal does indeed trigger + // before the QGLContext dies, but it seems that at this point we are no longer able to make the context + // current which is a requirement before we can do our OpenGL related cleanup. + // + // Another promising solution that seems to work reliably is to install an event filter and respond to + // the QEvent::PlatformSurface event. See our eventFilter() override + + // For Qt4 it seems that doing OpenGL related cleanup in the destructor is OK + // We're able to make the context current and delete any OpenGL resources necessary through the cvfShutdownOpenGLContext(); + + + // Note that calling this function is safe even if the context has already been shut down. + // It may however fail/assert if the context hasn't already been shut down and if we're unable to make the OpenGL context current + cvfShutdownOpenGLContext(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* GLWidget::cvfOpenGLContext() +{ + return m_cvfForwardingOpenGLContext.p(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget::cvfShutdownOpenGLContext() +{ + if (m_cvfForwardingOpenGLContext.notNull()) + { + makeCurrent(); + + // If we're not able to make the context current, the eventual un-initialize that will happen + // in the context group when we remove the last context will fail. + const QGLContext* myContext = context(); + const QGLContext* currContext = QGLContext::currentContext(); + if (myContext != currContext) + { + CVF_LOG_WARNING(m_logger, "Could not make the widget's OpenGL context current for context shutdown"); + } + + m_cvfOpenGLContextGroup->contextAboutToBeShutdown(m_cvfForwardingOpenGLContext.p()); + m_cvfForwardingOpenGLContext = NULL; + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget::initializeGL() +{ + //cvf::Trace::show("GLWidget::initializeGL()"); + + // According to Qt doc this function is called once before the first call to paintGL() or resizeGL(), + // and then once whenever the widget has been assigned a new QGLContext. There is no need to call makeCurrent() because + // this has already been done when this function is called. + + if (m_cvfForwardingOpenGLContext.isNull()) + { + CVF_LOG_ERROR(m_logger, "Unexpected error in GLWidget::initializeGL(), no forwarding OpenGL context present"); + return; + } + + // Initialization of context group should already be done, but for good measure + CVF_ASSERT(m_cvfOpenGLContextGroup.notNull()); + if (!m_cvfOpenGLContextGroup->isContextGroupInitialized()) + { + CVF_LOG_DEBUG(m_logger, "Doing late initialization of context group in GLWidget::initializeGL()"); + if (!m_cvfOpenGLContextGroup->initializeContextGroup(m_cvfForwardingOpenGLContext.p())) + { + CVF_LOG_ERROR(m_logger, "Initialization of context group in GLWidget::initializeGL() failed"); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget::resizeGL(int /*width*/, int /*height*/) +{ + // Intentionally empty, and no implementation in QGLWidget::resizeGL() either. + // Should normally be implemented in derived class +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget::paintGL() +{ + // No implementation here and no significant implementation in QGLWidget either. + // In Qt4 QGLWidget::paintGL() does nothing. In Qt5 QGLWidget::paintGL() merely clears the depth and color buffer. + // Derived classes must reimplement this function in order to do painting. +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget::qtOpenGLContextAboutToBeDestroyed() +{ + //cvf::Trace::show("GLWidget::qtOpenGLContextAboutToBeDestroyed()"); + + cvfShutdownOpenGLContext(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool GLWidget::eventFilter(QObject* watched, QEvent* event) +{ + // The most reliable way we have found of detecting when an OpenGL context is about to be destroyed is + // hooking into the QEvent::PlatformSurface event and checking for the SurfaceAboutToBeDestroyed event type. + // From the Qt doc: + // The underlying native surface will be destroyed immediately after this event. + // The SurfaceAboutToBeDestroyed event type is useful as a means of stopping rendering to a platform window before it is destroyed. + if (event->type() == QEvent::PlatformSurface) + { + QPlatformSurfaceEvent* platformSurfaceEvent = static_cast(event); + if (platformSurfaceEvent->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) + { + CVF_LOG_DEBUG(m_logger, "Shutting down OpenGL context in response to platform surface about to be destroyed"); + cvfShutdownOpenGLContext(); + } + } + + // Reading the Qt docs it can seem like reparenting of the QGLWidget might pose a problem for us. + // According to the doc, a change of parent will cause the widget's QGLContext to be deleted and a new one + // to be created. In Qt4, this does indeed seem to happen, whereas for Qt5 it does not. Still, it appears that Qt4 makes + // an effort to make the new QGLContext compatible with the old one, and does some tricks to set up temporary OpenGL + // resource sharing so that we may not actually be affected by this since we're actually not storing any references to + // the QGLContext, but accessing it indirectly through the widget in our ForwardingOpenGLContext. + // May also want to look out for + if (event->type() == QEvent::ParentChange) + { + CVF_LOG_DEBUG(m_logger, "cvfqt::GLWidget has been reparented. This may cause OpenGL issues"); + } + else if (event->type() == QEvent::ParentAboutToChange) + { + CVF_LOG_DEBUG(m_logger, "cvfqt::GLWidget is about to change parent. This may cause OpenGL issues"); + } + + return QGLWidget::eventFilter(watched, event); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget::logOpenGLInfo() +{ + CVF_LOG_INFO(m_logger, "Starting logging of OpenGL info (cvfqt::GLWidget)..."); + + cvf::String sQtVerInfo = cvf::String("Qt version: %1 (run-time=%2)").arg(QT_VERSION_STR).arg(qVersion()); + CVF_LOG_INFO(m_logger, sQtVerInfo); + + if (!context() || !isValid()) + { + CVF_LOG_WARNING(m_logger, "QGLWidget does not have a valid GL rendering context, reported info will not be correct!"); + } + + // Log output from querying Qt + CVF_LOG_INFO(m_logger, "Qt OpenGL format info:"); + + const QGLFormat qglFormat = format(); + const QGLFormat::OpenGLContextProfile profile = qglFormat.profile(); + const QGLFormat::OpenGLVersionFlags qglVersionFlags = QGLFormat::openGLVersionFlags(); + + cvf::String sInfo = cvf::String(" info: version %1.%2, depthSize: %3, software: %4, doubleBuffer: %5, sampleBuffers: %6 (size: %7)") + .arg(qglFormat.majorVersion()).arg(qglFormat.minorVersion()) + .arg(qglFormat.depthBufferSize()) + .arg(qglFormat.directRendering() ? "no" : "yes") + .arg(qglFormat.doubleBuffer() ? "yes" : "no") + .arg(qglFormat.sampleBuffers() ? "yes" : "no") + .arg(qglFormat.samples()); + CVF_LOG_INFO(m_logger, sInfo); + + cvf::String sProfile = "UNKNOWN"; + if (profile == QGLFormat::NoProfile) sProfile = "NoProfile"; + else if (profile == QGLFormat::CoreProfile) sProfile = "CoreProfile"; + else if (profile == QGLFormat::CompatibilityProfile) sProfile = "CompatibilityProfile"; + CVF_LOG_INFO(m_logger, " context profile: " + sProfile); + + cvf::String sVersionsPresent = cvf::String(" versions present: 1.1: %1, 2.0: %2, 2.1: %3, 3.0: %4, 3.3: %5, 4.0: %6, ES2: %7") + .arg(qglVersionFlags & QGLFormat::OpenGL_Version_1_1 ? "yes" : "no") + .arg(qglVersionFlags & QGLFormat::OpenGL_Version_2_0 ? "yes" : "no") + .arg(qglVersionFlags & QGLFormat::OpenGL_Version_2_1 ? "yes" : "no") + .arg(qglVersionFlags & QGLFormat::OpenGL_Version_3_0 ? "yes" : "no") + .arg(qglVersionFlags & QGLFormat::OpenGL_Version_3_3 ? "yes" : "no") + .arg(qglVersionFlags & QGLFormat::OpenGL_Version_4_0 ? "yes" : "no") + .arg(qglVersionFlags & QGLFormat::OpenGL_ES_Version_2_0 ? "yes" : "no"); + CVF_LOG_INFO(m_logger, sVersionsPresent); + + CVF_LOG_INFO(m_logger, " is sharing: " + cvf::String(isSharing() ? "yes" : "no")); + + + // Log the information we have gathered when initializing the context group + const cvf::OpenGLInfo oglInfo = m_cvfOpenGLContextGroup->info(); + CVF_LOG_INFO(m_logger, "OpenGL info:"); + CVF_LOG_INFO(m_logger, " version: " + oglInfo.version()); + CVF_LOG_INFO(m_logger, " vendor: " + oglInfo.vendor()); + CVF_LOG_INFO(m_logger, " renderer: " + oglInfo.renderer()); + + + // Lastly, query OpenGL implementation directly if this context is current + GLint smoothLineWidthRange[2] = { -1, -1 }; + GLint smoothPointSizeRange[2] = { -1, -1 }; + GLint aliasedLineWidthRange[2] = { -1, -1 }; + GLint aliasedPointSizeRange[2] = { -1, -1 }; + + // Note that GL_LINE_WIDTH_RANGE and GL_SMOOTH_LINE_WIDTH_RANGE are synonyms (0x0B22) + // Likewise for GL_POINT_SIZE_RANGE and GL_SMOOTH_POINT_SIZE_RANGE are synonyms (0x0B12) +#ifndef GL_ALIASED_LINE_WIDTH_RANGE + #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#endif +#ifndef GL_ALIASED_POINT_SIZE_RANGE + #define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#endif + + const bool thisContextIsCurrent = context() == QGLContext::currentContext(); + if (thisContextIsCurrent) + { + glGetIntegerv(GL_LINE_WIDTH_RANGE, smoothLineWidthRange); + glGetIntegerv(GL_POINT_SIZE_RANGE, smoothPointSizeRange); + if (qglVersionFlags & QGLFormat::OpenGL_Version_1_2) + { + glGetIntegerv(GL_ALIASED_LINE_WIDTH_RANGE, aliasedLineWidthRange); + glGetIntegerv(GL_ALIASED_POINT_SIZE_RANGE, aliasedPointSizeRange); + } + } + else + { + CVF_LOG_WARNING(m_logger, "Cannot query OpenGL directly, QGLWidget's context is not current"); + } + + cvf::String sLineInfo = cvf::String("OpenGL line width range: aliased lines: %1 to %2, smooth lines: %3 to %4").arg(aliasedLineWidthRange[0]).arg(aliasedLineWidthRange[1]).arg(smoothLineWidthRange[0]).arg(smoothLineWidthRange[1]); + cvf::String sPointInfo = cvf::String("OpenGL point size range: aliased points: %1 to %2, smooth points: %3 to %4").arg(aliasedPointSizeRange[0]).arg(aliasedPointSizeRange[1]).arg(smoothPointSizeRange[0]).arg(smoothPointSizeRange[1]); + CVF_LOG_INFO(m_logger, sLineInfo); + CVF_LOG_INFO(m_logger, sPointInfo); + + CVF_LOG_INFO(m_logger, "Finished logging of OpenGL info"); +} + + +} // namespace cvfqt + + diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget.h b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget.h new file mode 100644 index 0000000000..dd2cc736a3 --- /dev/null +++ b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget.h @@ -0,0 +1,86 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" + +#include + +namespace cvf { + class OpenGLContext; + class OpenGLContextGroup; + class Logger; +} + +namespace cvfqt { + + + +//================================================================================================== +// +// +// +//================================================================================================== +class GLWidget : public QGLWidget +{ +public: + GLWidget(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent, Qt::WindowFlags f = Qt::WindowFlags()); + GLWidget(GLWidget* shareWidget, QWidget* parent , Qt::WindowFlags f = Qt::WindowFlags()); + ~GLWidget(); + + cvf::OpenGLContext* cvfOpenGLContext(); + void cvfShutdownOpenGLContext(); + + void logOpenGLInfo(); + +protected: + virtual void initializeGL(); + virtual void resizeGL(int width, int height); + virtual void paintGL(); + virtual bool eventFilter(QObject* watched, QEvent* event); + +private: + void qtOpenGLContextAboutToBeDestroyed(); + +private: + cvf::ref m_cvfOpenGLContextGroup; + cvf::ref m_cvfForwardingOpenGLContext; + cvf::ref m_logger; +}; + +} diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget_deprecated.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget_deprecated.cpp new file mode 100644 index 0000000000..308f3b267a --- /dev/null +++ b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget_deprecated.cpp @@ -0,0 +1,164 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfBase.h" +#include "cvfOpenGLContextGroup.h" +#include "cvfqtCvfBoundQGLContext_deprecated.h" +#include "cvfqtGLWidget_deprecated.h" + +namespace cvfqt { + + + +//================================================================================================== +/// +/// \class cvfqt::GLWidget_deprecated +/// \ingroup GuiQt +/// +/// +/// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +GLWidget_deprecated::GLWidget_deprecated(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent, Qt::WindowFlags f) +: QGLWidget(new CvfBoundQGLContext_deprecated(contextGroup, format), parent, NULL, f) +{ + // This constructor can only be used with an empty context group! + // We're not able to check this up front, but assert that the count is 1 by the time we get here + CVF_ASSERT(contextGroup->contextCount() == 1); + + if (isValid()) + { + cvf::ref myContext = cvfOpenGLContext(); + if (myContext.notNull()) + { + // We must ensure the context is current before initialization + makeCurrent(); + contextGroup->initializeContextGroup(myContext.p()); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// Constructor +/// +/// Tries to create a widget that shares OpenGL resources with \a shareWidget +/// To check if creation was actually successful, you must call isValidContext() on the context +/// of the newly created widget. For example: +/// \code +/// myNewWidget->cvfOpenGLContext()->isValidContext(); +/// \endcode +/// +/// If the context is not valid, sharing failed and the newly created widget/context be discarded. +//-------------------------------------------------------------------------------------------------- +GLWidget_deprecated::GLWidget_deprecated(GLWidget_deprecated* shareWidget, QWidget* parent , Qt::WindowFlags f) +: QGLWidget(new CvfBoundQGLContext_deprecated(shareWidget->cvfOpenGLContext()->group(), shareWidget->format()), parent, shareWidget, f) +{ + CVF_ASSERT(shareWidget); + cvf::ref shareContext = shareWidget->cvfOpenGLContext(); + CVF_ASSERT(shareContext.notNull()); + + cvf::ref myContext = cvfOpenGLContext(); + if (myContext.notNull()) + { + cvf::OpenGLContextGroup* myOwnerContextGroup = myContext->group(); + CVF_ASSERT(myOwnerContextGroup == shareContext->group()); + + // We need to check if we actually got a context that shares resources with shareWidget. + if (isSharing()) + { + if (isValid()) + { + makeCurrent(); + myOwnerContextGroup->initializeContextGroup(myContext.p()); + } + } + else + { + // If we didn't, we need to remove the newly created context from the group it has been added to since + // the construction process above has already optimistically added the new context to the existing group. + // In this case, the newly context is basically defunct so we just shut it down (which will also remove it from the group) + // Normally, we would need to ensure the context is current before calling shutdown, but in this case we are not the last + // context in the group so there should be no need for cleaning up resources. + myOwnerContextGroup->contextAboutToBeShutdown(myContext.p()); + CVF_ASSERT(myContext->group() == NULL); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* GLWidget_deprecated::cvfOpenGLContext() const +{ + const QGLContext* qglContext = context(); + const CvfBoundQGLContext_deprecated* contextBinding = dynamic_cast(qglContext); + CVF_ASSERT(contextBinding); + + return contextBinding->cvfOpenGLContext(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void GLWidget_deprecated::cvfShutdownOpenGLContext() +{ + // It should be safe to call shutdown multiple times so this call should + // amount to a no-op if the user has already shut down the context + cvf::ref myContext = cvfOpenGLContext(); + if (myContext.notNull()) + { + cvf::OpenGLContextGroup* myOwnerContextGroup = myContext->group(); + + // If shutdown has already been called, the context is no longer member of any group + if (myOwnerContextGroup) + { + makeCurrent(); + myOwnerContextGroup->contextAboutToBeShutdown(myContext.p()); + } + } +} + + +} // namespace cvfqt + + diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget_deprecated.h b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget_deprecated.h new file mode 100644 index 0000000000..04a3962763 --- /dev/null +++ b/Fwk/VizFwk/LibGuiQt/cvfqtGLWidget_deprecated.h @@ -0,0 +1,66 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +#include + +namespace cvf +{ + class OpenGLContext; + class OpenGLContextGroup; +} + +namespace cvfqt { + + +//================================================================================================== +// +// Derived QGLWidget +// +//================================================================================================== +class GLWidget_deprecated : public QGLWidget +{ +public: + GLWidget_deprecated(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent, Qt::WindowFlags f = Qt::WindowFlags()); + GLWidget_deprecated(GLWidget_deprecated* shareWidget, QWidget* parent , Qt::WindowFlags f = Qt::WindowFlags()); + + cvf::OpenGLContext* cvfOpenGLContext() const; + void cvfShutdownOpenGLContext(); +}; + +} diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtMouseState.h b/Fwk/VizFwk/LibGuiQt/cvfqtMouseState.h index fc6c39cafc..36978105da 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtMouseState.h +++ b/Fwk/VizFwk/LibGuiQt/cvfqtMouseState.h @@ -40,7 +40,7 @@ class QMouseEvent; class QGraphicsSceneMouseEvent; -#include +#include namespace cvfqt { diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.cpp index fbfb54f65a..7de4e4c06e 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.cpp +++ b/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.cpp @@ -34,117 +34,301 @@ // //################################################################################################## - -#include "cvfBase.h" -#include "cvfOpenGLContextGroup.h" -#include "cvfqtCvfBoundQGLContext.h" #include "cvfqtOpenGLWidget.h" +#include "cvfTrace.h" +#include "cvfString.h" +#include "cvfOpenGLContext.h" +#include "cvfLogManager.h" + +#include +#include +#include +#include + namespace cvfqt { //================================================================================================== -/// -/// \class cvfqt::OpenGLWidget -/// \ingroup GuiQt -/// -/// -/// +// +// +// //================================================================================================== +class ForwardingOpenGLContext_OpenGLWidget : public cvf::OpenGLContext +{ +public: + ForwardingOpenGLContext_OpenGLWidget(cvf::OpenGLContextGroup* contextGroup, QOpenGLWidget* ownerQtOpenGLWidget) + : cvf::OpenGLContext(contextGroup), + m_ownerQtOpenGLWidget(ownerQtOpenGLWidget) + { + CVF_ASSERT(contextGroup); + + // In our current usage pattern the owner widget (and its contained Qt OpenGL context) + // must already be initialized/created + CVF_ASSERT(m_ownerQtOpenGLWidget); + CVF_ASSERT(m_ownerQtOpenGLWidget->isValid()); + CVF_ASSERT(m_ownerQtOpenGLWidget->context()); + CVF_ASSERT(m_ownerQtOpenGLWidget->context()->isValid()); + } + + virtual void makeCurrent() + { + if (m_ownerQtOpenGLWidget) + { + m_ownerQtOpenGLWidget->makeCurrent(); + } + } + + virtual bool isCurrent() const + { + QOpenGLContext* ownersContext = m_ownerQtOpenGLWidget ? m_ownerQtOpenGLWidget->context() : NULL; + if (ownersContext && QOpenGLContext::currentContext() == ownersContext) + { + return true; + } + + return false; + } + + virtual cvf::OglId defaultFramebufferObject() const + { + if (m_ownerQtOpenGLWidget) + { + return m_ownerQtOpenGLWidget->defaultFramebufferObject(); + } + + return 0; + } + + QOpenGLWidget* ownerQtOpenGLWidget() + { + return m_ownerQtOpenGLWidget; + } + +private: + QPointer m_ownerQtOpenGLWidget; +}; + + + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +OpenGLWidget::OpenGLWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent, Qt::WindowFlags f) +: QOpenGLWidget(parent, f), + m_instanceNumber(-1), + m_initializationState(UNINITIALIZED), + m_cvfOpenGlContextGroup(contextGroup), + m_logger(CVF_GET_LOGGER("cee.cvf.qt")) +{ + static int sl_nextInstanceNumber = 0; + m_instanceNumber = sl_nextInstanceNumber++; + + CVF_LOG_DEBUG(m_logger, cvf::String("OpenGLWidget[%1]::OpenGLWidget()").arg(m_instanceNumber)); + + CVF_ASSERT(m_cvfOpenGlContextGroup.notNull()); +} //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -OpenGLWidget::OpenGLWidget(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent, Qt::WindowFlags f) -: QGLWidget(new CvfBoundQGLContext(contextGroup, format), parent, NULL, f) +OpenGLWidget::~OpenGLWidget() { - // This constructor can only be used with an empty context group! - // We're not able to check this up front, but assert that the count is 1 by the time we get here - CVF_ASSERT(contextGroup->contextCount() == 1); + CVF_LOG_DEBUG(m_logger, cvf::String("OpenGLWidget[%1]::~OpenGLWidget()").arg(m_instanceNumber)); - if (isValid()) + if (m_initializationState == IS_INITIALIZED) { - cvf::ref myContext = cvfOpenGLContext(); - if (myContext.notNull()) + // Make sure we disconnect from the aboutToBeDestroyed signal since after this destructor has been + // called, our object is dangling and the call to the slot will cause a crash + QOpenGLContext* myQtOpenGLContext = context(); + if (myQtOpenGLContext) { - myContext->initializeContext(); + disconnect(myQtOpenGLContext, &QOpenGLContext::aboutToBeDestroyed, this, &OpenGLWidget::qtOpenGLContextAboutToBeDestroyed); } } -} + shutdownCvfOpenGLContext(); +} //-------------------------------------------------------------------------------------------------- -/// Constructor -/// -/// Tries to create a widget that shares OpenGL resources with \a shareWidget -/// To check if creation was actually successful, you must call isValidContext() on the context -/// of the newly created widget. For example: -/// \code -/// myNewWidget->cvfOpenGLContext()->isValidContext(); -/// \endcode -/// -/// If the context is not valid, sharing failed and the newly created widget/context be discarded. +/// This is where we do the custom initialization needed for the Qt binding to work +/// +/// Note that if you re-implement this function in your subclass, you must make +/// sure to call the base class. //-------------------------------------------------------------------------------------------------- -OpenGLWidget::OpenGLWidget(OpenGLWidget* shareWidget, QWidget* parent , Qt::WindowFlags f) -: QGLWidget(new CvfBoundQGLContext(shareWidget->cvfOpenGLContext()->group(), shareWidget->format()), parent, shareWidget, f) +void OpenGLWidget::initializeGL() { - CVF_ASSERT(shareWidget); - cvf::ref shareContext = shareWidget->cvfOpenGLContext(); - CVF_ASSERT(shareContext.notNull()); + CVF_LOG_DEBUG(m_logger, cvf::String("OpenGLWidget[%1]::initializeGL()").arg(m_instanceNumber)); - cvf::ref myContext = cvfOpenGLContext(); - if (myContext.notNull()) + if (!isValid()) { - // We need to check if we actually got a context that shares resources with shareWidget. - if (isSharing()) + CVF_LOG_WARNING(m_logger, cvf::String("OpenGLWidget[%1]: Widget is not valid for initialization").arg(m_instanceNumber)); + } + + // According to Qt doc this function is called once before the first call to paintGL() or resizeGL(). + // Further it is stated that this widget's QOpenGLContext is already current. + // We should be able to assume that we will only be called with a create, valid and current QOpenGLContext + // + // Note that in some scenarios, such as when a widget get reparented, initializeGL() ends up being called + // multiple times in the lifetime of the widget. In those cases, the widget's associated context is first destroyed + // and then a new one is created. This is then followed by a new call to initializeGL() where all OpenGL resources must get reinitialized. + + QOpenGLContext* myQtOpenGLContext = context(); + CVF_ASSERT(myQtOpenGLContext); + CVF_ASSERT(myQtOpenGLContext->isValid()); + CVF_ASSERT(QOpenGLContext::currentContext() == myQtOpenGLContext); + + if (m_initializationState != IS_INITIALIZED) + { + CVF_LOG_DEBUG(m_logger, cvf::String("OpenGLWidget[%1]: Starting internal initialization").arg(m_instanceNumber)); + + // This should either be the first call or the result of a destroy/recreate cycle + CVF_ASSERT(m_cvfForwardingOpenGlContext.isNull()); + + // Try and detect the situation where the user is trying to associate incompatible widgets/contexts in the same cvf OpenGLContextGroup + // The assert below will fail if two incompatible OpenGL contexts end up in the same context group + if (m_cvfOpenGlContextGroup->contextCount() > 0) { - if (isValid()) + for (size_t i = 0; i < m_cvfOpenGlContextGroup->contextCount(); i++) { - CVF_ASSERT(myContext->group() == shareContext->group()); - myContext->initializeContext(); + ForwardingOpenGLContext_OpenGLWidget* existingFwdContext = dynamic_cast(m_cvfOpenGlContextGroup->context(i)); + QOpenGLWidget* existingWidget = existingFwdContext ? existingFwdContext->ownerQtOpenGLWidget() : NULL; + QOpenGLContext* existingQtContext = existingWidget ? existingWidget->context() : NULL; + if (existingQtContext) + { + // Assert that these two contexts are actually sharing OpenGL resources + CVF_ASSERT(QOpenGLContext::areSharing(existingQtContext, myQtOpenGLContext)); + } } } - else + + // Create the actual wrapper/forwarding OpenGL context that implements the cvf::OpenGLContext that we need + cvf::ref myCvfContext = new ForwardingOpenGLContext_OpenGLWidget(m_cvfOpenGlContextGroup.p(), this); + + // Possibly initialize the context group + if (!m_cvfOpenGlContextGroup->isContextGroupInitialized()) + { + if (!m_cvfOpenGlContextGroup->initializeContextGroup(myCvfContext.p())) + { + CVF_LOG_ERROR(m_logger, cvf::String("OpenGLWidget[%1]: OpenGL context creation failed, could not initialize context group").arg(m_instanceNumber)); + return; + } + } + + // All is well, so store pointer to the cvf OpenGL context + m_cvfForwardingOpenGlContext = myCvfContext; + + const InitializationState prevInitState = m_initializationState; + m_initializationState = IS_INITIALIZED; + + // Connect to signal so we get notified when Qt's OpenGL context is about to be destroyed + connect(myQtOpenGLContext, &QOpenGLContext::aboutToBeDestroyed, this, &OpenGLWidget::qtOpenGLContextAboutToBeDestroyed); + + if (prevInitState == UNINITIALIZED) + { + // Call overridable notification function to indicate that OpenGL has been initialized + // Don't do this if we're being re-initialized + onWidgetOpenGLReady(); + } + + // Trigger a repaint if we're being re-initialized + if (prevInitState == PENDING_REINITIALIZATION) { - // If we didn't, we need to remove the newly created context from the group it has been added to since - // the construction process above has already optimistically added the new context to the existing group. - // In this case, the newly context is basically defunct so we just shut it down (which will also remove it from the group) - myContext->shutdownContext(); - CVF_ASSERT(myContext->group() == NULL); + update(); } } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void OpenGLWidget::resizeGL(int /*w*/, int /*h*/) +{ + // Empty, should normally be implemented in derived class +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void OpenGLWidget::paintGL() +{ + // No implementation here (nor in QOpenGLWidget::paintGL()) + // Derived classes must re-implement this function in order to do painting. + // + // Typical code would go something like this: + // cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); + // myRenderSequence->render(currentOglContext); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* OpenGLWidget::cvfOpenGLContext() +{ + return m_cvfForwardingOpenGlContext.p(); +} //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -cvf::OpenGLContext* OpenGLWidget::cvfOpenGLContext() const +int OpenGLWidget::instanceNumber() const { - const QGLContext* qglContext = context(); - const CvfBoundQGLContext* contextBinding = dynamic_cast(qglContext); - CVF_ASSERT(contextBinding); + return m_instanceNumber; +} - return contextBinding->cvfOpenGLContext(); +//-------------------------------------------------------------------------------------------------- +/// Notification function that will be called after internal CVF OpenGL initialization has +/// successfully completed. This includes both the creation of the CVF OpenGLContext and +/// successful initialization of the OpenGL context group +/// +/// Can be re-implemented in derived classes to take any needed actions. +//-------------------------------------------------------------------------------------------------- +void OpenGLWidget::onWidgetOpenGLReady() +{ + // Base implementation does nothing } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void OpenGLWidget::qtOpenGLContextAboutToBeDestroyed() +{ + CVF_LOG_DEBUG(m_logger, cvf::String("OpenGLWidget[%1]::qtOpenGLContextAboutToBeDestroyed()").arg(m_instanceNumber)); + + if (m_cvfForwardingOpenGlContext.notNull()) + { + CVF_LOG_DEBUG(m_logger, cvf::String("OpenGLWidget[%1]: Shutting down CVF OpenGL context since Qt context is about to be destroyed").arg(m_instanceNumber)); + shutdownCvfOpenGLContext(); + } + + if (m_initializationState == IS_INITIALIZED) + { + m_initializationState = PENDING_REINITIALIZATION; + } +} //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void OpenGLWidget::cvfShutdownOpenGLContext() +void OpenGLWidget::shutdownCvfOpenGLContext() { - // It should be safe to call shutdown multiple times so this call should - // amount to a no-op if the user has already shut down the context - cvf::ref myContext = cvfOpenGLContext(); - if (myContext.notNull()) + if (m_cvfForwardingOpenGlContext.notNull()) { - myContext->shutdownContext(); + makeCurrent(); + + m_cvfOpenGlContextGroup->contextAboutToBeShutdown(m_cvfForwardingOpenGlContext.p()); + m_cvfForwardingOpenGlContext = NULL; } } } // namespace cvfqt - diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.h b/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.h index c598f9997d..9b797cd27d 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.h +++ b/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLWidget.h @@ -34,33 +34,63 @@ // //################################################################################################## - #pragma once -#include +#include "cvfBase.h" +#include "cvfObject.h" -namespace cvf -{ +#include + +namespace cvf { class OpenGLContext; class OpenGLContextGroup; + class Logger; } namespace cvfqt { + //================================================================================================== // -// Derived QGLWidget +// // //================================================================================================== -class OpenGLWidget : public QGLWidget +class OpenGLWidget : public QOpenGLWidget { public: - OpenGLWidget(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent, Qt::WindowFlags f = 0); - OpenGLWidget(OpenGLWidget* shareWidget, QWidget* parent , Qt::WindowFlags f = 0); + OpenGLWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent, Qt::WindowFlags f = Qt::WindowFlags()); + ~OpenGLWidget(); + + cvf::OpenGLContext* cvfOpenGLContext(); + +protected: + virtual void initializeGL(); + virtual void resizeGL(int w, int h); + virtual void paintGL(); + + int instanceNumber() const; - cvf::OpenGLContext* cvfOpenGLContext() const; - void cvfShutdownOpenGLContext(); + virtual void onWidgetOpenGLReady(); + +private: + void qtOpenGLContextAboutToBeDestroyed(); + void shutdownCvfOpenGLContext(); + +private: + enum InitializationState + { + UNINITIALIZED, + PENDING_REINITIALIZATION, + IS_INITIALIZED + }; + + int m_instanceNumber; + InitializationState m_initializationState; + cvf::ref m_cvfOpenGlContextGroup; + cvf::ref m_cvfForwardingOpenGlContext; + cvf::ref m_logger; }; -} + +} \ No newline at end of file diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.cpp index df01e0df86..8c2127700d 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.cpp +++ b/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.cpp @@ -42,7 +42,7 @@ #include "cvfqtPerformanceInfoHud.h" #include "cvfOpenGLResourceManager.h" -#include +#include #include #include diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.h b/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.h index 457d0c0e27..0cc142a937 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.h +++ b/Fwk/VizFwk/LibGuiQt/cvfqtPerformanceInfoHud.h @@ -37,7 +37,7 @@ #pragma once -#include +#include namespace cvf { class PerformanceInfo; diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtUtils.cpp b/Fwk/VizFwk/LibGuiQt/cvfqtUtils.cpp index 2c777b26a4..7c5fa10735 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtUtils.cpp +++ b/Fwk/VizFwk/LibGuiQt/cvfqtUtils.cpp @@ -39,7 +39,7 @@ #include "cvfVector2.h" #include "cvfqtUtils.h" -#include +#include namespace cvfqt { diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtUtils.h b/Fwk/VizFwk/LibGuiQt/cvfqtUtils.h index 3def003140..61d64324e8 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtUtils.h +++ b/Fwk/VizFwk/LibGuiQt/cvfqtUtils.h @@ -40,7 +40,7 @@ #include "cvfString.h" #include "cvfTextureImage.h" -#include +#include #include namespace cvfqt { diff --git a/Fwk/VizFwk/LibIo/CMakeLists.txt b/Fwk/VizFwk/LibIo/CMakeLists.txt index 7c61491bf2..7ed7adb5bf 100644 --- a/Fwk/VizFwk/LibIo/CMakeLists.txt +++ b/Fwk/VizFwk/LibIo/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibIo) diff --git a/Fwk/VizFwk/LibIo/LibIo.vcxproj b/Fwk/VizFwk/LibIo/LibIo.vcxproj deleted file mode 100644 index fdd23639e1..0000000000 --- a/Fwk/VizFwk/LibIo/LibIo.vcxproj +++ /dev/null @@ -1,258 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {181472EE-4B37-01E8-49D5-6213678FE4F8} - LibIo - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibIo/LibIo.vcxproj.filters b/Fwk/VizFwk/LibIo/LibIo.vcxproj.filters deleted file mode 100644 index afa0eacdf8..0000000000 --- a/Fwk/VizFwk/LibIo/LibIo.vcxproj.filters +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibIo/cvfXml.cpp b/Fwk/VizFwk/LibIo/cvfXml.cpp index 47e445838b..c4c53bb81e 100644 --- a/Fwk/VizFwk/LibIo/cvfXml.cpp +++ b/Fwk/VizFwk/LibIo/cvfXml.cpp @@ -45,8 +45,15 @@ #pragma warning( disable : 4365 ) #endif +CVF_GCC_DIAGNOSTIC_PUSH +#if defined (CVF_GCC_VER) && (CVF_GCC_VER >= 70400) +CVF_GCC_DIAGNOSTIC_IGNORE("-Wimplicit-fallthrough=") +#endif + #include "cvfTinyXmlFused.hpp" +CVF_GCC_DIAGNOSTIC_POP + #ifdef _MSC_VER #pragma warning( pop ) #endif diff --git a/Fwk/VizFwk/LibRegGrid2D/CMakeLists.txt b/Fwk/VizFwk/LibRegGrid2D/CMakeLists.txt index 36384e37df..8da42760b1 100644 --- a/Fwk/VizFwk/LibRegGrid2D/CMakeLists.txt +++ b/Fwk/VizFwk/LibRegGrid2D/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibRegGrid2D) diff --git a/Fwk/VizFwk/LibRegGrid2D/LibRegGrid2D.vcxproj b/Fwk/VizFwk/LibRegGrid2D/LibRegGrid2D.vcxproj deleted file mode 100644 index 59bd54d927..0000000000 --- a/Fwk/VizFwk/LibRegGrid2D/LibRegGrid2D.vcxproj +++ /dev/null @@ -1,257 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {7AEF1888-268C-3BEF-4080-743645180A59} - LibRegGrid2D - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibIo - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibRegGrid2D/LibRegGrid2D.vcxproj.filters b/Fwk/VizFwk/LibRegGrid2D/LibRegGrid2D.vcxproj.filters deleted file mode 100644 index 4fc62ccb90..0000000000 --- a/Fwk/VizFwk/LibRegGrid2D/LibRegGrid2D.vcxproj.filters +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibRender/CMakeLists.txt b/Fwk/VizFwk/LibRender/CMakeLists.txt index c1b52c3543..94759337b4 100644 --- a/Fwk/VizFwk/LibRender/CMakeLists.txt +++ b/Fwk/VizFwk/LibRender/CMakeLists.txt @@ -45,8 +45,10 @@ cvfOpenGL.h cvfOpenGLCapabilities.h cvfOpenGLContext.h cvfOpenGLContextGroup.h +cvfOpenGLInfo.h cvfOpenGLResourceManager.h cvfOpenGLTypes.h +cvfOpenGLUtils.h cvfOverlayAxisCross.h cvfOverlayScalarMapperLegend.h cvfOverlayColorLegend.h @@ -122,7 +124,9 @@ cvfOglRc.cpp cvfOpenGLCapabilities.cpp cvfOpenGLContext.cpp cvfOpenGLContextGroup.cpp +cvfOpenGLInfo.cpp cvfOpenGLResourceManager.cpp +cvfOpenGLUtils.cpp cvfOpenGL.cpp cvfOverlayAxisCross.cpp cvfOverlayScalarMapperLegend.cpp @@ -199,3 +203,17 @@ if (CMAKE_UNITY_BUILD) set_source_files_properties (cvfOpenGL.cpp PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE) set_source_files_properties (cvfOpenGLContextGroup.cpp PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE) endif() + + +# Create a target for building the cvfShaderSourceStrings.h file from our GLSL files (currently Win only) +if (WIN32) + FILE(GLOB CEE_ALL_GLSL_FILES "${CMAKE_CURRENT_SOURCE_DIR}/glsl/*.glsl") + add_custom_target(run_Glsl2Include + COMMAND ../Tools/Glsl2Include/Glsl2Include glsl/ cvfShaderSourceStrings.h + COMMAND ${CMAKE_COMMAND} -E remove cvfShaderSourceStrings.h.temp + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + COMMENT "Launching Glsl2Include tool..." + VERBATIM + SOURCES ${CEE_ALL_GLSL_FILES} + ) +endif() diff --git a/Fwk/VizFwk/LibRender/LibRender.vcxproj b/Fwk/VizFwk/LibRender/LibRender.vcxproj deleted file mode 100644 index 0aeca74699..0000000000 --- a/Fwk/VizFwk/LibRender/LibRender.vcxproj +++ /dev/null @@ -1,589 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F} - LibRender - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - PrepareForBuild - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - true - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - true - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - true - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibGeometry;../LibIo;../ThirdParty/FreeType/include - true - - - true - true - true - - - ..\Tools\Glsl2Include\Glsl2Include.exe glsl\ cvfShaderSourceStrings.h - - - Building shader source strings - - - cvfShaderSourceStrings.h - FileWillNeverExist.txt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - Document - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibRender/LibRender.vcxproj.filters b/Fwk/VizFwk/LibRender/LibRender.vcxproj.filters deleted file mode 100644 index c511a1afa1..0000000000 --- a/Fwk/VizFwk/LibRender/LibRender.vcxproj.filters +++ /dev/null @@ -1,270 +0,0 @@ - - - - - {90f89af3-6cfb-48ea-ae6f-d85a67b4b6cd} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - - - glsl - - - glsl - - - - - - - - - - - - glsl - - - glsl - - - glsl - - - - glsl - - - - - - - - - - - - - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - glsl - - - - - glsl - - - glsl - - - - - glsl - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibRender/cvfCamera.cpp b/Fwk/VizFwk/LibRender/cvfCamera.cpp index f90ed87021..757a22e85d 100644 --- a/Fwk/VizFwk/LibRender/cvfCamera.cpp +++ b/Fwk/VizFwk/LibRender/cvfCamera.cpp @@ -1035,7 +1035,6 @@ Mat4d Camera::createLookAtMatrix(Vec3d eye, Vec3d vrp, Vec3d up) //-------------------------------------------------------------------------------------------------- void Camera::applyOpenGL() const { -#ifndef CVF_OPENGL_ES // apply the projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixd(m_projectionMatrix.ptr()); @@ -1043,7 +1042,6 @@ void Camera::applyOpenGL() const // apply the view matrix glMatrixMode(GL_MODELVIEW); glLoadMatrixd(viewMatrix().ptr()); -#endif } } // namespace cvf diff --git a/Fwk/VizFwk/LibRender/cvfDrawableGeo.cpp b/Fwk/VizFwk/LibRender/cvfDrawableGeo.cpp index 583eea8058..82a8350b5d 100644 --- a/Fwk/VizFwk/LibRender/cvfDrawableGeo.cpp +++ b/Fwk/VizFwk/LibRender/cvfDrawableGeo.cpp @@ -159,10 +159,6 @@ void DrawableGeo::renderFixedFunction(OpenGLContext* oglContext, const MatrixSta { CVF_ASSERT(BufferObjectManaged::supportedOpenGL(oglContext)); -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else - size_t numPrimitiveSets = m_primitiveSets.size(); if (numPrimitiveSets == 0 || m_vertexBundle->vertexCount() == 0) { @@ -184,9 +180,7 @@ void DrawableGeo::renderFixedFunction(OpenGLContext* oglContext, const MatrixSta CVF_CHECK_OGL(oglContext); m_vertexBundle->finishUseBundle(oglContext, &bundleUsage); - -#endif // CVF_OPENGL_ES - } +} //-------------------------------------------------------------------------------------------------- @@ -247,9 +241,6 @@ void DrawableGeo::releaseBufferObjectsGPU() //-------------------------------------------------------------------------------------------------- void DrawableGeo::renderImmediateMode(OpenGLContext* oglContext, const MatrixState&) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else CVF_ASSERT(oglContext); const Vec3fArray* vertexArr = m_vertexBundle->vertexArray(); @@ -292,8 +283,6 @@ void DrawableGeo::renderImmediateMode(OpenGLContext* oglContext, const MatrixSta glEnd(); } - -#endif // CVF_OPENGL_ES } diff --git a/Fwk/VizFwk/LibRender/cvfDrawableText.cpp b/Fwk/VizFwk/LibRender/cvfDrawableText.cpp index 9286fafd12..3936e5b145 100644 --- a/Fwk/VizFwk/LibRender/cvfDrawableText.cpp +++ b/Fwk/VizFwk/LibRender/cvfDrawableText.cpp @@ -55,10 +55,7 @@ #include "cvfRenderStateDepth.h" #include "cvfRenderStatePolygonOffset.h" #include "cvfRenderStateBlending.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -344,13 +341,11 @@ void DrawableText::renderText(OpenGLContext* oglContext, ShaderProgram* shaderPr ShaderProgram::useNoProgram(oglContext); } -#ifndef CVF_OPENGL_ES RenderStateMaterial_FF mat; mat.enableColorMaterial(true); RenderStateLighting_FF noLight(false); noLight.applyOpenGL(oglContext); -#endif } RenderStateDepth visibleCheckDepthRS(true, RenderStateDepth::LEQUAL, false); @@ -396,7 +391,6 @@ void DrawableText::renderText(OpenGLContext* oglContext, ShaderProgram* shaderPr RenderStateBlending resetBlend; resetBlend.applyOpenGL(oglContext); -#ifndef CVF_OPENGL_ES if (!shaderProgram) { RenderStateMaterial_FF mat; @@ -405,7 +399,6 @@ void DrawableText::renderText(OpenGLContext* oglContext, ShaderProgram* shaderPr RenderStateLighting_FF light; light.applyOpenGL(oglContext); } -#endif } TextDrawer drawer(m_font.p()); @@ -454,13 +447,11 @@ bool DrawableText::labelAnchorVisible(OpenGLContext* oglContext, const Vec3d win if (softwareRendering) { -#ifndef CVF_OPENGL_ES glPointSize(3); glColor3f(0.02f, 0.02f, 0.02f); glBegin(GL_POINTS); glVertex3fv(worldCoord.ptr()); glEnd(); -#endif } else { diff --git a/Fwk/VizFwk/LibRender/cvfDrawableVectors.cpp b/Fwk/VizFwk/LibRender/cvfDrawableVectors.cpp index a7c191ac1f..6b3e7ba35a 100644 --- a/Fwk/VizFwk/LibRender/cvfDrawableVectors.cpp +++ b/Fwk/VizFwk/LibRender/cvfDrawableVectors.cpp @@ -46,10 +46,7 @@ #include "cvfUniform.h" #include "cvfPrimitiveSetIndexedUShort.h" #include "cvfRay.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -219,10 +216,9 @@ void DrawableVectors::render(OpenGLContext* oglContext, ShaderProgram* shaderPro GLint colorUniformLocation = shaderProgram->uniformLocation(m_colorUniformName.toAscii().ptr()); CVF_ASSERT(colorUniformLocation != -1); -#ifndef CVF_OPENGL_ES uint minIndex = m_vectorGlyphPrimSet->minIndex(); uint maxIndex = m_vectorGlyphPrimSet->maxIndex(); -#endif + GLsizei indexCount = static_cast(m_vectorGlyphPrimSet->indexCount()); // Set the single color to use @@ -248,11 +244,7 @@ void DrawableVectors::render(OpenGLContext* oglContext, ShaderProgram* shaderPro } // Draw the arrow -#ifdef CVF_OPENGL_ES - glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, ptrOrOffset); -#else glDrawRangeElements(GL_TRIANGLES, minIndex, maxIndex, indexCount, GL_UNSIGNED_SHORT, ptrOrOffset); -#endif } // Cleanup @@ -277,9 +269,6 @@ void DrawableVectors::render(OpenGLContext* oglContext, ShaderProgram* shaderPro //-------------------------------------------------------------------------------------------------- void DrawableVectors::renderFixedFunction(OpenGLContext* oglContext, const MatrixState& matrixState) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else CVF_ASSERT(oglContext); CVF_ASSERT(m_vertexArray->size() == m_vectorArray->size()); CVF_ASSERT(m_vectorGlyph.notNull()); @@ -318,7 +307,6 @@ void DrawableVectors::renderFixedFunction(OpenGLContext* oglContext, const Matri glDisable(GL_NORMALIZE); CVF_CHECK_OGL(oglContext); -#endif // CVF_OPENGL_ES } @@ -327,9 +315,6 @@ void DrawableVectors::renderFixedFunction(OpenGLContext* oglContext, const Matri //-------------------------------------------------------------------------------------------------- void DrawableVectors::renderImmediateMode(OpenGLContext* oglContext, const MatrixState& matrixState) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else CVF_ASSERT(oglContext); CVF_ASSERT(m_vertexArray->size() == m_vectorArray->size()); CVF_ASSERT(m_vectorGlyph.notNull()); @@ -368,7 +353,6 @@ void DrawableVectors::renderImmediateMode(OpenGLContext* oglContext, const Matri glDisable(GL_NORMALIZE); CVF_CHECK_OGL(oglContext); -#endif // CVF_OPENGL_ES } diff --git a/Fwk/VizFwk/LibRender/cvfFramebufferObject.cpp b/Fwk/VizFwk/LibRender/cvfFramebufferObject.cpp index 3196999ff2..dc6cd59917 100644 --- a/Fwk/VizFwk/LibRender/cvfFramebufferObject.cpp +++ b/Fwk/VizFwk/LibRender/cvfFramebufferObject.cpp @@ -308,11 +308,7 @@ void FramebufferObject::applyOpenGL(OpenGLContext* oglContext) { if (texture->textureType() == Texture::TEXTURE_RECTANGLE) { -#ifndef CVF_OPENGL_ES glFramebufferTexture2D(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + i), GL_TEXTURE_RECTANGLE, texture->textureOglId(), 0); -#else - CVF_FAIL_MSG("Not supported on iOS"); -#endif } else { @@ -327,7 +323,6 @@ void FramebufferObject::applyOpenGL(OpenGLContext* oglContext) } // Setup draw buffers. Drawbuffer settings are stored in the FBO, so we only need to do this whenever the FBO attachments are changed. -#ifndef CVF_OPENGL_ES if (attachmentsModified) { size_t maxAttachmentIndex = CVF_MAX(m_colorRenderBuffers.size(), m_colorTextures.size()); @@ -369,7 +364,6 @@ void FramebufferObject::applyOpenGL(OpenGLContext* oglContext) glDrawBuffer(GL_NONE); } } -#endif // Depth attachment, can only have one CVF_ASSERT(!(m_depthTexture2d.notNull() && m_depthRenderBuffer.notNull())); @@ -410,11 +404,7 @@ void FramebufferObject::applyOpenGL(OpenGLContext* oglContext) } else if (m_depthTexture2d->textureType() == Texture::TEXTURE_RECTANGLE) { -#ifndef CVF_OPENGL_ES glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_RECTANGLE, m_depthTexture2d->textureOglId(), 0); -#else - CVF_FAIL_MSG("Not supported on iOS"); -#endif } else { @@ -437,11 +427,7 @@ void FramebufferObject::applyOpenGL(OpenGLContext* oglContext) } } -#ifndef CVF_OPENGL_ES glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, m_depthStencilRenderBuffer->renderbufferOglId()); -#else - CVF_FAIL_MSG("Not supported on iOS"); -#endif m_depthAttachmentVersionTick = m_depthStencilRenderBuffer->versionTick(); } @@ -461,19 +447,11 @@ void FramebufferObject::applyOpenGL(OpenGLContext* oglContext) if (m_depthStencilTexture2d->textureType() == Texture::TEXTURE_2D) { -#ifndef CVF_OPENGL_ES glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_depthStencilTexture2d->textureOglId(), 0); -#else - CVF_FAIL_MSG("Not supported on iOS"); -#endif } else if (m_depthStencilTexture2d->textureType() == Texture::TEXTURE_RECTANGLE) { -#ifndef CVF_OPENGL_ES glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_RECTANGLE, m_depthStencilTexture2d->textureOglId(), 0); -#else - CVF_FAIL_MSG("Not supported on iOS"); -#endif } else { @@ -507,12 +485,13 @@ void FramebufferObject::useDefaultWindowFramebuffer(OpenGLContext* oglContext) { CVF_CALLSITE_OPENGL(oglContext); -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("FrameBufferObject::useDefaultWindowFramebuffer() not supported on OpenGL ES"); -#else - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDrawBuffer(GL_BACK); -#endif + const OglId defaultFBO = oglContext->defaultFramebufferObject(); + glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); + + if (defaultFBO == 0) + { + glDrawBuffer(GL_BACK); + } CVF_CHECK_OGL(oglContext); } @@ -614,16 +593,11 @@ bool FramebufferObject::isFramebufferComplete(OpenGLContext* oglContext, String* case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT is returned if any of the framebuffer attachment points are framebuffer incomplete."; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT is returned if the framebuffer does not have at least one image attached to it."; break; case GL_FRAMEBUFFER_UNSUPPORTED: *failReason = "GL_FRAMEBUFFER_UNSUPPORTED is returned if the combination of internal formats of the attached images violates an implementation-dependent set of restrictions."; break; - -#ifdef CVF_OPENGL_ES - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS. Not all attached images has same width and height."; break; -#else case GL_FRAMEBUFFER_UNDEFINED: *failReason = "GL_FRAMEBUFFER_UNDEFINED is returned if target is the default framebuffer, but the default framebuffer does not exist."; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER is returned if the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for any color attachment point(s) named by GL_DRAWBUFFERi."; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER is returned if GL_READ_BUFFER is not GL_NONE and the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color attachment point named by GL_READ_BUFFER."; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE is returned if the value of GL_RENDERBUFFER_SAMPLES is not the same for all attached renderbuffers; if the value of GL_TEXTURE_SAMPLES is the not same for all attached textures; or, if the attached images are a mix of renderbuffers and textures, the value of GL_RENDERBUFFER_SAMPLES does not match the value of GL_TEXTURE_SAMPLES."; break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: *failReason = "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS is returned if any framebuffer attachment is layered, and any populated attachment is not layered, or if all populated color attachments are not from textures of the same target."; break; -#endif } } diff --git a/Fwk/VizFwk/LibRender/cvfGlyph.cpp b/Fwk/VizFwk/LibRender/cvfGlyph.cpp index 25e129beef..d0d6bd97a9 100644 --- a/Fwk/VizFwk/LibRender/cvfGlyph.cpp +++ b/Fwk/VizFwk/LibRender/cvfGlyph.cpp @@ -43,11 +43,8 @@ #include "cvfTexture.h" #include "cvfSampler.h" #include "cvfRenderStateTextureBindings.h" - -#ifndef CVF_OPENGL_ES #include "cvfTexture2D_FF.h" #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -267,7 +264,6 @@ void Glyph::setupAndBindTexture(OpenGLContext* oglContext, bool software) RenderState::Type renderStateType = m_textureBindings->type(); if (software) { -#ifndef CVF_OPENGL_ES if (renderStateType == RenderState::TEXTURE_MAPPING_FF) { RenderStateTextureMapping_FF* texMapping = static_cast(m_textureBindings.p()); @@ -275,9 +271,6 @@ void Glyph::setupAndBindTexture(OpenGLContext* oglContext, bool software) texMapping->applyOpenGL(oglContext); return; } -#else - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#endif } else { @@ -341,9 +334,6 @@ void Glyph::setupAndBindTexture(OpenGLContext* oglContext, bool software) if (software) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else // Use fixed function texture setup ref texture = new Texture2D_FF(m_textureImage.p()); texture->setWrapMode(Texture2D_FF::CLAMP); @@ -370,7 +360,6 @@ void Glyph::setupAndBindTexture(OpenGLContext* oglContext, bool software) textureMapping->setupTexture(oglContext); m_textureBindings = textureMapping; -#endif } else { diff --git a/Fwk/VizFwk/LibRender/cvfLibRender.h b/Fwk/VizFwk/LibRender/cvfLibRender.h index 61076e85ca..1821a4fcd6 100644 --- a/Fwk/VizFwk/LibRender/cvfLibRender.h +++ b/Fwk/VizFwk/LibRender/cvfLibRender.h @@ -61,6 +61,7 @@ #include "cvfOpenGLContextGroup.h" #include "cvfOpenGLResourceManager.h" #include "cvfOpenGLTypes.h" +#include "cvfOpenGLUtils.h" #include "cvfOverlayAxisCross.h" #include "cvfOverlayColorLegend.h" #include "cvfOverlayImage.h" @@ -108,9 +109,6 @@ #include "cvfVertexAttribute.h" #include "cvfVertexBundle.h" #include "cvfViewport.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" #include "cvfTexture2D_FF.h" -#endif diff --git a/Fwk/VizFwk/LibRender/cvfOpenGL.cpp b/Fwk/VizFwk/LibRender/cvfOpenGL.cpp index f27d8c3571..f3df20100c 100644 --- a/Fwk/VizFwk/LibRender/cvfOpenGL.cpp +++ b/Fwk/VizFwk/LibRender/cvfOpenGL.cpp @@ -46,8 +46,6 @@ CVF_GCC_DIAGNOSTIC_IGNORE("-Wconversion") -#ifndef CVF_OPENGL_ES - #undef glewGetContext extern "C" @@ -55,7 +53,6 @@ extern "C" #include "glew/glew.c" } -#endif // CVF_OPENGL_ES namespace cvf { @@ -133,10 +130,8 @@ String OpenGL::mapOpenGLErrorToString(cvfGLenum errorCode) case GL_INVALID_VALUE: errCodeStr = "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: errCodeStr = "GL_INVALID_OPERATION"; break; case GL_OUT_OF_MEMORY: errCodeStr = "GL_OUT_OF_MEMORY"; break; -#ifndef CVF_OPENGL_ES case GL_STACK_OVERFLOW: errCodeStr = "GL_STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: errCodeStr = "GL_STACK_UNDERFLOW"; break; -#endif case GL_NO_ERROR: errCodeStr = "GL_NO_ERROR"; break; default: diff --git a/Fwk/VizFwk/LibRender/cvfOpenGL.h b/Fwk/VizFwk/LibRender/cvfOpenGL.h index 00c50c02b8..28dd0fffc9 100644 --- a/Fwk/VizFwk/LibRender/cvfOpenGL.h +++ b/Fwk/VizFwk/LibRender/cvfOpenGL.h @@ -38,10 +38,8 @@ #pragma once -// Currently we utilize GLEW everywhere except for OpenGLES -#ifndef CVF_OPENGL_ES +// Currently we utilize GLEW everywhere #define CVF_USE_GLEW -#endif #ifdef CVF_USE_GLEW diff --git a/Fwk/VizFwk/LibRender/cvfOpenGLContext.cpp b/Fwk/VizFwk/LibRender/cvfOpenGLContext.cpp index f993313996..db9151f7e8 100644 --- a/Fwk/VizFwk/LibRender/cvfOpenGLContext.cpp +++ b/Fwk/VizFwk/LibRender/cvfOpenGLContext.cpp @@ -59,8 +59,7 @@ namespace cvf { /// The context will be added unconditionally to the \a contextGroup group //-------------------------------------------------------------------------------------------------- OpenGLContext::OpenGLContext(OpenGLContextGroup* contextGroup) -: m_contextGroup(contextGroup), - m_isValid(false) +: m_contextGroup(contextGroup) { CVF_ASSERT(m_contextGroup); m_contextGroup->addContext(this); @@ -74,8 +73,6 @@ OpenGLContext::~OpenGLContext() { //Trace::show("OpenGLContext destructor"); - m_isValid = false; - // Context group is holding references to contexts, so by the time we get to this // destructor the link to the context group must already be broken CVF_ASSERT(m_contextGroup == NULL); @@ -87,8 +84,7 @@ OpenGLContext::~OpenGLContext() //-------------------------------------------------------------------------------------------------- bool OpenGLContext::isContextValid() const { - // Also check on context group, since it may have been set to NULL after valid flag was set - if (m_contextGroup && m_isValid) + if (m_contextGroup && m_contextGroup->isContextGroupInitialized()) { return true; } @@ -102,59 +98,9 @@ bool OpenGLContext::isContextValid() const //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -bool OpenGLContext::initializeContext() +OglId OpenGLContext::defaultFramebufferObject() const { - makeCurrent(); - - if (!m_contextGroup) - { - return false; - } - - if (!m_contextGroup->isContextGroupInitialized()) - { - if (!m_contextGroup->initializeContextGroup(this)) - { - return false; - } - } - - m_isValid = true; - - return true; -} - - -//-------------------------------------------------------------------------------------------------- -/// Prepare the context for deletion -/// -/// Prepares the context for deletion by removing the context from its context group. If this is the -/// last context in the context group, this function will also try and delete the context group's -/// OpenGL resources. -/// -/// \warning After calling this function the context is no longer usable and should be deleted. -/// \warning May try and make the context current in order to free resources if this context -/// is the last context in the context group. -//-------------------------------------------------------------------------------------------------- -void OpenGLContext::shutdownContext() -{ - if (m_contextGroup) - { - CVF_ASSERT(m_contextGroup->containsContext(this)); - - // If our ref count is down to 1, there is probably something strange going on. - // Since one reference to us is being held by the context group, this means that the - // caller ISN'T holding a reference which may give him a nast surprise when this function returns! - CVF_ASSERT(refCount() > 1); - - // This call will remove the context from the group AND clean up resources in the - // group if we are the last context in the group - m_contextGroup->contextAboutToBeShutdown(this); - } - - CVF_ASSERT(m_contextGroup == NULL); - - m_isValid = false; + return 0; } diff --git a/Fwk/VizFwk/LibRender/cvfOpenGLContext.h b/Fwk/VizFwk/LibRender/cvfOpenGLContext.h index 254a656c60..2dc7af7b17 100644 --- a/Fwk/VizFwk/LibRender/cvfOpenGLContext.h +++ b/Fwk/VizFwk/LibRender/cvfOpenGLContext.h @@ -39,6 +39,7 @@ #include "cvfObject.h" #include "cvfOpenGLContextGroup.h" +#include "cvfOpenGLTypes.h" namespace cvf { @@ -58,11 +59,10 @@ class OpenGLContext : public Object virtual ~OpenGLContext(); bool isContextValid() const; - virtual bool initializeContext(); - virtual void shutdownContext(); virtual void makeCurrent() = 0; virtual bool isCurrent() const = 0; + virtual OglId defaultFramebufferObject() const; OpenGLContextGroup* group(); const OpenGLContextGroup* group() const; @@ -71,7 +71,6 @@ class OpenGLContext : public Object private: OpenGLContextGroup* m_contextGroup; // Raw pointer (to avoid circular reference) to the context group that this context belongs to. - bool m_isValid; // Will be set to true after successful initialization friend class OpenGLContextGroup; }; diff --git a/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.cpp b/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.cpp index 006f0fba96..a1779e2594 100644 --- a/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.cpp +++ b/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.cpp @@ -42,6 +42,7 @@ #include "cvfOpenGLResourceManager.h" #include "cvfOpenGLCapabilities.h" #include "cvfLogManager.h" +#include "cvfTrace.h" #include @@ -75,6 +76,8 @@ OpenGLContextGroup::OpenGLContextGroup() m_glewContextStruct(NULL), m_wglewContextStruct(NULL) { + //Trace::show("OpenGLContextGroup constructor"); + m_resourceManager = new OpenGLResourceManager; m_logger = CVF_GET_LOGGER("cee.cvf.OpenGL"); m_capabilities = new OpenGLCapabilities; @@ -105,7 +108,10 @@ OpenGLContextGroup::~OpenGLContextGroup() m_contexts.clear(); - uninitializeContextGroup(); + if (m_isInitialized) + { + uninitializeContextGroup(); + } } @@ -129,6 +135,8 @@ bool OpenGLContextGroup::isContextGroupInitialized() const //-------------------------------------------------------------------------------------------------- bool OpenGLContextGroup::initializeContextGroup(OpenGLContext* currentContext) { + //Trace::show("OpenGLContextGroup::initializeContextGroup()"); + CVF_ASSERT(currentContext); CVF_ASSERT(currentContext->isCurrent()); CVF_ASSERT(containsContext(currentContext)); @@ -139,20 +147,27 @@ bool OpenGLContextGroup::initializeContextGroup(OpenGLContext* currentContext) if (!initializeGLEW(currentContext)) { + CVF_LOG_ERROR(m_logger.p(), "Failed to intitialize GLEW in context group"); return false; } - configureCapablititesFromGLEW(currentContext); + configureCapabilitiesFromGLEW(currentContext); #ifdef WIN32 if (!initializeWGLEW(currentContext)) { + CVF_LOG_ERROR(m_logger.p(), "Failed to intitialize WGLEW in context group"); return false; } #endif #endif + CVF_LOG_DEBUG(m_logger.p(), "OpenGL initialized in context group"); + CVF_LOG_DEBUG(m_logger.p(), " version: " + m_info.version()); + CVF_LOG_DEBUG(m_logger.p(), " vendor: " + m_info.vendor()); + CVF_LOG_DEBUG(m_logger.p(), " renderer: " + m_info.renderer()); + m_isInitialized = true; } @@ -165,10 +180,12 @@ bool OpenGLContextGroup::initializeContextGroup(OpenGLContext* currentContext) //-------------------------------------------------------------------------------------------------- void OpenGLContextGroup::uninitializeContextGroup() { + //Trace::show("OpenGLContextGroup::uninitializeContextGroup()"); + CVF_ASSERT(m_contexts.empty()); CVF_ASSERT(!m_resourceManager->hasAnyOpenGLResources()); - // Just replace capablities with a new object + // Just replace capabilities with a new object m_capabilities = new OpenGLCapabilities; #ifdef CVF_USE_GLEW @@ -186,28 +203,30 @@ void OpenGLContextGroup::uninitializeContextGroup() //-------------------------------------------------------------------------------------------------- -/// Called by OpenGLContext objects when they are being shut down +/// Prepare a context for deletion /// -/// This function will remove the context \a contextToShutdown from the context group. -/// If \a contextToShutdown is the last context in the group, all resources in the group's +/// This function will remove the context \a currentContextToShutdown from the context group. +/// If \a currentContextToShutdown is the last context in the group, all resources in the group's /// resource manager will be deleted and the context group will be reset to uninitialized. /// -/// \warning This function may try and make the context passed in \a contextToShutdown curreent! +/// \warning The passed context must be the current OpenGL context! +/// \warning After calling this function the context is no longer usable and should be deleted. //-------------------------------------------------------------------------------------------------- -void OpenGLContextGroup::contextAboutToBeShutdown(OpenGLContext* contextToShutdown) +void OpenGLContextGroup::contextAboutToBeShutdown(OpenGLContext* currentContextToShutdown) { - CVF_ASSERT(contextToShutdown); - CVF_ASSERT(containsContext(contextToShutdown)); + //Trace::show("OpenGLContextGroup::contextAboutToBeShutdown()"); + + CVF_ASSERT(currentContextToShutdown); + CVF_ASSERT(containsContext(currentContextToShutdown)); // If this is the last context in the group, we'll delete all the OpenGL resources in the s resource manager before we go bool shouldUninitializeGroup = false; if (contextCount() == 1) { CVF_ASSERT(m_resourceManager.notNull()); - if (m_resourceManager->hasAnyOpenGLResources() && contextToShutdown->isContextValid()) + if (m_resourceManager->hasAnyOpenGLResources() && currentContextToShutdown->isContextValid()) { - contextToShutdown->makeCurrent(); - m_resourceManager->deleteAllOpenGLResources(contextToShutdown); + m_resourceManager->deleteAllOpenGLResources(currentContextToShutdown); } shouldUninitializeGroup = true; @@ -217,12 +236,12 @@ void OpenGLContextGroup::contextAboutToBeShutdown(OpenGLContext* contextToShutdo // Since one reference to the context is being held by this context group, this means that the // caller isn't holding a reference to the context. In this case the context object will evaporate // during the call below, and the caller will most likely get a nasty surprise - CVF_ASSERT(contextToShutdown->refCount() > 1); + CVF_ASSERT(currentContextToShutdown->refCount() > 1); // Make sure we set the back pointer before removing it from our collection // since the removal from the list may actually trigger destruction of the context (see comment above) - contextToShutdown->m_contextGroup = NULL; - m_contexts.erase(contextToShutdown); + currentContextToShutdown->m_contextGroup = NULL; + m_contexts.erase(currentContextToShutdown); if (shouldUninitializeGroup) { @@ -239,11 +258,23 @@ void OpenGLContextGroup::contextAboutToBeShutdown(OpenGLContext* contextToShutdo //-------------------------------------------------------------------------------------------------- bool OpenGLContextGroup::initializeGLEW(OpenGLContext* currentContext) { + //Trace::show("OpenGLContextGroup::initializeGLEW()"); + CVF_ASSERT(currentContext); CVF_ASSERT(m_glewContextStruct == NULL); #ifdef CVF_USE_GLEW + // Usage of GLEW requires that we have a standard OpenGL implementation available (not any Qt wrapper etc) + // Supposedly the version string should always contain at least one '.' + // Try and test this by querying the OpenGL version number and assume that there is no OpenGL available if it fails + const String sVersion(reinterpret_cast(glGetString(GL_VERSION))); + if (sVersion.find(".") == String::npos) + { + CVF_LOG_ERROR(m_logger, "Error initializing OpenGL functions, probe for OpenGL version failed. No valid OpenGL context is current"); + return false; + } + // Since we're sometimes (when using Core OpenGL) seeing some OGL errors from GLEW, check before and after call to help find them CVF_CHECK_OGL(currentContext); @@ -253,6 +284,7 @@ bool OpenGLContextGroup::initializeGLEW(OpenGLContext* currentContext) GLenum err = glewContextInit(theContextStruct); if (err != GLEW_OK) { + CVF_LOG_ERROR(m_logger, String("Error initializing GLEW, glewContextInit() returned %1").arg(err)); delete theContextStruct; return false; } @@ -261,6 +293,10 @@ bool OpenGLContextGroup::initializeGLEW(OpenGLContext* currentContext) CVF_CHECK_OGL(currentContext); + String sVendor(reinterpret_cast(glGetString(GL_VENDOR))); + String sRenderer(reinterpret_cast(glGetString(GL_RENDERER))); + m_info.setOpenGLStrings(sVersion, sVendor, sRenderer); + #else CVF_FAIL_MSG("Not implemented"); @@ -315,7 +351,7 @@ bool OpenGLContextGroup::initializeWGLEW(OpenGLContext* currentContext) /// /// \warning The passed context must be current and GLEW must already be initialized! //-------------------------------------------------------------------------------------------------- -void OpenGLContextGroup::configureCapablititesFromGLEW(OpenGLContext* currentContext) +void OpenGLContextGroup::configureCapabilitiesFromGLEW(OpenGLContext* currentContext) { #ifdef CVF_USE_GLEW CVF_CALLSITE_GLEW(currentContext); @@ -362,6 +398,15 @@ size_t OpenGLContextGroup::contextCount() const } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* OpenGLContextGroup::context(size_t index) +{ + return m_contexts.at(index); +} + + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -432,6 +477,15 @@ OpenGLCapabilities* OpenGLContextGroup::capabilities() } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +OpenGLInfo OpenGLContextGroup::info() const +{ + return m_info; +} + + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.h b/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.h index 82268b4ca2..d8052bfb30 100644 --- a/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.h +++ b/Fwk/VizFwk/LibRender/cvfOpenGLContextGroup.h @@ -40,6 +40,8 @@ #include "cvfObject.h" #include "cvfCollection.h" #include "cvfLogger.h" +#include "cvfOpenGLCapabilities.h" +#include "cvfOpenGLInfo.h" struct GLEWContextStruct; struct WGLEWContextStruct; @@ -48,7 +50,6 @@ namespace cvf { class OpenGLContext; class OpenGLResourceManager; -class OpenGLCapabilities; //================================================================================================== @@ -63,24 +64,27 @@ class OpenGLContextGroup : public Object virtual ~OpenGLContextGroup(); bool isContextGroupInitialized() const; + bool initializeContextGroup(OpenGLContext* currentContext); + void contextAboutToBeShutdown(OpenGLContext* currentContextToShutdown); size_t contextCount() const; + OpenGLContext* context(size_t index); bool containsContext(const OpenGLContext* context) const; OpenGLResourceManager* resourceManager(); Logger* logger(); OpenGLCapabilities* capabilities(); + OpenGLInfo info() const; + GLEWContextStruct* glewContextStruct(); WGLEWContextStruct* wglewContextStruct(); private: - bool initializeContextGroup(OpenGLContext* currentContext); void uninitializeContextGroup(); - void contextAboutToBeShutdown(OpenGLContext* contextToShutdown); bool initializeGLEW(OpenGLContext* currentContext); bool initializeWGLEW(OpenGLContext* currentContext); - void configureCapablititesFromGLEW(OpenGLContext* currentContext); + void configureCapabilitiesFromGLEW(OpenGLContext* currentContext); void addContext(OpenGLContext* contextToAdd); private: @@ -89,6 +93,7 @@ class OpenGLContextGroup : public Object ref m_resourceManager; // Resource manager that is shared between all contexts in this group ref m_logger; ref m_capabilities; // Capabilities of the contexts in this group context + OpenGLInfo m_info; GLEWContextStruct* m_glewContextStruct; // Pointer to the GLEW context struct WGLEWContextStruct* m_wglewContextStruct; // Pointer to the GLEW context struct diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext.cpp b/Fwk/VizFwk/LibRender/cvfOpenGLInfo.cpp similarity index 69% rename from Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext.cpp rename to Fwk/VizFwk/LibRender/cvfOpenGLInfo.cpp index c3734d7af2..198c19b6af 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext.cpp +++ b/Fwk/VizFwk/LibRender/cvfOpenGLInfo.cpp @@ -36,58 +36,66 @@ #include "cvfBase.h" -#include "cvfqtCvfBoundQGLContext.h" -#include "cvfqtOpenGLContext.h" - -namespace cvfqt { +#include "cvfOpenGLInfo.h" +namespace cvf { //================================================================================================== /// -/// \class cvfqt::CvfBoundQGLContext -/// \ingroup GuiQt +/// \class cvf::OpenGLInfo +/// \ingroup Render /// /// -/// +/// //================================================================================================== //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -CvfBoundQGLContext::CvfBoundQGLContext(cvf::OpenGLContextGroup* contextGroup, const QGLFormat & format) -: QGLContext(format) +OpenGLInfo::OpenGLInfo() { - m_cvfGLContext = new OpenGLContext(contextGroup, this); } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -CvfBoundQGLContext::~CvfBoundQGLContext() +OpenGLInfo::~OpenGLInfo() { - if (m_cvfGLContext.notNull()) - { - // TODO - // Need to resolve the case where the Qt QGLcontext (that we're deriving from) is deleted - // and we are still holding a reference to one or more OpenGLContext objects - // By the time we get here we expect that we're holding the only reference - CVF_ASSERT(m_cvfGLContext->refCount() == 1); - m_cvfGLContext = NULL; - } } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -cvf::OpenGLContext* CvfBoundQGLContext::cvfOpenGLContext() const +String OpenGLInfo::version() const { - return const_cast(m_cvfGLContext.p()); + return m_version; } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +String OpenGLInfo::vendor() const +{ + return m_vendor; +} -} // namespace cvfqt +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +String OpenGLInfo::renderer() const +{ + return m_renderer; +} +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void OpenGLInfo::setOpenGLStrings(String version, String vendor, String renderer) +{ + m_version = version; + m_vendor = vendor; + m_renderer = renderer; +} +} // namespace cvf diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext.h b/Fwk/VizFwk/LibRender/cvfOpenGLInfo.h similarity index 82% rename from Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext.h rename to Fwk/VizFwk/LibRender/cvfOpenGLInfo.h index 5160f372fc..fba0f01dd2 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtCvfBoundQGLContext.h +++ b/Fwk/VizFwk/LibRender/cvfOpenGLInfo.h @@ -37,28 +37,32 @@ #pragma once -#include "cvfOpenGLContext.h" +#include "cvfString.h" -#include - -namespace cvfqt { +namespace cvf { //================================================================================================== // -// Utility class used to piggyback OpenGLContext onto Qt's QGLContext +// // //================================================================================================== -class CvfBoundQGLContext : public QGLContext +class OpenGLInfo { public: - CvfBoundQGLContext(cvf::OpenGLContextGroup* contextGroup, const QGLFormat & format); - virtual ~CvfBoundQGLContext(); + OpenGLInfo(); + ~OpenGLInfo(); + + String version() const; + String vendor() const; + String renderer() const; - cvf::OpenGLContext* cvfOpenGLContext() const; + void setOpenGLStrings(String version, String vendor, String renderer); private: - cvf::ref m_cvfGLContext; + String m_version; + String m_vendor; + String m_renderer; }; } diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLContext.cpp b/Fwk/VizFwk/LibRender/cvfOpenGLUtils.cpp similarity index 60% rename from Fwk/VizFwk/LibGuiQt/cvfqtOpenGLContext.cpp rename to Fwk/VizFwk/LibRender/cvfOpenGLUtils.cpp index 7d29682d30..70bb4440a8 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLContext.cpp +++ b/Fwk/VizFwk/LibRender/cvfOpenGLUtils.cpp @@ -36,105 +36,30 @@ #include "cvfBase.h" +#include "cvfOpenGLUtils.h" #include "cvfOpenGL.h" -#include "cvfqtOpenGLContext.h" -#include "cvfqtCvfBoundQGLContext.h" - -#include "cvfOpenGLContextGroup.h" +#include "cvfOpenGLContext.h" #include "cvfOpenGLCapabilities.h" -namespace cvfqt { +namespace cvf { //================================================================================================== /// -/// \class cvfqt::OpenGLContext -/// \ingroup GuiQt +/// \class cvf::OpenGLUtils +/// \ingroup Render /// -/// Derived OpenGLContext that adapts a Qt QGLContext +/// Static class providing OpenGL helpers /// //================================================================================================== //-------------------------------------------------------------------------------------------------- +/// Store the current OpenGL context settings by using OpenGL's built in push methods. /// +/// Note: This call MUST be matched with a corresponding popOpenGLState() call. //-------------------------------------------------------------------------------------------------- -OpenGLContext::OpenGLContext(cvf::OpenGLContextGroup* contextGroup, QGLContext* backingQGLContext) -: cvf::OpenGLContext(contextGroup), - m_isCoreOpenGLProfile(false), - m_majorVersion(0), - m_minorVersion(0) -{ - m_qtGLContext = backingQGLContext; - - CVF_ASSERT(m_qtGLContext); - QGLFormat glFormat = m_qtGLContext->format(); - m_majorVersion = glFormat.majorVersion(); - m_minorVersion = glFormat.minorVersion(); - m_isCoreOpenGLProfile = (glFormat.profile() == QGLFormat::CoreProfile) ? true : false; -} - - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -OpenGLContext::~OpenGLContext() -{ - m_qtGLContext = NULL; -} - - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool OpenGLContext::initializeContext() -{ - if (!cvf::OpenGLContext::initializeContext()) - { - return false; - } - - // Possibly override setting for fixed function support - if (m_isCoreOpenGLProfile) - { - group()->capabilities()->setSupportsFixedFunction(false); - } - - return true; -} - - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void OpenGLContext::makeCurrent() -{ - CVF_ASSERT(m_qtGLContext); - m_qtGLContext->makeCurrent(); -} - - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -bool OpenGLContext::isCurrent() const -{ - if (m_qtGLContext) - { - if (QGLContext::currentContext() == m_qtGLContext) - { - return true; - } - } - - return false; -} - - -//-------------------------------------------------------------------------------------------------- -/// Make an effort to save current OpenGL state. Must be matched by a call to restoreOpenGLState() -//-------------------------------------------------------------------------------------------------- -void OpenGLContext::saveOpenGLState(cvf::OpenGLContext* oglContext) +void OpenGLUtils::pushOpenGLState(OpenGLContext* oglContext) { CVF_CALLSITE_OPENGL(oglContext); const cvf::OpenGLCapabilities* oglCaps = oglContext->capabilities(); @@ -178,9 +103,11 @@ void OpenGLContext::saveOpenGLState(cvf::OpenGLContext* oglContext) //-------------------------------------------------------------------------------------------------- -/// Restore OpenGL state that has been saved by saveOpenGLState() +/// Set back the stored OpenGL context settings by using OpenGL's built in pop methods. +/// +/// Note: This call MUST be matched with a corresponding pushOpenGLState() call. //-------------------------------------------------------------------------------------------------- -void OpenGLContext::restoreOpenGLState(cvf::OpenGLContext* oglContext) +void OpenGLUtils::popOpenGLState(OpenGLContext* oglContext) { CVF_CALLSITE_OPENGL(oglContext); const cvf::OpenGLCapabilities* oglCaps = oglContext->capabilities(); @@ -212,7 +139,7 @@ void OpenGLContext::restoreOpenGLState(cvf::OpenGLContext* oglContext) glPopAttrib(); CVF_CHECK_OGL(oglContext); - + // Currently not pushing vertex attribs, so comment out the pop //glPopClientAttrib(); @@ -221,6 +148,5 @@ void OpenGLContext::restoreOpenGLState(cvf::OpenGLContext* oglContext) } -} // namespace cvfqt - +} // namespace cvf diff --git a/Fwk/VizFwk/LibRender/cvfOpenGLUtils.h b/Fwk/VizFwk/LibRender/cvfOpenGLUtils.h new file mode 100644 index 0000000000..3297b18edd --- /dev/null +++ b/Fwk/VizFwk/LibRender/cvfOpenGLUtils.h @@ -0,0 +1,58 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +namespace cvf { + +class OpenGLContext; + + +//================================================================================================== +// +// +// +//================================================================================================== +class OpenGLUtils +{ +public: + static void pushOpenGLState(OpenGLContext* oglContext); + static void popOpenGLState(OpenGLContext* oglContext); +}; + +} + diff --git a/Fwk/VizFwk/LibRender/cvfOverlayAxisCross.cpp b/Fwk/VizFwk/LibRender/cvfOverlayAxisCross.cpp index 8949efe212..098f5b96c4 100644 --- a/Fwk/VizFwk/LibRender/cvfOverlayAxisCross.cpp +++ b/Fwk/VizFwk/LibRender/cvfOverlayAxisCross.cpp @@ -53,10 +53,7 @@ #include "cvfArrowGenerator.h" #include "cvfBufferObjectManaged.h" #include "cvfDrawableText.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -250,9 +247,6 @@ void OverlayAxisCross::renderAxis(OpenGLContext* oglContext, const MatrixState& //-------------------------------------------------------------------------------------------------- void OverlayAxisCross::renderAxisImmediateMode(OpenGLContext* oglContext, const MatrixState& matrixState) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else m_axis->renderImmediateMode(oglContext, matrixState); // Draw X axis triangle @@ -264,7 +258,6 @@ void OverlayAxisCross::renderAxisImmediateMode(OpenGLContext* oglContext, const RenderStateMaterial_FF yMaterial(RenderStateMaterial_FF::PURE_GREEN); yMaterial.applyOpenGL(oglContext); m_yAxisTriangle->renderImmediateMode(oglContext, matrixState); -#endif // CVF_OPENGL_ES } diff --git a/Fwk/VizFwk/LibRender/cvfOverlayColorLegend.cpp b/Fwk/VizFwk/LibRender/cvfOverlayColorLegend.cpp index b32588bcb9..19be0e7195 100644 --- a/Fwk/VizFwk/LibRender/cvfOverlayColorLegend.cpp +++ b/Fwk/VizFwk/LibRender/cvfOverlayColorLegend.cpp @@ -55,10 +55,7 @@ #include "cvfGlyph.h" #include "cvfRenderStateDepth.h" #include "cvfRenderStateLine.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -421,11 +418,7 @@ void OverlayColorLegend::renderLegend(OpenGLContext* oglContext, OverlayColorLeg UniformFloat uniformColor("u_color", Color4f(Color3f(clr))); shaderProgram->applyUniform(oglContext, uniformColor); -#ifdef CVF_OPENGL_ES - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, trianglesConnects); -#else glDrawRangeElements(GL_TRIANGLES, 0, 4, 6, GL_UNSIGNED_SHORT, trianglesConnects); -#endif } // Draw legend lines @@ -435,11 +428,7 @@ void OverlayColorLegend::renderLegend(OpenGLContext* oglContext, OverlayColorLeg UniformFloat uniformColor("u_color", Color4f(m_lineColor)); shaderProgram->applyUniform(oglContext, uniformColor); -#ifdef CVF_OPENGL_ES - glDrawElements(GL_LINES, 8, GL_UNSIGNED_SHORT, linesConnects); -#else glDrawRangeElements(GL_LINES, 0, 5, 8, GL_UNSIGNED_SHORT, linesConnects); -#endif } } @@ -464,10 +453,6 @@ void OverlayColorLegend::renderLegend(OpenGLContext* oglContext, OverlayColorLeg //-------------------------------------------------------------------------------------------------- void OverlayColorLegend::renderLegendImmediateMode(OpenGLContext* oglContext, OverlayColorLegendLayoutInfo* layout) { -#ifdef CVF_OPENGL_ES - CVF_UNUSED(layout); - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else CVF_TIGHT_ASSERT(layout); CVF_TIGHT_ASSERT(layout->size.x() > 0); CVF_TIGHT_ASSERT(layout->size.y() > 0); @@ -551,7 +536,6 @@ void OverlayColorLegend::renderLegendImmediateMode(OpenGLContext* oglContext, Ov resetDepth.applyOpenGL(oglContext); CVF_CHECK_OGL(oglContext); -#endif // CVF_OPENGL_ES } diff --git a/Fwk/VizFwk/LibRender/cvfOverlayImage.cpp b/Fwk/VizFwk/LibRender/cvfOverlayImage.cpp index 3728ab19e7..074d3466a1 100644 --- a/Fwk/VizFwk/LibRender/cvfOverlayImage.cpp +++ b/Fwk/VizFwk/LibRender/cvfOverlayImage.cpp @@ -54,10 +54,7 @@ #include "cvfRenderStateDepth.h" #include "cvfRenderStateTextureBindings.h" #include "cvfRenderStateBlending.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif #include "cvfTexture2D_FF.h" namespace cvf { @@ -173,7 +170,6 @@ void OverlayImage::render(OpenGLContext* oglContext, const Vec2i& position, cons ShaderProgram::useNoProgram(oglContext); } -#ifndef CVF_OPENGL_ES RenderStateMaterial_FF mat; mat.enableColorMaterial(true); mat.applyOpenGL(oglContext); @@ -196,7 +192,7 @@ void OverlayImage::render(OpenGLContext* oglContext, const Vec2i& position, cons m_textureBindings = textureMapping; } -#endif + // Adjust texture coordinates if (m_pow2Image.notNull()) { @@ -234,6 +230,10 @@ void OverlayImage::render(OpenGLContext* oglContext, const Vec2i& position, cons gen.addFragmentCode(ShaderSourceRepository::fs_Unlit); m_shaderProgram = gen.generate(); + } + + if (m_shaderProgram->programOglId() == 0) + { m_shaderProgram->linkProgram(oglContext); } @@ -282,7 +282,6 @@ void OverlayImage::render(OpenGLContext* oglContext, const Vec2i& position, cons if (software) { -#ifndef CVF_OPENGL_ES glColor4f(1.0f, 1.0f, 1.0f, m_blendMode == GLOBAL_ALPHA ? m_alpha : 1.0f); glBegin(GL_TRIANGLE_FAN); glTexCoord2f(textureCoords[0], textureCoords[1]); @@ -294,7 +293,6 @@ void OverlayImage::render(OpenGLContext* oglContext, const Vec2i& position, cons glTexCoord2f(textureCoords[6], textureCoords[7]); glVertex3fv(v4); glEnd(); -#endif } else { @@ -318,10 +316,8 @@ void OverlayImage::render(OpenGLContext* oglContext, const Vec2i& position, cons if (software) { -#ifndef CVF_OPENGL_ES RenderStateTextureMapping_FF resetTextureMapping; resetTextureMapping.applyOpenGL(oglContext); -#endif } if (!software) diff --git a/Fwk/VizFwk/LibRender/cvfOverlayNavigationCube.cpp b/Fwk/VizFwk/LibRender/cvfOverlayNavigationCube.cpp index 74cec4d5a6..e647829ace 100644 --- a/Fwk/VizFwk/LibRender/cvfOverlayNavigationCube.cpp +++ b/Fwk/VizFwk/LibRender/cvfOverlayNavigationCube.cpp @@ -64,11 +64,8 @@ #include "cvfSampler.h" #include "cvfRenderStateTextureBindings.h" #include "cvfRect.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" #include "cvfTexture2D_FF.h" -#endif namespace cvf { @@ -286,11 +283,7 @@ void OverlayNavigationCube::renderAxis(OpenGLContext* oglContext, const MatrixSt //-------------------------------------------------------------------------------------------------- void OverlayNavigationCube::renderAxisImmediateMode(OpenGLContext* oglContext, const MatrixState& matrixState) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else m_axis->renderImmediateMode(oglContext, matrixState); -#endif // CVF_OPENGL_ES } @@ -367,7 +360,6 @@ void OverlayNavigationCube::updateTextureBindings(OpenGLContext* oglContext, boo { if (software) { -#ifndef CVF_OPENGL_ES // Use fixed function texture setup ref texture = new Texture2D_FF(it->second.p()); texture->setWrapMode(Texture2D_FF::CLAMP); @@ -380,10 +372,6 @@ void OverlayNavigationCube::updateTextureBindings(OpenGLContext* oglContext, boo textureMapping->setTextureFunction(RenderStateTextureMapping_FF::MODULATE); m_faceTextureBindings[face] = textureMapping; -#else - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#endif - } else { @@ -420,14 +408,12 @@ void OverlayNavigationCube::renderCubeGeos(OpenGLContext* oglContext, bool softw if (software) { -#ifndef CVF_OPENGL_ES RenderStateMaterial_FF mat; mat.enableColorMaterial(true); mat.applyOpenGL(oglContext); RenderStateLighting_FF light; light.applyOpenGL(oglContext); -#endif } for (size_t i = 0; i < 6; i++) @@ -485,12 +471,8 @@ void OverlayNavigationCube::renderCubeGeos(OpenGLContext* oglContext, bool softw if (software) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else glColor3fv(renderFaceColor.ptr()); m_cubeGeos[i]->renderImmediateMode(oglContext, matrixState); -#endif } else { @@ -533,15 +515,11 @@ void OverlayNavigationCube::render2dItems(OpenGLContext* oglContext, const Vec2i if (software) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else RenderStateLighting_FF light(false); light.applyOpenGL(oglContext); glColor3fv(m_hightlightItem == NCI_HOME ? m_itemHighlightColor.ptr() : m_2dItemsColor.ptr()); m_homeGeo->renderImmediateMode(oglContext, matrixState); -#endif } else { @@ -568,12 +546,8 @@ void OverlayNavigationCube::render2dItems(OpenGLContext* oglContext, const Vec2i if (software) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else glColor3fv(renderFaceColor.ptr()); m_2dGeos[i]->renderImmediateMode(oglContext, matrixState); -#endif } else { @@ -590,12 +564,8 @@ void OverlayNavigationCube::render2dItems(OpenGLContext* oglContext, const Vec2i if (software) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else RenderStateLighting_FF resetLight; resetLight.applyOpenGL(oglContext); -#endif } } diff --git a/Fwk/VizFwk/LibRender/cvfOverlayScalarMapperLegend.cpp b/Fwk/VizFwk/LibRender/cvfOverlayScalarMapperLegend.cpp index f2d22c006c..27a3ecdcd1 100644 --- a/Fwk/VizFwk/LibRender/cvfOverlayScalarMapperLegend.cpp +++ b/Fwk/VizFwk/LibRender/cvfOverlayScalarMapperLegend.cpp @@ -55,11 +55,7 @@ #include "cvfGlyph.h" #include "cvfRenderStateDepth.h" #include "cvfRenderStateLine.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif - #include "cvfScalarMapper.h" namespace cvf { @@ -435,11 +431,7 @@ void OverlayScalarMapperLegend::renderLegend(OpenGLContext* oglContext, OverlayC UniformFloat uniformColor("u_color", Color4f(Color3f(clr))); shaderProgram->applyUniform(oglContext, uniformColor); -#ifdef CVF_OPENGL_ES - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, trianglesConnects); -#else glDrawRangeElements(GL_TRIANGLES, 0, 4, 6, GL_UNSIGNED_SHORT, trianglesConnects); -#endif } } } @@ -459,11 +451,7 @@ void OverlayScalarMapperLegend::renderLegend(OpenGLContext* oglContext, OverlayC UniformFloat uniformColor("u_color", Color4f(m_lineColor)); shaderProgram->applyUniform(oglContext, uniformColor); -#ifdef CVF_OPENGL_ES - glDrawElements(GL_LINES, 8, GL_UNSIGNED_SHORT, frameConnects); -#else glDrawRangeElements(GL_LINES, 0, 3, 8, GL_UNSIGNED_SHORT, frameConnects); -#endif } // Render tickmarks @@ -502,11 +490,7 @@ void OverlayScalarMapperLegend::renderLegend(OpenGLContext* oglContext, OverlayC linesConnects = tickLinesWoLabel; } -#ifdef CVF_OPENGL_ES - glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, linesConnects); -#else glDrawRangeElements(GL_LINES, 0, 4, 2, GL_UNSIGNED_SHORT, linesConnects); -#endif } } @@ -531,10 +515,6 @@ void OverlayScalarMapperLegend::renderLegend(OpenGLContext* oglContext, OverlayC //-------------------------------------------------------------------------------------------------- void OverlayScalarMapperLegend::renderLegendImmediateMode(OpenGLContext* oglContext, OverlayColorLegendLayoutInfo* layout) { -#ifdef CVF_OPENGL_ES - CVF_UNUSED(layout); - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else CVF_TIGHT_ASSERT(layout); CVF_TIGHT_ASSERT(layout->size.x() > 0); CVF_TIGHT_ASSERT(layout->size.y() > 0); @@ -661,7 +641,6 @@ void OverlayScalarMapperLegend::renderLegendImmediateMode(OpenGLContext* oglCont resetDepth.applyOpenGL(oglContext); CVF_CHECK_OGL(oglContext); -#endif // CVF_OPENGL_ES } diff --git a/Fwk/VizFwk/LibRender/cvfOverlayTextBox.cpp b/Fwk/VizFwk/LibRender/cvfOverlayTextBox.cpp index f615501b97..31a83bf8d8 100644 --- a/Fwk/VizFwk/LibRender/cvfOverlayTextBox.cpp +++ b/Fwk/VizFwk/LibRender/cvfOverlayTextBox.cpp @@ -49,10 +49,7 @@ #include "cvfFont.h" #include "cvfGlyph.h" #include "cvfRenderStateLine.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -183,14 +180,13 @@ void OverlayTextBox::renderBackgroundAndBorder(OpenGLContext* oglContext, const ShaderProgram::useNoProgram(oglContext); } -#ifndef CVF_OPENGL_ES RenderStateMaterial_FF mat; mat.enableColorMaterial(true); mat.applyOpenGL(oglContext); RenderStateLighting_FF light(false); light.applyOpenGL(oglContext); -#endif + projCam.applyOpenGL(); } else @@ -225,7 +221,6 @@ void OverlayTextBox::renderBackgroundAndBorder(OpenGLContext* oglContext, const { if (software) { -#ifndef CVF_OPENGL_ES glColor4fv(m_backgroundColor.ptr()); glBegin(GL_TRIANGLE_FAN); glVertex3fv(v1); @@ -233,7 +228,6 @@ void OverlayTextBox::renderBackgroundAndBorder(OpenGLContext* oglContext, const glVertex3fv(v3); glVertex3fv(v4); glEnd(); -#endif } else { @@ -248,7 +242,6 @@ void OverlayTextBox::renderBackgroundAndBorder(OpenGLContext* oglContext, const { if (software) { -#ifndef CVF_OPENGL_ES glColor3fv(m_borderColor.ptr()); glBegin(GL_LINE_LOOP); glVertex3fv(v1); @@ -256,7 +249,6 @@ void OverlayTextBox::renderBackgroundAndBorder(OpenGLContext* oglContext, const glVertex3fv(v3); glVertex3fv(v4); glEnd(); -#endif } else { diff --git a/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUInt.cpp b/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUInt.cpp index 223172aa5e..4f803b4363 100644 --- a/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUInt.cpp +++ b/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUInt.cpp @@ -122,11 +122,7 @@ void PrimitiveSetIndexedUInt::render(OpenGLContext* oglContext) const ptrOrOffset = m_indices->ptr(); } -#ifdef CVF_OPENGL_ES - glDrawElements(primitiveTypeOpenGL(), numIndices, GL_UNSIGNED_INT, ptrOrOffset); -#else glDrawRangeElements(primitiveTypeOpenGL(), m_minIndex, m_maxIndex, numIndices, GL_UNSIGNED_INT, ptrOrOffset); -#endif CVF_CHECK_OGL(oglContext); } diff --git a/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUShort.cpp b/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUShort.cpp index 24a3c8ef5d..41ccb08ac6 100644 --- a/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUShort.cpp +++ b/Fwk/VizFwk/LibRender/cvfPrimitiveSetIndexedUShort.cpp @@ -121,11 +121,7 @@ void PrimitiveSetIndexedUShort::render(OpenGLContext* oglContext) const ptrOrOffset = m_indices->ptr(); } -#ifdef CVF_OPENGL_ES - glDrawElements(primitiveTypeOpenGL(), numIndices, GL_UNSIGNED_SHORT, ptrOrOffset); -#else glDrawRangeElements(primitiveTypeOpenGL(), m_minIndex, m_maxIndex, numIndices, GL_UNSIGNED_SHORT, ptrOrOffset); -#endif } diff --git a/Fwk/VizFwk/LibRender/cvfRenderState.h b/Fwk/VizFwk/LibRender/cvfRenderState.h index 4ddcac7bd2..17b44a0dc8 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderState.h +++ b/Fwk/VizFwk/LibRender/cvfRenderState.h @@ -66,13 +66,11 @@ class RenderState : public Object STENCIL, TEXTURE_BINDINGS, -#ifndef CVF_OPENGL_ES LIGHTING_FF, //Fixed function MATERIAL_FF, //Fixed function NORMALIZE_FF, //Fixed function TEXTURE_MAPPING_FF, //Fixed function CLIP_PLANES_FF, //Fixed function -#endif COUNT // Must be the last entry }; diff --git a/Fwk/VizFwk/LibRender/cvfRenderStateBlending.cpp b/Fwk/VizFwk/LibRender/cvfRenderStateBlending.cpp index 5ffb8d9713..252505393a 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderStateBlending.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderStateBlending.cpp @@ -229,10 +229,8 @@ cvfGLenum RenderStateBlending::blendEquationOpenGL(Equation eq) const case FUNC_ADD: return GL_FUNC_ADD; case FUNC_SUBTRACT: return GL_FUNC_SUBTRACT; case FUNC_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT; -#ifndef CVF_OPENGL_ES case MIN: return GL_MIN; case MAX: return GL_MAX; -#endif } CVF_FAIL_MSG("Unhandled blend equation"); diff --git a/Fwk/VizFwk/LibRender/cvfRenderStateLine.cpp b/Fwk/VizFwk/LibRender/cvfRenderStateLine.cpp index 5c6458fb7e..ae3233f831 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderStateLine.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderStateLine.cpp @@ -110,7 +110,6 @@ void RenderStateLine::applyOpenGL(OpenGLContext* oglContext) const glLineWidth(m_lineWidth); -#ifndef CVF_OPENGL_ES if (m_smooth) { glEnable(GL_LINE_SMOOTH); @@ -119,7 +118,6 @@ void RenderStateLine::applyOpenGL(OpenGLContext* oglContext) const { glDisable(GL_LINE_SMOOTH); } -#endif } diff --git a/Fwk/VizFwk/LibRender/cvfRenderStatePoint.cpp b/Fwk/VizFwk/LibRender/cvfRenderStatePoint.cpp index b6bff4dcf6..c6fe7c9ea8 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderStatePoint.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderStatePoint.cpp @@ -128,9 +128,7 @@ void RenderStatePoint::applyOpenGL(OpenGLContext* oglContext) const { CVF_CALLSITE_OPENGL(oglContext); - // OpenGL ES does not support fixed point size // Point size is always specified using GLSL's gl_PointSize -#ifndef CVF_OPENGL_ES bool openGL2Support = oglContext->capabilities()->supportsOpenGL2(); if (m_sizeMode == FIXED_SIZE) @@ -173,7 +171,6 @@ void RenderStatePoint::applyOpenGL(OpenGLContext* oglContext) const CVF_LOG_RENDER_ERROR(oglContext, "Context does not support point sprites."); } } -#endif CVF_CHECK_OGL(oglContext); } diff --git a/Fwk/VizFwk/LibRender/cvfRenderStatePolygonMode.cpp b/Fwk/VizFwk/LibRender/cvfRenderStatePolygonMode.cpp index 4224172e94..f908b44e89 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderStatePolygonMode.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderStatePolygonMode.cpp @@ -114,7 +114,6 @@ RenderStatePolygonMode::Mode RenderStatePolygonMode::backFace() const //-------------------------------------------------------------------------------------------------- void RenderStatePolygonMode::applyOpenGL(OpenGLContext* oglContext) const { -#ifndef CVF_OPENGL_ES if (m_frontFaceMode == m_backFaceMode) { glPolygonMode(GL_FRONT_AND_BACK, polygonModeOpenGL(m_frontFaceMode)); @@ -124,7 +123,6 @@ void RenderStatePolygonMode::applyOpenGL(OpenGLContext* oglContext) const glPolygonMode(GL_FRONT, polygonModeOpenGL(m_frontFaceMode)); glPolygonMode(GL_BACK, polygonModeOpenGL(m_backFaceMode)); } -#endif CVF_CHECK_OGL(oglContext); } @@ -137,12 +135,10 @@ cvfGLenum RenderStatePolygonMode::polygonModeOpenGL(Mode mode) { switch (mode) { -#ifndef CVF_OPENGL_ES case FILL: return GL_FILL; case LINE: return GL_LINE; case POINT: return GL_POINT; default: CVF_FAIL_MSG("Unhandled polygon mode"); -#endif } return 0; diff --git a/Fwk/VizFwk/LibRender/cvfRenderStatePolygonOffset.cpp b/Fwk/VizFwk/LibRender/cvfRenderStatePolygonOffset.cpp index f799eb25fa..2eb5692d4d 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderStatePolygonOffset.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderStatePolygonOffset.cpp @@ -197,13 +197,11 @@ void RenderStatePolygonOffset::applyOpenGL(OpenGLContext* oglContext) const if (m_enableFillMode) glEnable(GL_POLYGON_OFFSET_FILL); else glDisable(GL_POLYGON_OFFSET_FILL); -#ifndef CVF_OPENGL_ES if (m_enableLineMode) glEnable(GL_POLYGON_OFFSET_LINE); else glDisable(GL_POLYGON_OFFSET_LINE); if (m_enablePointMode) glEnable(GL_POLYGON_OFFSET_POINT); else glDisable(GL_POLYGON_OFFSET_POINT); -#endif CVF_CHECK_OGL(oglContext); } diff --git a/Fwk/VizFwk/LibRender/cvfRenderStateTracker.cpp b/Fwk/VizFwk/LibRender/cvfRenderStateTracker.cpp index 250b9e5f5a..f5a73dbe9a 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderStateTracker.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderStateTracker.cpp @@ -51,10 +51,7 @@ #include "cvfRenderStateTextureBindings.h" #include "cvfOpenGLContext.h" #include "cvfOpenGLCapabilities.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif #include @@ -100,13 +97,11 @@ void RenderStateTracker::setupDefaultRenderStates() m_defaultRenderStates[RenderState::STENCIL] = new RenderStateStencil; m_defaultRenderStates[RenderState::TEXTURE_BINDINGS] = new RenderStateTextureBindings; -#ifndef CVF_OPENGL_ES m_defaultRenderStates[RenderState::LIGHTING_FF] = new RenderStateLighting_FF; m_defaultRenderStates[RenderState::MATERIAL_FF] = new RenderStateMaterial_FF; m_defaultRenderStates[RenderState::NORMALIZE_FF] = new RenderStateNormalize_FF(false); m_defaultRenderStates[RenderState::TEXTURE_MAPPING_FF] = new RenderStateTextureMapping_FF; m_defaultRenderStates[RenderState::CLIP_PLANES_FF] = new RenderStateClipPlanes_FF; -#endif } diff --git a/Fwk/VizFwk/LibRender/cvfRenderbufferObject.cpp b/Fwk/VizFwk/LibRender/cvfRenderbufferObject.cpp index 29bfc7d24d..47a114e7f3 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderbufferObject.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderbufferObject.cpp @@ -165,11 +165,9 @@ cvfGLenum RenderbufferObject::intenalFormatOpenGL() const { case RGBA: return GL_RGBA; case DEPTH_COMPONENT16: return GL_DEPTH_COMPONENT16; -#ifndef CVF_OPENGL_ES case DEPTH_COMPONENT24: return GL_DEPTH_COMPONENT24; case DEPTH_COMPONENT32: return GL_DEPTH_COMPONENT32; case DEPTH24_STENCIL8: return GL_DEPTH24_STENCIL8; -#endif } CVF_FAIL_MSG("Illegal renderbuffer format"); diff --git a/Fwk/VizFwk/LibRender/cvfRenderingScissor.cpp b/Fwk/VizFwk/LibRender/cvfRenderingScissor.cpp index 4fbb780e5e..2e6cf0fae8 100644 --- a/Fwk/VizFwk/LibRender/cvfRenderingScissor.cpp +++ b/Fwk/VizFwk/LibRender/cvfRenderingScissor.cpp @@ -139,9 +139,7 @@ void RenderingScissor::applyOpenGL(OpenGLContext* oglContext, Viewport::ClearMod if ( clearFlags & GL_DEPTH_BUFFER_BIT ) { glDepthMask(GL_TRUE); - #ifndef CVF_OPENGL_ES glClearDepth(1.0f); - #endif // CVF_OPENGL_ES } if ( clearFlags & GL_STENCIL_BUFFER_BIT ) @@ -174,6 +172,8 @@ void RenderingScissor::unApplyOpenGL(OpenGLContext* oglContext) m_scissorBoxToRestore[1], m_scissorBoxToRestore[2], m_scissorBoxToRestore[3]); + + CVF_CHECK_OGL(oglContext); } } \ No newline at end of file diff --git a/Fwk/VizFwk/LibRender/cvfShader.cpp b/Fwk/VizFwk/LibRender/cvfShader.cpp index ca6ac8f549..f578ff6f9e 100644 --- a/Fwk/VizFwk/LibRender/cvfShader.cpp +++ b/Fwk/VizFwk/LibRender/cvfShader.cpp @@ -141,9 +141,7 @@ bool Shader::compile(OpenGLContext* oglContext) { case VERTEX_SHADER: glShaderType = GL_VERTEX_SHADER; break; case FRAGMENT_SHADER: glShaderType = GL_FRAGMENT_SHADER; break; -#ifndef CVF_OPENGL_ES case GEOMETRY_SHADER: glShaderType = GL_GEOMETRY_SHADER; break; -#endif default: CVF_FAIL_MSG("Unhandled shader type"); break; } @@ -183,6 +181,16 @@ bool Shader::compile(OpenGLContext* oglContext) String errStr = String("Error compiling shader: '%1'\n").arg(m_shaderName); errStr += "GLSL details:\n"; errStr += shaderInfoLog(oglContext); + + // { + // errStr += "Shader prog:\n"; + // std::vector progArr = m_source.split("\n"); + // for (size_t i = 0; i < progArr.size(); ++i) + // { + // errStr += String("%1: %2\n").arg(static_cast(i + 1), 3).arg(progArr[i]); + // } + // } + CVF_LOG_RENDER_ERROR(oglContext, errStr); return false; } diff --git a/Fwk/VizFwk/LibRender/cvfShaderProgramGenerator.cpp b/Fwk/VizFwk/LibRender/cvfShaderProgramGenerator.cpp index 68e9640977..5cd7c8b51e 100644 --- a/Fwk/VizFwk/LibRender/cvfShaderProgramGenerator.cpp +++ b/Fwk/VizFwk/LibRender/cvfShaderProgramGenerator.cpp @@ -241,10 +241,6 @@ String ShaderSourceCombiner::combinedSource() const combinedSource = String("#version %1\n\n").arg(maxVersion); } -#ifdef CVF_OPENGL_ES - combinedSource += "#define CVF_OPENGL_ES\n"; -#endif - for (i = 0; i < m_shaderCodes.size(); i++) { if (m_enableDebugComments) diff --git a/Fwk/VizFwk/LibRender/cvfShaderSourceRepository.cpp b/Fwk/VizFwk/LibRender/cvfShaderSourceRepository.cpp index 67eee1594c..2decf3369a 100644 --- a/Fwk/VizFwk/LibRender/cvfShaderSourceRepository.cpp +++ b/Fwk/VizFwk/LibRender/cvfShaderSourceRepository.cpp @@ -82,17 +82,12 @@ String ShaderSourceRepository::shaderSource(ShaderIdent shaderIdent) { if (rawSource.size() > 0) { -#ifdef CVF_OPENGL_ES - // Always version 100 on OpenGL ES - shaderProg = "#version 100\nprecision highp float;\n"; -#else // Default on desktop is GLSL 1.2 (OpenGL 2.1) unless the shader explicitly specifies a version if (rawSource[0] != '#') { shaderProg = "#version 120\n"; } -#endif - + shaderProg += rawSource.ptr(); } } diff --git a/Fwk/VizFwk/LibRender/cvfShaderSourceStrings.h b/Fwk/VizFwk/LibRender/cvfShaderSourceStrings.h index c6a027a8ab..32eb38d77e 100644 --- a/Fwk/VizFwk/LibRender/cvfShaderSourceStrings.h +++ b/Fwk/VizFwk/LibRender/cvfShaderSourceStrings.h @@ -7,11 +7,7 @@ //############################################################################################################################# static const char calcClipDistances_inl[] = " \n" -"#ifdef CVF_OPENGL_ES \n" -"uniform mediump int u_clipPlaneCount; \n" -"#else \n" "uniform int u_clipPlaneCount; \n" -"#endif \n" " \n" "uniform vec4 u_ecClipPlanes[6]; \n" " \n" @@ -1066,10 +1062,6 @@ static const char vs_Minimal_inl[] = " vec3 ecPosition = (cvfu_modelViewMatrix * cvfa_vertex).xyz; \n" " calcClipDistances(vec4(ecPosition, 1)); \n" "#endif \n" -" \n" -"#ifdef CVF_OPENGL_ES \n" -" gl_PointSize = 1.0; \n" -"#endif \n" "} \n"; @@ -1100,10 +1092,6 @@ static const char vs_MinimalTexture_inl[] = " vec3 ecPosition = (cvfu_modelViewMatrix * cvfa_vertex).xyz; \n" " calcClipDistances(vec4(ecPosition, 1)); \n" "#endif \n" -" \n" -"#ifdef CVF_OPENGL_ES \n" -" gl_PointSize = 1.0; \n" -"#endif \n" "} \n"; diff --git a/Fwk/VizFwk/LibRender/cvfTextDrawer.cpp b/Fwk/VizFwk/LibRender/cvfTextDrawer.cpp index a4c4350c71..708d74440a 100644 --- a/Fwk/VizFwk/LibRender/cvfTextDrawer.cpp +++ b/Fwk/VizFwk/LibRender/cvfTextDrawer.cpp @@ -54,10 +54,7 @@ #include "cvfRenderStateBlending.h" #include "cvfRenderStatePolygonOffset.h" #include "cvfOpenGLCapabilities.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -309,7 +306,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix ShaderProgram::useNoProgram(oglContext); } -#ifndef CVF_OPENGL_ES RenderStateMaterial_FF mat; mat.enableColorMaterial(true); mat.applyOpenGL(oglContext); @@ -329,7 +325,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix glDisable(GL_TEXTURE_2D); projCam.applyOpenGL(); -#endif } else { @@ -390,7 +385,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix { if (softwareRendering) { -#ifndef CVF_OPENGL_ES glEnable(GL_COLOR_MATERIAL); glDisable(GL_TEXTURE_2D); glColor3fv(m_backgroundColor.ptr()); @@ -400,7 +394,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix glVertex3fv(vertices[v]); } glEnd(); -#endif } else { @@ -416,7 +409,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix { if (softwareRendering) { -#ifndef CVF_OPENGL_ES glColor3fv(m_borderColor.ptr()); glBegin(GL_LINE_LOOP); for (size_t v = 0; v < vertices.size(); ++v) @@ -424,7 +416,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix glVertex3fv(vertices[v]); } glEnd(); -#endif } else { @@ -448,10 +439,8 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix // ------------------------------------------------------------------------- if (softwareRendering) { -#ifndef CVF_OPENGL_ES glEnable(GL_TEXTURE_2D); glColor3fv(m_textColor.ptr()); -#endif } else { @@ -547,7 +536,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix if (softwareRendering) { -#ifndef CVF_OPENGL_ES glBegin(GL_TRIANGLES); // First triangle in quad @@ -567,7 +555,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix glVertex3fv(vertices[3]); glEnd(); -#endif } else { @@ -590,7 +577,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix if (softwareRendering) { -#ifndef CVF_OPENGL_ES // apply the projection matrix glMatrixMode(GL_PROJECTION); glLoadMatrixf(matrixState.projectionMatrix().ptr()); @@ -604,7 +590,6 @@ void TextDrawer::doRender2d(OpenGLContext* oglContext, const MatrixState& matrix RenderStateLighting_FF light; light.applyOpenGL(oglContext); -#endif } else { diff --git a/Fwk/VizFwk/LibRender/cvfTexture.cpp b/Fwk/VizFwk/LibRender/cvfTexture.cpp index c7572e7ccf..3e0165e0a2 100644 --- a/Fwk/VizFwk/LibRender/cvfTexture.cpp +++ b/Fwk/VizFwk/LibRender/cvfTexture.cpp @@ -261,18 +261,12 @@ bool Texture::setupTexture(OpenGLContext* oglContext) } else if (m_internalFormat == DEPTH24_STENCIL8) { -#ifndef CVF_OPENGL_ES - CVF_ASSERT(m_image.isNull()); CVF_ASSERT(!m_enableMipmapGeneration); glTexImage2D(GL_TEXTURE_2D, 0, internalFormatOpenGL(), static_cast(m_width), static_cast(m_height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, 0); -#else - CVF_FAIL_MSG("Not supported on IOS"); -#endif } else { -#ifndef CVF_OPENGL_ES if (!supportsGenerateMipmapFunc) { // Explicit mipmap generation not supported so must configure before specifying texture image @@ -286,7 +280,6 @@ bool Texture::setupTexture(OpenGLContext* oglContext) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_FALSE); } } -#endif glTexImage2D(GL_TEXTURE_2D, 0, internalFormatOpenGL(), static_cast(m_width), static_cast(m_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, m_image.notNull() ? m_image->ptr() : 0); @@ -302,7 +295,6 @@ bool Texture::setupTexture(OpenGLContext* oglContext) case TEXTURE_RECTANGLE: { -#ifndef CVF_OPENGL_ES CVF_ASSERT(!m_enableMipmapGeneration); if (m_internalFormat == DEPTH_COMPONENT16 || m_internalFormat == DEPTH_COMPONENT24 || m_internalFormat == DEPTH_COMPONENT32) @@ -314,9 +306,7 @@ bool Texture::setupTexture(OpenGLContext* oglContext) { glTexImage2D(GL_TEXTURE_RECTANGLE, 0, internalFormatOpenGL(), static_cast(m_width), static_cast(m_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, m_image.notNull() ? m_image->ptr() : 0); } -#else - CVF_FAIL_MSG("Not supported on iOS"); -#endif + break; } @@ -332,7 +322,6 @@ bool Texture::setupTexture(OpenGLContext* oglContext) } else { -#ifndef CVF_OPENGL_ES if (!supportsGenerateMipmapFunc) { if (m_enableMipmapGeneration) @@ -345,7 +334,6 @@ bool Texture::setupTexture(OpenGLContext* oglContext) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_FALSE); } } -#endif CVF_ASSERT(m_cubeMapImages.size() == 6); uint i; @@ -400,12 +388,7 @@ bool Texture::isBound(OpenGLContext* /*oglContext*/) const switch (m_textureType) { case TEXTURE_2D: glGetIntegerv(GL_TEXTURE_BINDING_2D, ¤tTextureBinding); break; - case TEXTURE_RECTANGLE: -#ifndef CVF_OPENGL_ES - glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, ¤tTextureBinding); break; -#else - CVF_FAIL_MSG("Not supported on iOS"); break; -#endif + case TEXTURE_RECTANGLE: glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE, ¤tTextureBinding); break; case TEXTURE_CUBE_MAP: glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, ¤tTextureBinding); break; } @@ -438,12 +421,7 @@ void Texture::setupTextureParamsFromSampler(OpenGLContext* oglContext, const Sam { case Sampler::CLAMP_TO_EDGE: oglWrapS = GL_CLAMP_TO_EDGE; break; case Sampler::REPEAT: oglWrapS = GL_REPEAT; break; - case Sampler::CLAMP_TO_BORDER: -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("CLAMP_TO_BORDER not supported"); break; -#else - oglWrapS = GL_CLAMP_TO_BORDER; break; -#endif + case Sampler::CLAMP_TO_BORDER: oglWrapS = GL_CLAMP_TO_BORDER; break; case Sampler::MIRRORED_REPEAT: oglWrapS = GL_MIRRORED_REPEAT; break; } @@ -451,11 +429,7 @@ void Texture::setupTextureParamsFromSampler(OpenGLContext* oglContext, const Sam { case Sampler::CLAMP_TO_EDGE: oglWrapT = GL_CLAMP_TO_EDGE; break; case Sampler::REPEAT: oglWrapT = GL_REPEAT; break; -#ifdef CVF_OPENGL_ES - case Sampler::CLAMP_TO_BORDER: CVF_FAIL_MSG("CLAMP_TO_BORDER not supported"); break; -#else case Sampler::CLAMP_TO_BORDER: oglWrapT = GL_CLAMP_TO_BORDER; break; -#endif case Sampler::MIRRORED_REPEAT: oglWrapT = GL_MIRRORED_REPEAT; break; } @@ -486,13 +460,11 @@ void Texture::setupTextureParamsFromSampler(OpenGLContext* oglContext, const Sam glTexParameteri(textureType, GL_TEXTURE_MAG_FILTER, oglMagFilter); // HACK -#ifndef CVF_OPENGL_ES if (m_internalFormat == DEPTH_COMPONENT16 || m_internalFormat == DEPTH_COMPONENT24 || m_internalFormat == DEPTH_COMPONENT32) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); } -#endif // Set these to openGL // TODO TEXTURE_WRAP_R, TEXTURE_BORDER_COLOR, TEXTURE_MIN_LOD, TEXTURE_MAX_LOD, TEXTURE_LOD_BIAS, @@ -664,13 +636,11 @@ cvfGLint Texture::internalFormatOpenGL() const { case RGBA: return GL_RGBA; case DEPTH_COMPONENT16: return GL_DEPTH_COMPONENT16; -#ifndef CVF_OPENGL_ES case RGBA32F: return GL_RGBA32F; case R32F: return GL_R32F; case DEPTH_COMPONENT24: return GL_DEPTH_COMPONENT24; case DEPTH_COMPONENT32: return GL_DEPTH_COMPONENT32; case DEPTH24_STENCIL8: return GL_DEPTH24_STENCIL8; -#endif } CVF_FAIL_MSG("Illegal texture internal format"); @@ -686,9 +656,7 @@ cvfGLenum Texture::textureTypeOpenGL() const switch(m_textureType) { case TEXTURE_2D: return GL_TEXTURE_2D; -#ifndef CVF_OPENGL_ES case TEXTURE_RECTANGLE: return GL_TEXTURE_RECTANGLE; -#endif case TEXTURE_CUBE_MAP: return GL_TEXTURE_CUBE_MAP; } diff --git a/Fwk/VizFwk/LibRender/cvfVertexAttribute.cpp b/Fwk/VizFwk/LibRender/cvfVertexAttribute.cpp index 51c65fcd09..f954a7c831 100644 --- a/Fwk/VizFwk/LibRender/cvfVertexAttribute.cpp +++ b/Fwk/VizFwk/LibRender/cvfVertexAttribute.cpp @@ -175,9 +175,7 @@ void AttribSetupStrategyInt::setupFromBufferObject(OpenGLContext* oglContext, ui if (oglContext->capabilities()->supportsOpenGLVer(3)) { -#ifndef CVF_OPENGL_ES glVertexAttribIPointer(static_cast(vertexAttributeIndex), static_cast(compCount), compTypeOpenGL, static_cast(strideInBytes), CVF_OGL_BUFFER_OFFSET(bufferOffsetInBytes)); -#endif } else { @@ -197,9 +195,7 @@ void AttribSetupStrategyInt::setupFromClientMemory(OpenGLContext* oglContext, ui if (oglContext->capabilities()->supportsOpenGLVer(3)) { -#ifndef CVF_OPENGL_ES glVertexAttribIPointer(static_cast(vertexAttributeIndex), static_cast(compCount), compTypeOpenGL, 0, ptr); -#endif } else { diff --git a/Fwk/VizFwk/LibRender/cvfVertexBundle.cpp b/Fwk/VizFwk/LibRender/cvfVertexBundle.cpp index 33a3ef6888..6e8725fb63 100644 --- a/Fwk/VizFwk/LibRender/cvfVertexBundle.cpp +++ b/Fwk/VizFwk/LibRender/cvfVertexBundle.cpp @@ -581,10 +581,6 @@ void VertexBundle::useBundleFixedFunction(OpenGLContext* oglContext, VertexBundl bundleUsage->setFixedFunction(true); -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else - if (m_attribVertices.notNull()) { if (m_boVertices.notNull() && m_boVertices->isUploaded()) @@ -658,8 +654,6 @@ void VertexBundle::useBundleFixedFunction(OpenGLContext* oglContext, VertexBundl } CVF_CHECK_OGL(oglContext); - -#endif // CVF_OPENGL_ES } @@ -672,16 +666,12 @@ void VertexBundle::finishUseBundle(OpenGLContext* oglContext, VertexBundleUsage* if (bundleUsage->fixedFunction()) { -#ifdef CVF_OPENGL_ES - CVF_FAIL_MSG("Not supported on OpenGL ES"); -#else CVF_TIGHT_ASSERT(oglContext->capabilities()->supportsFixedFunction()); if (m_vertexCount > 0) glDisableClientState(GL_VERTEX_ARRAY); if (m_hasNormals) glDisableClientState(GL_NORMAL_ARRAY); if (m_hasTexCoords) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (m_hasColors) glDisableClientState(GL_COLOR_ARRAY); -#endif } else { diff --git a/Fwk/VizFwk/LibRender/cvfViewport.cpp b/Fwk/VizFwk/LibRender/cvfViewport.cpp index c8ebdba73d..0756afc192 100644 --- a/Fwk/VizFwk/LibRender/cvfViewport.cpp +++ b/Fwk/VizFwk/LibRender/cvfViewport.cpp @@ -206,9 +206,7 @@ void Viewport::applyOpenGL(OpenGLContext* oglContext, ClearMode clearMode) if (clearFlags & GL_DEPTH_BUFFER_BIT) { glDepthMask(GL_TRUE); - #ifndef CVF_OPENGL_ES glClearDepth(m_clearDepth); - #endif // CVF_OPENGL_ES } if (clearFlags & GL_STENCIL_BUFFER_BIT) diff --git a/Fwk/VizFwk/LibRender/glsl/calcClipDistances.glsl b/Fwk/VizFwk/LibRender/glsl/calcClipDistances.glsl index 3b23bf1d65..99e150e912 100644 --- a/Fwk/VizFwk/LibRender/glsl/calcClipDistances.glsl +++ b/Fwk/VizFwk/LibRender/glsl/calcClipDistances.glsl @@ -1,9 +1,5 @@ -#ifdef CVF_OPENGL_ES -uniform mediump int u_clipPlaneCount; -#else uniform int u_clipPlaneCount; -#endif uniform vec4 u_ecClipPlanes[6]; diff --git a/Fwk/VizFwk/LibRender/glsl/vs_Minimal.glsl b/Fwk/VizFwk/LibRender/glsl/vs_Minimal.glsl index b60a1ed6af..38e28f1c6c 100644 --- a/Fwk/VizFwk/LibRender/glsl/vs_Minimal.glsl +++ b/Fwk/VizFwk/LibRender/glsl/vs_Minimal.glsl @@ -18,8 +18,4 @@ void main () vec3 ecPosition = (cvfu_modelViewMatrix * cvfa_vertex).xyz; calcClipDistances(vec4(ecPosition, 1)); #endif - -#ifdef CVF_OPENGL_ES - gl_PointSize = 1.0; -#endif } diff --git a/Fwk/VizFwk/LibRender/glsl/vs_MinimalTexture.glsl b/Fwk/VizFwk/LibRender/glsl/vs_MinimalTexture.glsl index c2e29dd7e7..d570c465e3 100644 --- a/Fwk/VizFwk/LibRender/glsl/vs_MinimalTexture.glsl +++ b/Fwk/VizFwk/LibRender/glsl/vs_MinimalTexture.glsl @@ -21,8 +21,4 @@ void main () vec3 ecPosition = (cvfu_modelViewMatrix * cvfa_vertex).xyz; calcClipDistances(vec4(ecPosition, 1)); #endif - -#ifdef CVF_OPENGL_ES - gl_PointSize = 1.0; -#endif } diff --git a/Fwk/VizFwk/LibStructGrid/CMakeLists.txt b/Fwk/VizFwk/LibStructGrid/CMakeLists.txt index a8e657429f..f516a7b784 100644 --- a/Fwk/VizFwk/LibStructGrid/CMakeLists.txt +++ b/Fwk/VizFwk/LibStructGrid/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibStructGrid) diff --git a/Fwk/VizFwk/LibStructGrid/LibStructGrid.vcxproj b/Fwk/VizFwk/LibStructGrid/LibStructGrid.vcxproj deleted file mode 100644 index e6dc90aa67..0000000000 --- a/Fwk/VizFwk/LibStructGrid/LibStructGrid.vcxproj +++ /dev/null @@ -1,259 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {C22D8A0D-2318-3353-F75A-E83B82A3B29F} - LibStructGrid - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibStructGrid/LibStructGrid.vcxproj.filters b/Fwk/VizFwk/LibStructGrid/LibStructGrid.vcxproj.filters deleted file mode 100644 index 4a348125f0..0000000000 --- a/Fwk/VizFwk/LibStructGrid/LibStructGrid.vcxproj.filters +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibUtilities/CMakeLists.txt b/Fwk/VizFwk/LibUtilities/CMakeLists.txt index ac16f1a9c0..3409cf93d6 100644 --- a/Fwk/VizFwk/LibUtilities/CMakeLists.txt +++ b/Fwk/VizFwk/LibUtilities/CMakeLists.txt @@ -1,10 +1,14 @@ -cmake_minimum_required(VERSION 2.8) - project(LibUtilities) -# Use our strict compile flags -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STRICT_CXX_FLAGS}") +# Use our strict compile flags only on windows since C++17 gives too +# much trouble in the JPEG code when using GCC +if (WIN32) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STRICT_CXX_FLAGS}") +else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_BASE_CXX_FLAGS}") +endif() + if (CMAKE_COMPILER_IS_GNUCXX) # Don't allow the compiler to assume strict aliasing when doing optimizations (the culprit is JPEG code) diff --git a/Fwk/VizFwk/LibUtilities/LibUtilities.vcxproj b/Fwk/VizFwk/LibUtilities/LibUtilities.vcxproj deleted file mode 100644 index fc5caabb41..0000000000 --- a/Fwk/VizFwk/LibUtilities/LibUtilities.vcxproj +++ /dev/null @@ -1,272 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {ECF1BECD-E624-F971-C70A-F84686A36084} - LibUtilities - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../LibViewing;../LibIo - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibUtilities/LibUtilities.vcxproj.filters b/Fwk/VizFwk/LibUtilities/LibUtilities.vcxproj.filters deleted file mode 100644 index 4bf82b8e29..0000000000 --- a/Fwk/VizFwk/LibUtilities/LibUtilities.vcxproj.filters +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibUtilities/cvfuImageJpeg.cpp b/Fwk/VizFwk/LibUtilities/cvfuImageJpeg.cpp index c7ca8a5c01..90298096de 100644 --- a/Fwk/VizFwk/LibUtilities/cvfuImageJpeg.cpp +++ b/Fwk/VizFwk/LibUtilities/cvfuImageJpeg.cpp @@ -46,6 +46,9 @@ CVF_GCC_DIAGNOSTIC_IGNORE("-Wconversion") CVF_GCC_DIAGNOSTIC_IGNORE("-Wunused-parameter") +CVF_GCC_DIAGNOSTIC_IGNORE("-Wshift-negative-value") +CVF_GCC_DIAGNOSTIC_IGNORE("-Wimplicit-fallthrough=") +CVF_GCC_DIAGNOSTIC_IGNORE("-Wmisleading-indentation") #ifdef WIN32 #include @@ -56,6 +59,12 @@ CVF_GCC_DIAGNOSTIC_IGNORE("-Wunused-parameter") #include #endif + +// !!! +// Big time hack since C++17 does not allow ‘register’ storage class specifier +#define register + + // Doxygen conditional section to hide contents of the cvfu_jpgFreeImage namespace /// \cond CVF_NEVER_INCLUDE @@ -25126,7 +25135,7 @@ SetMemoryIO(FreeImageIO *io) { // // Design and implementation by // - Ryan Rubley -// - Hervé Drolon (drolon@infonie.fr) +// - Herv� Drolon (drolon@infonie.fr) // // This file is part of FreeImage 3 // diff --git a/Fwk/VizFwk/LibViewing/LibViewing.vcxproj b/Fwk/VizFwk/LibViewing/LibViewing.vcxproj deleted file mode 100644 index 63f8354e04..0000000000 --- a/Fwk/VizFwk/LibViewing/LibViewing.vcxproj +++ /dev/null @@ -1,305 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {122D4663-11D6-D12F-8748-629A34E9075E} - LibViewing - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../ThirdParty/TBB/include - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - - - - - EnableAllWarnings - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../ThirdParty/TBB/include - true - - - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../ThirdParty/TBB/include - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry - true - - - true - true - true - - - - - EnableAllWarnings - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../LibCore;../LibRender;../LibGeometry;../ThirdParty/TBB/include - true - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibViewing/LibViewing.vcxproj.filters b/Fwk/VizFwk/LibViewing/LibViewing.vcxproj.filters deleted file mode 100644 index 77629a8981..0000000000 --- a/Fwk/VizFwk/LibViewing/LibViewing.vcxproj.filters +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/LibViewing/cvfEffect.cpp b/Fwk/VizFwk/LibViewing/cvfEffect.cpp index 9711a02503..357bdda428 100644 --- a/Fwk/VizFwk/LibViewing/cvfEffect.cpp +++ b/Fwk/VizFwk/LibViewing/cvfEffect.cpp @@ -42,11 +42,8 @@ #include "cvfUniformSet.h" #include "cvfRenderStateSet.h" #include "cvfRenderStateTextureBindings.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" #include "cvfTexture2D_FF.h" -#endif namespace cvf { @@ -286,7 +283,6 @@ void Effect::deleteOrReleaseOpenGLResources(OpenGLContext* oglContext) } } -#ifndef CVF_OPENGL_ES RenderStateTextureMapping_FF* textureMapping = static_cast(m_renderStateSet->renderStateOfType(RenderState::TEXTURE_MAPPING_FF)); if (textureMapping) { @@ -296,7 +292,6 @@ void Effect::deleteOrReleaseOpenGLResources(OpenGLContext* oglContext) texture->deleteTexture(oglContext); } } -#endif } } diff --git a/Fwk/VizFwk/LibViewing/cvfRenderEngine.cpp b/Fwk/VizFwk/LibViewing/cvfRenderEngine.cpp index 1869342b8f..0a883e0444 100644 --- a/Fwk/VizFwk/LibViewing/cvfRenderEngine.cpp +++ b/Fwk/VizFwk/LibViewing/cvfRenderEngine.cpp @@ -262,13 +262,11 @@ void RenderEngine::render(OpenGLContext* oglContext, RenderQueue* renderQueue, s } else { -#ifndef CVF_OPENGL_ES if (lastAppliedMatrixStateVersionTickFixedFunction != matrixState.versionTick()) { glLoadMatrixf(matrixState.modelViewMatrix().ptr()); lastAppliedMatrixStateVersionTickFixedFunction = matrixState.versionTick(); } -#endif // CVF_OPENGL_ES } diff --git a/Fwk/VizFwk/LibViewing/cvfRenderQueueBuilder.cpp b/Fwk/VizFwk/LibViewing/cvfRenderQueueBuilder.cpp index fc39e82522..dae48e66e7 100644 --- a/Fwk/VizFwk/LibViewing/cvfRenderQueueBuilder.cpp +++ b/Fwk/VizFwk/LibViewing/cvfRenderQueueBuilder.cpp @@ -48,10 +48,7 @@ #include "cvfBufferObjectManaged.h" #include "cvfCamera.h" #include "cvfRenderStateTextureBindings.h" - -#ifndef CVF_OPENGL_ES #include "cvfRenderState_FF.h" -#endif namespace cvf { @@ -198,13 +195,11 @@ void RenderQueueBuilder::populateRenderQueue(RenderQueue* renderQueue) textureBindings->setupTextures(m_oglContext.p()); } -#ifndef CVF_OPENGL_ES RenderStateTextureMapping_FF* textureMapping = static_cast(effect->renderStateOfType(RenderState::TEXTURE_MAPPING_FF)); if (textureMapping && canAddToQueue) { textureMapping->setupTexture(m_oglContext.p()); } -#endif if (canAddToQueue) { diff --git a/Fwk/VizFwk/LibViewing/cvfRenderSequence.cpp b/Fwk/VizFwk/LibViewing/cvfRenderSequence.cpp index de8cf9582b..bd1a17800b 100644 --- a/Fwk/VizFwk/LibViewing/cvfRenderSequence.cpp +++ b/Fwk/VizFwk/LibViewing/cvfRenderSequence.cpp @@ -335,7 +335,6 @@ void RenderSequence::preRenderApplyExpectedOpenGLState(OpenGLContext* oglContext CVF_CHECK_OGL(oglContext); -#ifndef CVF_OPENGL_ES if (oglCaps->supportsFixedFunction()) { glMatrixMode(GL_TEXTURE); @@ -385,7 +384,6 @@ void RenderSequence::preRenderApplyExpectedOpenGLState(OpenGLContext* oglContext CVF_CHECK_OGL(oglContext); } -#endif } diff --git a/Fwk/VizFwk/LibViewing/cvfRendering.cpp b/Fwk/VizFwk/LibViewing/cvfRendering.cpp index 678801341e..152ff541b9 100644 --- a/Fwk/VizFwk/LibViewing/cvfRendering.cpp +++ b/Fwk/VizFwk/LibViewing/cvfRendering.cpp @@ -205,12 +205,10 @@ void Rendering::render(OpenGLContext* oglContext) } else { -#ifndef CVF_OPENGL_ES if (FramebufferObject::supportedOpenGL(oglContext)) { FramebufferObject::useDefaultWindowFramebuffer(oglContext); } -#endif } // Setup camera and view diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtMinimal/CMakeLists.txt index 0e63844ec5..437badd3f1 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/CMakeLists.txt +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal/CMakeLists.txt @@ -1,9 +1,7 @@ -cmake_minimum_required(VERSION 2.8.12) - project(QtMinimal) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_BASE_CXX_FLAGS}") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STANDARD_CXX_FLAGS}") if (CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") @@ -12,6 +10,17 @@ endif() find_package(OpenGL) +if (CEE_USE_QT6) + find_package(Qt6 COMPONENTS REQUIRED OpenGLWidgets) + set(QT_LIBRARIES Qt6::OpenGLWidgets ) +elseif (CEE_USE_QT5) + find_package(Qt5 REQUIRED COMPONENTS Widgets) + set(QT_LIBRARIES Qt5::Widgets) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + + include_directories(${LibCore_SOURCE_DIR}) include_directories(${LibGeometry_SOURCE_DIR}) include_directories(${LibRender_SOURCE_DIR}) @@ -19,55 +28,27 @@ include_directories(${LibViewing_SOURCE_DIR}) include_directories(${LibGuiQt_SOURCE_DIR}) set(CEE_LIBS LibGuiQt LibViewing LibRender LibGeometry LibCore) - -set(CEE_SOURCE_FILES + +set(CEE_CODE_FILES QMMain.cpp QMMainWindow.cpp +QMMainWindow.h QMWidget.cpp +QMWidget.h ) # Headers that need MOCing set(MOC_HEADER_FILES QMMainWindow.h -QMWidget.h ) -# Qt -if (CEE_USE_QT5) - find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) - set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) - qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) -else() - find_package(Qt4 COMPONENTS QtCore QtGui QtOpenGl REQUIRED) - include(${QT_USE_FILE}) - qt4_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) -endif(CEE_USE_QT5) - -add_definitions(-DCVF_USING_CMAKE) - -set(SYSTEM_LIBRARIES) -if (CMAKE_COMPILER_IS_GNUCXX) - set(SYSTEM_LIBRARIES -lrt -lpthread) -endif(CMAKE_COMPILER_IS_GNUCXX) +if (CEE_USE_QT6) + qt_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +elseif (CEE_USE_QT5) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() -add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${MOC_SOURCE_FILES}) -target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES} ${SYSTEM_LIBRARIES}) +add_executable(${PROJECT_NAME} ${CEE_CODE_FILES} ${MOC_SOURCE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES}) -if (CEE_USE_QT5) - foreach (qtlib ${QT_LIBRARIES}) - add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different $ $ - ) - endforeach(qtlib) -else() - # Copy Qt Dlls - if (MSVC) - set (QTLIBLIST QtCore QtGui QtOpenGl) - foreach (qtlib ${QTLIBLIST}) - add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different ${QT_BINARY_DIR}/$,${qtlib}d4.dll,${qtlib}4.dll> $ - ) - endforeach( qtlib ) - endif(MSVC) -endif(CEE_USE_QT5) diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMain.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMain.cpp index 5e7a334a62..f9ed43dfe3 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMain.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMain.cpp @@ -34,17 +34,13 @@ // //################################################################################################## - #include "cvfLibCore.h" #include "QMMainWindow.h" -#include -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif + +#include //-------------------------------------------------------------------------------------------------- @@ -52,6 +48,9 @@ //-------------------------------------------------------------------------------------------------- int main(int argc, char *argv[]) { + cvf::LogManager* logManager = cvf::LogManager::instance(); + logManager->logger("cee.cvf.OpenGL")->setLevel(cvf::Logger::LL_DEBUG); + QApplication app(argc, argv); // On Linux, Qt will use the system locale, force number formatting settings back to "C" locale diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.cpp index 4c28ef5f60..f223ccac66 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.cpp @@ -34,7 +34,6 @@ // //################################################################################################## - #include "cvfLibCore.h" #include "cvfLibRender.h" #include "cvfLibGeometry.h" @@ -42,20 +41,12 @@ #include "QMMainWindow.h" #include "QMWidget.h" -#if QT_VERSION >= 0x050000 + #include #include #include #include #include -#else -#include -#include -#include -#include -#include -#endif -using cvf::ref; @@ -69,41 +60,57 @@ QMMainWindow::QMMainWindow() setCentralWidget(mainFrame); m_contextGroup = new cvf::OpenGLContextGroup; - m_vizWidget = new QMWidget(m_contextGroup.p(), mainFrame); + + // Pass pointer to ourselves to get notified when the vizWidget is ready for use and we can load our default scene + m_vizWidget = new QMWidget(m_contextGroup.p(), mainFrame, this); m_vizWidget->setFocus(); frameLayout->addWidget(m_vizWidget); - - m_createDefaultSceneAction = new QAction("Default Scene", this); - m_clearSceneAction = new QAction("Clear Scene", this); - connect(m_createDefaultSceneAction, SIGNAL(triggered()), SLOT(slotCreateDefaultScene())); - connect(m_clearSceneAction, SIGNAL(triggered()), SLOT(slotClearScene())); - QMenu* menu = menuBar()->addMenu("&Scenes"); - menu->addAction(m_createDefaultSceneAction); + menu->addAction("Default Scene", this, SLOT(slotCreateDefaultScene())); menu->addSeparator(); - menu->addAction(m_clearSceneAction); + menu->addAction("Clear Scene", this, SLOT(slotClearScene())); +} +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow::handleVizWidgetIsOpenGLReady() +{ slotCreateDefaultScene(); } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void QMMainWindow::slotCreateDefaultScene() { - ref model = new cvf::ModelBasicList; + cvf::ref model = new cvf::ModelBasicList; + + const bool useShaders = true; + + CVF_ASSERT(m_contextGroup->isContextGroupInitialized()); + cvf::ShaderProgramGenerator spGen("SimpleHeadlight", cvf::ShaderSourceProvider::instance()); + spGen.configureStandardHeadlightColor(); + cvf::ref shaderProg = spGen.generate(); { cvf::GeometryBuilderDrawableGeo builder; cvf::GeometryUtils::createSphere(2, 10, 10, &builder); - ref eff = new cvf::Effect; - eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); - - ref part = new cvf::Part; + cvf::ref eff = new cvf::Effect; + if (useShaders) + { + eff->setShaderProgram(shaderProg.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GREEN))); + } + else + { + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + } + + cvf::ref part = new cvf::Part; part->setName("MySphere"); part->setDrawable(0, builder.drawableGeo().p()); part->setEffect(eff.p()); @@ -115,10 +122,18 @@ void QMMainWindow::slotCreateDefaultScene() cvf::GeometryBuilderDrawableGeo builder; cvf::GeometryUtils::createBox(cvf::Vec3f(5, 0, 0), 2, 3, 4, &builder); - ref eff = new cvf::Effect; - eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); - - ref part = new cvf::Part; + cvf::ref eff = new cvf::Effect; + if (useShaders) + { + eff->setShaderProgram(shaderProg.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::YELLOW))); + } + else + { + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + } + + cvf::ref part = new cvf::Part; part->setName("MyBox"); part->setDrawable(0, builder.drawableGeo().p()); part->setEffect(eff.p()); @@ -128,7 +143,7 @@ void QMMainWindow::slotCreateDefaultScene() model->updateBoundingBoxesRecursive(); - ref scene = new cvf::Scene; + cvf::ref scene = new cvf::Scene; scene->addModel(model.p()); CVF_ASSERT(m_vizWidget); @@ -146,22 +161,3 @@ void QMMainWindow::slotClearScene() } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -void QMMainWindow::closeEvent(QCloseEvent* /*event*/) -{ - CVF_ASSERT(m_contextGroup.notNull()); - CVF_ASSERT(m_vizWidget); - - // Shut down the CeeViz OpenGL context contained in the widget - // Deletes all OpenGL resources and removes context from context group - m_vizWidget->cvfShutdownOpenGLContext(); -} - - -#ifndef CVF_USING_CMAKE -//######################################################## -#include "qt-generated/moc_QMMainWindow.cpp" -//######################################################## -#endif diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.h b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.h index 56272b94ba..01625b7628 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.h +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMMainWindow.h @@ -40,12 +40,8 @@ #include "cvfObject.h" #include "cvfOpenGLContextGroup.h" -#include -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif +#include class QMWidget; @@ -62,17 +58,14 @@ class QMMainWindow : public QMainWindow public: QMMainWindow(); + void handleVizWidgetIsOpenGLReady(); + private slots: void slotCreateDefaultScene(); void slotClearScene(); -private: - void closeEvent(QCloseEvent* event); - private: cvf::ref m_contextGroup; - QMWidget* m_vizWidget; - QAction* m_createDefaultSceneAction; - QAction* m_clearSceneAction; + QPointer m_vizWidget; }; diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.cpp index 1e9ad82a15..72996cea2f 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.cpp @@ -34,35 +34,44 @@ // //################################################################################################## - -#include "cvfLibCore.h" -#include "cvfLibRender.h" -#include "cvfLibGeometry.h" -#include "cvfLibViewing.h" - #include "QMWidget.h" +#include "QMMainWindow.h" + +#include "cvfRendering.h" +#include "cvfRenderSequence.h" +#include "cvfScene.h" +#include "cvfCamera.h" +#include "cvfManipulatorTrackball.h" +#include "cvfOverlayAxisCross.h" +#include "cvfFixedAtlasFont.h" +#include "cvfRayIntersectSpec.h" +#include "cvfHitItemCollection.h" +#include "cvfHitItem.h" +#include "cvfTrace.h" +#include "cvfPart.h" -#include "cvfqtOpenGLContext.h" - -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif -using cvf::ref; +//================================================================================================== +// +// +// +//================================================================================================== //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QMWidget::QMWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent) -: cvfqt::OpenGLWidget(contextGroup, QGLFormat(), parent) +QMWidget::QMWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent, QMMainWindow* mainWindow) +: cvfqt::OpenGLWidget(contextGroup, parent), + m_mainWindow(mainWindow) { + CVF_ASSERT(contextGroup); + m_camera = new cvf::Camera; - ref rendering = new cvf::Rendering; + cvf::ref rendering = new cvf::Rendering; rendering->setCamera(m_camera.p()); rendering->addOverlayItem(new cvf::OverlayAxisCross(m_camera.p(), new cvf::FixedAtlasFont(cvf::FixedAtlasFont::STANDARD))); @@ -73,7 +82,6 @@ QMWidget::QMWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent) m_trackball->setCamera(m_camera.p()); } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -81,17 +89,15 @@ QMWidget::~QMWidget() { } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void QMWidget::setScene(cvf::Scene* scene) { - ref rendering = m_renderSequence->firstRendering(); + cvf::ref rendering = m_renderSequence->firstRendering(); CVF_ASSERT(rendering.notNull()); rendering->setScene(scene); - if (scene) { cvf::BoundingBox bb = scene->boundingBox(); @@ -105,52 +111,32 @@ void QMWidget::setScene(cvf::Scene* scene) update(); } - //-------------------------------------------------------------------------------------------------- -/// +/// //-------------------------------------------------------------------------------------------------- -void QMWidget::resizeGL(int width, int height) +void QMWidget::resizeGL(int w, int h) { if (m_camera.notNull()) { - m_camera->viewport()->set(0, 0, width, height); + m_camera->viewport()->set(0, 0, w, h); m_camera->setProjectionAsPerspective(m_camera->fieldOfViewYDeg(), m_camera->nearPlane(), m_camera->farPlane()); } } - //-------------------------------------------------------------------------------------------------- -/// +/// //-------------------------------------------------------------------------------------------------- -void QMWidget::paintEvent(QPaintEvent* /*event*/) +void QMWidget::paintGL() { - QPainter painter(this); - - makeCurrent(); - cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); CVF_ASSERT(currentOglContext); - CVF_CHECK_OGL(currentOglContext); - -#if QT_VERSION >= 0x040600 - painter.beginNativePainting(); -#endif - - cvfqt::OpenGLContext::saveOpenGLState(currentOglContext); if (m_renderSequence.notNull()) { m_renderSequence->render(currentOglContext); } - - cvfqt::OpenGLContext::restoreOpenGLState(currentOglContext); - -#if QT_VERSION >= 0x040600 - painter.endNativePainting(); -#endif } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -159,19 +145,24 @@ void QMWidget::mouseMoveEvent(QMouseEvent* event) if (m_renderSequence.isNull()) return; Qt::MouseButtons mouseBn = event->buttons(); - int posX = event->x(); - int posY = height() - event->y(); +#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) + const int posX = event->position().toPoint().x(); + const int posY = height() - event->position().toPoint().y(); +#else + const int posX = event->x(); + const int posY = height() - event->y(); +#endif cvf::ManipulatorTrackball::NavigationType navType = cvf::ManipulatorTrackball::NONE; if (mouseBn == Qt::LeftButton) { navType = cvf::ManipulatorTrackball::PAN; } - else if (mouseBn == Qt::RightButton) + else if (mouseBn == Qt::RightButton) { navType = cvf::ManipulatorTrackball::ROTATE; } - else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MidButton) + else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MiddleButton) { navType = cvf::ManipulatorTrackball::WALK; } @@ -188,7 +179,6 @@ void QMWidget::mouseMoveEvent(QMouseEvent* event) } } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -196,10 +186,19 @@ void QMWidget::mousePressEvent(QMouseEvent* event) { if (m_renderSequence.isNull()) return; - if (event->buttons() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier) +#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) + const int posX = event->position().toPoint().x(); + const int posY = height() - event->position().toPoint().y(); +#else + const int posX = event->x(); + const int posY = height() - event->y(); +#endif + + if (event->buttons() == Qt::LeftButton && + event->modifiers() == Qt::ControlModifier) { cvf::Rendering* r = m_renderSequence->firstRendering(); - ref ris = r->rayIntersectSpecFromWindowCoordinates(event->x(), height() - event->y()); + cvf::ref ris = r->rayIntersectSpecFromWindowCoordinates(posX, posY); cvf::HitItemCollection hic; if (r->rayIntersect(*ris, &hic)) @@ -215,7 +214,6 @@ void QMWidget::mousePressEvent(QMouseEvent* event) } } - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -225,10 +223,13 @@ void QMWidget::mouseReleaseEvent(QMouseEvent* /*event*/) } - - -#ifndef CVF_USING_CMAKE -//######################################################## -#include "qt-generated/moc_QMWidget.cpp" -//######################################################## -#endif +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget::onWidgetOpenGLReady() +{ + if (m_mainWindow) + { + m_mainWindow->handleVizWidgetIsOpenGLReady(); + } +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.h b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.h index 0a789c9eb7..f1de9bdff6 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.h +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QMWidget.h @@ -34,7 +34,6 @@ // //################################################################################################## - #pragma once #include "cvfBase.h" @@ -46,6 +45,9 @@ #include "cvfqtOpenGLWidget.h" +#include + +class QMMainWindow; //================================================================================================== @@ -55,26 +57,27 @@ //================================================================================================== class QMWidget : public cvfqt::OpenGLWidget { - Q_OBJECT - public: - QMWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent); + QMWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent, QMMainWindow* mainWindow); ~QMWidget(); void setScene(cvf::Scene* scene); protected: - void resizeGL(int width, int height); - void paintEvent(QPaintEvent *event); + virtual void resizeGL(int w, int h); + virtual void paintGL(); - void mousePressEvent(QMouseEvent* event); - void mouseMoveEvent(QMouseEvent* event); - void mouseReleaseEvent(QMouseEvent* event); + virtual void mouseMoveEvent(QMouseEvent* event); + virtual void mousePressEvent(QMouseEvent* event); + virtual void mouseReleaseEvent(QMouseEvent* event); private: + virtual void onWidgetOpenGLReady(); + +private: + QPointer m_mainWindow; cvf::ref m_renderSequence; cvf::ref m_camera; cvf::ref m_trackball; }; - diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QtMinimal.vcxproj b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QtMinimal.vcxproj deleted file mode 100644 index 5936f08099..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QtMinimal.vcxproj +++ /dev/null @@ -1,206 +0,0 @@ - - - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9} - QtMinimal - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibGuiQt;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibGuiQt;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibGuiQt;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibGuiQt;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - - - - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - - - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {fbfac173-30fe-2c09-3f2e-d54477b433de} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QtMinimal.vcxproj.filters b/Fwk/VizFwk/TestApps/Qt/QtMinimal/QtMinimal.vcxproj.filters deleted file mode 100644 index 854502b45a..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtMinimal/QtMinimal.vcxproj.filters +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/CMakeLists.txt new file mode 100644 index 0000000000..9ce977557a --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/CMakeLists.txt @@ -0,0 +1,47 @@ +project(QtMinimal_GLWidget) + + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STANDARD_CXX_FLAGS}") + +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") +endif() + + +find_package(OpenGL) + +if (CEE_USE_QT5) + find_package(Qt5 REQUIRED COMPONENTS Widgets OpenGL) + set(QT_LIBRARIES Qt5::Widgets Qt5::OpenGL) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + + +include_directories(${LibCore_SOURCE_DIR}) +include_directories(${LibGeometry_SOURCE_DIR}) +include_directories(${LibRender_SOURCE_DIR}) +include_directories(${LibViewing_SOURCE_DIR}) +include_directories(${LibGuiQt_SOURCE_DIR}) + +set(CEE_LIBS LibGuiQt LibViewing LibRender LibGeometry LibCore) + + +set(CEE_SOURCE_FILES +QMMain_GLW.cpp +QMMainWindow_GLW.cpp +QMWidget_GLW.cpp +) + +# Headers that need MOCing +set(MOC_HEADER_FILES +QMMainWindow_GLW.h +QMWidget_GLW.h +) + +if (CEE_USE_QT5) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() + +add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${MOC_SOURCE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES}) diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMainWindow_GLW.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMainWindow_GLW.cpp new file mode 100644 index 0000000000..b9d687f7b6 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMainWindow_GLW.cpp @@ -0,0 +1,153 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QMMainWindow_GLW.h" +#include "QMWidget_GLW.h" + +#include +#include +#include +#include +#include + +using cvf::ref; + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMMainWindow_GLW::QMMainWindow_GLW() +{ + QFrame* mainFrame = new QFrame; + QHBoxLayout* frameLayout = new QHBoxLayout(mainFrame); + setCentralWidget(mainFrame); + + m_contextGroup = new cvf::OpenGLContextGroup; + m_vizWidget = new QMWidget_GLW(m_contextGroup.p(), mainFrame); + + m_vizWidget->setFocus(); + frameLayout->addWidget(m_vizWidget); + + + m_createDefaultSceneAction = new QAction("Default Scene", this); + m_clearSceneAction = new QAction("Clear Scene", this); + connect(m_createDefaultSceneAction, SIGNAL(triggered()), SLOT(slotCreateDefaultScene())); + connect(m_clearSceneAction, SIGNAL(triggered()), SLOT(slotClearScene())); + + QMenu* menu = menuBar()->addMenu("&Scenes"); + menu->addAction(m_createDefaultSceneAction); + menu->addSeparator(); + menu->addAction(m_clearSceneAction); + + slotCreateDefaultScene(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow_GLW::slotCreateDefaultScene() +{ + ref model = new cvf::ModelBasicList; + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createSphere(2, 10, 10, &builder); + + ref eff = new cvf::Effect; + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + + ref part = new cvf::Part; + part->setName("MySphere"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createBox(cvf::Vec3f(5, 0, 0), 2, 3, 4, &builder); + + ref eff = new cvf::Effect; + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + + ref part = new cvf::Part; + part->setName("MyBox"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + model->updateBoundingBoxesRecursive(); + + ref scene = new cvf::Scene; + scene->addModel(model.p()); + + CVF_ASSERT(m_vizWidget); + m_vizWidget->setScene(scene.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow_GLW::slotClearScene() +{ + CVF_ASSERT(m_vizWidget); + m_vizWidget->setScene(NULL); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow_GLW::closeEvent(QCloseEvent* /*event*/) +{ + CVF_ASSERT(m_contextGroup.notNull()); + CVF_ASSERT(m_vizWidget); + + // Shut down the CeeViz OpenGL context contained in the widget + // Deletes all OpenGL resources and removes context from context group + m_vizWidget->cvfShutdownOpenGLContext(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMainWindow_GLW.h b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMainWindow_GLW.h new file mode 100644 index 0000000000..d337ec92d4 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMainWindow_GLW.h @@ -0,0 +1,73 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" +#include "cvfOpenGLContextGroup.h" + +#include + +class QMWidget_GLW; + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMMainWindow_GLW : public QMainWindow +{ + Q_OBJECT + +public: + QMMainWindow_GLW(); + +private slots: + void slotCreateDefaultScene(); + void slotClearScene(); + +private: + void closeEvent(QCloseEvent* event); + +private: + cvf::ref m_contextGroup; + QMWidget_GLW* m_vizWidget; + QAction* m_createDefaultSceneAction; + QAction* m_clearSceneAction; +}; + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMain_GLW.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMain_GLW.cpp new file mode 100644 index 0000000000..2d9e6fe26a --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMMain_GLW.cpp @@ -0,0 +1,63 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" + +#include "QMMainWindow_GLW.h" + +#include "QApplication" + +#include + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + // On Linux, Qt will use the system locale, force number formatting settings back to "C" locale + setlocale(LC_NUMERIC,"C"); + + QMMainWindow_GLW window; + QString platform = cvf::System::is64Bit() ? "(64bit)" : "(32bit)"; + window.setWindowTitle("Qt Minimal GLWidget " + platform); + window.resize(1000, 800);; + window.show(); + + return app.exec(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMWidget_GLW.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMWidget_GLW.cpp new file mode 100644 index 0000000000..7f6dd48cec --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMWidget_GLW.cpp @@ -0,0 +1,215 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QMWidget_GLW.h" + +#include + +using cvf::ref; + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMWidget_GLW::QMWidget_GLW(cvf::OpenGLContextGroup* contextGroup, QWidget* parent) +: cvfqt::GLWidget(contextGroup, QGLFormat(), parent) +{ + m_camera = new cvf::Camera; + + ref rendering = new cvf::Rendering; + rendering->setCamera(m_camera.p()); + rendering->addOverlayItem(new cvf::OverlayAxisCross(m_camera.p(), new cvf::FixedAtlasFont(cvf::FixedAtlasFont::STANDARD))); + + m_renderSequence = new cvf::RenderSequence; + m_renderSequence->addRendering(rendering.p()); + + m_trackball = new cvf::ManipulatorTrackball; + m_trackball->setCamera(m_camera.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMWidget_GLW::~QMWidget_GLW() +{ +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_GLW::setScene(cvf::Scene* scene) +{ + ref rendering = m_renderSequence->firstRendering(); + CVF_ASSERT(rendering.notNull()); + + rendering->setScene(scene); + + if (scene) + { + cvf::BoundingBox bb = scene->boundingBox(); + if (bb.isValid()) + { + m_camera->fitView(bb, -cvf::Vec3d::Z_AXIS, cvf::Vec3d::Y_AXIS); + m_trackball->setRotationPoint(bb.center()); + } + } + + update(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_GLW::resizeGL(int width, int height) +{ + if (m_camera.notNull()) + { + m_camera->viewport()->set(0, 0, width, height); + m_camera->setProjectionAsPerspective(m_camera->fieldOfViewYDeg(), m_camera->nearPlane(), m_camera->farPlane()); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_GLW::paintEvent(QPaintEvent* /*event*/) +{ + QPainter painter(this); + + makeCurrent(); + + cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); + CVF_ASSERT(currentOglContext); + CVF_CHECK_OGL(currentOglContext); + + painter.beginNativePainting(); + + cvf::OpenGLUtils::pushOpenGLState(currentOglContext); + + if (m_renderSequence.notNull()) + { + m_renderSequence->render(currentOglContext); + } + + cvf::OpenGLUtils::popOpenGLState(currentOglContext); + + painter.endNativePainting(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_GLW::mouseMoveEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + Qt::MouseButtons mouseBn = event->buttons(); + int posX = event->x(); + int posY = height() - event->y(); + + cvf::ManipulatorTrackball::NavigationType navType = cvf::ManipulatorTrackball::NONE; + if (mouseBn == Qt::LeftButton) + { + navType = cvf::ManipulatorTrackball::PAN; + } + else if (mouseBn == Qt::RightButton) + { + navType = cvf::ManipulatorTrackball::ROTATE; + } + else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MiddleButton) + { + navType = cvf::ManipulatorTrackball::WALK; + } + + if (navType != m_trackball->activeNavigation()) + { + m_trackball->startNavigation(navType, posX, posY); + } + + bool needRedraw = m_trackball->updateNavigation(posX, posY); + if (needRedraw) + { + update(); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_GLW::mousePressEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + if (event->buttons() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier) + { + cvf::Rendering* r = m_renderSequence->firstRendering(); + ref ris = r->rayIntersectSpecFromWindowCoordinates(event->x(), height() - event->y()); + + cvf::HitItemCollection hic; + if (r->rayIntersect(*ris, &hic)) + { + cvf::HitItem* item = hic.firstItem(); + CVF_ASSERT(item && item->part()); + + cvf::Vec3d isect = item->intersectionPoint(); + m_trackball->setRotationPoint(isect); + + cvf::Trace::show("hitting part: '%s' coords: %.3f %.3f %.3f", item->part()->name().toAscii().ptr(), isect.x(), isect.y(), isect.z()); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_GLW::mouseReleaseEvent(QMouseEvent* /*event*/) +{ + m_trackball->endNavigation(); +} + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMWidget_GLW.h b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMWidget_GLW.h new file mode 100644 index 0000000000..6913faf9aa --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_GLWidget/QMWidget_GLW.h @@ -0,0 +1,79 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" +#include "cvfRenderSequence.h" +#include "cvfManipulatorTrackball.h" +#include "cvfScene.h" +#include "cvfOpenGLContextGroup.h" + +#include "cvfqtGLWidget.h" + + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMWidget_GLW : public cvfqt::GLWidget +{ + Q_OBJECT + +public: + QMWidget_GLW(cvf::OpenGLContextGroup* contextGroup, QWidget* parent); + ~QMWidget_GLW(); + + void setScene(cvf::Scene* scene); + +protected: + void resizeGL(int width, int height); + void paintEvent(QPaintEvent *event); + + void mousePressEvent(QMouseEvent* event); + void mouseMoveEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + +private: + cvf::ref m_renderSequence; + cvf::ref m_camera; + cvf::ref m_trackball; +}; + + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/CMakeLists.txt new file mode 100644 index 0000000000..bee5f07910 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/CMakeLists.txt @@ -0,0 +1,50 @@ +project(QtMinimal_deprecated) + + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_BASE_CXX_FLAGS}") + +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") +endif() + + +find_package(OpenGL) + +include_directories(${LibCore_SOURCE_DIR}) +include_directories(${LibGeometry_SOURCE_DIR}) +include_directories(${LibRender_SOURCE_DIR}) +include_directories(${LibViewing_SOURCE_DIR}) +include_directories(${LibGuiQt_SOURCE_DIR}) + +set(CEE_LIBS LibGuiQt LibViewing LibRender LibGeometry LibCore) + + +set(CEE_SOURCE_FILES +QMMain_deprecated.cpp +QMMainWindow_deprecated.cpp +QMWidget_deprecated.cpp +) + +# Headers that need MOCing +set(MOC_HEADER_FILES +QMMainWindow_deprecated.h +QMWidget_deprecated.h +) + +# Qt +if (CEE_USE_QT5) + find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + +set(SYSTEM_LIBRARIES) +if (CMAKE_COMPILER_IS_GNUCXX) + set(SYSTEM_LIBRARIES -lrt -lpthread) +endif(CMAKE_COMPILER_IS_GNUCXX) + +add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${MOC_SOURCE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES} ${SYSTEM_LIBRARIES}) + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMainWindow_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMainWindow_deprecated.cpp new file mode 100644 index 0000000000..16fa6a8007 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMainWindow_deprecated.cpp @@ -0,0 +1,154 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QMMainWindow_deprecated.h" +#include "QMWidget_deprecated.h" + +#include +#include +#include +#include +#include + +using cvf::ref; + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMMainWindow_deprecated::QMMainWindow_deprecated() +{ + QFrame* mainFrame = new QFrame; + QHBoxLayout* frameLayout = new QHBoxLayout(mainFrame); + setCentralWidget(mainFrame); + + m_contextGroup = new cvf::OpenGLContextGroup; + m_vizWidget = new QMWidget_deprecated(m_contextGroup.p(), mainFrame); + + m_vizWidget->setFocus(); + frameLayout->addWidget(m_vizWidget); + + + m_createDefaultSceneAction = new QAction("Default Scene", this); + m_clearSceneAction = new QAction("Clear Scene", this); + connect(m_createDefaultSceneAction, SIGNAL(triggered()), SLOT(slotCreateDefaultScene())); + connect(m_clearSceneAction, SIGNAL(triggered()), SLOT(slotClearScene())); + + QMenu* menu = menuBar()->addMenu("&Scenes"); + menu->addAction(m_createDefaultSceneAction); + menu->addSeparator(); + menu->addAction(m_clearSceneAction); + + slotCreateDefaultScene(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow_deprecated::slotCreateDefaultScene() +{ + ref model = new cvf::ModelBasicList; + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createSphere(2, 10, 10, &builder); + + ref eff = new cvf::Effect; + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + + ref part = new cvf::Part; + part->setName("MySphere"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createBox(cvf::Vec3f(5, 0, 0), 2, 3, 4, &builder); + + ref eff = new cvf::Effect; + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + + ref part = new cvf::Part; + part->setName("MyBox"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + model->updateBoundingBoxesRecursive(); + + ref scene = new cvf::Scene; + scene->addModel(model.p()); + + CVF_ASSERT(m_vizWidget); + m_vizWidget->setScene(scene.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow_deprecated::slotClearScene() +{ + CVF_ASSERT(m_vizWidget); + m_vizWidget->setScene(NULL); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMMainWindow_deprecated::closeEvent(QCloseEvent* /*event*/) +{ + CVF_ASSERT(m_contextGroup.notNull()); + CVF_ASSERT(m_vizWidget); + + // Shut down the CeeViz OpenGL context contained in the widget + // Deletes all OpenGL resources and removes context from context group + m_vizWidget->cvfShutdownOpenGLContext(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMainWindow_deprecated.h b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMainWindow_deprecated.h new file mode 100644 index 0000000000..8ee07b3fe4 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMainWindow_deprecated.h @@ -0,0 +1,74 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" +#include "cvfOpenGLContextGroup.h" + +#include +#include + +class QMWidget_deprecated; + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMMainWindow_deprecated : public QMainWindow +{ + Q_OBJECT + +public: + QMMainWindow_deprecated(); + +private slots: + void slotCreateDefaultScene(); + void slotClearScene(); + +private: + void closeEvent(QCloseEvent* event); + +private: + cvf::ref m_contextGroup; + QMWidget_deprecated* m_vizWidget; + QAction* m_createDefaultSceneAction; + QAction* m_clearSceneAction; +}; + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMain_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMain_deprecated.cpp new file mode 100644 index 0000000000..2040cda55c --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMMain_deprecated.cpp @@ -0,0 +1,65 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" + +#include "QMMainWindow_deprecated.h" + +#include +#include + +#include + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + // On Linux, Qt will use the system locale, force number formatting settings back to "C" locale + setlocale(LC_NUMERIC,"C"); + + QMMainWindow_deprecated window; + QString platform = cvf::System::is64Bit() ? "(64bit)" : "(32bit)"; + window.setWindowTitle("Qt Minimal deprecated" + platform); + window.resize(1000, 800);; + window.show(); + + return app.exec(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMWidget_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMWidget_deprecated.cpp new file mode 100644 index 0000000000..979f4856d6 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMWidget_deprecated.cpp @@ -0,0 +1,215 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QMWidget_deprecated.h" + +#include + +using cvf::ref; + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMWidget_deprecated::QMWidget_deprecated(cvf::OpenGLContextGroup* contextGroup, QWidget* parent) +: cvfqt::GLWidget_deprecated(contextGroup, QGLFormat(), parent) +{ + m_camera = new cvf::Camera; + + ref rendering = new cvf::Rendering; + rendering->setCamera(m_camera.p()); + rendering->addOverlayItem(new cvf::OverlayAxisCross(m_camera.p(), new cvf::FixedAtlasFont(cvf::FixedAtlasFont::STANDARD))); + + m_renderSequence = new cvf::RenderSequence; + m_renderSequence->addRendering(rendering.p()); + + m_trackball = new cvf::ManipulatorTrackball; + m_trackball->setCamera(m_camera.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMWidget_deprecated::~QMWidget_deprecated() +{ +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_deprecated::setScene(cvf::Scene* scene) +{ + ref rendering = m_renderSequence->firstRendering(); + CVF_ASSERT(rendering.notNull()); + + rendering->setScene(scene); + + if (scene) + { + cvf::BoundingBox bb = scene->boundingBox(); + if (bb.isValid()) + { + m_camera->fitView(bb, -cvf::Vec3d::Z_AXIS, cvf::Vec3d::Y_AXIS); + m_trackball->setRotationPoint(bb.center()); + } + } + + update(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_deprecated::resizeGL(int width, int height) +{ + if (m_camera.notNull()) + { + m_camera->viewport()->set(0, 0, width, height); + m_camera->setProjectionAsPerspective(m_camera->fieldOfViewYDeg(), m_camera->nearPlane(), m_camera->farPlane()); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_deprecated::paintEvent(QPaintEvent* /*event*/) +{ + QPainter painter(this); + + makeCurrent(); + + cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); + CVF_ASSERT(currentOglContext); + CVF_CHECK_OGL(currentOglContext); + + painter.beginNativePainting(); + + cvf::OpenGLUtils::pushOpenGLState(currentOglContext); + + if (m_renderSequence.notNull()) + { + m_renderSequence->render(currentOglContext); + } + + cvf::OpenGLUtils::popOpenGLState(currentOglContext); + + painter.endNativePainting(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_deprecated::mouseMoveEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + Qt::MouseButtons mouseBn = event->buttons(); + int posX = event->x(); + int posY = height() - event->y(); + + cvf::ManipulatorTrackball::NavigationType navType = cvf::ManipulatorTrackball::NONE; + if (mouseBn == Qt::LeftButton) + { + navType = cvf::ManipulatorTrackball::PAN; + } + else if (mouseBn == Qt::RightButton) + { + navType = cvf::ManipulatorTrackball::ROTATE; + } + else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MiddleButton) + { + navType = cvf::ManipulatorTrackball::WALK; + } + + if (navType != m_trackball->activeNavigation()) + { + m_trackball->startNavigation(navType, posX, posY); + } + + bool needRedraw = m_trackball->updateNavigation(posX, posY); + if (needRedraw) + { + update(); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_deprecated::mousePressEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + if (event->buttons() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier) + { + cvf::Rendering* r = m_renderSequence->firstRendering(); + ref ris = r->rayIntersectSpecFromWindowCoordinates(event->x(), height() - event->y()); + + cvf::HitItemCollection hic; + if (r->rayIntersect(*ris, &hic)) + { + cvf::HitItem* item = hic.firstItem(); + CVF_ASSERT(item && item->part()); + + cvf::Vec3d isect = item->intersectionPoint(); + m_trackball->setRotationPoint(isect); + + cvf::Trace::show("hitting part: '%s' coords: %.3f %.3f %.3f", item->part()->name().toAscii().ptr(), isect.x(), isect.y(), isect.z()); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMWidget_deprecated::mouseReleaseEvent(QMouseEvent* /*event*/) +{ + m_trackball->endNavigation(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMWidget_deprecated.h b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMWidget_deprecated.h new file mode 100644 index 0000000000..5d4f95c51b --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMinimal_deprecated/QMWidget_deprecated.h @@ -0,0 +1,80 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" +#include "cvfRenderSequence.h" +#include "cvfManipulatorTrackball.h" +#include "cvfScene.h" +#include "cvfOpenGLContextGroup.h" + +#include "cvfqtGLWidget_deprecated.h" + + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMWidget_deprecated : public cvfqt::GLWidget_deprecated +{ + Q_OBJECT + +public: + QMWidget_deprecated(cvf::OpenGLContextGroup* contextGroup, QWidget* parent); + ~QMWidget_deprecated(); + + void setScene(cvf::Scene* scene); + +protected: + void resizeGL(int width, int height); + void paintEvent(QPaintEvent *event); + + void mousePressEvent(QMouseEvent* event); + void mouseMoveEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + +private: + cvf::ref m_renderSequence; + cvf::ref m_camera; + cvf::ref m_trackball; +}; + + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtMultiView/CMakeLists.txt index 6b01a6c884..93bf747943 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/CMakeLists.txt +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/CMakeLists.txt @@ -1,9 +1,7 @@ -cmake_minimum_required(VERSION 2.8.12) - project(QtMultiView) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_BASE_CXX_FLAGS}") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STANDARD_CXX_FLAGS}") if (CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") @@ -12,21 +10,35 @@ endif() find_package(OpenGL) +if (CEE_USE_QT6) + find_package(Qt6 COMPONENTS REQUIRED OpenGLWidgets) + set(QT_LIBRARIES Qt6::OpenGLWidgets ) +elseif (CEE_USE_QT5) + find_package(Qt5 REQUIRED COMPONENTS Widgets) + set(QT_LIBRARIES Qt5::Widgets) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + + include_directories(${LibCore_SOURCE_DIR}) include_directories(${LibGeometry_SOURCE_DIR}) include_directories(${LibRender_SOURCE_DIR}) include_directories(${LibViewing_SOURCE_DIR}) -include_directories(${LibGuiQt_SOURCE_DIR}) include_directories(${LibUtilities_SOURCE_DIR}) +include_directories(${LibGuiQt_SOURCE_DIR}) + +set(CEE_LIBS LibGuiQt LibUtilities LibViewing LibRender LibGeometry LibIo LibCore) -set(CEE_LIBS LibUtilities LibGuiQt LibViewing LibRender LibGeometry LibIo LibCore) -set(EXTERNAL_LIBS) -set(CEE_SOURCE_FILES +set(CEE_CODE_FILES QMVFactory.cpp +QMVFactory.h QMVMain.cpp QMVMainWindow.cpp +QMVMainWindow.h QMVWidget.cpp +QMVWidget.h ) # Headers that need MOCing @@ -35,42 +47,12 @@ QMVMainWindow.h QMVWidget.h ) -# Qt -if (CEE_USE_QT5) - find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) - set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) - qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) -else() - find_package(Qt4 COMPONENTS QtCore QtGui QtOpenGl REQUIRED) - include(${QT_USE_FILE}) - qt4_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) -endif(CEE_USE_QT5) - -# Run MOC on the headers -add_definitions(-DCVF_USING_CMAKE) - -set(SYSTEM_LIBRARIES) -if (CMAKE_COMPILER_IS_GNUCXX) - set(SYSTEM_LIBRARIES -lrt -lpthread) -endif(CMAKE_COMPILER_IS_GNUCXX) +if (CEE_USE_QT6) + qt_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +elseif (CEE_USE_QT5) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() -add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${MOC_SOURCE_FILES}) -target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES} ${SYSTEM_LIBRARIES}) +add_executable(${PROJECT_NAME} ${CEE_CODE_FILES} ${MOC_SOURCE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES}) -if (CEE_USE_QT5) - foreach (qtlib ${QT_LIBRARIES}) - add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different $ $ - ) - endforeach(qtlib) -else() - # Copy Qt Dlls - if (MSVC) - set (QTLIBLIST QtCore QtGui QtOpenGl) - foreach (qtlib ${QTLIBLIST}) - add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different ${QT_BINARY_DIR}/$,${qtlib}d4.dll,${qtlib}4.dll> $ - ) - endforeach( qtlib ) - endif(MSVC) -endif(CEE_USE_QT5) diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.cpp index 802687dccf..e60d728a25 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.cpp @@ -34,7 +34,6 @@ // //################################################################################################## - #include "cvfLibCore.h" #include "cvfLibRender.h" #include "cvfLibGeometry.h" @@ -46,7 +45,6 @@ - //================================================================================================== // // @@ -56,8 +54,9 @@ //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QMVModelFactory::QMVModelFactory(bool useShaders) -: m_useShaders(useShaders) +QMVModelFactory::QMVModelFactory(bool useShaders, const cvf::OpenGLCapabilities& capabilities) +: m_useShaders(useShaders), + m_capabilities(capabilities) { } @@ -65,24 +64,27 @@ QMVModelFactory::QMVModelFactory(bool useShaders) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVModelFactory::createSphereAndBox() +cvf::ref QMVModelFactory::createSphereAndBox() { - ref model = new cvf::ModelBasicList; + cvf::ref model = new cvf::ModelBasicList; { cvf::GeometryBuilderDrawableGeo builder; cvf::GeometryUtils::createSphere(2, 10, 10, &builder); - ref eff = new cvf::Effect; - eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + cvf::ref eff = new cvf::Effect; if (m_useShaders) { - ref prog = createProgramStandardHeadlightColor(); + cvf::ref prog = createProgramStandardHeadlightColor(); eff->setShaderProgram(prog.p()); eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GREEN))); } + else + { + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + } - ref part = new cvf::Part; + cvf::ref part = new cvf::Part; part->setName("MySphere"); part->setDrawable(0, builder.drawableGeo().p()); part->setEffect(eff.p()); @@ -94,16 +96,19 @@ ref QMVModelFactory::createSphereAndBox() cvf::GeometryBuilderDrawableGeo builder; cvf::GeometryUtils::createBox(cvf::Vec3f(5, 0, 0), 2, 3, 4, &builder); - ref eff = new cvf::Effect; - eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + cvf::ref eff = new cvf::Effect; if (m_useShaders) { - ref prog = createProgramUnlit(); + cvf::ref prog = createProgramUnlit(); eff->setShaderProgram(prog.p()); eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GREEN))); } + else + { + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + } - ref part = new cvf::Part; + cvf::ref part = new cvf::Part; part->setName("MyBox"); part->setDrawable(0, builder.drawableGeo().p()); part->setEffect(eff.p()); @@ -120,9 +125,10 @@ ref QMVModelFactory::createSphereAndBox() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVModelFactory::createSpheres() +cvf::ref QMVModelFactory::createSpheres() { cvfu::PartCompoundGenerator gen; + gen.setUseShaders(m_useShaders); gen.setPartDistribution(cvf::Vec3i(5, 5, 5)); gen.setNumEffects(8); gen.useRandomEffectAssignment(false); @@ -132,9 +138,9 @@ ref QMVModelFactory::createSpheres() cvf::Collection parts; gen.generateSpheres(20, 20, &parts); - ref model = new cvf::ModelBasicList; + cvf::ref model = new cvf::ModelBasicList; - ref prog = createProgramStandardHeadlightColor(); + cvf::ref prog = createProgramStandardHeadlightColor(); size_t i; for (i = 0; i < parts.size(); i++) @@ -158,9 +164,10 @@ ref QMVModelFactory::createSpheres() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVModelFactory::createBoxes() +cvf::ref QMVModelFactory::createBoxes() { cvfu::PartCompoundGenerator gen; + gen.setUseShaders(m_useShaders); gen.setPartDistribution(cvf::Vec3i(5, 5, 5)); gen.setNumEffects(8); gen.useRandomEffectAssignment(false); @@ -170,9 +177,9 @@ ref QMVModelFactory::createBoxes() cvf::Collection parts; gen.generateBoxes(&parts); - ref model = new cvf::ModelBasicList; + cvf::ref model = new cvf::ModelBasicList; - ref prog = createProgramStandardHeadlightColor(); + cvf::ref prog = createProgramStandardHeadlightColor(); size_t i; for (i = 0; i < parts.size(); i++) @@ -196,9 +203,10 @@ ref QMVModelFactory::createBoxes() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVModelFactory::createTriangles() +cvf::ref QMVModelFactory::createTriangles() { cvfu::PartCompoundGenerator gen; + gen.setUseShaders(m_useShaders); gen.setPartDistribution(cvf::Vec3i(5, 5, 5)); gen.setNumEffects(8); gen.useRandomEffectAssignment(false); @@ -208,9 +216,9 @@ ref QMVModelFactory::createTriangles() cvf::Collection parts; gen.generateTriangles(&parts); - ref model = new cvf::ModelBasicList; + cvf::ref model = new cvf::ModelBasicList; - ref prog = createProgramStandardHeadlightColor(); + cvf::ref prog = createProgramStandardHeadlightColor(); size_t i; for (i = 0; i < parts.size(); i++) @@ -234,11 +242,11 @@ ref QMVModelFactory::createTriangles() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVModelFactory::createProgramStandardHeadlightColor() +cvf::ref QMVModelFactory::createProgramStandardHeadlightColor() { cvf::ShaderProgramGenerator gen("StandardHeadlightColor", cvf::ShaderSourceProvider::instance()); gen.configureStandardHeadlightColor(); - ref prog = gen.generate(); + cvf::ref prog = gen.generate(); return prog; } @@ -246,13 +254,13 @@ ref QMVModelFactory::createProgramStandardHeadlightColor() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVModelFactory::createProgramUnlit() +cvf::ref QMVModelFactory::createProgramUnlit() { cvf::ShaderProgramGenerator gen("Unlit", cvf::ShaderSourceProvider::instance()); gen.addVertexCode(cvf::ShaderSourceRepository::vs_Standard); gen.addFragmentCode(cvf::ShaderSourceRepository::src_Color); gen.addFragmentCode(cvf::ShaderSourceRepository::fs_Unlit); - ref prog = gen.generate(); + cvf::ref prog = gen.generate(); return prog; } @@ -275,9 +283,9 @@ QMVSceneFactory::QMVSceneFactory(QMVModelFactory* modelFactory) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVSceneFactory::createNumberedScene(int sceneNumber) +cvf::ref QMVSceneFactory::createNumberedScene(int sceneNumber) { - ref model; + cvf::ref model; switch (sceneNumber) { case 0: model = m_modelFactory->createSphereAndBox(); break; @@ -293,9 +301,9 @@ ref QMVSceneFactory::createNumberedScene(int sceneNumber) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVSceneFactory::createFromModel(cvf::Model* model) +cvf::ref QMVSceneFactory::createFromModel(cvf::Model* model) { - ref scene = new cvf::Scene; + cvf::ref scene = new cvf::Scene; if (model) { @@ -316,9 +324,9 @@ ref QMVSceneFactory::createFromModel(cvf::Model* model) //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -ref QMVRenderSequenceFactory::createFromScene(cvf::Scene* scene) +cvf::ref QMVRenderSequenceFactory::createFromScene(cvf::Scene* scene) { - ref rendering = new cvf::Rendering; + cvf::ref rendering = new cvf::Rendering; rendering->renderEngine()->enableItemCountUpdate(true); rendering->setScene(scene); @@ -334,7 +342,7 @@ ref QMVRenderSequenceFactory::createFromScene(cvf::Scene* s } } - ref renderSeq = new cvf::RenderSequence; + cvf::ref renderSeq = new cvf::RenderSequence; renderSeq->addRendering(rendering.p()); return renderSeq; diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.h b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.h index d4fcc7e96b..c835edce2f 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.h +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVFactory.h @@ -34,10 +34,8 @@ // //################################################################################################## - #pragma once -using cvf::ref; //================================================================================================== @@ -48,19 +46,20 @@ using cvf::ref; class QMVModelFactory { public: - QMVModelFactory(bool useShaders); + QMVModelFactory(bool useShaders, const cvf::OpenGLCapabilities& capabilities); - ref createSphereAndBox(); - ref createSpheres(); - ref createBoxes(); - ref createTriangles(); + cvf::ref createSphereAndBox(); + cvf::ref createSpheres(); + cvf::ref createBoxes(); + cvf::ref createTriangles(); private: - ref createProgramStandardHeadlightColor(); - ref createProgramUnlit(); + cvf::ref createProgramStandardHeadlightColor(); + cvf::ref createProgramUnlit(); private: bool m_useShaders; + cvf::OpenGLCapabilities m_capabilities; }; @@ -75,8 +74,8 @@ class QMVSceneFactory public: QMVSceneFactory(QMVModelFactory* modelFactory); - ref createNumberedScene(int sceneNumber); - ref createFromModel(cvf::Model* model); + cvf::ref createNumberedScene(int sceneNumber); + cvf::ref createFromModel(cvf::Model* model); private: QMVModelFactory* m_modelFactory; @@ -92,6 +91,6 @@ class QMVSceneFactory class QMVRenderSequenceFactory { public: - ref createFromScene(cvf::Scene* model); + cvf::ref createFromScene(cvf::Scene* model); }; diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMain.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMain.cpp index fe9aac16e9..dd1f7d0262 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMain.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMain.cpp @@ -34,17 +34,14 @@ // //################################################################################################## - #include "cvfLibCore.h" #include "QMVMainWindow.h" -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif -#include "QtOpenGL/qgl.h" + +#include + //-------------------------------------------------------------------------------------------------- @@ -52,19 +49,30 @@ //-------------------------------------------------------------------------------------------------- int main(int argc, char *argv[]) { - // It seems that if we are using paintEvent() instead of paintGL() to - // draw we might have to set OpenGL as the preferred paint engine - //QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); + // Enables resource sharing between QOpenGLWidget instances that belong to different top-level windows + // Must be enabled if we want to create multiple OpenGL widgets in the same context group and they're not sitting as direct children of the same widget. + // Enable here so we can experiment with creating widgets as floating dialogs + QApplication::setAttribute(Qt::AA_ShareOpenGLContexts); + + // Can be used as a work-around if OpenGL scene appears as black in combination with remote desktop for Win7 clients + // See: https://bugreports.qt.io/browse/QTBUG-47975 + //QSurfaceFormat surface; + //surface.setAlphaBufferSize(8); + //QSurfaceFormat::setDefaultFormat(surface); + QApplication app(argc, argv); + cvf::LogManager* logManager = cvf::LogManager::instance(); + logManager->logger("cee.cvf.OpenGL")->setLevel(4); + // On Linux, Qt will use the system locale, force number formatting settings back to "C" locale setlocale(LC_NUMERIC,"C"); QMVMainWindow window; QString platform = cvf::System::is64Bit() ? "(64bit)" : "(32bit)"; window.setWindowTitle("Qt MultiView " + platform); - window.resize(1000, 800);; + window.resize(1000, 800); window.show(); return app.exec(); diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.cpp index f7a22acfee..5b70c01d33 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.cpp @@ -34,7 +34,6 @@ // //################################################################################################## - #include "cvfLibCore.h" #include "cvfLibRender.h" #include "cvfLibGeometry.h" @@ -44,8 +43,7 @@ #include "QMVWidget.h" #include "QMVFactory.h" -#include -#if QT_VERSION >= 0x050000 +#include #include #include #include @@ -53,17 +51,6 @@ #include #include #include -#else -#include -#include -#include -#include -#include -#include -#include -#endif - -using cvf::ref; @@ -80,98 +67,72 @@ QMVMainWindow::QMVMainWindow() setCentralWidget(mainFrame); + QMenu* widgetsMenu = menuBar()->addMenu("&Widgets"); + + m_createWidgetsAsFloatingDialogsAction = new QAction("Create Widgets as Floating Dialogs", this); + m_createWidgetsAsFloatingDialogsAction->setCheckable(true); + m_recycleScenesInWidgetConfigAction = new QAction("Recycle Scenes When Changing Widget Config", this); m_recycleScenesInWidgetConfigAction->setCheckable(true); - m_softwareRenderingWidgetsAction = new QAction("Software Rendering in Widgets", this); - m_softwareRenderingWidgetsAction->setCheckable(true); - connect(m_softwareRenderingWidgetsAction, SIGNAL(toggled(bool)), SLOT(slotSoftwareRenderingWidgets(bool))); - - m_configNumWidgets1Action = new QAction("1 Widget", this); - m_configNumWidgets2Action = new QAction("2 Widgets", this); - m_configNumWidgets4Action = new QAction("4 Widgets", this); - m_configNumWidgetsNoneAction= new QAction("No Widgets", this); - connect(m_configNumWidgets1Action, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); - connect(m_configNumWidgets2Action, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); - connect(m_configNumWidgets4Action, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); - connect(m_configNumWidgetsNoneAction, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); - - m_createSphereAndBoxSceneAction = new QAction("Sphere And Box Scene", this); - m_createSpheresSceneAction = new QAction("Spheres Scene", this); - m_createBoxesSceneAction = new QAction("Boxes Scene", this); - m_createTrianglesSceneAction = new QAction("Triangles Scene", this); - m_allWidgetsDifferentSceneAction = new QAction("All Widgets Show Different Scene", this); - m_clearSceneAction = new QAction("Clear Scene", this); - connect(m_createSphereAndBoxSceneAction, SIGNAL(triggered()), SLOT(slotCreateSphereAndBoxScene())); - connect(m_createSpheresSceneAction, SIGNAL(triggered()), SLOT(slotCreateSpheresScene())); - connect(m_createBoxesSceneAction, SIGNAL(triggered()), SLOT(slotCreateBoxesScene())); - connect(m_createTrianglesSceneAction, SIGNAL(triggered()), SLOT(slotCreateTrianglesScene())); - connect(m_allWidgetsDifferentSceneAction, SIGNAL(triggered()), SLOT(slotAllWidgetsDifferentScene())); - connect(m_clearSceneAction, SIGNAL(triggered()), SLOT(slotClearScene())); - - m_useBufferObjectsAction = new QAction("Use Buffer Objects", this); - m_useClientVertexArraysAction = new QAction("Use Client Vertex Arrays", this); - connect(m_useBufferObjectsAction, SIGNAL(triggered()), SLOT(slotUseBufferObjects())); - connect(m_useClientVertexArraysAction, SIGNAL(triggered()), SLOT(slotUseClientVertexArrays())); - - m_deleteAllResourcesInResourceManagerAction = new QAction("Delete All Resources In Resource Manager", this); - connect(m_deleteAllResourcesInResourceManagerAction, SIGNAL(triggered()), SLOT(slotDeleteAllResourcesInResourceManager())); - + m_configNumWidgets1Action = new QAction("1 Widget", this); + m_configNumWidgets2Action = new QAction("2 Widgets", this); + m_configNumWidgets4Action = new QAction("4 Widgets", this); + m_configNumWidgetsNoneAction = new QAction("No Widgets", this); + connect(m_configNumWidgets1Action, SIGNAL(triggered()), SLOT(slotConfigNumVizWidgets())); + connect(m_configNumWidgets2Action, SIGNAL(triggered()), SLOT(slotConfigNumVizWidgets())); + connect(m_configNumWidgets4Action, SIGNAL(triggered()), SLOT(slotConfigNumVizWidgets())); + connect(m_configNumWidgetsNoneAction, SIGNAL(triggered()), SLOT(slotConfigNumVizWidgets())); - QMenu* widgetsMenu = menuBar()->addMenu("&Widgets"); - widgetsMenu->addAction(m_recycleScenesInWidgetConfigAction); + widgetsMenu->addAction(m_createWidgetsAsFloatingDialogsAction); widgetsMenu->addSeparator(); - widgetsMenu->addAction(m_softwareRenderingWidgetsAction); + widgetsMenu->addAction(m_recycleScenesInWidgetConfigAction); widgetsMenu->addSeparator(); widgetsMenu->addAction(m_configNumWidgets1Action); widgetsMenu->addAction(m_configNumWidgets2Action); widgetsMenu->addAction(m_configNumWidgets4Action); widgetsMenu->addAction(m_configNumWidgetsNoneAction); + widgetsMenu->addSeparator(); + widgetsMenu->addAction("Delete First Widget", this, SLOT(slotDeleteFirstVizWidget())); + widgetsMenu->addAction("Delete Second Widget", this, SLOT(slotDeleteSecondVizWidget())); + QMenu* scenesMenu = menuBar()->addMenu("&Scenes"); - scenesMenu->addAction(m_createSphereAndBoxSceneAction); - scenesMenu->addAction(m_createSpheresSceneAction); - scenesMenu->addAction(m_createBoxesSceneAction); - scenesMenu->addAction(m_createTrianglesSceneAction); + + m_useShadersAction = new QAction("Use Shaders When Creating Scenes", this); + m_useShadersAction->setCheckable(true); + m_useShadersAction->setChecked(true); + + scenesMenu->addAction(m_useShadersAction); scenesMenu->addSeparator(); - scenesMenu->addAction(m_allWidgetsDifferentSceneAction); + scenesMenu->addAction("Sphere And Box Scene", this, SLOT(slotCreateSphereAndBoxScene())); + scenesMenu->addAction("Spheres Scene", this, SLOT(slotCreateSpheresScene())); + scenesMenu->addAction("Boxes Scene", this, SLOT(slotCreateBoxesScene())); + scenesMenu->addAction("Triangles Scene", this, SLOT(slotCreateTrianglesScene())); scenesMenu->addSeparator(); - scenesMenu->addAction(m_clearSceneAction); + scenesMenu->addAction("All Widgets Show Different Scene", this, SLOT(slotAllWidgetsDifferentScene())); + scenesMenu->addSeparator(); + scenesMenu->addAction("Clear Scene", this, SLOT(slotClearScene())); + QMenu* renderingMenu = menuBar()->addMenu("&Rendering"); - renderingMenu->addAction(m_useBufferObjectsAction); - renderingMenu->addAction(m_useClientVertexArraysAction); + renderingMenu->addAction("Use Buffer Objects", this, SLOT(slotUseBufferObjects())); + renderingMenu->addAction("Use Client Vertex Arrays", this, SLOT(slotUseClientVertexArrays())); + QMenu* testMenu = menuBar()->addMenu("&Test"); - testMenu->addAction(m_deleteAllResourcesInResourceManagerAction); + testMenu->addAction("Delete All Resources In Resource Manager", this, SLOT(slotDeleteAllResourcesInResourceManager())); + testMenu->addAction("Delete or Release OpenGL Resources in All Widgets", this, SLOT(slotDeleteOrReleaseOpenGLResourcesInAllVizWidgets())); + // Must create context group before launching any widgets m_contextGroup = new cvf::OpenGLContextGroup; - createVizWidgets(1, m_softwareRenderingWidgetsAction->isChecked(), false); - slotCreateSphereAndBoxScene(); + createVizWidgets(1, false); QTimer* timer = new QTimer; connect(timer, SIGNAL(timeout()), SLOT(slotUpdateStatusbar())); timer->start(250); - - /* - { - QWidget* myWidget = new QWidget; - QGridLayout* layout = new QGridLayout(myWidget); - - QLabel* l1 = new QLabel("JALLA", myWidget); - QLabel* l2 = new QLabel("BALLA", myWidget); - QLabel* l3 = new QLabel("TRALLA", myWidget); - layout->addWidget(l1, 0, 0); - layout->addWidget(l2, 0, 1); - layout->addWidget(l3, 1, 1); - - QStatusBar* sb = statusBar(); - //sb->addPermanentWidget(new QLabel("JALLA")); - sb->addPermanentWidget(myWidget); - } - */ } @@ -207,7 +168,7 @@ int QMVMainWindow::vizWidgetCount() //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void QMVMainWindow::createVizWidgets(int numWidgets, bool software, bool recycleScenes) +void QMVMainWindow::createVizWidgets(int numWidgets, bool recycleScenes) { CVF_ASSERT(numWidgets <= MAX_NUM_WIDGETS); @@ -219,40 +180,39 @@ void QMVMainWindow::createVizWidgets(int numWidgets, bool software, bool recycle deleteAllVizWidgets(); - QWidget* parentWidget = centralWidget(); - QGridLayout* layout = dynamic_cast(parentWidget->layout()); - CVF_ASSERT(layout); + // Note that creating the widgets as floating dialogs will only work if the + // Qt::AA_ShareOpenGLContexts has been set using QApplication::setAttribute(Qt::AA_ShareOpenGLContexts) before Application object is constructed + const bool createAsDialogs = m_createWidgetsAsFloatingDialogsAction->isChecked(); - QGLFormat oglFormat; - if (software) - { - oglFormat.setOption(QGL::IndirectRendering); - } + QWidget* parentWidget = centralWidget(); // The context group that all the contexts end up in CVF_ASSERT(m_contextGroup.notNull()); CVF_ASSERT(m_contextGroup->contextCount() == 0); - QMVWidget* shareWidget = NULL; - int i; for (i = 0; i < numWidgets; i++) { QMVWidget* newWidget = NULL; - if (shareWidget) + + if (createAsDialogs) { - newWidget = new QMVWidget(shareWidget, parentWidget); + newWidget = new QMVWidget(m_contextGroup.p(), i, parentWidget, Qt::Dialog); + newWidget->resize(600, 400); + newWidget->show(); } else { - newWidget = new QMVWidget(m_contextGroup.p(), oglFormat, parentWidget); - shareWidget = newWidget; + newWidget = new QMVWidget(m_contextGroup.p(), i, parentWidget); + QGridLayout* layout = parentWidget ? dynamic_cast(parentWidget->layout()) : NULL; + if (layout) + { + int row = i/2; + int col = i-2*row; + layout->addWidget(newWidget, row, col); + } } - int row = i/2; - int col = i-2*row; - layout->addWidget(newWidget, row, col); - m_vizWidgets[i] = newWidget; } @@ -266,12 +226,12 @@ void QMVMainWindow::createVizWidgets(int numWidgets, bool software, bool recycle //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void QMVMainWindow::deleteAllOpenGLResourcesInAllVizWidgets() +void QMVMainWindow::deleteOrReleaseOpenGLResourcesInAllVizWidgets() { - cvf::OpenGLResourceManager* resourceManager = m_contextGroup.notNull() ? m_contextGroup->resourceManager() : NULL; + // Will be set to one of the OpenGL contexts so we can use it in final evict call + cvf::OpenGLContext* someOglContext = NULL; - // The loop below should not be needed now that we can clean up resources - // by calling on the resource manager, but leave it as long as deleteOrReleaseOpenGLResources() is in place + // Loops over all the widgets and deletes/releases the OpenGL resources for each of them int i; for (i = 0; i < MAX_NUM_WIDGETS; i++) { @@ -282,19 +242,42 @@ void QMVMainWindow::deleteAllOpenGLResourcesInAllVizWidgets() cvf::OpenGLContext* oglContext = vizWidget->cvfOpenGLContext(); CVF_ASSERT(oglContext); CVF_ASSERT(oglContext->isCurrent()); + someOglContext = oglContext; cvf::RenderSequence* renderSeq = vizWidget->renderSequence(); if (renderSeq) { renderSeq->deleteOrReleaseOpenGLResources(oglContext); } - - CVF_ASSERT(resourceManager); - resourceManager->deleteAllOpenGLResources(oglContext); } } + + cvf::OpenGLResourceManager* resourceManager = m_contextGroup.notNull() ? m_contextGroup->resourceManager() : NULL; + if (resourceManager && someOglContext) + { + resourceManager->evictOrphanedOpenGLResources(someOglContext); + } } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow::deleteAllOpenGLResourcesInResourceManager() +{ + if (m_contextGroup.notNull()) + { + cvf::OpenGLResourceManager* rcMgr = m_contextGroup->resourceManager(); + CVF_ASSERT(rcMgr); + + if (m_contextGroup->contextCount() > 0) + { + // Grab any context in the group + cvf::OpenGLContext* oglContext = m_contextGroup->context(0); + oglContext->makeCurrent(); + rcMgr->deleteAllOpenGLResources(oglContext); + } + } +} //-------------------------------------------------------------------------------------------------- /// @@ -304,7 +287,9 @@ void QMVMainWindow::deleteAllVizWidgets() QWidget* parentWidget = centralWidget(); QLayout* layout = parentWidget->layout(); - deleteAllOpenGLResourcesInAllVizWidgets(); + // Should not be needed, but left for experimentation + //deleteOrReleaseOpenGLResourcesInAllVizWidgets(); + //deleteAllOpenGLResourcesInResourceManager(); int i; for (i = 0; i < MAX_NUM_WIDGETS; i++) @@ -320,6 +305,21 @@ void QMVMainWindow::deleteAllVizWidgets() CVF_ASSERT(m_contextGroup.isNull() || m_contextGroup->contextCount() == 0); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow::deleteVizWidgetAt(int index) +{ + QWidget* parentWidget = centralWidget(); + QLayout* layout = parentWidget->layout(); + + if (m_vizWidgets[index]) + { + layout->removeWidget(m_vizWidgets[index]); + delete m_vizWidgets[index]; + m_vizWidgets[index] = NULL; + } +} //-------------------------------------------------------------------------------------------------- /// @@ -333,7 +333,7 @@ void QMVMainWindow::setSceneInAllVizWidgets(cvf::Scene* scene) { if (m_vizWidgets[i] != NULL) { - ref renderSeq = factory.createFromScene(scene); + cvf::ref renderSeq = factory.createFromScene(scene); m_vizWidgets[i]->setRenderSequence(renderSeq.p()); } } @@ -358,7 +358,7 @@ void QMVMainWindow::spreadScenesAcrossVizWidgets(cvf::Collection* sc cvf::Scene* scene = (sceneCollection->size() > i) ? sceneCollection->at(i) : NULL; if (scene) { - ref renderSeq = factory.createFromScene(scene); + cvf::ref renderSeq = factory.createFromScene(scene); vizWidget->setRenderSequence(renderSeq.p()); } } @@ -449,49 +449,56 @@ void QMVMainWindow::setRenderModeInAllModels(cvf::DrawableGeo::RenderMode render //-------------------------------------------------------------------------------------------------- void QMVMainWindow::closeEvent(QCloseEvent*) { - deleteAllOpenGLResourcesInAllVizWidgets(); + // Should not be needed any more, but left for experimentation + //deleteOrReleaseOpenGLResourcesInAllVizWidgets(); + //deleteAllOpenGLResourcesInResourceManager(); } //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void QMVMainWindow::slotSoftwareRenderingWidgets(bool software) +void QMVMainWindow::slotConfigNumVizWidgets() { - int currNumWidgets = vizWidgetCount(); + QObject* senderAct = sender(); - // Just recreate with the same number of widgets - createVizWidgets(currNumWidgets, software, m_recycleScenesInWidgetConfigAction->isChecked()); -} + bool recycleScenes = m_recycleScenesInWidgetConfigAction->isChecked(); + if (senderAct == m_configNumWidgets1Action) createVizWidgets(1, recycleScenes); + else if (senderAct == m_configNumWidgets2Action) createVizWidgets(2, recycleScenes); + else if (senderAct == m_configNumWidgets4Action) createVizWidgets(4, recycleScenes); + else if (senderAct == m_configNumWidgetsNoneAction) createVizWidgets(0, recycleScenes); +} //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -void QMVMainWindow::slotConfigNumWidgets() +void QMVMainWindow::slotDeleteFirstVizWidget() { - QObject* senderAct = sender(); - - bool software = m_softwareRenderingWidgetsAction->isChecked(); - bool recycleScenes = m_recycleScenesInWidgetConfigAction->isChecked(); - - if (senderAct == m_configNumWidgets1Action) createVizWidgets(1, software, recycleScenes); - else if (senderAct == m_configNumWidgets2Action) createVizWidgets(2, software, recycleScenes); - else if (senderAct == m_configNumWidgets4Action) createVizWidgets(4, software, recycleScenes); - else if (senderAct == m_configNumWidgetsNoneAction) createVizWidgets(0, software, recycleScenes); + deleteVizWidgetAt(0); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow::slotDeleteSecondVizWidget() +{ + deleteVizWidgetAt(1); +} //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- void QMVMainWindow::slotCreateSphereAndBoxScene() { - QMVModelFactory modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + // Without initialization we're not getting the correct capabilities + CVF_ASSERT(m_contextGroup->isContextGroupInitialized()); + + QMVModelFactory modelFactory(m_useShadersAction->isChecked(), *m_contextGroup->capabilities()); QMVSceneFactory sceneFactory(&modelFactory); - ref model = modelFactory.createSphereAndBox(); - ref scene = sceneFactory.createFromModel(model.p()); + cvf::ref model = modelFactory.createSphereAndBox(); + cvf::ref scene = sceneFactory.createFromModel(model.p()); setSceneInAllVizWidgets(scene.p()); } @@ -502,11 +509,14 @@ void QMVMainWindow::slotCreateSphereAndBoxScene() //-------------------------------------------------------------------------------------------------- void QMVMainWindow::slotCreateSpheresScene() { - QMVModelFactory modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + // Without initialization we're not getting the correct capabilities + CVF_ASSERT(m_contextGroup->isContextGroupInitialized()); + + QMVModelFactory modelFactory(m_useShadersAction->isChecked(), *m_contextGroup->capabilities()); QMVSceneFactory sceneFactory(&modelFactory); - ref model = modelFactory.createSpheres(); - ref scene = sceneFactory.createFromModel(model.p()); + cvf::ref model = modelFactory.createSpheres(); + cvf::ref scene = sceneFactory.createFromModel(model.p()); setSceneInAllVizWidgets(scene.p()); } @@ -517,11 +527,14 @@ void QMVMainWindow::slotCreateSpheresScene() //-------------------------------------------------------------------------------------------------- void QMVMainWindow::slotCreateBoxesScene() { - QMVModelFactory modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + // Without initialization we're not getting the correct capabilities + CVF_ASSERT(m_contextGroup->isContextGroupInitialized()); + + QMVModelFactory modelFactory(m_useShadersAction->isChecked(), *m_contextGroup->capabilities()); QMVSceneFactory sceneFactory(&modelFactory); - ref model = modelFactory.createBoxes(); - ref scene = sceneFactory.createFromModel(model.p()); + cvf::ref model = modelFactory.createBoxes(); + cvf::ref scene = sceneFactory.createFromModel(model.p()); setSceneInAllVizWidgets(scene.p()); } @@ -532,11 +545,14 @@ void QMVMainWindow::slotCreateBoxesScene() //-------------------------------------------------------------------------------------------------- void QMVMainWindow::slotCreateTrianglesScene() { - QMVModelFactory modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + // Without initialization we're not getting the correct capabilities + CVF_ASSERT(m_contextGroup->isContextGroupInitialized()); + + QMVModelFactory modelFactory(m_useShadersAction->isChecked(), *m_contextGroup->capabilities()); QMVSceneFactory sceneFactory(&modelFactory); - ref model = modelFactory.createTriangles(); - ref scene = sceneFactory.createFromModel(model.p()); + cvf::ref model = modelFactory.createTriangles(); + cvf::ref scene = sceneFactory.createFromModel(model.p()); setSceneInAllVizWidgets(scene.p()); } @@ -547,7 +563,10 @@ void QMVMainWindow::slotCreateTrianglesScene() //-------------------------------------------------------------------------------------------------- void QMVMainWindow::slotAllWidgetsDifferentScene() { - QMVModelFactory modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + // Without initialization we're not getting the correct capabilities + CVF_ASSERT(m_contextGroup->isContextGroupInitialized()); + + QMVModelFactory modelFactory(m_useShadersAction->isChecked(), *m_contextGroup->capabilities()); QMVSceneFactory sceneFactory(&modelFactory); QMVRenderSequenceFactory renderSeqFactory; @@ -556,8 +575,8 @@ void QMVMainWindow::slotAllWidgetsDifferentScene() { if (m_vizWidgets[i] != NULL) { - ref scene = sceneFactory.createNumberedScene(i); - ref renderSeq = renderSeqFactory.createFromScene(scene.p()); + cvf::ref scene = sceneFactory.createNumberedScene(i); + cvf::ref renderSeq = renderSeqFactory.createFromScene(scene.p()); m_vizWidgets[i]->setRenderSequence(renderSeq.p()); } } @@ -607,23 +626,16 @@ void QMVMainWindow::slotUseClientVertexArrays() //-------------------------------------------------------------------------------------------------- void QMVMainWindow::slotDeleteAllResourcesInResourceManager() { - if (m_contextGroup.notNull()) - { - cvf::OpenGLResourceManager* rcMgr = m_contextGroup->resourceManager(); - CVF_ASSERT(rcMgr); - - QMVWidget* vizWidget = m_vizWidgets[0]; - cvf::OpenGLContext* oglContext = vizWidget ? vizWidget->cvfOpenGLContext() : NULL; - if (oglContext) - { - oglContext->makeCurrent(); - rcMgr->deleteAllOpenGLResources(oglContext); - } - } - - redrawAllVizWidgets(); + deleteAllOpenGLResourcesInResourceManager(); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow::slotDeleteOrReleaseOpenGLResourcesInAllVizWidgets() +{ + deleteOrReleaseOpenGLResourcesInAllVizWidgets(); +} //-------------------------------------------------------------------------------------------------- /// @@ -650,22 +662,20 @@ void QMVMainWindow::slotUpdateStatusbar() if (renderSeq) { cvf::PerformanceInfo pi = renderSeq->performanceInfo(); - QGLFormat oglFormat = vizWidget->format(); - QString hwSw = oglFormat.testOption(QGL::IndirectRendering) ? "sw" : "hw"; - QString viewMsg = QString("V%1(%2) #p=%3 #t=%4 ").arg(i).arg(hwSw).arg(pi.visiblePartsCount).arg((pi.triangleCount)); + QString viewMsg = QString("V%1 #p=%2 #t=%3 ").arg(i).arg(pi.visiblePartsCount).arg((pi.triangleCount)); msg += viewMsg; } } } + if (m_contextGroup.notNull()) + { + const cvf::OpenGLInfo info = m_contextGroup->info(); + msg += QString(" | ") + QString::fromStdString(info.renderer().toStdString()); + } + QStatusBar* sb = statusBar(); sb->showMessage(msg); } -//######################################################## -#ifndef CVF_USING_CMAKE -#include "qt-generated/moc_QMVMainWindow.cpp" -#endif -//######################################################## - diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.h b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.h index e92294926e..f1628b59a0 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.h +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVMainWindow.h @@ -34,24 +34,18 @@ // //################################################################################################## - #pragma once #include "cvfBase.h" #include "cvfCollection.h" #include "cvfDrawableGeo.h" -#include -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif +#include class QMVWidget; namespace cvf { - class View; class Scene; class OpenGLResourceManager; class OpenGLContextGroup; @@ -74,22 +68,24 @@ class QMVMainWindow : public QMainWindow private: int vizWidgetCount(); - void createVizWidgets(int numWidgets, bool software, bool recycleScenes); - void deleteAllOpenGLResourcesInAllVizWidgets(); + void createVizWidgets(int numWidgets, bool recycleScenes); + void deleteAllOpenGLResourcesInResourceManager(); + void deleteOrReleaseOpenGLResourcesInAllVizWidgets(); void deleteAllVizWidgets(); + void deleteVizWidgetAt(int index); void setSceneInAllVizWidgets(cvf::Scene* scene); void spreadScenesAcrossVizWidgets(cvf::Collection* sceneCollection); void gatherAllScenes(cvf::Collection* sceneCollection); void redrawAllVizWidgets(); void setRenderModeInAllModels(cvf::DrawableGeo::RenderMode renderMode); - // Protected overrides protected: virtual void closeEvent(QCloseEvent* pCE); private slots: - void slotSoftwareRenderingWidgets(bool); - void slotConfigNumWidgets(); + void slotConfigNumVizWidgets(); + void slotDeleteFirstVizWidget(); + void slotDeleteSecondVizWidget(); void slotCreateSphereAndBoxScene(); void slotCreateSpheresScene(); @@ -102,31 +98,22 @@ private slots: void slotUseClientVertexArrays(); void slotDeleteAllResourcesInResourceManager(); + void slotDeleteOrReleaseOpenGLResourcesInAllVizWidgets(); void slotUpdateStatusbar(); private: static const int MAX_NUM_WIDGETS = 4; cvf::ref m_contextGroup; - QMVWidget* m_vizWidgets[MAX_NUM_WIDGETS]; + QPointer m_vizWidgets[MAX_NUM_WIDGETS]; + QAction* m_createWidgetsAsFloatingDialogsAction; QAction* m_recycleScenesInWidgetConfigAction; - QAction* m_softwareRenderingWidgetsAction; QAction* m_configNumWidgets1Action; QAction* m_configNumWidgets2Action; QAction* m_configNumWidgets4Action; QAction* m_configNumWidgetsNoneAction; - QAction* m_createSphereAndBoxSceneAction; - QAction* m_createSpheresSceneAction; - QAction* m_createBoxesSceneAction; - QAction* m_createTrianglesSceneAction; - QAction* m_allWidgetsDifferentSceneAction; - QAction* m_clearSceneAction; - - QAction* m_useBufferObjectsAction; - QAction* m_useClientVertexArraysAction; - - QAction* m_deleteAllResourcesInResourceManagerAction; + QAction* m_useShadersAction; }; diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.cpp index f0a5bcef96..fb8e6ba51c 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.cpp @@ -34,7 +34,6 @@ // //################################################################################################## - #include "cvfLibCore.h" #include "cvfLibRender.h" #include "cvfLibGeometry.h" @@ -42,47 +41,23 @@ #include "QMVWidget.h" -#include "cvfqtOpenGLContext.h" - -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif - -using cvf::ref; +#include //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- -QMVWidget::QMVWidget(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent) -: cvfqt::OpenGLWidget(contextGroup, format, parent) +QMVWidget::QMVWidget(cvf::OpenGLContextGroup* contextGroup, int indexOfWidget, QWidget* parent, Qt::WindowFlags f) +: cvfqt::OpenGLWidget(contextGroup, parent, f), + m_indexOfWidget(indexOfWidget), + m_paintCount(0) { m_trackball = new cvf::ManipulatorTrackball; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QMVWidget::QMVWidget(QMVWidget* shareWidget, QWidget* parent) -: cvfqt::OpenGLWidget(shareWidget, parent) -{ - m_trackball = new cvf::ManipulatorTrackball; -} - - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -QMVWidget::~QMVWidget() -{ - cvfShutdownOpenGLContext(); -} - - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -118,6 +93,14 @@ cvf::RenderSequence* QMVWidget::renderSequence() } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* QMVWidget::cvfOpenGLContext() +{ + return cvfqt::OpenGLWidget::cvfOpenGLContext(); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -129,10 +112,6 @@ void QMVWidget::resizeGL(int width, int height) camera->viewport()->set(0, 0, width, height); camera->setProjectionAsPerspective(camera->fieldOfViewYDeg(), camera->nearPlane(), camera->farPlane()); } - else - { - glViewport(0, 0, width, height); - } } @@ -145,7 +124,7 @@ void QMVWidget::paintGL() CVF_ASSERT(currentOglContext); CVF_CHECK_OGL(currentOglContext); - cvfqt::OpenGLContext::saveOpenGLState(currentOglContext); + cvf::OpenGLUtils::pushOpenGLState(currentOglContext); if (m_renderSequence.notNull()) { @@ -153,11 +132,17 @@ void QMVWidget::paintGL() } else { - glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + // Reddish background for empty widgets + glClearColor(0.9f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); } - cvfqt::OpenGLContext::restoreOpenGLState(currentOglContext); + cvf::OpenGLUtils::popOpenGLState(currentOglContext); + + m_paintCount++; + QPainter p(this); + p.setPen(Qt::red); + p.drawText(10, 20, QString("VP%1, paint count: %2").arg(m_indexOfWidget).arg(m_paintCount)); } @@ -187,8 +172,13 @@ void QMVWidget::mouseMoveEvent(QMouseEvent* event) if (m_renderSequence.isNull()) return; Qt::MouseButtons mouseBn = event->buttons(); - int posX = event->x(); - int posY = height() - event->y(); +#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) + const int posX = event->position().toPoint().x(); + const int posY = height() - event->position().toPoint().y(); +#else + const int posX = event->x(); + const int posY = height() - event->y(); +#endif cvf::ManipulatorTrackball::NavigationType navType = cvf::ManipulatorTrackball::NONE; if (mouseBn == Qt::LeftButton) @@ -199,7 +189,7 @@ void QMVWidget::mouseMoveEvent(QMouseEvent* event) { navType = cvf::ManipulatorTrackball::ROTATE; } - else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MidButton) + else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MiddleButton) { navType = cvf::ManipulatorTrackball::WALK; } @@ -224,10 +214,18 @@ void QMVWidget::mousePressEvent(QMouseEvent* event) { if (m_renderSequence.isNull()) return; +#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) + const int posX = event->position().toPoint().x(); + const int posY = height() - event->position().toPoint().y(); +#else + const int posX = event->x(); + const int posY = height() - event->y(); +#endif + if (event->buttons() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier) { cvf::Rendering* r = m_renderSequence->firstRendering(); - ref ris = r->rayIntersectSpecFromWindowCoordinates(event->x(), height() - event->y()); + cvf::ref ris = r->rayIntersectSpecFromWindowCoordinates(posX, posY); cvf::HitItemCollection hic; if (r->rayIntersect(*ris, &hic)) @@ -253,9 +251,3 @@ void QMVWidget::mouseReleaseEvent(QMouseEvent* /*event*/) } -//######################################################## -#ifndef CVF_USING_CMAKE -#include "qt-generated/moc_QMVWidget.cpp" -#endif -//######################################################## - diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.h b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.h index f9d1d0812c..b983d9e138 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.h +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QMVWidget.h @@ -34,12 +34,12 @@ // //################################################################################################## - #pragma once #include "cvfBase.h" #include "cvfRenderSequence.h" #include "cvfManipulatorTrackball.h" + #include "cvfqtOpenGLWidget.h" @@ -53,13 +53,13 @@ class QMVWidget : public cvfqt::OpenGLWidget Q_OBJECT public: - QMVWidget(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent); - QMVWidget(QMVWidget* shareWidget, QWidget* parent); - ~QMVWidget(); + QMVWidget(cvf::OpenGLContextGroup* contextGroup, int indexOfWidget, QWidget* parent, Qt::WindowFlags f = Qt::WindowFlags()); void setRenderSequence(cvf::RenderSequence* renderSequence); cvf::RenderSequence* renderSequence(); + cvf::OpenGLContext* cvfOpenGLContext(); + private: void resizeGL(int width, int height); void paintGL(); @@ -70,8 +70,10 @@ class QMVWidget : public cvfqt::OpenGLWidget void mouseReleaseEvent(QMouseEvent* event); private: - cvf::ref m_renderSequence; + int m_indexOfWidget; + int m_paintCount; cvf::ref m_trackball; + cvf::ref m_renderSequence; }; diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QtMultiView.vcxproj b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QtMultiView.vcxproj deleted file mode 100644 index c6b95acd82..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QtMultiView.vcxproj +++ /dev/null @@ -1,212 +0,0 @@ - - - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {2DCDF259-11B5-431F-94FE-C323E2D27AB1} - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)\lib - - - - - - - - - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - - - - - {ecf1becd-e624-f971-c70a-f84686a36084} - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {fbfac173-30fe-2c09-3f2e-d54477b433de} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QtMultiView.vcxproj.filters b/Fwk/VizFwk/TestApps/Qt/QtMultiView/QtMultiView.vcxproj.filters deleted file mode 100644 index 375358d1f9..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtMultiView/QtMultiView.vcxproj.filters +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/CMakeLists.txt new file mode 100644 index 0000000000..0f9c5d279e --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/CMakeLists.txt @@ -0,0 +1,51 @@ +project(QtMultiView_deprecated) + + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_BASE_CXX_FLAGS}") + +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") +endif() + + +find_package(OpenGL) + +include_directories(${LibCore_SOURCE_DIR}) +include_directories(${LibGeometry_SOURCE_DIR}) +include_directories(${LibRender_SOURCE_DIR}) +include_directories(${LibViewing_SOURCE_DIR}) +include_directories(${LibGuiQt_SOURCE_DIR}) +include_directories(${LibUtilities_SOURCE_DIR}) + +set(CEE_LIBS LibUtilities LibGuiQt LibViewing LibRender LibGeometry LibIo LibCore) +set(EXTERNAL_LIBS) + +set(CEE_SOURCE_FILES +QMVFactory_deprecated.cpp +QMVMain_deprecated.cpp +QMVMainWindow_deprecated.cpp +QMVWidget_deprecated.cpp +) + +# Headers that need MOCing +set(MOC_HEADER_FILES +QMVMainWindow_deprecated.h +QMVWidget_deprecated.h +) + +# Qt +if (CEE_USE_QT5) + find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + +set(SYSTEM_LIBRARIES) +if (CMAKE_COMPILER_IS_GNUCXX) + set(SYSTEM_LIBRARIES -lrt -lpthread) +endif(CMAKE_COMPILER_IS_GNUCXX) + +add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${MOC_SOURCE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES} ${SYSTEM_LIBRARIES}) diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVFactory_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVFactory_deprecated.cpp new file mode 100644 index 0000000000..1c43343ca2 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVFactory_deprecated.cpp @@ -0,0 +1,341 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "cvfuPartCompoundGenerator.h" + +#include "QMVFactory_deprecated.h" + + + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVModelFactory_deprecated::QMVModelFactory_deprecated(bool useShaders) +: m_useShaders(useShaders) +{ +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVModelFactory_deprecated::createSphereAndBox() +{ + ref model = new cvf::ModelBasicList; + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createSphere(2, 10, 10, &builder); + + ref eff = new cvf::Effect; + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + if (m_useShaders) + { + ref prog = createProgramStandardHeadlightColor(); + eff->setShaderProgram(prog.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GREEN))); + } + + ref part = new cvf::Part; + part->setName("MySphere"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createBox(cvf::Vec3f(5, 0, 0), 2, 3, 4, &builder); + + ref eff = new cvf::Effect; + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + if (m_useShaders) + { + ref prog = createProgramUnlit(); + eff->setShaderProgram(prog.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GREEN))); + } + + ref part = new cvf::Part; + part->setName("MyBox"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + model->updateBoundingBoxesRecursive(); + + return model; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVModelFactory_deprecated::createSpheres() +{ + cvfu::PartCompoundGenerator gen; + gen.setPartDistribution(cvf::Vec3i(5, 5, 5)); + gen.setNumEffects(8); + gen.useRandomEffectAssignment(false); + gen.setExtent(cvf::Vec3f(3,3,3)); + gen.setOrigin(cvf::Vec3f(-1.5f, -1.5f, -1.5f)); + + cvf::Collection parts; + gen.generateSpheres(20, 20, &parts); + + ref model = new cvf::ModelBasicList; + + ref prog = createProgramStandardHeadlightColor(); + + size_t i; + for (i = 0; i < parts.size(); i++) + { + cvf::Part* part = parts[i].p(); + if (m_useShaders) + { + cvf::Effect* eff = part->effect(); + eff->setShaderProgram(prog.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::INDIGO))); + } + model->addPart(part); + } + + model->updateBoundingBoxesRecursive(); + + return model; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVModelFactory_deprecated::createBoxes() +{ + cvfu::PartCompoundGenerator gen; + gen.setPartDistribution(cvf::Vec3i(5, 5, 5)); + gen.setNumEffects(8); + gen.useRandomEffectAssignment(false); + gen.setExtent(cvf::Vec3f(3,3,3)); + gen.setOrigin(cvf::Vec3f(-1.5f, -1.5f, -1.5f)); + + cvf::Collection parts; + gen.generateBoxes(&parts); + + ref model = new cvf::ModelBasicList; + + ref prog = createProgramStandardHeadlightColor(); + + size_t i; + for (i = 0; i < parts.size(); i++) + { + cvf::Part* part = parts[i].p(); + if (m_useShaders) + { + cvf::Effect* eff = part->effect(); + eff->setShaderProgram(prog.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::CYAN))); + } + model->addPart(part); + } + + model->updateBoundingBoxesRecursive(); + + return model; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVModelFactory_deprecated::createTriangles() +{ + cvfu::PartCompoundGenerator gen; + gen.setPartDistribution(cvf::Vec3i(5, 5, 5)); + gen.setNumEffects(8); + gen.useRandomEffectAssignment(false); + gen.setExtent(cvf::Vec3f(3,3,3)); + gen.setOrigin(cvf::Vec3f(-1.5f, -1.5f, -1.5f)); + + cvf::Collection parts; + gen.generateTriangles(&parts); + + ref model = new cvf::ModelBasicList; + + ref prog = createProgramStandardHeadlightColor(); + + size_t i; + for (i = 0; i < parts.size(); i++) + { + cvf::Part* part = parts[i].p(); + if (m_useShaders) + { + cvf::Effect* eff = part->effect(); + eff->setShaderProgram(prog.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GOLD))); + } + model->addPart(part); + } + + model->updateBoundingBoxesRecursive(); + + return model; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVModelFactory_deprecated::createProgramStandardHeadlightColor() +{ + cvf::ShaderProgramGenerator gen("StandardHeadlightColor", cvf::ShaderSourceProvider::instance()); + gen.configureStandardHeadlightColor(); + ref prog = gen.generate(); + return prog; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVModelFactory_deprecated::createProgramUnlit() +{ + cvf::ShaderProgramGenerator gen("Unlit", cvf::ShaderSourceProvider::instance()); + gen.addVertexCode(cvf::ShaderSourceRepository::vs_Standard); + gen.addFragmentCode(cvf::ShaderSourceRepository::src_Color); + gen.addFragmentCode(cvf::ShaderSourceRepository::fs_Unlit); + ref prog = gen.generate(); + return prog; +} + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVSceneFactory_deprecated::QMVSceneFactory_deprecated(QMVModelFactory_deprecated* modelFactory) +: m_modelFactory(modelFactory) +{ +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVSceneFactory_deprecated::createNumberedScene(int sceneNumber) +{ + ref model; + switch (sceneNumber) + { + case 0: model = m_modelFactory->createSphereAndBox(); break; + case 1: model = m_modelFactory->createSpheres(); break; + case 2: model = m_modelFactory->createBoxes(); break; + default: model = m_modelFactory->createTriangles(); break; + } + + return createFromModel(model.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVSceneFactory_deprecated::createFromModel(cvf::Model* model) +{ + ref scene = new cvf::Scene; + + if (model) + { + scene->addModel(model); + } + + return scene; +} + + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +ref QMVRenderSequenceFactory_deprecated::createFromScene(cvf::Scene* scene) +{ + ref rendering = new cvf::Rendering; + rendering->renderEngine()->enableItemCountUpdate(true); + rendering->setScene(scene); + + cvf::Camera* cam = rendering->camera(); + rendering->addOverlayItem(new cvf::OverlayAxisCross(cam, new cvf::FixedAtlasFont(cvf::FixedAtlasFont::STANDARD))); + + if (scene) + { + cvf::BoundingBox bb = scene->boundingBox(); + if (bb.isValid()) + { + cam->fitView(bb, -cvf::Vec3d::Z_AXIS, cvf::Vec3d::Y_AXIS); + } + } + + ref renderSeq = new cvf::RenderSequence; + renderSeq->addRendering(rendering.p()); + + return renderSeq; +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVFactory_deprecated.h b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVFactory_deprecated.h new file mode 100644 index 0000000000..850e17a405 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVFactory_deprecated.h @@ -0,0 +1,97 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +using cvf::ref; + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMVModelFactory_deprecated +{ +public: + QMVModelFactory_deprecated(bool useShaders); + + ref createSphereAndBox(); + ref createSpheres(); + ref createBoxes(); + ref createTriangles(); + +private: + ref createProgramStandardHeadlightColor(); + ref createProgramUnlit(); + +private: + bool m_useShaders; +}; + + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMVSceneFactory_deprecated +{ +public: + QMVSceneFactory_deprecated(QMVModelFactory_deprecated* modelFactory); + + ref createNumberedScene(int sceneNumber); + ref createFromModel(cvf::Model* model); + +private: + QMVModelFactory_deprecated* m_modelFactory; +}; + + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMVRenderSequenceFactory_deprecated +{ +public: + ref createFromScene(cvf::Scene* model); +}; + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMainWindow_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMainWindow_deprecated.cpp new file mode 100644 index 0000000000..0a5d1b3c4d --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMainWindow_deprecated.cpp @@ -0,0 +1,653 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QMVMainWindow_deprecated.h" +#include "QMVWidget_deprecated.h" +#include "QMVFactory_deprecated.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using cvf::ref; + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVMainWindow_deprecated::QMVMainWindow_deprecated() +{ + memset(m_vizWidgets, 0, sizeof(m_vizWidgets)); + + QFrame* mainFrame = new QFrame; + QGridLayout* frameLayout = new QGridLayout; + mainFrame->setLayout(frameLayout); + setCentralWidget(mainFrame); + + + m_recycleScenesInWidgetConfigAction = new QAction("Recycle Scenes When Changing Widget Config", this); + m_recycleScenesInWidgetConfigAction->setCheckable(true); + + m_softwareRenderingWidgetsAction = new QAction("Software Rendering in Widgets", this); + m_softwareRenderingWidgetsAction->setCheckable(true); + connect(m_softwareRenderingWidgetsAction, SIGNAL(toggled(bool)), SLOT(slotSoftwareRenderingWidgets(bool))); + + m_configNumWidgets1Action = new QAction("1 Widget", this); + m_configNumWidgets2Action = new QAction("2 Widgets", this); + m_configNumWidgets4Action = new QAction("4 Widgets", this); + m_configNumWidgetsNoneAction= new QAction("No Widgets", this); + connect(m_configNumWidgets1Action, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); + connect(m_configNumWidgets2Action, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); + connect(m_configNumWidgets4Action, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); + connect(m_configNumWidgetsNoneAction, SIGNAL(triggered()), SLOT(slotConfigNumWidgets())); + + m_createSphereAndBoxSceneAction = new QAction("Sphere And Box Scene", this); + m_createSpheresSceneAction = new QAction("Spheres Scene", this); + m_createBoxesSceneAction = new QAction("Boxes Scene", this); + m_createTrianglesSceneAction = new QAction("Triangles Scene", this); + m_allWidgetsDifferentSceneAction = new QAction("All Widgets Show Different Scene", this); + m_clearSceneAction = new QAction("Clear Scene", this); + connect(m_createSphereAndBoxSceneAction, SIGNAL(triggered()), SLOT(slotCreateSphereAndBoxScene())); + connect(m_createSpheresSceneAction, SIGNAL(triggered()), SLOT(slotCreateSpheresScene())); + connect(m_createBoxesSceneAction, SIGNAL(triggered()), SLOT(slotCreateBoxesScene())); + connect(m_createTrianglesSceneAction, SIGNAL(triggered()), SLOT(slotCreateTrianglesScene())); + connect(m_allWidgetsDifferentSceneAction, SIGNAL(triggered()), SLOT(slotAllWidgetsDifferentScene())); + connect(m_clearSceneAction, SIGNAL(triggered()), SLOT(slotClearScene())); + + m_useBufferObjectsAction = new QAction("Use Buffer Objects", this); + m_useClientVertexArraysAction = new QAction("Use Client Vertex Arrays", this); + connect(m_useBufferObjectsAction, SIGNAL(triggered()), SLOT(slotUseBufferObjects())); + connect(m_useClientVertexArraysAction, SIGNAL(triggered()), SLOT(slotUseClientVertexArrays())); + + m_deleteAllResourcesInResourceManagerAction = new QAction("Delete All Resources In Resource Manager", this); + connect(m_deleteAllResourcesInResourceManagerAction, SIGNAL(triggered()), SLOT(slotDeleteAllResourcesInResourceManager())); + + + QMenu* widgetsMenu = menuBar()->addMenu("&Widgets"); + widgetsMenu->addAction(m_recycleScenesInWidgetConfigAction); + widgetsMenu->addSeparator(); + widgetsMenu->addAction(m_softwareRenderingWidgetsAction); + widgetsMenu->addSeparator(); + widgetsMenu->addAction(m_configNumWidgets1Action); + widgetsMenu->addAction(m_configNumWidgets2Action); + widgetsMenu->addAction(m_configNumWidgets4Action); + widgetsMenu->addAction(m_configNumWidgetsNoneAction); + + QMenu* scenesMenu = menuBar()->addMenu("&Scenes"); + scenesMenu->addAction(m_createSphereAndBoxSceneAction); + scenesMenu->addAction(m_createSpheresSceneAction); + scenesMenu->addAction(m_createBoxesSceneAction); + scenesMenu->addAction(m_createTrianglesSceneAction); + scenesMenu->addSeparator(); + scenesMenu->addAction(m_allWidgetsDifferentSceneAction); + scenesMenu->addSeparator(); + scenesMenu->addAction(m_clearSceneAction); + + QMenu* renderingMenu = menuBar()->addMenu("&Rendering"); + renderingMenu->addAction(m_useBufferObjectsAction); + renderingMenu->addAction(m_useClientVertexArraysAction); + + QMenu* testMenu = menuBar()->addMenu("&Test"); + testMenu->addAction(m_deleteAllResourcesInResourceManagerAction); + + // Must create context group before launching any widgets + m_contextGroup = new cvf::OpenGLContextGroup; + + createVizWidgets(1, m_softwareRenderingWidgetsAction->isChecked(), false); + slotCreateSphereAndBoxScene(); + + QTimer* timer = new QTimer; + connect(timer, SIGNAL(timeout()), SLOT(slotUpdateStatusbar())); + timer->start(250); + + /* + { + QWidget* myWidget = new QWidget; + QGridLayout* layout = new QGridLayout(myWidget); + + QLabel* l1 = new QLabel("JALLA", myWidget); + QLabel* l2 = new QLabel("BALLA", myWidget); + QLabel* l3 = new QLabel("TRALLA", myWidget); + layout->addWidget(l1, 0, 0); + layout->addWidget(l2, 0, 1); + layout->addWidget(l3, 1, 1); + + QStatusBar* sb = statusBar(); + //sb->addPermanentWidget(new QLabel("JALLA")); + sb->addPermanentWidget(myWidget); + } + */ +} + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVMainWindow_deprecated::~QMVMainWindow_deprecated() +{ +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int QMVMainWindow_deprecated::vizWidgetCount() +{ + int count = 0; + + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i]) + { + count++; + } + } + + return count; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::createVizWidgets(int numWidgets, bool software, bool recycleScenes) +{ + CVF_ASSERT(numWidgets <= MAX_NUM_WIDGETS); + + cvf::Collection sceneCollection; + if (recycleScenes) + { + gatherAllScenes(&sceneCollection); + } + + deleteAllVizWidgets(); + + QWidget* parentWidget = centralWidget(); + QGridLayout* layout = dynamic_cast(parentWidget->layout()); + CVF_ASSERT(layout); + + QGLFormat oglFormat; + if (software) + { + oglFormat.setOption(QGL::IndirectRendering); + } + + // The context group that all the contexts end up in + CVF_ASSERT(m_contextGroup.notNull()); + CVF_ASSERT(m_contextGroup->contextCount() == 0); + + QMVWidget_deprecated* shareWidget = NULL; + + int i; + for (i = 0; i < numWidgets; i++) + { + QMVWidget_deprecated* newWidget = NULL; + if (shareWidget) + { + newWidget = new QMVWidget_deprecated(shareWidget, parentWidget); + } + else + { + newWidget = new QMVWidget_deprecated(m_contextGroup.p(), oglFormat, parentWidget); + shareWidget = newWidget; + } + + int row = i/2; + int col = i-2*row; + layout->addWidget(newWidget, row, col); + + m_vizWidgets[i] = newWidget; + } + + if (recycleScenes) + { + spreadScenesAcrossVizWidgets(&sceneCollection); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::deleteAllOpenGLResourcesInAllVizWidgets() +{ + cvf::OpenGLResourceManager* resourceManager = m_contextGroup.notNull() ? m_contextGroup->resourceManager() : NULL; + + // The loop below should not be needed now that we can clean up resources + // by calling on the resource manager, but leave it as long as deleteOrReleaseOpenGLResources() is in place + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + QMVWidget_deprecated* vizWidget = m_vizWidgets[i]; + if (vizWidget) + { + vizWidget->makeCurrent(); + cvf::OpenGLContext* oglContext = vizWidget->cvfOpenGLContext(); + CVF_ASSERT(oglContext); + CVF_ASSERT(oglContext->isCurrent()); + + cvf::RenderSequence* renderSeq = vizWidget->renderSequence(); + if (renderSeq) + { + renderSeq->deleteOrReleaseOpenGLResources(oglContext); + } + + CVF_ASSERT(resourceManager); + resourceManager->deleteAllOpenGLResources(oglContext); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::deleteAllVizWidgets() +{ + QWidget* parentWidget = centralWidget(); + QLayout* layout = parentWidget->layout(); + + deleteAllOpenGLResourcesInAllVizWidgets(); + + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i]) + { + layout->removeWidget(m_vizWidgets[i]); + delete m_vizWidgets[i]; + m_vizWidgets[i] = NULL; + } + } + + CVF_ASSERT(m_contextGroup.isNull() || m_contextGroup->contextCount() == 0); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::setSceneInAllVizWidgets(cvf::Scene* scene) +{ + QMVRenderSequenceFactory_deprecated factory; + + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i] != NULL) + { + ref renderSeq = factory.createFromScene(scene); + m_vizWidgets[i]->setRenderSequence(renderSeq.p()); + } + } + + redrawAllVizWidgets(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::spreadScenesAcrossVizWidgets(cvf::Collection* sceneCollection) +{ + QMVRenderSequenceFactory_deprecated factory; + + cvf::uint i; + for (i = 0; i < static_cast(MAX_NUM_WIDGETS); i++) + { + QMVWidget_deprecated* vizWidget = m_vizWidgets[i]; + if (vizWidget) + { + cvf::Scene* scene = (sceneCollection->size() > i) ? sceneCollection->at(i) : NULL; + if (scene) + { + ref renderSeq = factory.createFromScene(scene); + vizWidget->setRenderSequence(renderSeq.p()); + } + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::gatherAllScenes(cvf::Collection* sceneCollection) +{ + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i] != NULL) + { + cvf::RenderSequence* renderSeq = m_vizWidgets[i]->renderSequence(); + cvf::Rendering* rendering = renderSeq ? renderSeq->firstRendering() : NULL; + cvf::Scene* scene = rendering ? rendering->scene() : NULL; + if (scene) + { + sceneCollection->push_back(scene); + } + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::redrawAllVizWidgets() +{ + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i] != NULL) + { + m_vizWidgets[i]->update(); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::setRenderModeInAllModels(cvf::DrawableGeo::RenderMode renderMode) +{ + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i] != NULL) + { + cvf::RenderSequence* renderSeq = m_vizWidgets[i]->renderSequence(); + cvf::Rendering* rendering = renderSeq ? renderSeq->firstRendering() : NULL; + cvf::Scene* scene = rendering ? rendering->scene() : NULL; + if (scene) + { + cvf::Collection allParts; + scene->allParts(&allParts); + + size_t numParts = allParts.size(); + size_t partIdx; + for (partIdx = 0; partIdx < numParts; partIdx++) + { + cvf::Part* part = allParts.at(partIdx); + + cvf::uint lod; + for (lod = 0; lod < cvf::Part::MAX_NUM_LOD_LEVELS; lod++) + { + cvf::DrawableGeo* drawableGeo = dynamic_cast(part->drawable(lod)); + if (drawableGeo) + { + drawableGeo->setRenderMode(renderMode); + } + } + } + } + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::closeEvent(QCloseEvent*) +{ + deleteAllOpenGLResourcesInAllVizWidgets(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotSoftwareRenderingWidgets(bool software) +{ + int currNumWidgets = vizWidgetCount(); + + // Just recreate with the same number of widgets + createVizWidgets(currNumWidgets, software, m_recycleScenesInWidgetConfigAction->isChecked()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotConfigNumWidgets() +{ + QObject* senderAct = sender(); + + bool software = m_softwareRenderingWidgetsAction->isChecked(); + bool recycleScenes = m_recycleScenesInWidgetConfigAction->isChecked(); + + if (senderAct == m_configNumWidgets1Action) createVizWidgets(1, software, recycleScenes); + else if (senderAct == m_configNumWidgets2Action) createVizWidgets(2, software, recycleScenes); + else if (senderAct == m_configNumWidgets4Action) createVizWidgets(4, software, recycleScenes); + else if (senderAct == m_configNumWidgetsNoneAction) createVizWidgets(0, software, recycleScenes); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotCreateSphereAndBoxScene() +{ + QMVModelFactory_deprecated modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + QMVSceneFactory_deprecated sceneFactory(&modelFactory); + + ref model = modelFactory.createSphereAndBox(); + ref scene = sceneFactory.createFromModel(model.p()); + + setSceneInAllVizWidgets(scene.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotCreateSpheresScene() +{ + QMVModelFactory_deprecated modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + QMVSceneFactory_deprecated sceneFactory(&modelFactory); + + ref model = modelFactory.createSpheres(); + ref scene = sceneFactory.createFromModel(model.p()); + + setSceneInAllVizWidgets(scene.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotCreateBoxesScene() +{ + QMVModelFactory_deprecated modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + QMVSceneFactory_deprecated sceneFactory(&modelFactory); + + ref model = modelFactory.createBoxes(); + ref scene = sceneFactory.createFromModel(model.p()); + + setSceneInAllVizWidgets(scene.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotCreateTrianglesScene() +{ + QMVModelFactory_deprecated modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + QMVSceneFactory_deprecated sceneFactory(&modelFactory); + + ref model = modelFactory.createTriangles(); + ref scene = sceneFactory.createFromModel(model.p()); + + setSceneInAllVizWidgets(scene.p()); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotAllWidgetsDifferentScene() +{ + QMVModelFactory_deprecated modelFactory(!m_softwareRenderingWidgetsAction->isChecked()); + QMVSceneFactory_deprecated sceneFactory(&modelFactory); + QMVRenderSequenceFactory_deprecated renderSeqFactory; + + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i] != NULL) + { + ref scene = sceneFactory.createNumberedScene(i); + ref renderSeq = renderSeqFactory.createFromScene(scene.p()); + m_vizWidgets[i]->setRenderSequence(renderSeq.p()); + } + } + + redrawAllVizWidgets(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotClearScene() +{ + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + if (m_vizWidgets[i] != NULL) + { + m_vizWidgets[i]->setRenderSequence(NULL); + } + } + + redrawAllVizWidgets(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotUseBufferObjects() +{ + setRenderModeInAllModels(cvf::DrawableGeo::BUFFER_OBJECT); + redrawAllVizWidgets(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotUseClientVertexArrays() +{ + setRenderModeInAllModels(cvf::DrawableGeo::VERTEX_ARRAY); + redrawAllVizWidgets(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotDeleteAllResourcesInResourceManager() +{ + if (m_contextGroup.notNull()) + { + cvf::OpenGLResourceManager* rcMgr = m_contextGroup->resourceManager(); + CVF_ASSERT(rcMgr); + + QMVWidget_deprecated* vizWidget = m_vizWidgets[0]; + cvf::OpenGLContext* oglContext = vizWidget ? vizWidget->cvfOpenGLContext() : NULL; + if (oglContext) + { + oglContext->makeCurrent(); + rcMgr->deleteAllOpenGLResources(oglContext); + } + } + + redrawAllVizWidgets(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVMainWindow_deprecated::slotUpdateStatusbar() +{ + cvf::OpenGLResourceManager* resourceManager = m_contextGroup.notNull() ? m_contextGroup->resourceManager() : NULL; + + QString msg = "N/A "; + if (resourceManager) + { + cvf::uint boCount = resourceManager->bufferObjectCount(); + double boMemUsageMB = static_cast(resourceManager->bufferObjectMemoryUsage())/(1024.0*1024.0); + msg = QString("#bo=%1 (MB=%2) | ").arg(boCount).arg(boMemUsageMB, 0, 'f', 3); + } + + int i; + for (i = 0; i < MAX_NUM_WIDGETS; i++) + { + QMVWidget_deprecated* vizWidget = m_vizWidgets[i]; + if (vizWidget) + { + cvf::RenderSequence* renderSeq = vizWidget->renderSequence(); + if (renderSeq) + { + cvf::PerformanceInfo pi = renderSeq->performanceInfo(); + QGLFormat oglFormat = vizWidget->format(); + QString hwSw = oglFormat.testOption(QGL::IndirectRendering) ? "sw" : "hw"; + QString viewMsg = QString("V%1(%2) #p=%3 #t=%4 ").arg(i).arg(hwSw).arg(pi.visiblePartsCount).arg((pi.triangleCount)); + msg += viewMsg; + } + } + } + + QStatusBar* sb = statusBar(); + sb->showMessage(msg); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMainWindow_deprecated.h b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMainWindow_deprecated.h new file mode 100644 index 0000000000..5352d436dd --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMainWindow_deprecated.h @@ -0,0 +1,128 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +#include "cvfBase.h" +#include "cvfCollection.h" +#include "cvfDrawableGeo.h" + +#include +#include + +class QMVWidget_deprecated; + +namespace cvf { + class View; + class Scene; + class OpenGLResourceManager; + class OpenGLContextGroup; +} + + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMVMainWindow_deprecated : public QMainWindow +{ + Q_OBJECT + +public: + QMVMainWindow_deprecated(); + ~QMVMainWindow_deprecated(); + +private: + int vizWidgetCount(); + void createVizWidgets(int numWidgets, bool software, bool recycleScenes); + void deleteAllOpenGLResourcesInAllVizWidgets(); + void deleteAllVizWidgets(); + void setSceneInAllVizWidgets(cvf::Scene* scene); + void spreadScenesAcrossVizWidgets(cvf::Collection* sceneCollection); + void gatherAllScenes(cvf::Collection* sceneCollection); + void redrawAllVizWidgets(); + void setRenderModeInAllModels(cvf::DrawableGeo::RenderMode renderMode); + + // Protected overrides +protected: + virtual void closeEvent(QCloseEvent* pCE); + +private slots: + void slotSoftwareRenderingWidgets(bool); + void slotConfigNumWidgets(); + + void slotCreateSphereAndBoxScene(); + void slotCreateSpheresScene(); + void slotCreateBoxesScene(); + void slotCreateTrianglesScene(); + void slotAllWidgetsDifferentScene(); + void slotClearScene(); + + void slotUseBufferObjects(); + void slotUseClientVertexArrays(); + + void slotDeleteAllResourcesInResourceManager(); + + void slotUpdateStatusbar(); + +private: + static const int MAX_NUM_WIDGETS = 4; + cvf::ref m_contextGroup; + QMVWidget_deprecated* m_vizWidgets[MAX_NUM_WIDGETS]; + + QAction* m_recycleScenesInWidgetConfigAction; + QAction* m_softwareRenderingWidgetsAction; + QAction* m_configNumWidgets1Action; + QAction* m_configNumWidgets2Action; + QAction* m_configNumWidgets4Action; + QAction* m_configNumWidgetsNoneAction; + + QAction* m_createSphereAndBoxSceneAction; + QAction* m_createSpheresSceneAction; + QAction* m_createBoxesSceneAction; + QAction* m_createTrianglesSceneAction; + QAction* m_allWidgetsDifferentSceneAction; + QAction* m_clearSceneAction; + + QAction* m_useBufferObjectsAction; + QAction* m_useClientVertexArraysAction; + + QAction* m_deleteAllResourcesInResourceManagerAction; +}; + diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMain_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMain_deprecated.cpp new file mode 100644 index 0000000000..6cd2167ec7 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVMain_deprecated.cpp @@ -0,0 +1,69 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" + +#include "QMVMainWindow_deprecated.h" + +#include +#include "QtOpenGL/qgl.h" + +#include + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int main(int argc, char *argv[]) +{ + // It seems that if we are using paintEvent() instead of paintGL() to + // draw we might have to set OpenGL as the preferred paint engine + //QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); + + QApplication app(argc, argv); + + // On Linux, Qt will use the system locale, force number formatting settings back to "C" locale + setlocale(LC_NUMERIC,"C"); + + QMVMainWindow_deprecated window; + QString platform = cvf::System::is64Bit() ? "(64bit)" : "(32bit)"; + window.setWindowTitle("Qt MultiView " + platform); + window.resize(1000, 800);; + window.show(); + + return app.exec(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVWidget_deprecated.cpp b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVWidget_deprecated.cpp new file mode 100644 index 0000000000..f52d2fab00 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVWidget_deprecated.cpp @@ -0,0 +1,247 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QMVWidget_deprecated.h" + +#include + +using cvf::ref; + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVWidget_deprecated::QMVWidget_deprecated(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent) +: cvfqt::GLWidget_deprecated(contextGroup, format, parent) +{ + m_trackball = new cvf::ManipulatorTrackball; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVWidget_deprecated::QMVWidget_deprecated(QMVWidget_deprecated* shareWidget, QWidget* parent) +: cvfqt::GLWidget_deprecated(shareWidget, parent) +{ + m_trackball = new cvf::ManipulatorTrackball; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QMVWidget_deprecated::~QMVWidget_deprecated() +{ + cvfShutdownOpenGLContext(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVWidget_deprecated::setRenderSequence(cvf::RenderSequence* renderSequence) +{ + m_trackball->setCamera(NULL); + m_renderSequence = renderSequence; + + if (m_renderSequence.notNull()) + { + // Camera extracted from first rendering of the view + cvf::Camera* camera = currentCamera(); + camera->viewport()->set(0, 0, width(), height()); + camera->setProjectionAsPerspective(camera->fieldOfViewYDeg(), camera->nearPlane(), camera->farPlane()); + + m_trackball->setCamera(camera); + + cvf::BoundingBox bb = m_renderSequence->boundingBox(); + if (bb.isValid()) + { + m_trackball->setRotationPoint(bb.center()); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::RenderSequence* QMVWidget_deprecated::renderSequence() +{ + return m_renderSequence.p(); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVWidget_deprecated::resizeGL(int width, int height) +{ + cvf::Camera* camera = currentCamera(); + if (camera) + { + camera->viewport()->set(0, 0, width, height); + camera->setProjectionAsPerspective(camera->fieldOfViewYDeg(), camera->nearPlane(), camera->farPlane()); + } + else + { + glViewport(0, 0, width, height); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVWidget_deprecated::paintGL() +{ + cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); + CVF_ASSERT(currentOglContext); + CVF_CHECK_OGL(currentOglContext); + + cvf::OpenGLUtils::pushOpenGLState(currentOglContext); + + if (m_renderSequence.notNull()) + { + m_renderSequence->render(currentOglContext); + } + else + { + glClearColor(0.5f, 0.5f, 0.5f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + } + + cvf::OpenGLUtils::popOpenGLState(currentOglContext); +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Camera* QMVWidget_deprecated::currentCamera() +{ + if (m_renderSequence.notNull()) + { + cvf::Rendering* rendering = m_renderSequence->firstRendering(); + if (rendering) + { + return rendering->camera(); + } + } + + return NULL; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVWidget_deprecated::mouseMoveEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + Qt::MouseButtons mouseBn = event->buttons(); + int posX = event->x(); + int posY = height() - event->y(); + + cvf::ManipulatorTrackball::NavigationType navType = cvf::ManipulatorTrackball::NONE; + if (mouseBn == Qt::LeftButton) + { + navType = cvf::ManipulatorTrackball::PAN; + } + else if (mouseBn == Qt::RightButton) + { + navType = cvf::ManipulatorTrackball::ROTATE; + } + else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MiddleButton) + { + navType = cvf::ManipulatorTrackball::WALK; + } + + if (navType != m_trackball->activeNavigation()) + { + m_trackball->startNavigation(navType, posX, posY); + } + + bool needRedraw = m_trackball->updateNavigation(posX, posY); + if (needRedraw) + { + update(); + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVWidget_deprecated::mousePressEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + if (event->buttons() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier) + { + cvf::Rendering* r = m_renderSequence->firstRendering(); + ref ris = r->rayIntersectSpecFromWindowCoordinates(event->x(), height() - event->y()); + + cvf::HitItemCollection hic; + if (r->rayIntersect(*ris, &hic)) + { + cvf::HitItem* item = hic.firstItem(); + CVF_ASSERT(item && item->part()); + + cvf::Vec3d isect = item->intersectionPoint(); + m_trackball->setRotationPoint(isect); + + cvf::Trace::show("hitting part: '%s' coords: %.3f %.3f %.3f", item->part()->name().toAscii().ptr(), isect.x(), isect.y(), isect.z()); + } + } +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QMVWidget_deprecated::mouseReleaseEvent(QMouseEvent* /*event*/) +{ + m_trackball->endNavigation(); +} diff --git a/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVWidget_deprecated.h b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVWidget_deprecated.h new file mode 100644 index 0000000000..919be20086 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtMultiView_deprecated/QMVWidget_deprecated.h @@ -0,0 +1,77 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + + +#pragma once + +#include "cvfBase.h" +#include "cvfRenderSequence.h" +#include "cvfManipulatorTrackball.h" +#include "cvfqtGLWidget_deprecated.h" + + +//================================================================================================== +// +// +// +//================================================================================================== +class QMVWidget_deprecated : public cvfqt::GLWidget_deprecated +{ + Q_OBJECT + +public: + QMVWidget_deprecated(cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent); + QMVWidget_deprecated(QMVWidget_deprecated* shareWidget, QWidget* parent); + ~QMVWidget_deprecated(); + + void setRenderSequence(cvf::RenderSequence* renderSequence); + cvf::RenderSequence* renderSequence(); + +private: + void resizeGL(int width, int height); + void paintGL(); + + cvf::Camera* currentCamera(); + void mousePressEvent(QMouseEvent* event); + void mouseMoveEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + +private: + cvf::ref m_renderSequence; + cvf::ref m_trackball; +}; + + diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/CMakeLists.txt index edd0a63303..e4e75b18b3 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/CMakeLists.txt +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8.12) - project(QtSnippetRunner) @@ -37,6 +35,15 @@ QSRStdInclude.cpp QSRTranslateEvent.cpp ) +set(CEE_HEADER_FILES +QSRCommandLineArgs.h +QSRPropertiesPanel.h +QSRRunPanel.h +QSRSnippetWidget.h +QSRStdInclude.h +QSRTranslateEvent.h +) + # Headers that need MOCing set(MOC_HEADER_FILES QSRMainWindow.h @@ -45,42 +52,24 @@ QSRRunPanel.h QSRSnippetWidget.h ) + # Qt -if (CEE_USE_QT5) - find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) - set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) - qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) +if (CEE_USE_QT6) + find_package(Qt6 COMPONENTS REQUIRED OpenGLWidgets) + set(QT_LIBRARIES Qt6::OpenGLWidgets ) + qt_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +elseif (CEE_USE_QT5) + find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) else() - find_package(Qt4 COMPONENTS QtCore QtGui QtOpenGl REQUIRED) - include(${QT_USE_FILE}) - qt4_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES} ) -endif(CEE_USE_QT5) - -add_definitions(-DCVF_USING_CMAKE) + message(FATAL_ERROR "No supported Qt version selected for build") +endif() set(SYSTEM_LIBRARIES) if (CMAKE_COMPILER_IS_GNUCXX) set(SYSTEM_LIBRARIES -lrt -lpthread) endif(CMAKE_COMPILER_IS_GNUCXX) -add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${MOC_SOURCE_FILES}) +add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES} ${CEE_HEADER_FILES} ${MOC_SOURCE_FILES}) target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES} ${SYSTEM_LIBRARIES}) - - -if (CEE_USE_QT5) - foreach (qtlib ${QT_LIBRARIES}) - add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different $ $ - ) - endforeach(qtlib) -else() - # Copy Qt Dlls - if (MSVC) - set (QTLIBLIST QtCore QtGui QtOpenGl) - foreach (qtlib ${QTLIBLIST}) - add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different ${QT_BINARY_DIR}/$,${qtlib}d4.dll,${qtlib}4.dll> $ - ) - endforeach( qtlib ) - endif(MSVC) -endif(CEE_USE_QT5) diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRCommandLineArgs.h b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRCommandLineArgs.h index 11f303df27..d3854020d8 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRCommandLineArgs.h +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRCommandLineArgs.h @@ -37,7 +37,7 @@ #pragma once -class QStringList; +#include //================================================================================================== diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMain.cpp b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMain.cpp index 3a7d2391b2..ddc8b6d38e 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMain.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMain.cpp @@ -47,6 +47,8 @@ #include #include +#include + //-------------------------------------------------------------------------------------------------- /// @@ -58,9 +60,12 @@ int main(int argc, char *argv[]) // On Linux, Qt will use the system locale, force number formatting settings back to "C" locale setlocale(LC_NUMERIC,"C"); - // These directories are correct when running from within visual studio - cvf::String testDataDir = "../../../Tests/TestData/"; - cvf::String shaderDir = "../../../Tests/SnippetsBasis/Shaders/"; + cvf::String testDataDir = ""; + cvf::String shaderDir = ""; +#ifdef CVF_CEEVIZ_ROOT_SOURCE_DIR + testDataDir = CVF_CEEVIZ_ROOT_SOURCE_DIR "/Tests/TestData/"; + shaderDir = CVF_CEEVIZ_ROOT_SOURCE_DIR "/Tests/SnippetsBasis/Shaders/"; +#endif { QSRCommandLineArgs cmdLineArgs; @@ -93,6 +98,8 @@ int main(int argc, char *argv[]) // Comment in this line to be able to read the glsl directly from file //cvf::ShaderSourceProvider::instance()->setSourceRepository(new cvf::ShaderSourceRepositoryFile("../../../LibRender/glsl/")); + cvf::LogManager* logManager = cvf::LogManager::instance(); + logManager->logger("cee.cvf.OpenGL")->setLevel(cvf::Logger::LL_DEBUG); QSRMainWindow window; window.resize(1000, 800);; diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.cpp b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.cpp index a815b18be2..9707e3afd8 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.cpp @@ -127,7 +127,7 @@ void QSRMainWindow::createActions() } m_activateLastUsedSnippetAction = new QAction("Load last used snippet", this); - m_activateLastUsedSnippetAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L)); + m_activateLastUsedSnippetAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L)); connect(m_activateLastUsedSnippetAction, SIGNAL(triggered()), SLOT(slotRunLastUsedSnippet())); m_closeCurrentSnippetAction = new QAction("Close Current Snippet", this); @@ -136,19 +136,19 @@ void QSRMainWindow::createActions() // View menu m_showHUDAction = new QAction("Show HUD", this); m_showHUDAction->setCheckable(true); - m_showHUDAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_H)); + m_showHUDAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_H)); connect(m_showHUDAction, SIGNAL(triggered()), SLOT(slotShowHUD())); m_redrawAction = new QAction("Redraw view", this); - m_redrawAction ->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R)); + m_redrawAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_R)); connect(m_redrawAction, SIGNAL(triggered()), SLOT(slotViewRedraw())); m_multipleRedrawAction = new QAction("Redraw 10 times", this); - m_multipleRedrawAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_M)); + m_multipleRedrawAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_M)); connect(m_multipleRedrawAction, SIGNAL(triggered()), SLOT(slotViewMultipleRedraw())); m_multipleRedrawManyAction = new QAction("Redraw 50 times", this); - m_multipleRedrawManyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_M)); + m_multipleRedrawManyAction->setShortcut(QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_M)); connect(m_multipleRedrawManyAction, SIGNAL(triggered()), SLOT(slotViewMultipleRedrawMany())); @@ -302,8 +302,22 @@ void QSRMainWindow::createDockPanels() //-------------------------------------------------------------------------------------------------- void QSRMainWindow::executeTestSnippetInNewWidget(const cvf::String& snippetId, TestSnippet* snippet) { + cvf::Trace::show("Executing snippet: %s", snippetId.toAscii().ptr()); + closeCurrentSnippet(); + QWidget* parentWidget = centralWidget(); + CVF_ASSERT(m_contextGroup.notNull()); + +#ifdef QSR_USE_OPENGLWIDGET + + QSurfaceFormat surfFormat; + surfFormat.setSamples(m_formatMultisampleAction->isChecked() ? 8 : 0); + m_currentSnippetWidget = new QSRSnippetWidget(snippet, m_contextGroup.p(), parentWidget); + m_currentSnippetWidget->setFormat(surfFormat); + +#else + QGLFormat glFormat; glFormat.setDirectRendering(!m_formatSoftwareAction->isChecked()); @@ -320,9 +334,11 @@ void QSRMainWindow::executeTestSnippetInNewWidget(const cvf::String& snippetId, // For FSAA, use with glEnable(GL_MULTISAMPLE); //glFormat.setSampleBuffers(true); - QWidget* parentWidget = centralWidget(); - CVF_ASSERT(m_contextGroup.notNull()); m_currentSnippetWidget = new QSRSnippetWidget(snippet, m_contextGroup.p(), glFormat, parentWidget); + +#endif + + m_currentSnippetWidget->setFocus(); if (m_formatMultisampleAction->isChecked()) @@ -344,7 +360,7 @@ void QSRMainWindow::executeTestSnippetInNewWidget(const cvf::String& snippetId, // Store ID of this 'last run' snippet in registry QSettings settings("Ceetron", "SnippetRunner"); - settings.setValue("LastUsedSnippetID", snippetId.toAscii().ptr()); + settings.setValue("LastUsedSnippetID", cvfqt::Utils::toQString(snippetId)); repaint(); } @@ -537,6 +553,9 @@ void QSRMainWindow::slotViewMultipleRedrawMany() //-------------------------------------------------------------------------------------------------- void QSRMainWindow::slotSaveFrameBufferToFile() { +#ifdef QSR_USE_OPENGLWIDGET + cvf::Trace::show("NOT IMPLEMENTED!!"); +#else if (!m_currentSnippetWidget) { cvf::Trace::show("No current widget"); @@ -556,7 +575,7 @@ void QSRMainWindow::slotSaveFrameBufferToFile() { cvf::Trace::show("FAILED to saved image: %s", (const char*)fileName.toLatin1()); } - +#endif } @@ -740,34 +759,49 @@ void QSRMainWindow::slotShowHelp() } // OpenGL info + cvf::OpenGLContext* currentOglContext = m_currentSnippetWidget->cvfOpenGLContext(); + if (currentOglContext) { + cvf::OpenGLInfo cvfOglInfo = currentOglContext->group()->info(); oglInfo = QString("OpenGL info:"); - oglInfo += QString("\nversion:\t") + reinterpret_cast(glGetString(GL_VERSION)); - oglInfo += QString("\nrenderer:\t") + reinterpret_cast(glGetString(GL_RENDERER)); - oglInfo += QString("\nvendor:\t") + reinterpret_cast(glGetString(GL_VENDOR)); - oglInfo += QString("\nglsl ver.:\t") + reinterpret_cast(glGetString(GL_SHADING_LANGUAGE_VERSION)); + oglInfo += QString("\nversion: ") + cvfqt::Utils::toQString(cvfOglInfo.version()); + oglInfo += QString("\nrenderer: ") + cvfqt::Utils::toQString(cvfOglInfo.renderer()); + oglInfo += QString("\nvendor: ") + cvfqt::Utils::toQString(cvfOglInfo.vendor()); } +#ifdef QSR_USE_OPENGLWIDGET { - oglInfo += "\n\nReported by Qt:"; - - QGLFormat currrentFormat = m_currentSnippetWidget->format(); + oglInfo += "\n\nReported by Qt QSurfaceFormat:"; -#if QT_VERSION >= 0x040700 + QSurfaceFormat currrentFormat = m_currentSnippetWidget->format(); oglInfo += QString("\nOpenGL version:\t%1.%2").arg(currrentFormat.majorVersion()).arg(currrentFormat.minorVersion()); - switch (currrentFormat.profile()) { - case QGLFormat::NoProfile: oglInfo += "\nProfile:\t\tNoProfile (GLver < 3.3)"; break; - case QGLFormat::CoreProfile: oglInfo += "\nProfile:\t\tCoreProfile"; break; - case QGLFormat::CompatibilityProfile: oglInfo += "\nProfile:\t\tCompatibilityProfile"; break; + case QSurfaceFormat::NoProfile: oglInfo += "\nProfile:NoProfile (GLver < 3.3)"; break; + case QSurfaceFormat::CoreProfile: oglInfo += "\nProfile:CoreProfile"; break; + case QSurfaceFormat::CompatibilityProfile: oglInfo += "\nProfile:CompatibilityProfile"; break; } -#endif - oglInfo += QString("\nColor buffer size:\t<%1 %2 %3 %4>").arg(currrentFormat.redBufferSize()).arg(currrentFormat.greenBufferSize()).arg(currrentFormat.blueBufferSize()).arg(currrentFormat.alphaBufferSize()); - oglInfo += QString("\nDepth buffer size:\t%1").arg(currrentFormat.depthBufferSize()); + oglInfo += QString("\nColor buffer size:<%1 %2 %3 %4>").arg(currrentFormat.redBufferSize()).arg(currrentFormat.greenBufferSize()).arg(currrentFormat.blueBufferSize()).arg(currrentFormat.alphaBufferSize()); + oglInfo += QString("\nDepth buffer size:%1").arg(currrentFormat.depthBufferSize()); } +#else + { + oglInfo += "\n\nReported by Qt QGLFormat:"; + + QGLFormat currrentFormat = m_currentSnippetWidget->format(); + oglInfo += QString("\nOpenGL version:\t%1.%2").arg(currrentFormat.majorVersion()).arg(currrentFormat.minorVersion()); + switch (currrentFormat.profile()) + { + case QGLFormat::NoProfile: oglInfo += "\nProfile:NoProfile (GLver < 3.3)"; break; + case QGLFormat::CoreProfile: oglInfo += "\nProfile:CoreProfile"; break; + case QGLFormat::CompatibilityProfile: oglInfo += "\nProfile:CompatibilityProfile"; break; + } + oglInfo += QString("\nColor buffer size:<%1 %2 %3 %4>").arg(currrentFormat.redBufferSize()).arg(currrentFormat.greenBufferSize()).arg(currrentFormat.blueBufferSize()).arg(currrentFormat.alphaBufferSize()); + oglInfo += QString("\nDepth buffer size:%1").arg(currrentFormat.depthBufferSize()); + } +#endif } QMessageBox dlg(this); @@ -832,9 +866,3 @@ void QSRMainWindow::slotUpdateViewMenu() m_showHUDAction->blockSignals(false); } - - -// ------------------------------------------------------- -#ifndef CVF_USING_CMAKE -#include "qt-generated/moc_QSRMainWindow.cpp" -#endif diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.h b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.h index f5814cd7c5..e1db85fd4b 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.h +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRMainWindow.h @@ -46,11 +46,7 @@ #include "cvfuSnippetFactory.h" #include -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif class QAction; class QSRSnippetWidget; diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.cpp b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.cpp index f4d5e74539..c88595d682 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.cpp @@ -42,7 +42,6 @@ #include "cvfuSnippetPropertyPublisher.h" #include "cvfqtUtils.h" -#if QT_VERSION >= 0x050000 #include #include #include @@ -54,17 +53,6 @@ #include #include #include -#else -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif //================================================================================================== @@ -626,10 +614,3 @@ void QSRPropertiesPanel::onPropertyValueChangedBySnippet(cvfu::Property* propert } } } - - -// ------------------------------------------------------- -#ifndef CVF_USING_CMAKE -#include "qt-generated/moc_QSRPropertiesPanel.cpp" -#endif - diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.h b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.h index 906952849c..1563c3ef05 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.h +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRPropertiesPanel.h @@ -44,12 +44,8 @@ #include "cvfuProperty.h" #include "cvfuSnippetPropertyPublisher.h" -#include -#if QT_VERSION >= 0x050000 +#include #include -#else -#include -#endif class QSRSnippetWidget; class QComboBox; diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.cpp b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.cpp index a028fc1a9f..cd988355df 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.cpp @@ -43,7 +43,6 @@ #include "cvfuTestSnippet.h" #include "cvfqtUtils.h" -#if QT_VERSION >= 0x050000 #include #include #include @@ -52,13 +51,7 @@ #include #include #include -#else -#include -#include -#include -#include -#include -#endif + using cvfu::TestSnippet; using cvfu::SnippetInfo; using cvfu::SnippetRegistry; @@ -232,10 +225,3 @@ void QSRRunPanel::slotPrevButtonClicked() executeCurrentSnippet(); updateCurrSnippetInfoWidgets(); } - - -// ------------------------------------------------------- -#ifndef CVF_USING_CMAKE -#include "qt-generated/moc_QSRRunPanel.cpp" -#endif - diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.h b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.h index 47d6918210..b6407b15b0 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.h +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRRunPanel.h @@ -44,11 +44,7 @@ #include "cvfuSnippetFactory.h" #include -#if QT_VERSION >= 0x050000 #include -#else -#include -#endif class QDockWidget; class QLabel; diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.cpp b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.cpp index d69b63914d..e6d00cc8ce 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.cpp @@ -40,10 +40,10 @@ #include "QSRTranslateEvent.h" #include "cvfqtPerformanceInfoHud.h" -#include "cvfqtOpenGLContext.h" #include +#include #include using cvfu::TestSnippet; @@ -53,8 +53,13 @@ using cvfu::TestSnippet; //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- +#ifdef QSR_USE_OPENGLWIDGET +QSRSnippetWidget::QSRSnippetWidget(TestSnippet* snippet, cvf::OpenGLContextGroup* contextGroup, QWidget* parent) +: OglWidgetBaseClass(contextGroup, parent), +#else QSRSnippetWidget::QSRSnippetWidget(TestSnippet* snippet, cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent) -: cvfqt::OpenGLWidget(contextGroup, format, parent), +: OglWidgetBaseClass(contextGroup, format, parent), +#endif m_drawHUD(false), m_lastSetRenderMode(DrawableGeo::VERTEX_ARRAY), m_enableMultisampleWhenDrawing(false) @@ -88,8 +93,6 @@ QSRSnippetWidget::~QSRSnippetWidget() m_snippet->destroySnippet(); m_snippet = NULL; } - - cvfShutdownOpenGLContext(); } @@ -526,6 +529,8 @@ void QSRSnippetWidget::showModelStatistics() //-------------------------------------------------------------------------------------------------- void QSRSnippetWidget::initializeGL() { + OglWidgetBaseClass::initializeGL(); + CVF_ASSERT(m_snippet.notNull()); cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); @@ -534,6 +539,7 @@ void QSRSnippetWidget::initializeGL() bool bInitOK = m_snippet->initializeSnippet(currentOglContext); CVF_ASSERT(bInitOK); + CVF_UNUSED(bInitOK); CVF_CHECK_OGL(currentOglContext); @@ -592,14 +598,10 @@ void QSRSnippetWidget::paintEvent(QPaintEvent* /*event*/) QPainter painter(this); -#if QT_VERSION >= 0x040600 - // Qt 4.6 painter.beginNativePainting(); CVF_CHECK_OGL(currentOglContext); -#endif - - cvfqt::OpenGLContext::saveOpenGLState(currentOglContext); + cvf::OpenGLUtils::pushOpenGLState(currentOglContext); CVF_CHECK_OGL(currentOglContext); if (m_enableMultisampleWhenDrawing) @@ -616,7 +618,7 @@ void QSRSnippetWidget::paintEvent(QPaintEvent* /*event*/) glDisable(GL_MULTISAMPLE); } - cvfqt::OpenGLContext::restoreOpenGLState(currentOglContext); + cvf::OpenGLUtils::popOpenGLState(currentOglContext); CVF_CHECK_OGL(currentOglContext); if (postEventAction == cvfu::REDRAW) @@ -624,12 +626,8 @@ void QSRSnippetWidget::paintEvent(QPaintEvent* /*event*/) update(); } - -#if QT_VERSION >= 0x040600 - // Qt 4.6 painter.endNativePainting(); CVF_CHECK_OGL(currentOglContext); -#endif if (m_drawHUD) { @@ -753,11 +751,3 @@ void QSRSnippetWidget::keyPressEvent(QKeyEvent* event) parentWidget()->repaint(); } } - - -//######################################################## -#ifndef CVF_USING_CMAKE -#include "qt-generated/moc_QSRSnippetWidget.cpp" -#endif -//######################################################## - diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.h b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.h index 9a74e7f514..b80f975934 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.h +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRSnippetWidget.h @@ -45,22 +45,35 @@ #include "cvfuTestSnippet.h" -#include "cvfqtOpenGLWidget.h" - class QTimer; +#define QSR_USE_OPENGLWIDGET + +#ifdef QSR_USE_OPENGLWIDGET +#include "cvfqtOpenGLWidget.h" +typedef cvfqt::OpenGLWidget OglWidgetBaseClass; +#else +#include "cvfqtGLWidget.h" +typedef cvfqt::GLWidget OglWidgetBaseClass; +#endif + + //================================================================================================== // // // //================================================================================================== -class QSRSnippetWidget : public cvfqt::OpenGLWidget +class QSRSnippetWidget : public OglWidgetBaseClass { Q_OBJECT public: +#ifdef QSR_USE_OPENGLWIDGET + QSRSnippetWidget(cvfu::TestSnippet* snippet, cvf::OpenGLContextGroup* contextGroup, QWidget* parent); +#else QSRSnippetWidget(cvfu::TestSnippet* snippet, cvf::OpenGLContextGroup* contextGroup, const QGLFormat& format, QWidget* parent); +#endif ~QSRSnippetWidget(); cvfu::TestSnippet* snippet(); diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRStdInclude.h b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRStdInclude.h index 43cade5914..aad11911f8 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRStdInclude.h +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRStdInclude.h @@ -11,14 +11,8 @@ #include "cvfuSnippetFactory.h" #include "cvfuInputEvents.h" -#include -#if QT_VERSION >= 0x050000 -#include -#include -#include -#else -#include -#endif +#include +#include // Introduce name of commonly used classes (that are unlikely to create clashes) from the cvf namespace. // We allow the use of using-declarations in this include file since its sole usage is as a precompiled header file. diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRTranslateEvent.cpp b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRTranslateEvent.cpp index d69c6a21f0..a088561cd4 100644 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRTranslateEvent.cpp +++ b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QSRTranslateEvent.cpp @@ -51,7 +51,7 @@ cvfu::MouseEvent QSRTranslateEvent::translateMouseEvent(int widgetHeight, const Qt::MouseButtons qtButtons = event.buttons(); cvfu::MouseButtons buttons = cvfu::NoButton; if (qtButtons & Qt::LeftButton) buttons |= cvfu::LeftButton; - if (qtButtons & Qt::MidButton) buttons |= cvfu::MiddleButton; + if (qtButtons & Qt::MiddleButton) buttons |= cvfu::MiddleButton; if (qtButtons & Qt::RightButton) buttons |= cvfu::RightButton; Qt::KeyboardModifiers qtModifiers = event.modifiers(); @@ -69,7 +69,7 @@ cvfu::MouseEvent QSRTranslateEvent::translateMouseEvent(int widgetHeight, const cvfu::MouseButton QSRTranslateEvent::translateMouseButton(Qt::MouseButton qtMouseButton) { if (qtMouseButton == Qt::LeftButton) return cvfu::LeftButton; - if (qtMouseButton == Qt::MidButton) return cvfu::MiddleButton; + if (qtMouseButton == Qt::MiddleButton) return cvfu::MiddleButton; if (qtMouseButton == Qt::RightButton) return cvfu::RightButton; return cvfu::NoButton; diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QtSnippetRunner.vcxproj b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QtSnippetRunner.vcxproj deleted file mode 100644 index deec52e7b6..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QtSnippetRunner.vcxproj +++ /dev/null @@ -1,491 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {A88592D2-824D-4BD4-717F-88B3A5A65E9A} - QtSnippetRunner - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib - Windows - - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../../ThirdParty/TBB/lib/$(Platform)_VS2010 - Windows - - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib - Windows - - - - - Level3 - Disabled - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;_DEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - qtmaind.lib;QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../../ThirdParty/TBB/lib/$(Platform)_VS2010 - Windows - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib - Windows - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../../ThirdParty/TBB/lib/$(Platform)_VS2010 - Windows - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib - Windows - - - - - Level3 - MaxSpeed - true - true - $(QTDIR)/include;$(QTDIR)/include/Qt;../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../LibGuiQt;../../../Tests/SnippetsBasis;. - WIN32;_WINDOWS;NDEBUG;%(PreprocessorDefinitions) - Use - QSRStdInclude.h - - - true - true - true - qtmain.lib;QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;Winmm.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../../ThirdParty/TBB/lib/$(Platform)_VS2010 - Windows - - - - - {2667ac1d-ca80-42f8-8644-ddb58d342ff2} - - - {181472ee-4b37-01e8-49d5-6213678fe4f8} - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {fbfac173-30fe-2c09-3f2e-d54477b433de} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - {c22d8a0d-2318-3353-f75a-e83b82a3b29f} - - - {ecf1becd-e624-f971-c70a-f84686a36084} - - - {0d83607b-e0f7-dba8-2f1f-8400c30b2008} - - - {78b079bd-9fc7-4b9e-b4a6-96da0f00248b} - - - - - - - - - - - Create - Create - Create - Create - Create - Create - Create - Create - - - - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - - - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - %QTDIR%\bin\moc.exe %(FullPath) -o Qt-Generated\moc_%(Filename).cpp - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - MOCing %(FullPath)... - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - Qt-Generated\moc_%(FileName).cpp - - - - - - - - COPY /Y /B "..\..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - COPY /Y /B "..\..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - $(TargetDir)tbb.dll - COPY /Y /B "..\..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - COPY /Y /B "..\..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QtSnippetRunner.vcxproj.filters b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QtSnippetRunner.vcxproj.filters deleted file mode 100644 index 81fcc1defa..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/QtSnippetRunner.vcxproj.filters +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/TriggerTBBCopy.txt b/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/QtSnippetRunner/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/CMakeLists.txt b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/CMakeLists.txt new file mode 100644 index 0000000000..9cf439ac77 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/CMakeLists.txt @@ -0,0 +1,58 @@ +project(QtTestBenchOpenGLWidget) + + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STANDARD_CXX_FLAGS}") + +if (CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-long-long") +endif() + + +find_package(OpenGL) + +if (CEE_USE_QT6) + find_package(Qt6 COMPONENTS REQUIRED OpenGLWidgets) + set(QT_LIBRARIES Qt6::OpenGLWidgets ) +elseif (CEE_USE_QT5) + find_package(Qt5 REQUIRED COMPONENTS Widgets) + set(QT_LIBRARIES Qt5::Widgets) +else() + message(FATAL_ERROR "No supported Qt version selected for build") +endif() + + +include_directories(${LibCore_SOURCE_DIR}) +include_directories(${LibGeometry_SOURCE_DIR}) +include_directories(${LibRender_SOURCE_DIR}) +include_directories(${LibViewing_SOURCE_DIR}) +include_directories(${LibUtilities_SOURCE_DIR}) +include_directories(${LibGuiQt_SOURCE_DIR}) + +set(CEE_LIBS LibGuiQt LibUtilities LibViewing LibRender LibGeometry LibIo LibCore) + + +set(CEE_CODE_FILES +QTBMain.cpp +QTBMainWindow.cpp +QTBMainWindow.h +QTBSceneFactory.cpp +QTBSceneFactory.h +QTBVizWidget.cpp +QTBVizWidget.h +) + +# Headers that need MOCing +set(MOC_HEADER_FILES +QTBMainWindow.h +QTBVizWidget.h +) + +if (CEE_USE_QT6) + qt_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +elseif (CEE_USE_QT5) + qt5_wrap_cpp(MOC_SOURCE_FILES ${MOC_HEADER_FILES}) +endif() + +add_executable(${PROJECT_NAME} ${CEE_CODE_FILES} ${MOC_SOURCE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES} ${QT_LIBRARIES}) + diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMain.cpp b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMain.cpp new file mode 100644 index 0000000000..cb61b3eab5 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMain.cpp @@ -0,0 +1,103 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include + +#include "QTBMainWindow.h" + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +int main(int argc, char* argv[]) +{ + // Used to get registry settings in the right place + QCoreApplication::setOrganizationName("CeetronSolutions"); + QCoreApplication::setApplicationName("QtTestBenchOpenGLWidget"); + + // Note! + // The Qt::AA_ShareOpenGLContexts setting is needed when we have multiple viz widgets in flight + // and we have a setup where these widgets belong to different top-level windows, or end up + // belonging to different top-level windows through re-parenting. + // This is indeed the situation we encounter in this test application. + // For example: + // * Two viz widgets inside the same central widget => OK + // * Two viz widgets docked inside two different dock widgets => OK + // * One viz widget in docked dock widget and one viz widget in central widget => OK + // * Two viz widgets as different top level windows => FAIL + // * One viz widget in docked dock widget and one viz widget in floating dock widget => FAIL + // * One viz widget in central widget and one widget as top level window => FAIL + // + // In the failing situations the viz widgets should really belong to different context groups (which + // has it own implications), but as a workaround we can use the Qt::AA_ShareOpenGLContexts flag + QApplication::setAttribute(Qt::AA_ShareOpenGLContexts); + + // May want to do some further experimentation with these as well + //QApplication::setAttribute(Qt::AA_NativeWindows); + //QApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); + + //QApplication::setAttribute(Qt::AA_UseDesktopOpenGL); + //QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL); + //QApplication::setAttribute(Qt::AA_UseOpenGLES); + + + cvf::LogManager* logManager = cvf::LogManager::instance(); + logManager->logger("cee.cvf.OpenGL")->setLevel(cvf::Logger::LL_DEBUG); + + // To display logging from GLWidget::logOpenGLInfo() + logManager->logger("cee.cvf.qt")->setLevel(cvf::Logger::LL_INFO); + + // For even more output + logManager->logger("cee.cvf.qt")->setLevel(cvf::Logger::LL_DEBUG); + + + QApplication app(argc, argv); + + QTBMainWindow mainWindow; + mainWindow.setWindowTitle(QString("QtTestBenchOpenGLWidget (qtVer=%1)").arg(qVersion())); + mainWindow.resize(1000, 800); + mainWindow.show(); + + const int appRetCode = app.exec(); + return appRetCode; +} + diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMainWindow.cpp b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMainWindow.cpp new file mode 100644 index 0000000000..2ed8d44a71 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMainWindow.cpp @@ -0,0 +1,676 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QTBMainWindow.h" +#include "QTBVizWidget.h" +#include "QTBSceneFactory.h" + +#include "cvfqtUtils.h" + +#include +#include +#include +#include +#include +#include +#include + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QTBMainWindow::QTBMainWindow() +{ + QFrame* mainFrame = new QFrame(this); + QVBoxLayout* layout = new QVBoxLayout(mainFrame); + mainFrame->setLayout(layout); + setCentralWidget(mainFrame); + + m_dockWidget_1 = new QDockWidget("MyDockWidget_1", this); + m_dockWidget_1->setObjectName("myDockWidget_1"); + addDockWidget(Qt::LeftDockWidgetArea, m_dockWidget_1); + + m_dockWidget_2 = new QDockWidget("MyDockWidget_2", this); + m_dockWidget_2->setObjectName("myDockWidget_2"); + addDockWidget(Qt::LeftDockWidgetArea, m_dockWidget_2); + + resizeDocks({ m_dockWidget_1, m_dockWidget_2 }, { 200, 200 }, Qt::Horizontal); + //loadWinGeoAndDockToolBarLayout(); + + + // The common context group must be created before launching any widgets + // If we don't create one, each widget will get its own context group + m_commonContextGroup = new cvf::OpenGLContextGroup; + + addVizWidget(AddToCentralWidget); + addVizWidget(InDockWidget_1); + addVizWidget(InDockWidget_2); + addVizWidget(AsNewTopLevelWidget); + + { + QMenu* menu = menuBar()->addMenu("&Widgets"); + menu->addAction("Add VizWidget into CentralWidget", this, SLOT(slotAddVizWidget()))->setData(AddToCentralWidget); + menu->addAction("Add VizWidget as TopLevel", this, SLOT(slotAddVizWidget()))->setData(AsNewTopLevelWidget); + menu->addAction("Add VizWidget into DockWidget_1", this, SLOT(slotAddVizWidget()))->setData(InDockWidget_1); + menu->addAction("Add VizWidget into DockWidget_2", this, SLOT(slotAddVizWidget()))->setData(InDockWidget_2); + + menu->addSeparator(); + menu->addAction("Delete VizWidget", this, SLOT(slotDeleteVizWidget())); + + menu->addSeparator(); + menu->addAction("Reparent VizWidget into CentralWidget", this, SLOT(slotReparentVizWidgetIntoCentralWidget())); + menu->addAction("Reparent VizWidget as Top Level", this, SLOT(slotReparentVizWidgetAsTopLevel())); + menu->addAction("Move VizWidget to DockWidget_1", this, SLOT(slotMoveVizWidgetToDockWidget_1())); + menu->addAction("Move VizWidget to DockWidget_2", this, SLOT(slotMoveVizWidgetToDockWidget_2())); + menu->addSeparator(); + menu->addAction("Reparent ALL VizWidgets into CentralWidget", this, SLOT(slotReparentAllVizWidgetsIntoCentralWidget())); + + menu->addSeparator(); + menu->addAction("Refresh VizWidget arr", this, SLOT(slotRefreshVizWidgetArr())); + } + { + QMenu* menu = menuBar()->addMenu("&Activate"); + connect(menu, SIGNAL(aboutToShow()), SLOT(slotAboutToShowActivateMenu())); + } + { + QMenu* menu = menuBar()->addMenu("&Scenes"); + + menu->addAction("Create test scene", this, SLOT(slotCreateTestScene())); + menu->addAction("Clear scene", this, SLOT(slotClearScene())); + } + { + QMenu* menu = menuBar()->addMenu("&Test"); + + menu->addAction("Save layout", this, SLOT(slotSaveLayout())); + menu->addAction("Restore layout", this, SLOT(slotRestoreLayout())); + menu->addSeparator(); + menu->addAction("Grab a native handle", this, SLOT(slotGrabNativeHandle())); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QTBMainWindow::~QTBMainWindow() +{ + cvf::Trace::show("QTBMainWindow::~QTBMainWindow()"); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::addVizWidget(NewWidgetPlacement newWidgetPlacement) +{ + // Guard against creating duplicate viewers inside dock widgets + if (newWidgetPlacement == InDockWidget_1 && m_dockWidget_1->widget()) + { + cvf::Trace::show("DockWidget_1 already contains a viewer"); + return; + } + if (newWidgetPlacement == InDockWidget_2 && m_dockWidget_2->widget()) + { + cvf::Trace::show("DockWidget_2 already contains a viewer"); + return; + } + + removeStaleEntriesFromVizWidgetArr(); + + QWidget* parentToUseOnConstruction = this; + //QWidget* parentToUseOnConstruction = NULL; + + // Use the common context group if we have one - otherwise create a new context group per widget + cvf::ref contextGroupToUse = m_commonContextGroup; + if (contextGroupToUse.isNull()) + { + contextGroupToUse = new cvf::OpenGLContextGroup; + } + + QTBVizWidget* newVizWidget = newVizWidget = new QTBVizWidget(contextGroupToUse.p(), parentToUseOnConstruction, this); + + m_vizWidgetArr.push_back(newVizWidget); + + // Place the widget where instructed + if (newWidgetPlacement == AddToCentralWidget) + { + centralWidget()->layout()->addWidget(newVizWidget); + } + else if (newWidgetPlacement == AsNewTopLevelWidget) + { + newVizWidget->setParent(nullptr); + newVizWidget->resize(400, 300); + newVizWidget->move(50, 200); + newVizWidget->show(); + } + else if (newWidgetPlacement == InDockWidget_1) + { + m_dockWidget_1->setWidget(newVizWidget); + newVizWidget->show(); + } + else if (newWidgetPlacement == InDockWidget_2) + { + m_dockWidget_2->setWidget(newVizWidget); + newVizWidget->show(); + } + + assignViewTitlesToVizWidgetsInArr(); + decideNewActiveVizWidgetAndHighlight(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::handleVizWidgetIsOpenGLReady(QTBVizWidget* vizWidget) +{ + cvf::Trace::show("QTBMainWindow::handleVizWidgetIsOpenGLReady()"); + + CVF_ASSERT(vizWidget->isValid()); + cvf::OpenGLContext* oglContext = vizWidget->cvfOpenGLContext(); + cvf::OpenGLContextGroup* oglContextGroup = oglContext->group(); + CVF_ASSERT(oglContextGroup->isContextGroupInitialized()); + + if (m_commonContextGroup.notNull()) + { + CVF_ASSERT(m_commonContextGroup == oglContextGroup); + CVF_ASSERT(m_commonContextGroup->containsContext(oglContext)); + populateAllValidVizWidgetsWithTestScene(true); + } + else + { + populateAllValidVizWidgetsWithTestScene(false); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::populateAllValidVizWidgetsWithTestScene(bool allWidgetsShareSameScene) +{ + if (allWidgetsShareSameScene) + { + cvf::ref sceneToShow; + + // Look for an existing scene + for (auto vizWidget : m_vizWidgetArr) + { + if (vizWidget->isValid() && vizWidget->scene()) + { + sceneToShow = vizWidget->scene(); + break; + } + } + + if (sceneToShow.isNull()) + { + QTBVizWidget* firstValidVizWidget = nullptr; + for (auto vizWidget : m_vizWidgetArr) + { + if (vizWidget->isValid()) + { + firstValidVizWidget = vizWidget; + break; + } + } + + if (!firstValidVizWidget) + { + cvf::Trace::show("Could not find any valid VizWidgets"); + return; + } + + cvf::OpenGLContext* oglContext = firstValidVizWidget->cvfOpenGLContext(); + CVF_ASSERT(oglContext); + const cvf::OpenGLCapabilities capabilities = *(oglContext->capabilities()); + const bool useShaders = capabilities.supportsOpenGL2(); + QTBSceneFactory sceneFactory(useShaders); + sceneToShow = sceneFactory.createTestScene(capabilities); + } + + for (auto vizWidget : m_vizWidgetArr) + { + vizWidget->setScene(sceneToShow.p()); + vizWidget->update(); + } + } + else + { + for (auto vizWidget : m_vizWidgetArr) + { + if (vizWidget->isValid() && !vizWidget->scene()) + { + cvf::OpenGLContext* oglContext = vizWidget->cvfOpenGLContext(); + CVF_ASSERT(oglContext); + const cvf::OpenGLCapabilities capabilities = *(oglContext->capabilities()); + const bool useShaders = capabilities.supportsOpenGL2(); + QTBSceneFactory sceneFactory(useShaders); + cvf::ref scene = sceneFactory.createTestScene(capabilities); + + vizWidget->setScene(scene.p()); + vizWidget->update(); + } + } + } +} + + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::removeStaleEntriesFromVizWidgetArr() +{ + std::vector > oldArr = m_vizWidgetArr; + m_vizWidgetArr.clear(); + + for (size_t i = 0; i < oldArr.size(); i++) + { + QTBVizWidget* vizWidget = oldArr[i]; + if (vizWidget) + { + m_vizWidgetArr.push_back(vizWidget); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::assignViewTitlesToVizWidgetsInArr() +{ + for (size_t i = 0; i < m_vizWidgetArr.size(); i++) + { + QTBVizWidget* vizWidget = m_vizWidgetArr[i]; + if (vizWidget) + { + vizWidget->setViewTitle(cvf::String("view_%1").arg(static_cast(i))); + vizWidget->update(); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +std::vector QTBMainWindow::vizWidgetNames() +{ + std::vector nameArr; + for (auto vizWidget : m_vizWidgetArr) + { + nameArr.push_back(vizWidget->viewTitle()); + } + + return nameArr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::decideNewActiveVizWidgetAndHighlight() +{ + // For now, simply choose the last one + m_activeVizWidgetName = ""; + const std::vector nameArr = vizWidgetNames(); + if (nameArr.size() > 0) + { + m_activeVizWidgetName = nameArr.back(); + } + + highlightActiveVizWidget(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::highlightActiveVizWidget() +{ + for (auto vizWidget : m_vizWidgetArr) + { + const bool isActive = vizWidget->viewTitle() == m_activeVizWidgetName; + vizWidget->setViewTitleHighlighted(isActive); + vizWidget->update(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QTBVizWidget* QTBMainWindow::getActiveVizWidget() +{ + if (m_vizWidgetArr.size() == 0) + { + cvf::Trace::show("Could not get active VizWidget, no widgets present"); + return nullptr; + } + + for (auto vizWidget : m_vizWidgetArr) + { + if (vizWidget->viewTitle() == m_activeVizWidgetName) + { + return vizWidget; + } + } + + return nullptr; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::saveWinGeoAndDockToolBarLayout() +{ + QSettings settings; + settings.setValue("winGeometry", saveGeometry()); + settings.setValue("dockAndToolBarLayout", saveState(0)); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::loadWinGeoAndDockToolBarLayout() +{ + QSettings settings; + QVariant winGeo = settings.value("winGeometry"); + QVariant layout = settings.value("dockAndToolBarLayout"); + + if (winGeo.isValid()) + { + if (restoreGeometry(winGeo.toByteArray())) + { + if (layout.isValid()) + { + restoreState(layout.toByteArray(), 0); + } + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::closeEvent(QCloseEvent* event) +{ + cvf::Trace::show("QTBMainWindow::closeEvent()"); + QMainWindow::closeEvent(event); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotAddVizWidget() +{ + QAction* senderAction = dynamic_cast(sender()); + const int newWidgetPlacementInt = senderAction->data().toInt(); + NewWidgetPlacement newWidgetPlacement = static_cast(newWidgetPlacementInt); + + addVizWidget(newWidgetPlacement); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotDeleteVizWidget() +{ + removeStaleEntriesFromVizWidgetArr(); + + QTBVizWidget* vizWidget = getActiveVizWidget(); + if (!vizWidget) + { + return; + } + + delete vizWidget; + + removeStaleEntriesFromVizWidgetArr(); + assignViewTitlesToVizWidgetsInArr(); + decideNewActiveVizWidgetAndHighlight(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotReparentVizWidgetIntoCentralWidget() +{ + QTBVizWidget* vizWidget = getActiveVizWidget(); + if (!vizWidget) + { + return; + } + + CVF_ASSERT(vizWidget->isValid()); + + centralWidget()->layout()->addWidget(vizWidget); + vizWidget->show(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotReparentVizWidgetAsTopLevel() +{ + QTBVizWidget* vizWidget = getActiveVizWidget(); + if (!vizWidget) + { + return; + } + + CVF_ASSERT(vizWidget->isValid()); + + vizWidget->setParent(nullptr); + vizWidget->move(100, 100); + vizWidget->resize(600, 400); + vizWidget->show(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotMoveVizWidgetToDockWidget_1() +{ + if (m_dockWidget_1->widget()) + { + cvf::Trace::show("DockWidget_1 already contains a vizWiget"); + return; + } + + QTBVizWidget* vizWidget = getActiveVizWidget(); + if (!vizWidget) + { + return; + } + + CVF_ASSERT(vizWidget->isValid()); + + m_dockWidget_1->setWidget(vizWidget); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotMoveVizWidgetToDockWidget_2() +{ + if (m_dockWidget_2->widget()) + { + cvf::Trace::show("DockWidget_2 already contains a vizWiget"); + return; + } + + QTBVizWidget* vizWidget = getActiveVizWidget(); + if (!vizWidget) + { + return; + } + + CVF_ASSERT(vizWidget->isValid()); + + m_dockWidget_2->setWidget(vizWidget); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotReparentAllVizWidgetsIntoCentralWidget() +{ + for (size_t i = 0; i < m_vizWidgetArr.size(); i++) + { + QTBVizWidget* vizWidget = m_vizWidgetArr[i]; + if (vizWidget) + { + centralWidget()->layout()->addWidget(vizWidget); + vizWidget->show(); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotRefreshVizWidgetArr() +{ + const size_t numWidgetsBefore = m_vizWidgetArr.size(); + + removeStaleEntriesFromVizWidgetArr(); + assignViewTitlesToVizWidgetsInArr(); + + const size_t numWidgetsAfter = m_vizWidgetArr.size(); + + cvf::Trace::show("Refreshed VizWidgetArr, oldCount=%d newCount=%d", numWidgetsBefore, numWidgetsAfter); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotAboutToShowActivateMenu() +{ + QMenu* senderMenu = dynamic_cast(sender()); + CVF_ASSERT(senderMenu); + senderMenu->clear(); + + const std::vector nameArr = vizWidgetNames(); + for (auto widgetName : nameArr) + { + const QString qstrWidgetName(cvfqt::Utils::toQString(widgetName)); + senderMenu->addAction(qstrWidgetName, this, SLOT(slotSomeVizWidgetActivated()))->setData(qstrWidgetName); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotSomeVizWidgetActivated() +{ + QAction* senderAction = dynamic_cast(sender()); + CVF_ASSERT(senderAction); + const QString qstrWidgetName = senderAction->data().toString(); + m_activeVizWidgetName = cvfqt::Utils::toString(qstrWidgetName); + + highlightActiveVizWidget(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotCreateTestScene() +{ + if (m_vizWidgetArr.size() == 0) + { + return; + } + + const bool allWidgetsShareSameScene = m_commonContextGroup.notNull() ? true : false; + populateAllValidVizWidgetsWithTestScene(allWidgetsShareSameScene); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotClearScene() +{ + for (size_t i = 0; i < m_vizWidgetArr.size(); i++) + { + QTBVizWidget* vizWidget = m_vizWidgetArr[i]; + CVF_ASSERT(vizWidget); + vizWidget->setScene(nullptr); + vizWidget->update(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotSaveLayout() +{ + saveWinGeoAndDockToolBarLayout(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotRestoreLayout() +{ + loadWinGeoAndDockToolBarLayout(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBMainWindow::slotGrabNativeHandle() +{ + QTBVizWidget* vizWidget = getActiveVizWidget(); + if (!vizWidget) + { + return; + } + + CVF_ASSERT(vizWidget->isValid()); + cvf::String vizWidgetName = vizWidget->viewTitle(); + cvf::Trace::show("Trying to get native handle for %s by calling QWidget::winId()", vizWidgetName.toAscii().ptr()); + + // Calling this seems to wreak havoc for Qt itself. + // For Qt5 it seems that under certain circumstances it will work, BUT for Qt6 it basically breaks the entire app + WId theWinId = vizWidget->winId(); + cvf::Trace::show("Got WinId = 0x%x", (cvf::uint64)(theWinId)); +} + diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMainWindow.h b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMainWindow.h new file mode 100644 index 0000000000..b2a75f87e2 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBMainWindow.h @@ -0,0 +1,118 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" + +#include "QTBVizWidget.h" + +#include +#include + + + +//================================================================================================== +// +// +// +//================================================================================================== +class QTBMainWindow : public QMainWindow +{ + Q_OBJECT + +public: + QTBMainWindow(); + ~QTBMainWindow(); + + void handleVizWidgetIsOpenGLReady(QTBVizWidget* vizWidget); + +private: + enum NewWidgetPlacement + { + AddToCentralWidget, + AsNewTopLevelWidget, + InDockWidget_1, + InDockWidget_2 + }; + +private: + void addVizWidget(NewWidgetPlacement newWidgetPlacement); + void populateAllValidVizWidgetsWithTestScene(bool allWidgetsShareSameScene); + void removeStaleEntriesFromVizWidgetArr(); + void assignViewTitlesToVizWidgetsInArr(); + std::vector vizWidgetNames(); + void decideNewActiveVizWidgetAndHighlight(); + void highlightActiveVizWidget(); + QTBVizWidget* getActiveVizWidget(); + void saveWinGeoAndDockToolBarLayout(); + void loadWinGeoAndDockToolBarLayout(); + + virtual void closeEvent(QCloseEvent* event); + +private slots: + void slotAddVizWidget(); + void slotDeleteVizWidget(); + void slotReparentVizWidgetIntoCentralWidget(); + void slotReparentVizWidgetAsTopLevel(); + void slotMoveVizWidgetToDockWidget_1(); + void slotMoveVizWidgetToDockWidget_2(); + void slotReparentAllVizWidgetsIntoCentralWidget(); + void slotRefreshVizWidgetArr(); + + void slotAboutToShowActivateMenu(); + void slotSomeVizWidgetActivated(); + + void slotCreateTestScene(); + void slotClearScene(); + + void slotSaveLayout(); + void slotRestoreLayout(); + void slotGrabNativeHandle(); + +private: + cvf::ref m_commonContextGroup; + std::vector> m_vizWidgetArr; + cvf::String m_activeVizWidgetName; + + QPointer m_dockWidget_1; + QPointer m_dockWidget_2; + + QPointer m_setWorkingVizWidgetFirstAction; + QPointer m_setWorkingVizWidgetLastAction; +}; + diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBSceneFactory.cpp b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBSceneFactory.cpp new file mode 100644 index 0000000000..8ee8858476 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBSceneFactory.cpp @@ -0,0 +1,291 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QTBSceneFactory.h" + + + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QTBSceneFactory::QTBSceneFactory(bool useShaders) +: m_useShaders(useShaders) +{ +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref QTBSceneFactory::createTestScene(const cvf::OpenGLCapabilities& capabilities) const +{ + cvf::ref model = new cvf::ModelBasicList; + + cvf::ShaderProgramGenerator spGen("MyStandardHeadlight", cvf::ShaderSourceProvider::instance()); + spGen.configureStandardHeadlightColor(); + cvf::ref shaderProg = spGen.generate(); + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createSphere(2, 10, 10, &builder); + + cvf::ref eff = new cvf::Effect; + if (m_useShaders) + { + eff->setShaderProgram(shaderProg.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::GREEN))); + } + else + { + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::BLUE)); + } + + cvf::ref part = new cvf::Part; + part->setName("MySphere"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + { + cvf::GeometryBuilderDrawableGeo builder; + cvf::GeometryUtils::createBox(cvf::Vec3f(5, 0, 0), 2, 3, 4, &builder); + + cvf::ref eff = new cvf::Effect; + if (m_useShaders) + { + eff->setShaderProgram(shaderProg.p()); + eff->setUniform(new cvf::UniformFloat("u_color", cvf::Color4f(cvf::Color3::YELLOW))); + } + else + { + eff->setRenderState(new cvf::RenderStateMaterial_FF(cvf::Color3::RED)); + } + + cvf::ref part = new cvf::Part; + part->setName("MyBox"); + part->setDrawable(0, builder.drawableGeo().p()); + part->setEffect(eff.p()); + + model->addPart(part.p()); + } + + + model->addPart(createTexturedPart(capabilities).p()); + + model->addPart(createDrawableTextPart(capabilities).p()); + + model->updateBoundingBoxesRecursive(); + + cvf::ref scene = new cvf::Scene; + scene->addModel(model.p()); + + return scene; +} + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref QTBSceneFactory::createQuadGeoWithTexCoords(const cvf::Vec3f& origin, const cvf::Vec3f& u, const cvf::Vec3f& v) +{ + cvf::ref vertices = new cvf::Vec3fArray(4); + vertices->set(0, origin); + vertices->set(1, origin + u); + vertices->set(2, origin + u + v); + vertices->set(3, origin + v); + + cvf::ref texCoords = new cvf::Vec2fArray(4); + texCoords->set(0, cvf::Vec2f(0, 0)); + texCoords->set(1, cvf::Vec2f(1, 0)); + texCoords->set(2, cvf::Vec2f(1, 1)); + texCoords->set(3, cvf::Vec2f(0, 1)); + + const cvf::uint conns[6] = { 0, 1, 2, 0, 2, 3}; + cvf::ref indices = new cvf::UIntArray(conns, 6); + + cvf::ref primSet = new cvf::PrimitiveSetIndexedUInt(cvf::PT_TRIANGLES); + primSet->setIndices(indices.p()); + + cvf::ref geo = new cvf::DrawableGeo; + geo->setVertexArray(vertices.p()); + geo->setTextureCoordArray(texCoords.p()); + geo->addPrimitiveSet(primSet.p()); + + geo->computeNormals(); + + return geo; + +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref QTBSceneFactory::create4x4ColoredImage() +{ + // Create a simple 4x4 texture with 16 unique colors + cvf::ref textureImage = new cvf::TextureImage; + + { + cvf::ref textureData = new cvf::Color4ubArray; + textureData->reserve(16); + textureData->add(cvf::Color4ub(cvf::Color3::RED)); + textureData->add(cvf::Color4ub(cvf::Color3::GREEN)); + textureData->add(cvf::Color4ub(cvf::Color3::BLUE)); + textureData->add(cvf::Color4ub(cvf::Color3::YELLOW)); + textureData->add(cvf::Color4ub(cvf::Color3::CYAN)); + textureData->add(cvf::Color4ub(cvf::Color3::MAGENTA)); + textureData->add(cvf::Color4ub(cvf::Color3::INDIGO)); + textureData->add(cvf::Color4ub(cvf::Color3::OLIVE)); + textureData->add(cvf::Color4ub(cvf::Color3::LIGHT_GRAY)); + textureData->add(cvf::Color4ub(cvf::Color3::BROWN)); + textureData->add(cvf::Color4ub(cvf::Color3::CRIMSON)); + textureData->add(cvf::Color4ub(cvf::Color3::DARK_BLUE)); + textureData->add(cvf::Color4ub(cvf::Color3::DARK_CYAN)); + textureData->add(cvf::Color4ub(cvf::Color3::DARK_GREEN)); + textureData->add(cvf::Color4ub(cvf::Color3::DARK_MAGENTA)); + textureData->add(cvf::Color4ub(cvf::Color3::DARK_ORANGE)); + textureImage->setData(textureData->ptr()->ptr(), 4, 4); + } + + CVF_ASSERT(textureImage->pixel(1, 0) == cvf::Color4ub(cvf::Color3::GREEN)); + CVF_ASSERT(textureImage->pixel(2, 0) == cvf::Color4ub(cvf::Color3::BLUE)); + + return textureImage; + +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref QTBSceneFactory::createTexturedPart(const cvf::OpenGLCapabilities& capabilities) const +{ + cvf::ref geo = createQuadGeoWithTexCoords(cvf::Vec3f(2, 2, 0), cvf::Vec3f(2, 0, 0), cvf::Vec3f(0, 3, 0)); + + cvf::ref textureImage = create4x4ColoredImage(); + + cvf::ref eff = new cvf::Effect; + + if (m_useShaders) + { + cvf::ref texture = new cvf::Texture(textureImage.p()); + + cvf::ref sampler = new cvf::Sampler; + sampler->setMinFilter(cvf::Sampler::LINEAR); + sampler->setMagFilter(cvf::Sampler::NEAREST); + sampler->setWrapModeS(cvf::Sampler::REPEAT); + sampler->setWrapModeT(cvf::Sampler::REPEAT); + + cvf::ref textureBindings = new cvf::RenderStateTextureBindings; + textureBindings->addBinding(texture.p(), sampler.p(), "u_texture2D"); + + eff->setRenderState(textureBindings.p()); + + cvf::ShaderProgramGenerator spGen("MyTexturedStandardHeadlight", cvf::ShaderSourceProvider::instance()); + spGen.configureStandardHeadlightTexture(); + cvf::ref shaderProg = spGen.generate(); + eff->setShaderProgram(shaderProg.p()); + } + else + { + cvf::ref texture = new cvf::Texture2D_FF(textureImage.p()); + texture->setMinFilter(cvf::Texture2D_FF::LINEAR); + texture->setMagFilter(cvf::Texture2D_FF::NEAREST); + texture->setWrapMode(cvf::Texture2D_FF::REPEAT); + + cvf::ref textureMapping = new cvf::RenderStateTextureMapping_FF(texture.p()); + + eff->setRenderState(textureMapping.p()); + } + + cvf::ref part = new cvf::Part; + part->setName("MyTexturedQuad"); + part->setDrawable(0, geo.p()); + part->setEffect(eff.p()); + + return part; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::ref QTBSceneFactory::createDrawableTextPart(const cvf::OpenGLCapabilities& capabilities) const +{ + static int sl_callCount = 0; + cvf::String textStr = cvf::String("Test text string %1").arg(sl_callCount++); + + cvf::ref drawableText = new cvf::DrawableText; + drawableText->setFont(new cvf::FixedAtlasFont(cvf::FixedAtlasFont::LARGE)); + drawableText->setTextColor(cvf::Color3::RED); + + drawableText->addText(textStr, cvf::Vec3f(2, 2, 0)); + drawableText->setCheckPosVisible(false); + + cvf::ref blending = new cvf::RenderStateBlending; + blending->configureTransparencyBlending(); + + cvf::ref eff = new cvf::Effect; + eff->setRenderState(blending.p()); + + if (m_useShaders) + { + cvf::ShaderProgramGenerator spGen("MyTextShaderProgram", cvf::ShaderSourceProvider::instance()); + spGen.addVertexCode(cvf::ShaderSourceRepository::vs_MinimalTexture); + spGen.addFragmentCode(cvf::ShaderSourceRepository::fs_Text); + cvf::ref shaderProg = spGen.generate(); + shaderProg->disableUniformTrackingForUniform("u_texture2D"); + shaderProg->disableUniformTrackingForUniform("u_color"); + eff->setShaderProgram(shaderProg.p()); + } + + cvf::ref part = new cvf::Part; + part->setDrawable(drawableText.p()); + part->setEffect(eff.p()); + + return part; +} diff --git a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLContext.h b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBSceneFactory.h similarity index 71% rename from Fwk/VizFwk/LibGuiQt/cvfqtOpenGLContext.h rename to Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBSceneFactory.h index 89dc0bc57b..17706009c8 100644 --- a/Fwk/VizFwk/LibGuiQt/cvfqtOpenGLContext.h +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBSceneFactory.h @@ -34,40 +34,31 @@ // //################################################################################################## - -#pragma once - +#include "cvfBase.h" +#include "cvfObject.h" +#include "cvfScene.h" #include "cvfOpenGLContext.h" -class QGLContext; - -namespace cvfqt { - //================================================================================================== // -// Derived OpenGLContext that adapts a Qt QGLContext +// // //================================================================================================== -class OpenGLContext : public cvf::OpenGLContext +class QTBSceneFactory { public: - OpenGLContext(cvf::OpenGLContextGroup* contextGroup, QGLContext* backingQGLContext); - virtual ~OpenGLContext(); - - virtual bool initializeContext(); + QTBSceneFactory(bool useShaders); - virtual void makeCurrent(); - virtual bool isCurrent() const; + cvf::ref createTestScene(const cvf::OpenGLCapabilities& capabilities) const; - static void saveOpenGLState(cvf::OpenGLContext* oglContext); - static void restoreOpenGLState(cvf::OpenGLContext* oglContext); +private: + cvf::ref createTexturedPart(const cvf::OpenGLCapabilities& capabilities) const; + cvf::ref createDrawableTextPart(const cvf::OpenGLCapabilities& capabilities) const; + static cvf::ref createQuadGeoWithTexCoords(const cvf::Vec3f& origin, const cvf::Vec3f& u, const cvf::Vec3f& v); + static cvf::ref create4x4ColoredImage(); private: - QGLContext* m_qtGLContext; - bool m_isCoreOpenGLProfile; // This is a Core OpenGL profile. Implies OpenGL version of 3.2 or more - int m_majorVersion; // OpenGL version as reported by Qt - int m_minorVersion; + bool m_useShaders; }; -} diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBVizWidget.cpp b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBVizWidget.cpp new file mode 100644 index 0000000000..7edf1cfc5e --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBVizWidget.cpp @@ -0,0 +1,333 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibGeometry.h" +#include "cvfLibViewing.h" + +#include "QTBVizWidget.h" +#include "QTBMainWindow.h" + +#include + + + +//================================================================================================== +// +// +// +//================================================================================================== + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QTBVizWidget::QTBVizWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent, QTBMainWindow* mainWindow) +: cvfqt::OpenGLWidget(contextGroup, parent), + m_mainWindow(mainWindow) +{ + cvf::Trace::show("QTBVizWidget[%d]::QTBVizWidget()", instanceNumber()); + + initializeMembers(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::initializeMembers() +{ + m_camera = new cvf::Camera; + + cvf::ref rendering = new cvf::Rendering; + rendering->setCamera(m_camera.p()); + + cvf::ref font = new cvf::FixedAtlasFont(cvf::FixedAtlasFont::STANDARD); + + rendering->addOverlayItem(new cvf::OverlayAxisCross(m_camera.p(), font.p())); + + m_titleOverlayTextBox = new cvf::OverlayTextBox(font.p()); + m_titleOverlayTextBox->setText("N/A"); + m_titleOverlayTextBox->setSizeToFitText(); + m_titleOverlayTextBox->setLayout(cvf::OverlayItem::VERTICAL, cvf::OverlayItem::TOP_LEFT); + rendering->addOverlayItem(m_titleOverlayTextBox.p()); + + m_renderSequence = new cvf::RenderSequence; + m_renderSequence->addRendering(rendering.p()); + + m_trackball = new cvf::ManipulatorTrackball; + m_trackball->setCamera(m_camera.p()); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::onWidgetOpenGLReady() +{ + cvf::Trace::show("QTBVizWidget[%d]::onWidgetOpenGLReady()", instanceNumber()); + m_mainWindow->handleVizWidgetIsOpenGLReady(this); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +QTBVizWidget::~QTBVizWidget() +{ + cvf::Trace::show("QTBVizWidget[%d]::~QTBVizWidget()", instanceNumber()); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::setViewTitle(cvf::String viewTitle) +{ + if (m_titleOverlayTextBox.isNull()) + { + return; + } + + m_titleOverlayTextBox->setText(viewTitle); + m_titleOverlayTextBox->setSizeToFitText(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::String QTBVizWidget::viewTitle() +{ + if (m_titleOverlayTextBox.isNull()) + { + return cvf::String(); + } + + return m_titleOverlayTextBox->text(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::setViewTitleHighlighted(bool highlighted) +{ + if (m_titleOverlayTextBox.isNull()) + { + return; + } + + const cvf::Color3f clr = highlighted ? cvf::Color3f(1.0f, 0.2f, 0.2f) : cvf::Color3f(0.2f, 0.2f, 1.0f); + m_titleOverlayTextBox->setBackgroundColor(clr); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::setScene(cvf::Scene* scene) +{ + cvf::ref rendering = m_renderSequence->firstRendering(); + CVF_ASSERT(rendering.notNull()); + + rendering->setScene(scene); + + if (scene) + { + cvf::BoundingBox bb = scene->boundingBox(); + if (bb.isValid()) + { + m_camera->fitView(bb, -cvf::Vec3d::Z_AXIS, cvf::Vec3d::Y_AXIS); + m_trackball->setRotationPoint(bb.center()); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::Scene* QTBVizWidget::scene() +{ + cvf::ref rendering = m_renderSequence->firstRendering(); + CVF_ASSERT(rendering.notNull()); + + return rendering->scene(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +cvf::OpenGLContext* QTBVizWidget::cvfOpenGLContext() +{ + return cvfqt::OpenGLWidget::cvfOpenGLContext(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::initializeGL() +{ + cvf::Trace::show("QTBVizWidget[%d]::initializeGL()", instanceNumber()); + + cvfqt::OpenGLWidget::initializeGL(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::resizeGL(int width, int height) +{ + cvf::Trace::show("QTBVizWidget[%d]::resizeGL() w=%d h=%d", instanceNumber(), width, height); + + if (m_camera.notNull()) + { + m_camera->viewport()->set(0, 0, width, height); + m_camera->setProjectionAsPerspective(m_camera->fieldOfViewYDeg(), m_camera->nearPlane(), m_camera->farPlane()); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::paintGL() +{ + const int w = width(); + const int h = height(); + cvf::Trace::show("QTBVizWidget[%d]::paintGL(), w=%d h=%d", instanceNumber(), w, h); + + // According to Qt docs, context should already be current + cvf::OpenGLContext* currentOglContext = cvfOpenGLContext(); + CVF_ASSERT(currentOglContext); + CVF_CHECK_OGL(currentOglContext); + + cvf::OpenGLUtils::pushOpenGLState(currentOglContext); + + if (m_renderSequence.notNull()) + { + m_renderSequence->render(currentOglContext); + } + + cvf::OpenGLUtils::popOpenGLState(currentOglContext); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::mouseMoveEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + + Qt::MouseButtons mouseBn = event->buttons(); +#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) + const int posX = event->position().toPoint().x(); + const int posY = height() - event->position().toPoint().y(); +#else + const int posX = event->x(); + const int posY = height() - event->y(); +#endif + + cvf::ManipulatorTrackball::NavigationType navType = cvf::ManipulatorTrackball::NONE; + if (mouseBn == Qt::LeftButton) + { + navType = cvf::ManipulatorTrackball::PAN; + } + else if (mouseBn == Qt::RightButton) + { + navType = cvf::ManipulatorTrackball::ROTATE; + } + else if (mouseBn == (Qt::LeftButton | Qt::RightButton) || mouseBn == Qt::MiddleButton) + { + navType = cvf::ManipulatorTrackball::WALK; + } + + if (navType != m_trackball->activeNavigation()) + { + m_trackball->startNavigation(navType, posX, posY); + } + + bool needRedraw = m_trackball->updateNavigation(posX, posY); + if (needRedraw) + { + update(); + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::mousePressEvent(QMouseEvent* event) +{ + if (m_renderSequence.isNull()) return; + +#if QT_VERSION >= QT_VERSION_CHECK(6,0,0) + const int posX = event->position().toPoint().x(); + const int posY = height() - event->position().toPoint().y(); +#else + const int posX = event->x(); + const int posY = height() - event->y(); +#endif + + if (event->buttons() == Qt::LeftButton && event->modifiers() == Qt::ControlModifier) + { + cvf::Rendering* r = m_renderSequence->firstRendering(); + cvf::ref ris = r->rayIntersectSpecFromWindowCoordinates(posX, posY); + + cvf::HitItemCollection hic; + if (r->rayIntersect(*ris, &hic)) + { + cvf::HitItem* item = hic.firstItem(); + CVF_ASSERT(item && item->part()); + + cvf::Vec3d isect = item->intersectionPoint(); + m_trackball->setRotationPoint(isect); + + cvf::Trace::show("hitting part: '%s' coords: %.3f %.3f %.3f", item->part()->name().toAscii().ptr(), isect.x(), isect.y(), isect.z()); + } + } +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::mouseReleaseEvent(QMouseEvent* /*event*/) +{ + m_trackball->endNavigation(); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +void QTBVizWidget::closeEvent(QCloseEvent* event) +{ + cvf::Trace::show("QTBVizWidget[%d]::closeEvent()", instanceNumber()); + + cvfqt::OpenGLWidget::closeEvent(event); +} + diff --git a/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBVizWidget.h b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBVizWidget.h new file mode 100644 index 0000000000..4ef0d3ee00 --- /dev/null +++ b/Fwk/VizFwk/TestApps/Qt/QtTestBenchOpenGLWidget/QTBVizWidget.h @@ -0,0 +1,95 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// This library 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 3 of the License, or +// (at your option) any later version. +// +// This library 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 at <> +// for more details. +// +// GNU Lesser General Public License Usage +// This library is free software; you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library 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 Lesser General Public License at <> +// for more details. +// +//################################################################################################## + +#pragma once + +#include "cvfBase.h" +#include "cvfObject.h" +#include "cvfRenderSequence.h" +#include "cvfManipulatorTrackball.h" +#include "cvfScene.h" +#include "cvfOpenGLContextGroup.h" +#include "cvfOverlayTextBox.h" + +#include "cvfqtOpenGLWidget.h" + +#include + +class QTBMainWindow; + + +//================================================================================================== +// +// +// +//================================================================================================== +class QTBVizWidget : public cvfqt::OpenGLWidget +{ + Q_OBJECT + +public: + QTBVizWidget(cvf::OpenGLContextGroup* contextGroup, QWidget* parent, QTBMainWindow* mainWindow); + ~QTBVizWidget(); + + void setViewTitle(cvf::String viewTitle); + cvf::String viewTitle(); + void setViewTitleHighlighted(bool highlighted); + + void setScene(cvf::Scene* scene); + cvf::Scene* scene(); + + cvf::OpenGLContext* cvfOpenGLContext(); + +private: + virtual void initializeGL(); + virtual void resizeGL(int width, int height); + virtual void paintGL(); + virtual void mousePressEvent(QMouseEvent* event); + virtual void mouseMoveEvent(QMouseEvent* event); + virtual void mouseReleaseEvent(QMouseEvent* event); + virtual void closeEvent(QCloseEvent *event); + void initializeMembers(); + virtual void onWidgetOpenGLReady(); + +private: + QPointer m_mainWindow; + cvf::ref m_renderSequence; + cvf::ref m_camera; + cvf::ref m_trackball; + cvf::ref m_titleOverlayTextBox; +}; + + diff --git a/Fwk/VizFwk/TestApps/Qt/VizFrameworkQt.sln b/Fwk/VizFwk/TestApps/Qt/VizFrameworkQt.sln deleted file mode 100644 index 53d79a3bda..0000000000 --- a/Fwk/VizFwk/TestApps/Qt/VizFrameworkQt.sln +++ /dev/null @@ -1,531 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "QtMinimal", "QtMinimal\QtMinimal.vcxproj", "{9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibCore", "..\..\LibCore\LibCore.vcxproj", "{A9C7A239-B761-A892-BF34-5AECA0D9EE88}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibViewing", "..\..\LibViewing\LibViewing.vcxproj", "{122D4663-11D6-D12F-8748-629A34E9075E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGeometry", "..\..\LibGeometry\LibGeometry.vcxproj", "{EFD5C9AC-8988-F190-AA2C-E36EBE361E90}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRender", "..\..\LibRender\LibRender.vcxproj", "{C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGuiQt", "..\..\LibGuiQt\LibGuiQt.vcxproj", "{FBFAC173-30FE-2C09-3F2E-D54477B433DE}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "QtSnippetRunner", "QtSnippetRunner\QtSnippetRunner.vcxproj", "{A88592D2-824D-4BD4-717F-88B3A5A65E9A}" - ProjectSection(ProjectDependencies) = postProject - {2667AC1D-CA80-42F8-8644-DDB58D342FF2} = {2667AC1D-CA80-42F8-8644-DDB58D342FF2} - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B} = {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B} - {181472EE-4B37-01E8-49D5-6213678FE4F8} = {181472EE-4B37-01E8-49D5-6213678FE4F8} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibUtilities", "..\..\LibUtilities\LibUtilities.vcxproj", "{ECF1BECD-E624-F971-C70A-F84686A36084}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibIo", "..\..\LibIo\LibIo.vcxproj", "{181472EE-4B37-01E8-49D5-6213678FE4F8}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRegGrid2D", "..\..\LibRegGrid2D\LibRegGrid2D.vcxproj", "{7AEF1888-268C-3BEF-4080-743645180A59}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibStructGrid", "..\..\LibStructGrid\LibStructGrid.vcxproj", "{C22D8A0D-2318-3353-F75A-E83B82A3B29F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibViewing_UnitTests", "..\..\Tests\LibViewing_UnitTests\LibViewing_UnitTests.vcxproj", "{8714C516-1322-AF26-8D73-8D8D6D2118BC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibCore_UnitTests", "..\..\Tests\LibCore_UnitTests\LibCore_UnitTests.vcxproj", "{0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGeometry_UnitTests", "..\..\Tests\LibGeometry_UnitTests\LibGeometry_UnitTests.vcxproj", "{86969588-4AA4-AFC9-EA54-FD5BC86810FC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibIo_UnitTests", "..\..\Tests\LibIo_UnitTests\LibIo_UnitTests.vcxproj", "{93516308-F124-5AD1-40C1-93A4E1DA7E02}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRegGrid2D_UnitTests", "..\..\Tests\LibRegGrid2D_UnitTests\LibRegGrid2D_UnitTests.vcxproj", "{BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRender_UnitTests", "..\..\Tests\LibRender_UnitTests\LibRender_UnitTests.vcxproj", "{E4C3CAB6-02B3-A353-1955-8DA235C4FB64}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibStructGrid_UnitTests", "..\..\Tests\LibStructGrid_UnitTests\LibStructGrid_UnitTests.vcxproj", "{1EB78B55-84DF-7014-1A6F-B48DA9D2E923}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibUtilities_UnitTests", "..\..\Tests\LibUtilities_UnitTests\LibUtilities_UnitTests.vcxproj", "{BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnitTestLauncher", "..\..\Tests\UnitTestLauncher\UnitTestLauncher.vcxproj", "{0C357E67-9A35-75D0-61AB-FDDAF3A444BC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SnippetsBasis", "..\..\Tests\SnippetsBasis\SnippetsBasis.vcxproj", "{0D83607B-E0F7-DBA8-2F1F-8400C30B2008}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "QtMultiView", "QtMultiView\QtMultiView.vcxproj", "{2DCDF259-11B5-431F-94FE-C323E2D27AB1}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "freetype", "..\..\ThirdParty\FreeType\builds\win32\vc2010\freetype.vcxproj", "{78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CeeVizFramework", "CeeVizFramework", "{A1C8111B-AC84-4C5E-922C-C8DA4B44DC37}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{7C2D95D1-7722-45A2-A4E8-5E3891B61EFB}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Applications", "Applications", "{63E2A616-50E0-4975-9D7A-1FB1631081DE}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApplicationSupport", "ApplicationSupport", "{2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{B99940A2-EB98-4F5E-B68A-2AEB9C402DAE}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{ED552EA3-2145-4D33-8172-439FD8E31034}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{FE14921F-B8FD-4488-9030-2A99B37C2836}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibFreeType", "..\..\LibFreeType\LibFreeType.vcxproj", "{2667AC1D-CA80-42F8-8644-DDB58D342FF2}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "!Doxygen", "..\..\Doxygen\!Doxygen.vcxproj", "{F5FA2496-1AD3-4569-8EA1-5B5F01450B03}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "!CMake", "..\..\CMake\!CMake.vcxproj", "{FB015304-89D5-4093-B01A-0E7F642971DC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGuiQt_UnitTests", "..\..\Tests\LibGuiQt_UnitTests\LibGuiQt_UnitTests.vcxproj", "{8FF27114-B51E-405A-8A9E-011349E9EDF1}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug MD TBB|Win32 = Debug MD TBB|Win32 - Debug MD TBB|x64 = Debug MD TBB|x64 - Debug MD|Win32 = Debug MD|Win32 - Debug MD|x64 = Debug MD|x64 - Release MD TBB|Win32 = Release MD TBB|Win32 - Release MD TBB|x64 = Release MD TBB|x64 - Release MD|Win32 = Release MD|Win32 - Release MD|x64 = Release MD|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Debug MD TBB|Win32.ActiveCfg = Debug MD|Win32 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Debug MD TBB|x64.ActiveCfg = Debug MD|x64 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Debug MD|x64.Build.0 = Debug MD|x64 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Release MD TBB|Win32.ActiveCfg = Release MD|Win32 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Release MD TBB|x64.ActiveCfg = Release MD|x64 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Release MD|Win32.Build.0 = Release MD|Win32 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Release MD|x64.ActiveCfg = Release MD|x64 - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9}.Release MD|x64.Build.0 = Release MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|x64.Build.0 = Debug MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|Win32.Build.0 = Release MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|x64.ActiveCfg = Release MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|x64.Build.0 = Release MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|x64.Build.0 = Debug MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|Win32.Build.0 = Release MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|x64.ActiveCfg = Release MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|x64.Build.0 = Release MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|x64.Build.0 = Debug MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|Win32.Build.0 = Release MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|x64.ActiveCfg = Release MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|x64.Build.0 = Release MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|x64.Build.0 = Debug MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|Win32.Build.0 = Release MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|x64.ActiveCfg = Release MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|x64.Build.0 = Release MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD TBB|Win32.ActiveCfg = Debug MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD TBB|Win32.Build.0 = Debug MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD TBB|x64.ActiveCfg = Debug MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD TBB|x64.Build.0 = Debug MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Debug MD|x64.Build.0 = Debug MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD TBB|Win32.ActiveCfg = Release MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD TBB|Win32.Build.0 = Release MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD TBB|x64.ActiveCfg = Release MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD TBB|x64.Build.0 = Release MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD|Win32.Build.0 = Release MD|Win32 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD|x64.ActiveCfg = Release MD|x64 - {FBFAC173-30FE-2C09-3F2E-D54477B433DE}.Release MD|x64.Build.0 = Release MD|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Debug MD|x64.Build.0 = Debug MD|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD|Win32.Build.0 = Release MD|Win32 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD|x64.ActiveCfg = Release MD|x64 - {A88592D2-824D-4BD4-717F-88B3A5A65E9A}.Release MD|x64.Build.0 = Release MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|x64.Build.0 = Debug MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|Win32.Build.0 = Release MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|x64.ActiveCfg = Release MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|x64.Build.0 = Release MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|x64.Build.0 = Debug MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|Win32.Build.0 = Release MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|x64.ActiveCfg = Release MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|x64.Build.0 = Release MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Debug MD|x64.Build.0 = Debug MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD|Win32.Build.0 = Release MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD|x64.ActiveCfg = Release MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.Release MD|x64.Build.0 = Release MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|x64.Build.0 = Debug MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|Win32.Build.0 = Release MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|x64.ActiveCfg = Release MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|x64.Build.0 = Release MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Debug MD|x64.Build.0 = Debug MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD|Win32.Build.0 = Release MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD|x64.ActiveCfg = Release MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.Release MD|x64.Build.0 = Release MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Debug MD|x64.Build.0 = Debug MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD|Win32.Build.0 = Release MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD|x64.ActiveCfg = Release MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.Release MD|x64.Build.0 = Release MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Debug MD|x64.Build.0 = Debug MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD|Win32.Build.0 = Release MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD|x64.ActiveCfg = Release MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.Release MD|x64.Build.0 = Release MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Debug MD|x64.Build.0 = Debug MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD|Win32.Build.0 = Release MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD|x64.ActiveCfg = Release MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.Release MD|x64.Build.0 = Release MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Debug MD|x64.Build.0 = Debug MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD|Win32.Build.0 = Release MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD|x64.ActiveCfg = Release MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.Release MD|x64.Build.0 = Release MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Debug MD|x64.Build.0 = Debug MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD|Win32.Build.0 = Release MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD|x64.ActiveCfg = Release MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.Release MD|x64.Build.0 = Release MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Debug MD|x64.Build.0 = Debug MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD|Win32.Build.0 = Release MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD|x64.ActiveCfg = Release MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.Release MD|x64.Build.0 = Release MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Debug MD|x64.Build.0 = Debug MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD|Win32.Build.0 = Release MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD|x64.ActiveCfg = Release MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.Release MD|x64.Build.0 = Release MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Debug MD|x64.Build.0 = Debug MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD|Win32.Build.0 = Release MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD|x64.ActiveCfg = Release MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.Release MD|x64.Build.0 = Release MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|x64.Build.0 = Debug MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|Win32.Build.0 = Release MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|x64.ActiveCfg = Release MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|x64.Build.0 = Release MD|x64 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Debug MD TBB|Win32.ActiveCfg = Debug MD|Win32 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Debug MD TBB|x64.ActiveCfg = Debug MD|x64 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Debug MD|x64.Build.0 = Debug MD|x64 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Release MD TBB|Win32.ActiveCfg = Release MD|Win32 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Release MD TBB|x64.ActiveCfg = Release MD|x64 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Release MD|Win32.Build.0 = Release MD|Win32 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Release MD|x64.ActiveCfg = Release MD|x64 - {2DCDF259-11B5-431F-94FE-C323E2D27AB1}.Release MD|x64.Build.0 = Release MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD TBB|Win32.ActiveCfg = Debug MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD TBB|Win32.Build.0 = Debug MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD TBB|x64.ActiveCfg = Debug MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD TBB|x64.Build.0 = Debug MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|x64.Build.0 = Debug MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD TBB|Win32.ActiveCfg = Release MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD TBB|Win32.Build.0 = Release MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD TBB|x64.ActiveCfg = Release MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD TBB|x64.Build.0 = Release MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|Win32.Build.0 = Release MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|x64.ActiveCfg = Release MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|x64.Build.0 = Release MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|x64.Build.0 = Debug MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|Win32.Build.0 = Release MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|x64.ActiveCfg = Release MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|x64.Build.0 = Release MD|x64 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Debug MD TBB|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Debug MD TBB|x64.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Debug MD|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Debug MD|x64.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Release MD TBB|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Release MD TBB|x64.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Release MD|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.Release MD|x64.ActiveCfg = Doxygen|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Debug MD TBB|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Debug MD TBB|x64.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Debug MD|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Debug MD|x64.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Release MD TBB|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Release MD TBB|x64.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Release MD|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.Release MD|x64.ActiveCfg = NotBuildable|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD TBB|x64.Build.0 = Debug MD TBB|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Debug MD|x64.Build.0 = Debug MD|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD TBB|x64.Build.0 = Release MD TBB|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD|Win32.Build.0 = Release MD|Win32 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD|x64.ActiveCfg = Release MD|x64 - {8FF27114-B51E-405A-8A9E-011349E9EDF1}.Release MD|x64.Build.0 = Release MD|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {A88592D2-824D-4BD4-717F-88B3A5A65E9A} = {63E2A616-50E0-4975-9D7A-1FB1631081DE} - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC} = {63E2A616-50E0-4975-9D7A-1FB1631081DE} - {2DCDF259-11B5-431F-94FE-C323E2D27AB1} = {63E2A616-50E0-4975-9D7A-1FB1631081DE} - {9EDEF87F-EC72-4422-8CB7-33DD68E5F2A9} = {63E2A616-50E0-4975-9D7A-1FB1631081DE} - {122D4663-11D6-D12F-8748-629A34E9075E} = {A1C8111B-AC84-4C5E-922C-C8DA4B44DC37} - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90} = {A1C8111B-AC84-4C5E-922C-C8DA4B44DC37} - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F} = {A1C8111B-AC84-4C5E-922C-C8DA4B44DC37} - {181472EE-4B37-01E8-49D5-6213678FE4F8} = {A1C8111B-AC84-4C5E-922C-C8DA4B44DC37} - {FE14921F-B8FD-4488-9030-2A99B37C2836} = {A1C8111B-AC84-4C5E-922C-C8DA4B44DC37} - {A9C7A239-B761-A892-BF34-5AECA0D9EE88} = {A1C8111B-AC84-4C5E-922C-C8DA4B44DC37} - {ECF1BECD-E624-F971-C70A-F84686A36084} = {2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795} - {ED552EA3-2145-4D33-8172-439FD8E31034} = {2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795} - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008} = {2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795} - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B} = {2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795} - {FBFAC173-30FE-2C09-3F2E-D54477B433DE} = {2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795} - {2667AC1D-CA80-42F8-8644-DDB58D342FF2} = {2F6DF4BE-2D35-4F33-ADF4-C1CC7369D795} - {C22D8A0D-2318-3353-F75A-E83B82A3B29F} = {7C2D95D1-7722-45A2-A4E8-5E3891B61EFB} - {B99940A2-EB98-4F5E-B68A-2AEB9C402DAE} = {7C2D95D1-7722-45A2-A4E8-5E3891B61EFB} - {7AEF1888-268C-3BEF-4080-743645180A59} = {7C2D95D1-7722-45A2-A4E8-5E3891B61EFB} - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3} = {FE14921F-B8FD-4488-9030-2A99B37C2836} - {86969588-4AA4-AFC9-EA54-FD5BC86810FC} = {FE14921F-B8FD-4488-9030-2A99B37C2836} - {93516308-F124-5AD1-40C1-93A4E1DA7E02} = {FE14921F-B8FD-4488-9030-2A99B37C2836} - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64} = {FE14921F-B8FD-4488-9030-2A99B37C2836} - {8714C516-1322-AF26-8D73-8D8D6D2118BC} = {FE14921F-B8FD-4488-9030-2A99B37C2836} - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923} = {B99940A2-EB98-4F5E-B68A-2AEB9C402DAE} - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E} = {B99940A2-EB98-4F5E-B68A-2AEB9C402DAE} - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62} = {ED552EA3-2145-4D33-8172-439FD8E31034} - {8FF27114-B51E-405A-8A9E-011349E9EDF1} = {ED552EA3-2145-4D33-8172-439FD8E31034} - EndGlobalSection -EndGlobal diff --git a/Fwk/VizFwk/TestApps/Win32/VizFrameworkWin32.sln b/Fwk/VizFwk/TestApps/Win32/VizFrameworkWin32.sln deleted file mode 100644 index 2547962dba..0000000000 --- a/Fwk/VizFwk/TestApps/Win32/VizFrameworkWin32.sln +++ /dev/null @@ -1,129 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Win32SnippetRunner", "Win32SnippetRunner\Win32SnippetRunner.vcxproj", "{8222DBB8-49C7-41B0-A3C1-F5F663B71F06}" - ProjectSection(ProjectDependencies) = postProject - {181472EE-4B37-01E8-49D5-6213678FE4F8} = {181472EE-4B37-01E8-49D5-6213678FE4F8} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibViewing", "..\..\LibViewing\LibViewing.vcxproj", "{122D4663-11D6-D12F-8748-629A34E9075E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibCore", "..\..\LibCore\LibCore.vcxproj", "{A9C7A239-B761-A892-BF34-5AECA0D9EE88}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGeometry", "..\..\LibGeometry\LibGeometry.vcxproj", "{EFD5C9AC-8988-F190-AA2C-E36EBE361E90}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRender", "..\..\LibRender\LibRender.vcxproj", "{C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibUtilities", "..\..\LibUtilities\LibUtilities.vcxproj", "{ECF1BECD-E624-F971-C70A-F84686A36084}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibStructGrid", "..\..\LibStructGrid\LibStructGrid.vcxproj", "{C22D8A0D-2318-3353-F75A-E83B82A3B29F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SnippetsBasis", "..\..\Tests\SnippetsBasis\SnippetsBasis.vcxproj", "{0D83607B-E0F7-DBA8-2F1F-8400C30B2008}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibFreeType", "..\..\LibFreeType\LibFreeType.vcxproj", "{2667AC1D-CA80-42F8-8644-DDB58D342FF2}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "freetype", "..\..\ThirdParty\FreeType\builds\win32\vc2010\freetype.vcxproj", "{78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibIo", "..\..\LibIo\LibIo.vcxproj", "{181472EE-4B37-01E8-49D5-6213678FE4F8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug MD|Win32 = Debug MD|Win32 - Debug MD|x64 = Debug MD|x64 - Release MD|Win32 = Release MD|Win32 - Release MD|x64 = Release MD|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Debug MD|x64.Build.0 = Debug MD|x64 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Release MD|Win32.Build.0 = Release MD|Win32 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Release MD|x64.ActiveCfg = Release MD|x64 - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06}.Release MD|x64.Build.0 = Release MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Debug MD|x64.Build.0 = Debug MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|Win32.Build.0 = Release MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|x64.ActiveCfg = Release MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.Release MD|x64.Build.0 = Release MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Debug MD|x64.Build.0 = Debug MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|Win32.Build.0 = Release MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|x64.ActiveCfg = Release MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.Release MD|x64.Build.0 = Release MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Debug MD|x64.Build.0 = Debug MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|Win32.Build.0 = Release MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|x64.ActiveCfg = Release MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.Release MD|x64.Build.0 = Release MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Debug MD|x64.Build.0 = Debug MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|Win32.Build.0 = Release MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|x64.ActiveCfg = Release MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.Release MD|x64.Build.0 = Release MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Debug MD|x64.Build.0 = Debug MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|Win32.Build.0 = Release MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|x64.ActiveCfg = Release MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.Release MD|x64.Build.0 = Release MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Debug MD|x64.Build.0 = Debug MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|Win32.Build.0 = Release MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|x64.ActiveCfg = Release MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.Release MD|x64.Build.0 = Release MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Debug MD|x64.Build.0 = Debug MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|Win32.Build.0 = Release MD|Win32 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|x64.ActiveCfg = Release MD|x64 - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008}.Release MD|x64.Build.0 = Release MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Debug MD|x64.Build.0 = Debug MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|Win32.Build.0 = Release MD|Win32 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|x64.ActiveCfg = Release MD|x64 - {2667AC1D-CA80-42F8-8644-DDB58D342FF2}.Release MD|x64.Build.0 = Release MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Debug MD|x64.Build.0 = Debug MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|Win32.Build.0 = Release MD|Win32 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|x64.ActiveCfg = Release MD|x64 - {78B079BD-9FC7-4B9E-B4A6-96DA0F00248B}.Release MD|x64.Build.0 = Release MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|Win32.ActiveCfg = Debug MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|Win32.Build.0 = Debug MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|x64.ActiveCfg = Debug MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Debug MD|x64.Build.0 = Debug MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|Win32.ActiveCfg = Release MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|Win32.Build.0 = Release MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|x64.ActiveCfg = Release MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.Release MD|x64.Build.0 = Release MD|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/CMakeLists.txt b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/CMakeLists.txt new file mode 100644 index 0000000000..3a11f7477f --- /dev/null +++ b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/CMakeLists.txt @@ -0,0 +1,36 @@ +project(Win32SnippetRunner) + + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CEE_STANDARD_CXX_FLAGS}") + + +find_package(OpenGL) + + +include_directories(${LibCore_SOURCE_DIR}) +include_directories(${LibGeometry_SOURCE_DIR}) +include_directories(${LibRender_SOURCE_DIR}) +include_directories(${LibViewing_SOURCE_DIR}) +include_directories(${LibUtilities_SOURCE_DIR}) +include_directories(${SnippetsBasis_SOURCE_DIR}) + +set(CEE_LIBS SnippetsBasis freetype LibFreeType LibUtilities LibViewing LibRender LibGeometry LibIo LibCore) + +set(CEE_CODE_FILES +Win32MessageKicker.cpp +Win32MessageKicker.h +Win32OpenGLContext.cpp +Win32OpenGLContext.h +Win32PropertiesPanel.cpp +Win32PropertiesPanel.h +Win32SnippetRunner.cpp +Win32SnippetWindow.cpp +Win32SnippetWindow.h +Win32Utils.cpp +Win32Utils.h +) + + +add_executable(${PROJECT_NAME} WIN32 ${CEE_CODE_FILES}) +target_link_libraries(${PROJECT_NAME} ${CEE_LIBS} ${OPENGL_LIBRARIES}) + diff --git a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.cpp b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.cpp index 69e999b807..9a8809e8d0 100644 --- a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.cpp +++ b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.cpp @@ -119,7 +119,9 @@ bool Win32OpenGLContext::createHardwareContext(HWND hWnd) m_hDC = hDC; m_hRC = hRC; - if (initializeContext()) + cvf::OpenGLContextGroup* ownerContextGroup = group(); + CVF_ASSERT(ownerContextGroup); + if (ownerContextGroup->initializeContextGroup(this)) { return true; } @@ -136,7 +138,11 @@ bool Win32OpenGLContext::createHardwareContext(HWND hWnd) void Win32OpenGLContext::shutdownContext() { // Clears up resources and removes us from our group - cvf::OpenGLContext::shutdownContext(); + cvf::OpenGLContextGroup* ownerContextGroup = group(); + CVF_ASSERT(ownerContextGroup); + + makeCurrent(); + ownerContextGroup->contextAboutToBeShutdown(this); if (m_hRC) { @@ -165,7 +171,14 @@ void Win32OpenGLContext::makeCurrent() { if (m_hDC && m_hRC) { - wglMakeCurrent(m_hDC, m_hRC); + HGLRC currRCBefore = wglGetCurrentContext(); + if (currRCBefore != m_hRC) + { + wglMakeCurrent(m_hDC, m_hRC); + HGLRC currRCAfter = wglGetCurrentContext(); + CVF_ASSERT(currRCAfter = m_hRC); + CVF_UNUSED(currRCAfter); + } } } @@ -177,7 +190,8 @@ bool Win32OpenGLContext::isCurrent() const { if (m_hDC && m_hRC) { - if (wglGetCurrentContext() == m_hRC) + HGLRC currRC = wglGetCurrentContext(); + if (currRC == m_hRC) { return true; } diff --git a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.h b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.h index 4e73b9fdc7..b6f8fd0b7b 100644 --- a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.h +++ b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32OpenGLContext.h @@ -52,7 +52,7 @@ class Win32OpenGLContext : public cvf::OpenGLContext ~Win32OpenGLContext(); bool createHardwareContext(HWND hWnd); - virtual void shutdownContext(); + void shutdownContext(); virtual void makeCurrent(); virtual bool isCurrent() const; diff --git a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.cpp b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.cpp index 47bb4fc16f..376e5e9424 100644 --- a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.cpp +++ b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.cpp @@ -69,11 +69,11 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCm UNREFERENCED_PARAMETER(lpCmdLine); cvf::ShaderSourceProvider* shaderProvider = cvf::ShaderSourceProvider::instance(); - shaderProvider->setSourceRepository(new cvf::ShaderSourceRepositoryFile("../../../LibRender/glsl/")); - shaderProvider->addFileSearchDirectory("../../../Tests/SnippetsBasis/Shaders/"); + shaderProvider->setSourceRepository(new cvf::ShaderSourceRepositoryFile(CVF_CEEVIZ_ROOT_SOURCE_DIR "/LibRender/glsl/")); + shaderProvider->addFileSearchDirectory(CVF_CEEVIZ_ROOT_SOURCE_DIR "/Tests/SnippetsBasis/Shaders/"); shaderProvider->addFileSearchDirectory("./"); - const cvf::String testDataDir = "../../../Tests/TestData/"; + const cvf::String testDataDir = CVF_CEEVIZ_ROOT_SOURCE_DIR "/Tests/TestData/"; cvfu::SnippetFactory* factoryBasis = new SnippetFactoryBasis; factoryBasis->setTestDataDir(testDataDir); @@ -168,7 +168,8 @@ LRESULT CALLBACK MainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lPar { //ref snippet = SnippetRegistry::instance()->createSnippet("snip::MinimalModel"); //ref snippet = SnippetRegistry::instance()->createSnippet("snip::Highlight"); - ref snippet = SnippetRegistry::instance()->createSnippet("snip::Stencil"); + //ref snippet = SnippetRegistry::instance()->createSnippet("snip::Stencil"); + ref snippet = SnippetRegistry::instance()->createSnippet("snip::TransparentWeightedAverage"); sl_snippetWnd = new Win32SnippetWindow; sl_snippetWnd->create(hWnd, snippet.p()); SetFocus(sl_snippetWnd->windowHandle()); diff --git a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.vcxproj b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.vcxproj deleted file mode 100644 index 33aa4ff28e..0000000000 --- a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.vcxproj +++ /dev/null @@ -1,207 +0,0 @@ - - - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {8222DBB8-49C7-41B0-A3C1-F5F663B71F06} - Win32Proj - Win32SnippetRunner - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - true - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - false - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - false - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level3 - Disabled - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - ../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../Tests/SnippetsBasis;../../../Tests/SnippetsModules;. - MultiThreadedDebugDLL - - - Windows - true - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level3 - Disabled - WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) - ../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../Tests/SnippetsBasis;../../../Tests/SnippetsModules;. - MultiThreadedDebugDLL - - - Windows - true - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level3 - MaxSpeed - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - ../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../Tests/SnippetsBasis;../../../Tests/SnippetsModules;. - MultiThreadedDLL - - - Windows - true - true - true - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level3 - MaxSpeed - true - true - WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) - ../../../LibCore;../../../LibRender;../../../LibGeometry;../../../LibViewing;../../../LibUtilities;../../../Tests/SnippetsBasis;../../../Tests/SnippetsModules;. - MultiThreadedDLL - - - Windows - true - true - true - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - - - - - - - - - {2667ac1d-ca80-42f8-8644-ddb58d342ff2} - - - {181472ee-4b37-01e8-49d5-6213678fe4f8} - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - {c22d8a0d-2318-3353-f75a-e83b82a3b29f} - - - {ecf1becd-e624-f971-c70a-f84686a36084} - - - {0d83607b-e0f7-dba8-2f1f-8400c30b2008} - - - {78b079bd-9fc7-4b9e-b4a6-96da0f00248b} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.vcxproj.filters b/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.vcxproj.filters deleted file mode 100644 index abba13185d..0000000000 --- a/Fwk/VizFwk/TestApps/Win32/Win32SnippetRunner/Win32SnippetRunner.vcxproj.filters +++ /dev/null @@ -1,65 +0,0 @@ - - - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - {01e663a4-0788-4d34-9df3-f9068d642ebc} - - - - - Resource Files - - - - - Resource Files - - - Files - - - Files - - - Files - - - Files - - - Files - - - Files - - - - - Files - - - Files - - - Files - - - Files - - - Files - - - Files - - - - - Resource Files - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/CMakeLists.txt b/Fwk/VizFwk/Tests/CMakeLists.txt index 5bcebcfef2..2f6892de5d 100644 --- a/Fwk/VizFwk/Tests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8) +cmake_minimum_required(VERSION 3.15) # Builds all the unit tests diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibCore_UnitTests/CMakeLists.txt index 69f599ef24..68901eb664 100644 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibCore_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibCore_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/LibCore_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibCore_UnitTests/LibCore_UnitTests.vcxproj deleted file mode 100644 index af7fad5028..0000000000 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/LibCore_UnitTests.vcxproj +++ /dev/null @@ -1,311 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3} - LibCore_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/LibCore_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibCore_UnitTests/LibCore_UnitTests.vcxproj.filters deleted file mode 100644 index 2355343553..0000000000 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/LibCore_UnitTests.vcxproj.filters +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibCore_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfBase64-Test.cpp b/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfBase64-Test.cpp index 77faadf70b..c42882c28d 100644 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfBase64-Test.cpp +++ b/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfBase64-Test.cpp @@ -59,7 +59,7 @@ TEST(Base64Test, EncodeDecode) size_t i; for (i = 0; i < binaryDataSize; i++) { - binaryData.set(i, static_cast(i%256)); + binaryData.set(i, static_cast(i%256)); } // Encode binary data diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfQuat-Test.cpp b/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfQuat-Test.cpp index adb7ca9708..be839dfc7c 100644 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfQuat-Test.cpp +++ b/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfQuat-Test.cpp @@ -875,6 +875,6 @@ AxisAngleQuat AAQ_ARRAY[] = -INSTANTIATE_TEST_CASE_P(ParamInst, QuatTestAxisAngle, ::testing::ValuesIn(AAQ_ARRAY)); +INSTANTIATE_TEST_SUITE_P(ParamInst, QuatTestAxisAngle, ::testing::ValuesIn(AAQ_ARRAY)); diff --git a/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfVector4-Test.cpp b/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfVector4-Test.cpp index 914d7ae82d..8f332f5292 100644 --- a/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfVector4-Test.cpp +++ b/Fwk/VizFwk/Tests/LibCore_UnitTests/cvfVector4-Test.cpp @@ -212,14 +212,17 @@ TEST(Vector4Test, AssignMemebers) vf.x() = 1.0f + 2.5f*3.0f; vf.y() = 2.0f - 2.5f*3.0f; vf.z() = 3.0f + 2.5f*2.0f; + vf.w() = 4.0f - 2.5f*2.0f; ASSERT_FLOAT_EQ(8.5f, vf.x()); ASSERT_FLOAT_EQ(-5.5f, vf.y()); ASSERT_FLOAT_EQ(8.0f, vf.z()); + ASSERT_FLOAT_EQ(-1.0f, vf.w()); vf.x() = 0.0f; vf.y() = 0.0f; vf.z() = 0.0f; + vf.w() = 0.0f; ASSERT_TRUE(vf.isZero()); vf.y() = 0.1f; @@ -231,14 +234,17 @@ TEST(Vector4Test, AssignMemebers) vd.x() = 1.0 + 2.5*3.0; vd.y() = 2.0 - 2.5*3.0; vd.z() = 3.0 + 2.5*2.0; + vd.w() = 4.0 - 2.5*2.0; ASSERT_DOUBLE_EQ(8.5, vd.x()); ASSERT_DOUBLE_EQ(-5.5, vd.y()); ASSERT_DOUBLE_EQ(8.0, vd.z()); + ASSERT_DOUBLE_EQ(-1.0, vd.w()); vd.x() = 0.0; vd.y() = 0.0; vd.z() = 0.0; + vd.w() = 0.0; ASSERT_TRUE(vd.isZero()); vd.y() = 0.1; diff --git a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/CMakeLists.txt index 81d805d618..c8498c906e 100644 --- a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibGeometry_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/LibGeometry_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/LibGeometry_UnitTests.vcxproj deleted file mode 100644 index db6873009a..0000000000 --- a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/LibGeometry_UnitTests.vcxproj +++ /dev/null @@ -1,304 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {86969588-4AA4-AFC9-EA54-FD5BC86810FC} - LibGeometry_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/LibGeometry_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/LibGeometry_UnitTests.vcxproj.filters deleted file mode 100644 index 3bb24304be..0000000000 --- a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/LibGeometry_UnitTests.vcxproj.filters +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/cvfBoundingBox-Test.cpp b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/cvfBoundingBox-Test.cpp index b6bc5bcd82..eea838f59c 100644 --- a/Fwk/VizFwk/Tests/LibGeometry_UnitTests/cvfBoundingBox-Test.cpp +++ b/Fwk/VizFwk/Tests/LibGeometry_UnitTests/cvfBoundingBox-Test.cpp @@ -229,15 +229,19 @@ TEST(BoundingBoxDeathTest, AccessInvalidBox) EXPECT_DEATH(bb.min(), "Assertion"); EXPECT_DEATH(bb.max(), "Assertion"); EXPECT_DEATH(bb.center(), "Assertion"); - EXPECT_DEATH(bb.extent(), "Assertion"); - EXPECT_DEATH(bb.radius(), "Assertion"); + + // Not any more + //EXPECT_DEATH(bb.extent(), "Assertion"); + //EXPECT_DEATH(bb.radius(), "Assertion"); bb.reset(); EXPECT_DEATH(bb.min(), "Assertion"); EXPECT_DEATH(bb.max(), "Assertion"); EXPECT_DEATH(bb.center(), "Assertion"); - EXPECT_DEATH(bb.extent(), "Assertion"); - EXPECT_DEATH(bb.radius(), "Assertion"); + + // Not any more + //EXPECT_DEATH(bb.extent(), "Assertion"); + //EXPECT_DEATH(bb.radius(), "Assertion"); } #endif diff --git a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/CMakeLists.txt index ca3ceaa3e0..7900127f4a 100644 --- a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/CMakeLists.txt @@ -1,19 +1,18 @@ -cmake_minimum_required(VERSION 2.8.12) - project(LibGuiQt_UnitTests) # Compile flags should already be setup by caller find_package(OpenGL) -# Qt -if (CEE_USE_QT5) - find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) - set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) +if (CEE_USE_QT6) + find_package(Qt6 COMPONENTS REQUIRED Core Gui Widgets OpenGLWidgets) + set(QT_LIBRARIES Qt6::Core Qt6::Gui Qt6::Widgets Qt6::OpenGLWidgets ) +elseif (CEE_USE_QT5) + find_package(Qt5 COMPONENTS REQUIRED Core Gui Widgets OpenGL) + set(QT_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets Qt5::OpenGL) else() - find_package(Qt4 COMPONENTS QtCore QtGui QtOpenGl REQUIRED) - include(${QT_USE_FILE}) -endif(CEE_USE_QT5) + message(FATAL_ERROR "No supported Qt version selected for build") +endif() include_directories(${LibCore_SOURCE_DIR}) include_directories(${LibIo_SOURCE_DIR}) @@ -33,8 +32,8 @@ LibGuiQt_UnitTests.cpp ) if (MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) - # VS 2017 : Disable warnings from from gtest code, using deprecated code related to TR1 - add_definitions(-D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING) + # VS 2017 : Disable warnings from from gtest code, using deprecated code related to TR1 + add_definitions(-D_SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING) endif() add_executable(${PROJECT_NAME} ${CEE_SOURCE_FILES}) diff --git a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/LibGuiQt_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/LibGuiQt_UnitTests.vcxproj deleted file mode 100644 index d861562c9a..0000000000 --- a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/LibGuiQt_UnitTests.vcxproj +++ /dev/null @@ -1,299 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {8FF27114-B51E-405A-8A9E-011349E9EDF1} - LibGuiQt_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - QtCored4.lib;QtGuid4.lib;QtOpenGLd4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib - - - - - Level3 - $(QTDIR)/include;$(QTDIR)/include/Qt;../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibGuiQt;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - QtCore4.lib;QtGui4.lib;QtOpenGL4.lib;opengl32.lib;glu32.lib;%(AdditionalDependencies) - $(QTDIR)/lib;../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {fbfac173-30fe-2c09-3f2e-d54477b433de} - - - {181472ee-4b37-01e8-49d5-6213678fe4f8} - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/LibGuiQt_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/LibGuiQt_UnitTests.vcxproj.filters deleted file mode 100644 index 5fac41b183..0000000000 --- a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/LibGuiQt_UnitTests.vcxproj.filters +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibGuiQt_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibIo_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibIo_UnitTests/CMakeLists.txt index d9ce18323a..a556512d6f 100644 --- a/Fwk/VizFwk/Tests/LibIo_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibIo_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibIo_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibIo_UnitTests/LibIo_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibIo_UnitTests/LibIo_UnitTests.vcxproj deleted file mode 100644 index d175d655be..0000000000 --- a/Fwk/VizFwk/Tests/LibIo_UnitTests/LibIo_UnitTests.vcxproj +++ /dev/null @@ -1,285 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {93516308-F124-5AD1-40C1-93A4E1DA7E02} - LibIo_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibIo;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {181472ee-4b37-01e8-49d5-6213678fe4f8} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibIo_UnitTests/LibIo_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibIo_UnitTests/LibIo_UnitTests.vcxproj.filters deleted file mode 100644 index f04be73881..0000000000 --- a/Fwk/VizFwk/Tests/LibIo_UnitTests/LibIo_UnitTests.vcxproj.filters +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibIo_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibIo_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibIo_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/CMakeLists.txt index 88260c2114..d1dafefaf9 100644 --- a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibRegGrid2D_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/LibRegGrid2D_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/LibRegGrid2D_UnitTests.vcxproj deleted file mode 100644 index 32815e7bd7..0000000000 --- a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/LibRegGrid2D_UnitTests.vcxproj +++ /dev/null @@ -1,297 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E} - LibRegGrid2D_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibIo;../../LibRegGrid2D;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {181472ee-4b37-01e8-49d5-6213678fe4f8} - - - {7aef1888-268c-3bef-4080-743645180a59} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/LibRegGrid2D_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/LibRegGrid2D_UnitTests.vcxproj.filters deleted file mode 100644 index a3a37c182c..0000000000 --- a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/LibRegGrid2D_UnitTests.vcxproj.filters +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibRegGrid2D_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibRender_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibRender_UnitTests/CMakeLists.txt index 6fda5381ab..82286af202 100644 --- a/Fwk/VizFwk/Tests/LibRender_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibRender_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibRender_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibRender_UnitTests/LibRender_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibRender_UnitTests/LibRender_UnitTests.vcxproj deleted file mode 100644 index f92576c0bb..0000000000 --- a/Fwk/VizFwk/Tests/LibRender_UnitTests/LibRender_UnitTests.vcxproj +++ /dev/null @@ -1,314 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64} - LibRender_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibRender_UnitTests/LibRender_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibRender_UnitTests/LibRender_UnitTests.vcxproj.filters deleted file mode 100644 index 91c0c15e0d..0000000000 --- a/Fwk/VizFwk/Tests/LibRender_UnitTests/LibRender_UnitTests.vcxproj.filters +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibRender_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibRender_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibRender_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibRender_UnitTests/cvfOpenGLContextGroup-Test.cpp b/Fwk/VizFwk/Tests/LibRender_UnitTests/cvfOpenGLContextGroup-Test.cpp index 8a9f6206f6..7a840a58ad 100644 --- a/Fwk/VizFwk/Tests/LibRender_UnitTests/cvfOpenGLContextGroup-Test.cpp +++ b/Fwk/VizFwk/Tests/LibRender_UnitTests/cvfOpenGLContextGroup-Test.cpp @@ -91,7 +91,7 @@ TEST(OpenGLContextGroupTest, LifeCycle) EXPECT_EQ(2, ctx2->refCount()); EXPECT_EQ(2, ctx3->refCount()); - ctx1->shutdownContext(); + grp->contextAboutToBeShutdown(ctx1.p()); EXPECT_EQ(1, ctx1->refCount()); EXPECT_TRUE(ctx1->group() == NULL); EXPECT_FALSE(grp->containsContext(ctx1.p())); diff --git a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/CMakeLists.txt index ad48954fd1..ecfbf0d2ad 100644 --- a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibStructGrid_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/LibStructGrid_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/LibStructGrid_UnitTests.vcxproj deleted file mode 100644 index d6bf056a50..0000000000 --- a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/LibStructGrid_UnitTests.vcxproj +++ /dev/null @@ -1,286 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923} - LibStructGrid_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibStructGrid;../../ThirdParty;%(AdditionalIncludeDirectories) - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {c22d8a0d-2318-3353-f75a-e83b82a3b29f} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/LibStructGrid_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/LibStructGrid_UnitTests.vcxproj.filters deleted file mode 100644 index 0d9fb30963..0000000000 --- a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/LibStructGrid_UnitTests.vcxproj.filters +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibStructGrid_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/CMakeLists.txt index 061fbc2466..02b578e510 100644 --- a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibUtilities_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.cpp b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.cpp index 29d5b81245..1821092558 100644 --- a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.cpp +++ b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.cpp @@ -38,7 +38,7 @@ #include "cvfBase.h" #include "gtest/gtest.h" -#include "gtest/cvftestUtils.h" + #include @@ -54,7 +54,5 @@ int main(int argc, char **argv) testing::InitGoogleTest(&argc, argv); - cvftest::TestDataDir::initializeInstance(cvftest::TestDataDir::DEFAULT_DEFINE_THEN_VIZ_FRAMEWORK, true); - return RUN_ALL_TESTS(); } diff --git a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.vcxproj deleted file mode 100644 index 888ebecc50..0000000000 --- a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.vcxproj +++ /dev/null @@ -1,297 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62} - LibUtilities_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../LibUtilities;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {181472ee-4b37-01e8-49d5-6213678fe4f8} - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - {ecf1becd-e624-f971-c70a-f84686a36084} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.vcxproj.filters deleted file mode 100644 index daf506f23d..0000000000 --- a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/LibUtilities_UnitTests.vcxproj.filters +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/cvfuImageTga-Test.cpp b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/cvfuImageTga-Test.cpp index cf09c6326e..e4a4927142 100644 --- a/Fwk/VizFwk/Tests/LibUtilities_UnitTests/cvfuImageTga-Test.cpp +++ b/Fwk/VizFwk/Tests/LibUtilities_UnitTests/cvfuImageTga-Test.cpp @@ -51,7 +51,7 @@ using namespace cvfu; //-------------------------------------------------------------------------------------------------- TEST(ImageTgaTest, LoadUncompressed24bit) { - String fullFileName = cvftest::TestDataDir::instance()->dataDir() + "TgaTestSuite/UTC24.TGA"; + String fullFileName = cvftest::Utils::getTestDataDir() + "TgaTestSuite/UTC24.TGA"; cvf::Trace::show("FN: %s\n", fullFileName.toAscii().ptr()); ref img = ImageTga::loadImage(fullFileName); ASSERT_TRUE(img.notNull()); @@ -68,7 +68,7 @@ TEST(ImageTgaTest, LoadUncompressed24bit) //-------------------------------------------------------------------------------------------------- TEST(ImageTgaTest, LoadCompressed24bit) { - String fullFileName = cvftest::TestDataDir::instance()->dataDir() + "TgaTestSuite/CTC24.TGA"; + String fullFileName = cvftest::Utils::getTestDataDir() + "TgaTestSuite/CTC24.TGA"; cvf::Trace::show("FN: %s\n", fullFileName.toAscii().ptr()); ref img = ImageTga::loadImage(fullFileName); ASSERT_TRUE(img.notNull()); @@ -85,7 +85,7 @@ TEST(ImageTgaTest, LoadCompressed24bit) //-------------------------------------------------------------------------------------------------- TEST(ImageTgaTest, LoadUncompressed32bit) { - String fullFileName = cvftest::TestDataDir::instance()->dataDir() + "TgaTestSuite/UTC32.TGA"; + String fullFileName = cvftest::Utils::getTestDataDir() + "TgaTestSuite/UTC32.TGA"; ref img = ImageTga::loadImage(fullFileName); ASSERT_TRUE(img.notNull()); @@ -101,7 +101,7 @@ TEST(ImageTgaTest, LoadUncompressed32bit) //-------------------------------------------------------------------------------------------------- TEST(ImageTgaTest, LoadCompressed32bit) { - String fullFileName = cvftest::TestDataDir::instance()->dataDir() + "TgaTestSuite/CTC32.TGA"; + String fullFileName = cvftest::Utils::getTestDataDir() + "TgaTestSuite/CTC32.TGA"; ref img = ImageTga::loadImage(fullFileName); ASSERT_TRUE(img.notNull()); diff --git a/Fwk/VizFwk/Tests/LibViewing_UnitTests/CMakeLists.txt b/Fwk/VizFwk/Tests/LibViewing_UnitTests/CMakeLists.txt index d2f23b36b5..04d35b079e 100644 --- a/Fwk/VizFwk/Tests/LibViewing_UnitTests/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/LibViewing_UnitTests/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(LibViewing_UnitTests) # Compile flags should already be setup by caller diff --git a/Fwk/VizFwk/Tests/LibViewing_UnitTests/LibViewing_UnitTests.vcxproj b/Fwk/VizFwk/Tests/LibViewing_UnitTests/LibViewing_UnitTests.vcxproj deleted file mode 100644 index 71fe5baff6..0000000000 --- a/Fwk/VizFwk/Tests/LibViewing_UnitTests/LibViewing_UnitTests.vcxproj +++ /dev/null @@ -1,304 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {8714C516-1322-AF26-8D73-8D8D6D2118BC} - LibViewing_UnitTests - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - - - - - Level4 - ../../LibCore;../../LibGeometry;../../LibRender;../../LibViewing;../../ThirdParty - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - - - true - true - true - Console - opengl32.lib;glu32.lib;%(AdditionalDependencies) - ../../ThirdParty/TBB/lib/$(Platform)_VS2010 - - - - - - - - - - - - - - - - - - - - - - - - - - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb_debug.dll" + NUL "$(TargetDir)tbb_debug.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb_debug.dll - COPY /Y /B "..\..\ThirdParty\TBB\bin\$(Platform)_VS2010\tbb.dll" + NUL "$(TargetDir)tbb.dll" - Copying Intel Threading Building Blocks DLL... - $(TargetDir)tbb.dll - - - - - {122d4663-11d6-d12f-8748-629a34e9075e} - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {efd5c9ac-8988-f190-aa2c-e36ebe361e90} - - - {c07ade80-5c4f-e6e3-dd1a-5a619403fa9f} - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibViewing_UnitTests/LibViewing_UnitTests.vcxproj.filters b/Fwk/VizFwk/Tests/LibViewing_UnitTests/LibViewing_UnitTests.vcxproj.filters deleted file mode 100644 index 2d53f8cfbd..0000000000 --- a/Fwk/VizFwk/Tests/LibViewing_UnitTests/LibViewing_UnitTests.vcxproj.filters +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/LibViewing_UnitTests/TriggerTBBCopy.txt b/Fwk/VizFwk/Tests/LibViewing_UnitTests/TriggerTBBCopy.txt deleted file mode 100644 index bf816d39e4..0000000000 --- a/Fwk/VizFwk/Tests/LibViewing_UnitTests/TriggerTBBCopy.txt +++ /dev/null @@ -1,2 +0,0 @@ - -Sole purpose of this file is to have custom build rules to trigger copying of TBB DLLs diff --git a/Fwk/VizFwk/Tests/LibViewing_UnitTests/cvfModelBasicList-Test.cpp b/Fwk/VizFwk/Tests/LibViewing_UnitTests/cvfModelBasicList-Test.cpp index 9fe362f5f5..0b00ea5f14 100644 --- a/Fwk/VizFwk/Tests/LibViewing_UnitTests/cvfModelBasicList-Test.cpp +++ b/Fwk/VizFwk/Tests/LibViewing_UnitTests/cvfModelBasicList-Test.cpp @@ -97,16 +97,30 @@ TEST(ModelBasicListTest, BasicLifeCycle) } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +TEST(ModelBasicListTest, RemoveWithNullPointerPart) +{ + // Test adjusted to fit recent framework code where removal of NULL-parts is allowed + ref myModel = new ModelBasicList; + myModel->addPart(new Part); + ASSERT_EQ(1, myModel->partCount()); + + myModel->removePart(NULL); + ASSERT_EQ(1, myModel->partCount()); +} + + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- #ifdef _DEBUG -TEST(ModelBasicListDeathTest, AddRemoveWithNullPointerPart) +TEST(ModelBasicListDeathTest, AddNullPointerPart) { ref myModel = new ModelBasicList; EXPECT_DEATH(myModel->addPart(NULL), "Assertion"); - EXPECT_DEATH(myModel->removePart(NULL), "Assertion"); } #endif diff --git a/Fwk/VizFwk/Tests/SnippetsBasis/CMakeLists.txt b/Fwk/VizFwk/Tests/SnippetsBasis/CMakeLists.txt index 2a41503dc1..cff2b716f4 100644 --- a/Fwk/VizFwk/Tests/SnippetsBasis/CMakeLists.txt +++ b/Fwk/VizFwk/Tests/SnippetsBasis/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(SnippetsBasis) diff --git a/Fwk/VizFwk/Tests/SnippetsBasis/SnippetsBasis.vcxproj b/Fwk/VizFwk/Tests/SnippetsBasis/SnippetsBasis.vcxproj deleted file mode 100644 index 84e1c7b2bb..0000000000 --- a/Fwk/VizFwk/Tests/SnippetsBasis/SnippetsBasis.vcxproj +++ /dev/null @@ -1,503 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Debug MT - Win32 - - - Debug MT - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - Release MT - Win32 - - - Release MT - x64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {0D83607B-E0F7-DBA8-2F1F-8400C30B2008} - SnippetsBasis - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - StaticLibrary - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - - - - - Level4 - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - - - - - Level4 - WIN32;_DEBUG;%(PreprocessorDefinitions) - MultiThreadedDebug - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - - - - - Level4 - WIN32;_DEBUG;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - - - - - Level4 - WIN32;_DEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - - - - - Level4 - WIN32;_DEBUG;%(PreprocessorDefinitions) - MultiThreadedDebug - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - - - - - Level4 - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;%(PreprocessorDefinitions) - MultiThreaded - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;CVF_USE_TBB;%(PreprocessorDefinitions) - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - true - true - - - - - Level4 - WIN32;NDEBUG;%(PreprocessorDefinitions) - MultiThreaded - ../../LibCore;../../LibGeometry;../../LibIo;../../LibFreeType;../../LibRender;../../LibViewing;../../LibUtilities;../../LibRegGrid2D;../../LibStructGrid - - - true - true - true - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/SnippetsBasis/SnippetsBasis.vcxproj.filters b/Fwk/VizFwk/Tests/SnippetsBasis/SnippetsBasis.vcxproj.filters deleted file mode 100644 index 00a4c4071d..0000000000 --- a/Fwk/VizFwk/Tests/SnippetsBasis/SnippetsBasis.vcxproj.filters +++ /dev/null @@ -1,465 +0,0 @@ - - - - - - {b4df9da0-f4a6-4f18-ae34-0452bb883956} - - - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - Snippets\Shaders - - - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - Snippets - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/SnippetsBasis/snipDepthPeelingFront.cpp b/Fwk/VizFwk/Tests/SnippetsBasis/snipDepthPeelingFront.cpp index dfa50e11c8..aaf81d3bf4 100644 --- a/Fwk/VizFwk/Tests/SnippetsBasis/snipDepthPeelingFront.cpp +++ b/Fwk/VizFwk/Tests/SnippetsBasis/snipDepthPeelingFront.cpp @@ -461,7 +461,7 @@ void DepthPeelingFront::renderFrontToBackPeeling() // 3. Final Pass // --------------------------------------------------------------------- - glBindFramebuffer(GL_FRAMEBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, m_openGLContext->defaultFramebufferObject()); glDrawBuffer(GL_BACK); glDisable(GL_DEPTH_TEST); diff --git a/Fwk/VizFwk/Tests/SnippetsBasis/snipTextDrawing.cpp b/Fwk/VizFwk/Tests/SnippetsBasis/snipTextDrawing.cpp index baf53d4830..7e92b530da 100644 --- a/Fwk/VizFwk/Tests/SnippetsBasis/snipTextDrawing.cpp +++ b/Fwk/VizFwk/Tests/SnippetsBasis/snipTextDrawing.cpp @@ -252,13 +252,13 @@ ref TextDrawing::createTextPart() m_textDrawable->setFont(NULL); m_textDrawable->setTextColor(Color3::RED); -// m_textDrawable->addText(L"Text:", cvf::Vec3f(50, 200, 0)); -// m_textDrawable->addText(L" ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ", cvf::Vec3f(50, 170, 0)); -// m_textDrawable->addText(L" abcdefghijklmnopqrstuvwxyzæøå", cvf::Vec3f(50, 140, 0)); -// m_textDrawable->addText(L" 0123456789 0123456789 0123456789", cvf::Vec3f(50, 110, 0)); -// m_textDrawable->addText(L" !\"#¤%&/()=?`^*@£$€{[]}´~¨',;.:+-_<>>addText(L" Unicode1: \x03B1\x03B2\x03B3\x03B4\x03B5", cvf::Vec3f(50, 50, 0)); -// m_textDrawable->addText(L" Unicode2: ä¸ä»…是因为这两ç§è¯­è¨€æˆªç„¶ä¸åŒ", cvf::Vec3f(50, 20, 0)); + m_textDrawable->addText(L"Text:", cvf::Vec3f(50, 200, 0)); + m_textDrawable->addText(L" ABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ", cvf::Vec3f(50, 170, 0)); + m_textDrawable->addText(L" abcdefghijklmnopqrstuvwxyzæøå", cvf::Vec3f(50, 140, 0)); + m_textDrawable->addText(L" 0123456789 0123456789 0123456789", cvf::Vec3f(50, 110, 0)); + m_textDrawable->addText(L" !\"#¤%&/()=?`^*@£$€{[]}´~¨',;.:+-_<>>addText(L" Unicode1: \x03B1\x03B2\x03B3\x03B4\x03B5", cvf::Vec3f(50, 50, 0)); + m_textDrawable->addText(L" Unicode2: ä¸ä»…是因为这两ç§è¯­è¨€æˆªç„¶ä¸åŒ", cvf::Vec3f(50, 20, 0)); // Set up transparency ref blending = new RenderStateBlending; diff --git a/Fwk/VizFwk/Tests/UnitTestLauncher/UnitTestLauncher.vcxproj b/Fwk/VizFwk/Tests/UnitTestLauncher/UnitTestLauncher.vcxproj deleted file mode 100644 index 595926d7f6..0000000000 --- a/Fwk/VizFwk/Tests/UnitTestLauncher/UnitTestLauncher.vcxproj +++ /dev/null @@ -1,294 +0,0 @@ - - - - - Debug MD TBB - Win32 - - - Debug MD TBB - x64 - - - Debug MD - Win32 - - - Debug MD - x64 - - - Release MD TBB - Win32 - - - Release MD TBB - x64 - - - Release MD - Win32 - - - Release MD - x64 - - - - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC} - UnitTestLauncher - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - Application - false - Unicode - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - Level4 - ../../LibCore - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;_DEBUG;%(PreprocessorDefinitions) - - - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - - - Level4 - ../../LibCore - WIN32;NDEBUG;%(PreprocessorDefinitions) - - - true - true - true - Console - %(AdditionalDependencies) - - - - - - - {a9c7a239-b761-a892-bf34-5aeca0d9ee88} - - - {8714c516-1322-af26-8d73-8d8d6d2118bc} - - - {0e5e5956-5efd-6d62-0abe-af60a0deaba3} - - - {86969588-4aa4-afc9-ea54-fd5bc86810fc} - - - {93516308-f124-5ad1-40c1-93a4e1da7e02} - - - {bf85dfdc-7e61-d1cb-aab3-fea48ee57b9e} - - - {e4c3cab6-02b3-a353-1955-8da235c4fb64} - - - {1eb78b55-84df-7014-1a6f-b48da9d2e923} - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tests/UnitTestLauncher/UnitTestLauncher.vcxproj.filters b/Fwk/VizFwk/Tests/UnitTestLauncher/UnitTestLauncher.vcxproj.filters deleted file mode 100644 index c3c051d219..0000000000 --- a/Fwk/VizFwk/Tests/UnitTestLauncher/UnitTestLauncher.vcxproj.filters +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/ThirdParty/FreeType/CMakeLists.txt b/Fwk/VizFwk/ThirdParty/FreeType/CMakeLists.txt index da5b0168f7..8cc74f651f 100644 --- a/Fwk/VizFwk/ThirdParty/FreeType/CMakeLists.txt +++ b/Fwk/VizFwk/ThirdParty/FreeType/CMakeLists.txt @@ -1,5 +1,3 @@ -cmake_minimum_required(VERSION 2.8) - project(freetype) diff --git a/Fwk/VizFwk/ThirdParty/gtest/cvftestUtils.h b/Fwk/VizFwk/ThirdParty/gtest/cvftestUtils.h index cead690dc6..f3cd3fbd16 100644 --- a/Fwk/VizFwk/ThirdParty/gtest/cvftestUtils.h +++ b/Fwk/VizFwk/ThirdParty/gtest/cvftestUtils.h @@ -2,7 +2,6 @@ namespace cvftest { - //================================================================================================== // // Static helper class for unit tests @@ -11,179 +10,35 @@ namespace cvftest { class Utils { public: - static bool doesEnvironmentVarExist(const char* name) - { - const char* env = testing::internal::posix::GetEnv(name); - return env ? true : false; - } - - static std::string getEnvironmentVar(const char* name) - { - const char* env = testing::internal::posix::GetEnv(name); - if (env) - { - return env; - } - else - { - return std::string(); - } - } - - static std::string getMyExecutablePath() + static cvf::String getTestDataDir() { -#ifdef WIN32 - std::string exe = std::string(testing::internal::GetArgvs()[0]); -#else - std::string dir = std::string(testing::internal::FilePath::GetCurrentDir().ToString()); - std::string exe = dir + std::string("/") + std::string(testing::internal::GetArgvs()[0]); + std::string testPath = ""; +#if defined(CVF_CEEVIZ_ROOT_SOURCE_DIR) + testPath = CVF_CEEVIZ_ROOT_SOURCE_DIR "/Tests/TestData/"; #endif - return exe; - } -}; - - - -//================================================================================================== -// -// Helper for making a test data directory available inside unit tests -// -// The data directories can be specified via the environment variables CVF_UTEST_DATA_DIR and -// CVF_UTEST_EXTRA_DATA_DIR. Expects a the path to contain a trailing slash. -// Linux: export CVF_UTEST_DATA_DIR="../../../Tests/TestData/" -// -// The main data dir may be populated with default values if the environment variable isn't set. -// The DefaultDataDir enum determines which default will be used. -//================================================================================================== -class TestDataDir -{ -public: - // What value to use if the test data dir environment variable isn't set? - enum DefaultDataDir - { - EMPTY_STRING, // Empty string - DEFAULT_DEFINE, // Try and set from the CVF_UTEST_DEFAULT_DATA_DIR define (must of course be defined, typical usage is via CMake) - DEFAULT_DEFINE_THEN_VIZ_FRAMEWORK // First try the define above, then fall back to the default test data directory for VizFramework - }; - -public: - /// Static initialize function that sets up the singleton and initializes - /// the values of the data directories based on value of the specified enum - //-------------------------------------------------------------------------------------------------- - static void initializeInstance(DefaultDataDir defaultDataDir, bool verbose) - { - TestDataDir* theInstance = internalInstance(); - theInstance->initialize(defaultDataDir, verbose); - } - /// Get pointer to singleton intance, must call initializeInstance() before use - //-------------------------------------------------------------------------------------------------- - static const TestDataDir* instance() - { - const TestDataDir* theInstance = internalInstance(); - if (!theInstance->m_isInitialized) + std::string testPathEnv = getEnvironmentVar("CVF_UTEST_DATA_DIR"); + if (testPathEnv.length() > 0) { - // Not sure if it is wise to use the gtest internal macros here, but haven't found another solution yet - GTEST_MESSAGE_("TestDataDir::initializeInstance() must be called first!", ::testing::TestPartResult::kFatalFailure); + testPath = testPathEnv; } - return theInstance; - } - /// Returns the main data directory - //-------------------------------------------------------------------------------------------------- - std::string dataDir() const - { - return m_dataDir; - } - - /// Returns the extra data directory - //-------------------------------------------------------------------------------------------------- - std::string extraDataDir() const - { - return m_extraDataDir; + return testPath; } private: - TestDataDir() - : m_isInitialized(false) - { - } - - // Initializes the data members - void initialize(DefaultDataDir defaultDataDir, bool verbose) - { - std::string valSrcStr = "empty"; - - if (Utils::doesEnvironmentVarExist("CVF_UTEST_DATA_DIR")) + static std::string getEnvironmentVar(const char* name) + { + const char* env = testing::internal::posix::GetEnv(name); + if (env) { - m_dataDir = Utils::getEnvironmentVar("CVF_UTEST_DATA_DIR"); - valSrcStr = "environmentVar"; + return env; } else { - if (defaultDataDir != EMPTY_STRING) - { - m_dataDir = getValueOfDefaultDefine(); - if (!m_dataDir.empty()) - { - valSrcStr = "define"; - } - else if (defaultDataDir == DEFAULT_DEFINE_THEN_VIZ_FRAMEWORK) - { - m_dataDir = getVizFrameworkDefault(); - if (!m_dataDir.empty()) - { - valSrcStr = "vizFramework"; - } - } - } - } - - m_extraDataDir = Utils::getEnvironmentVar("CVF_UTEST_EXTRA_DATA_DIR"); - - if (verbose) - { - printf("\n"); - printf("dataDir : \"%s\" [src=%s]\n", m_dataDir.c_str(), valSrcStr.c_str()); - printf("extraDir: \"%s\"\n", m_extraDataDir.c_str()); + return std::string(); } - - m_isInitialized = true; } - - // Extract value set via compile time define - static std::string getValueOfDefaultDefine() - { - std::string defDataDir; -#ifdef CVF_UTEST_DEFAULT_DATA_DIR - defDataDir = CVF_UTEST_DEFAULT_DATA_DIR; -#endif - return defDataDir; - } - - // Determine VizFramework default based on executable path and our fixed dir structure - static std::string getVizFrameworkDefault() - { - std::string exe = Utils::getMyExecutablePath(); - std::string dataDir; -#ifdef WIN32 - dataDir = exe.substr(0, exe.find("VizFwk\\")) + std::string("VizFwk\\Tests\\TestData\\"); -#else - dataDir = exe.substr(0, exe.find("VizFwk/")) + std::string("VizFwk/Tests/TestData/"); -#endif - return dataDir; - } - - static TestDataDir* internalInstance() - { - static TestDataDir sl_theInstance; - return &sl_theInstance; - } - -private: - bool m_isInitialized; - std::string m_dataDir; // The primary data directory - std::string m_extraDataDir; // Optional extra data dir, settable only via environment variable }; diff --git a/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.sln b/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.sln deleted file mode 100644 index 3562f85181..0000000000 --- a/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Glsl2Include", "Glsl2Include.vcxproj", "{7A13EE88-93C8-4308-A59B-FD69CA704A41}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {7A13EE88-93C8-4308-A59B-FD69CA704A41}.Debug|Win32.ActiveCfg = Debug|Win32 - {7A13EE88-93C8-4308-A59B-FD69CA704A41}.Debug|Win32.Build.0 = Debug|Win32 - {7A13EE88-93C8-4308-A59B-FD69CA704A41}.Release|Win32.ActiveCfg = Release|Win32 - {7A13EE88-93C8-4308-A59B-FD69CA704A41}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.vcxproj b/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.vcxproj deleted file mode 100644 index 51ab1b008e..0000000000 --- a/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.vcxproj +++ /dev/null @@ -1,94 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {7A13EE88-93C8-4308-A59B-FD69CA704A41} - Win32Proj - Glsl2Include - - - - Application - true - MultiByte - - - Application - false - true - MultiByte - - - - - - - - - - - - - true - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - false - $(Platform)_VS2010\$(Configuration)\ - $(Platform)_VS2010\$(Configuration)\ - - - - - - Level3 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreadedDebug - - - Console - true - - - - - Level3 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.vcxproj.filters b/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.vcxproj.filters deleted file mode 100644 index 9961518fea..0000000000 --- a/Fwk/VizFwk/Tools/Glsl2Include/src/Glsl2Include.vcxproj.filters +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/Fwk/VizFwk/VizFramework.sln b/Fwk/VizFwk/VizFramework.sln deleted file mode 100644 index b38637a3b7..0000000000 --- a/Fwk/VizFwk/VizFramework.sln +++ /dev/null @@ -1,382 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibCore", "LibCore\LibCore.vcxproj", "{A9C7A239-B761-A892-BF34-5AECA0D9EE88}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibCore_UnitTests", "Tests\LibCore_UnitTests\LibCore_UnitTests.vcxproj", "{0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGeometry", "LibGeometry\LibGeometry.vcxproj", "{EFD5C9AC-8988-F190-AA2C-E36EBE361E90}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibViewing", "LibViewing\LibViewing.vcxproj", "{122D4663-11D6-D12F-8748-629A34E9075E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRender", "LibRender\LibRender.vcxproj", "{C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibUtilities", "LibUtilities\LibUtilities.vcxproj", "{ECF1BECD-E624-F971-C70A-F84686A36084}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibViewing_UnitTests", "Tests\LibViewing_UnitTests\LibViewing_UnitTests.vcxproj", "{8714C516-1322-AF26-8D73-8D8D6D2118BC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibIo", "LibIo\LibIo.vcxproj", "{181472EE-4B37-01E8-49D5-6213678FE4F8}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRegGrid2D", "LibRegGrid2D\LibRegGrid2D.vcxproj", "{7AEF1888-268C-3BEF-4080-743645180A59}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibStructGrid", "LibStructGrid\LibStructGrid.vcxproj", "{C22D8A0D-2318-3353-F75A-E83B82A3B29F}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UnitTestLauncher", "Tests\UnitTestLauncher\UnitTestLauncher.vcxproj", "{0C357E67-9A35-75D0-61AB-FDDAF3A444BC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRegGrid2D_UnitTests", "Tests\LibRegGrid2D_UnitTests\LibRegGrid2D_UnitTests.vcxproj", "{BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibGeometry_UnitTests", "Tests\LibGeometry_UnitTests\LibGeometry_UnitTests.vcxproj", "{86969588-4AA4-AFC9-EA54-FD5BC86810FC}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibIo_UnitTests", "Tests\LibIo_UnitTests\LibIo_UnitTests.vcxproj", "{93516308-F124-5AD1-40C1-93A4E1DA7E02}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibRender_UnitTests", "Tests\LibRender_UnitTests\LibRender_UnitTests.vcxproj", "{E4C3CAB6-02B3-A353-1955-8DA235C4FB64}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibStructGrid_UnitTests", "Tests\LibStructGrid_UnitTests\LibStructGrid_UnitTests.vcxproj", "{1EB78B55-84DF-7014-1A6F-B48DA9D2E923}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LibUtilities_UnitTests", "Tests\LibUtilities_UnitTests\LibUtilities_UnitTests.vcxproj", "{BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{E1D21A36-81A2-4744-A4F3-45B7203D9A6D}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "!Doxygen", "Doxygen\!Doxygen.vcxproj", "{F5FA2496-1AD3-4569-8EA1-5B5F01450B03}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "CeeVizFramework", "CeeVizFramework", "{106B5AB3-257F-476E-AB91-5A7B30153D70}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{A36114F2-DD91-48C6-867E-B2F484EB1C37}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{05FB1641-AB43-4683-BFE1-534555DE8017}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ApplicationSupport", "ApplicationSupport", "{460DA356-CE42-4D6B-8ED8-E59F52B4B4E8}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UnitTests", "UnitTests", "{7471996A-9678-4D61-BDAD-73222EC9F805}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Applications", "Applications", "{DA71EF5E-9D45-4E4C-BCCD-C4A14E022078}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "!CMake", "CMake\!CMake.vcxproj", "{FB015304-89D5-4093-B01A-0E7F642971DC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - All Dbg MD TBB|Win32 = All Dbg MD TBB|Win32 - All Dbg MD TBB|x64 = All Dbg MD TBB|x64 - All Dbg MD|Win32 = All Dbg MD|Win32 - All Dbg MD|x64 = All Dbg MD|x64 - All Rel MD TBB|Win32 = All Rel MD TBB|Win32 - All Rel MD TBB|x64 = All Rel MD TBB|x64 - All Rel MD|Win32 = All Rel MD|Win32 - All Rel MD|x64 = All Rel MD|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {A9C7A239-B761-A892-BF34-5AECA0D9EE88}.All Rel MD|x64.Build.0 = Release MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3}.All Rel MD|x64.Build.0 = Release MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90}.All Rel MD|x64.Build.0 = Release MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {122D4663-11D6-D12F-8748-629A34E9075E}.All Rel MD|x64.Build.0 = Release MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F}.All Rel MD|x64.Build.0 = Release MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {ECF1BECD-E624-F971-C70A-F84686A36084}.All Rel MD|x64.Build.0 = Release MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {8714C516-1322-AF26-8D73-8D8D6D2118BC}.All Rel MD|x64.Build.0 = Release MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {181472EE-4B37-01E8-49D5-6213678FE4F8}.All Rel MD|x64.Build.0 = Release MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {7AEF1888-268C-3BEF-4080-743645180A59}.All Rel MD|x64.Build.0 = Release MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {C22D8A0D-2318-3353-F75A-E83B82A3B29F}.All Rel MD|x64.Build.0 = Release MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC}.All Rel MD|x64.Build.0 = Release MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E}.All Rel MD|x64.Build.0 = Release MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {86969588-4AA4-AFC9-EA54-FD5BC86810FC}.All Rel MD|x64.Build.0 = Release MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {93516308-F124-5AD1-40C1-93A4E1DA7E02}.All Rel MD|x64.Build.0 = Release MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64}.All Rel MD|x64.Build.0 = Release MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923}.All Rel MD|x64.Build.0 = Release MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD TBB|Win32.ActiveCfg = Debug MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD TBB|Win32.Build.0 = Debug MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD TBB|x64.ActiveCfg = Debug MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD TBB|x64.Build.0 = Debug MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD|Win32.ActiveCfg = Debug MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD|Win32.Build.0 = Debug MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD|x64.ActiveCfg = Debug MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Dbg MD|x64.Build.0 = Debug MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD TBB|Win32.ActiveCfg = Release MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD TBB|Win32.Build.0 = Release MD TBB|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD TBB|x64.ActiveCfg = Release MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD TBB|x64.Build.0 = Release MD TBB|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD|Win32.ActiveCfg = Release MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD|Win32.Build.0 = Release MD|Win32 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD|x64.ActiveCfg = Release MD|x64 - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62}.All Rel MD|x64.Build.0 = Release MD|x64 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Dbg MD TBB|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Dbg MD TBB|x64.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Dbg MD|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Dbg MD|x64.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Rel MD TBB|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Rel MD TBB|x64.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Rel MD|Win32.ActiveCfg = Doxygen|Win32 - {F5FA2496-1AD3-4569-8EA1-5B5F01450B03}.All Rel MD|x64.ActiveCfg = Doxygen|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Dbg MD TBB|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Dbg MD TBB|x64.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Dbg MD|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Dbg MD|x64.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Rel MD TBB|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Rel MD TBB|x64.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Rel MD|Win32.ActiveCfg = NotBuildable|Win32 - {FB015304-89D5-4093-B01A-0E7F642971DC}.All Rel MD|x64.ActiveCfg = NotBuildable|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {E1D21A36-81A2-4744-A4F3-45B7203D9A6D} = {106B5AB3-257F-476E-AB91-5A7B30153D70} - {EFD5C9AC-8988-F190-AA2C-E36EBE361E90} = {106B5AB3-257F-476E-AB91-5A7B30153D70} - {122D4663-11D6-D12F-8748-629A34E9075E} = {106B5AB3-257F-476E-AB91-5A7B30153D70} - {C07ADE80-5C4F-E6E3-DD1A-5A619403FA9F} = {106B5AB3-257F-476E-AB91-5A7B30153D70} - {181472EE-4B37-01E8-49D5-6213678FE4F8} = {106B5AB3-257F-476E-AB91-5A7B30153D70} - {A9C7A239-B761-A892-BF34-5AECA0D9EE88} = {106B5AB3-257F-476E-AB91-5A7B30153D70} - {8714C516-1322-AF26-8D73-8D8D6D2118BC} = {E1D21A36-81A2-4744-A4F3-45B7203D9A6D} - {86969588-4AA4-AFC9-EA54-FD5BC86810FC} = {E1D21A36-81A2-4744-A4F3-45B7203D9A6D} - {93516308-F124-5AD1-40C1-93A4E1DA7E02} = {E1D21A36-81A2-4744-A4F3-45B7203D9A6D} - {E4C3CAB6-02B3-A353-1955-8DA235C4FB64} = {E1D21A36-81A2-4744-A4F3-45B7203D9A6D} - {0E5E5956-5EFD-6D62-0ABE-AF60A0DEABA3} = {E1D21A36-81A2-4744-A4F3-45B7203D9A6D} - {7471996A-9678-4D61-BDAD-73222EC9F805} = {460DA356-CE42-4D6B-8ED8-E59F52B4B4E8} - {ECF1BECD-E624-F971-C70A-F84686A36084} = {460DA356-CE42-4D6B-8ED8-E59F52B4B4E8} - {C22D8A0D-2318-3353-F75A-E83B82A3B29F} = {A36114F2-DD91-48C6-867E-B2F484EB1C37} - {05FB1641-AB43-4683-BFE1-534555DE8017} = {A36114F2-DD91-48C6-867E-B2F484EB1C37} - {7AEF1888-268C-3BEF-4080-743645180A59} = {A36114F2-DD91-48C6-867E-B2F484EB1C37} - {0C357E67-9A35-75D0-61AB-FDDAF3A444BC} = {DA71EF5E-9D45-4E4C-BCCD-C4A14E022078} - {1EB78B55-84DF-7014-1A6F-B48DA9D2E923} = {05FB1641-AB43-4683-BFE1-534555DE8017} - {BF85DFDC-7E61-D1CB-AAB3-FEA48EE57B9E} = {05FB1641-AB43-4683-BFE1-534555DE8017} - {BC8FBFDE-64FE-8DAF-DE93-F89AD1082B62} = {7471996A-9678-4D61-BDAD-73222EC9F805} - EndGlobalSection -EndGlobal diff --git a/GrpcInterface/.clang-tidy b/GrpcInterface/.clang-tidy new file mode 100644 index 0000000000..43a4e6b10e --- /dev/null +++ b/GrpcInterface/.clang-tidy @@ -0,0 +1,5 @@ +--- +Checks: '-*,modernize-use-override,modernize-deprecated-headers,modernize-use-using,bugprone-bool-pointer-implicit-conversion,bugprone-parent-virtual-call,bugprone-redundant-branch-condition,bugprone-suspicious-semicolon,bugprone-suspicious-string-compare,modernize-redundant-void-arg,readability-static-accessed-through-instance,readability-simplify-boolean-expr,readability-container-size-empty' +WarningsAsErrors: '' +HeaderFilterRegex: 'GrpcInterface/*.*$' +FormatStyle: 'file' diff --git a/GrpcInterface/CMakeLists.txt b/GrpcInterface/CMakeLists.txt index 64fcfc6f6c..3747acc6e5 100644 --- a/GrpcInterface/CMakeLists.txt +++ b/GrpcInterface/CMakeLists.txt @@ -251,13 +251,10 @@ endif() # install gRPC Python files if(RESINSIGHT_GRPC_PYTHON_EXECUTABLE AND RESINSIGHT_GRPC_DOWNLOAD_PYTHON_MODULE) - message(STATUS "Installing Python modules") + message(STATUS "Installing Python modules (dev-requirements.txt)") add_custom_command( TARGET PipInstall - COMMAND ${RESINSIGHT_GRPC_PYTHON_EXECUTABLE} ARGS -m pip install --user - wheel setuptools pytest - COMMAND ${RESINSIGHT_GRPC_PYTHON_EXECUTABLE} ARGS -m pip install --user - grpcio-tools) + COMMAND ${RESINSIGHT_GRPC_PYTHON_EXECUTABLE} ARGS -m pip install -r ${GRPC_PYTHON_SOURCE_PATH}/dev-requirements.txt --user ) endif() if(RESINSIGHT_GRPC_PYTHON_EXECUTABLE AND RESINSIGHT_GRPC_BUNDLE_PYTHON_MODULE) diff --git a/GrpcInterface/GrpcProtos/PdmObject.proto b/GrpcInterface/GrpcProtos/PdmObject.proto index cff7e5db9b..d55aa11499 100644 --- a/GrpcInterface/GrpcProtos/PdmObject.proto +++ b/GrpcInterface/GrpcProtos/PdmObject.proto @@ -14,6 +14,7 @@ service PdmObjectService rpc CallPdmObjectGetter(PdmObjectGetterRequest) returns (stream PdmObjectGetterReply) {} rpc CallPdmObjectSetter(stream PdmObjectSetterChunk) returns (ClientToServerStreamReply) {} rpc CallPdmObjectMethod(PdmObjectMethodRequest) returns (PdmObject) {} + rpc DeleteExistingPdmObject(PdmObject) returns (Empty) {} } message PdmDescendantObjectRequest diff --git a/GrpcInterface/Python/dev-requirements.txt b/GrpcInterface/Python/dev-requirements.txt new file mode 100644 index 0000000000..26207d9c11 --- /dev/null +++ b/GrpcInterface/Python/dev-requirements.txt @@ -0,0 +1,6 @@ +grpcio +grpcio-tools +protobuf +wheel +typing-extensions +pytest diff --git a/GrpcInterface/Python/rips/PythonExamples/modeled_well_path.py b/GrpcInterface/Python/rips/PythonExamples/modeled_well_path.py index ba29d56c30..d385d63639 100644 --- a/GrpcInterface/Python/rips/PythonExamples/modeled_well_path.py +++ b/GrpcInterface/Python/rips/PythonExamples/modeled_well_path.py @@ -45,3 +45,28 @@ ) perforation.skin_factor = new_skin_factor perforation.update() + +# Optionally update the completion settings +completions_settings = well_path.completion_settings() +completions_settings.msw_roughness = 12.34 +completions_settings.msw_liner_diameter = 0.2222 +completions_settings.well_name_for_export = "file name" +completions_settings.group_name_for_export = "msj" +completions_settings.well_type_for_export = "GAS" +completions_settings.update() # Commit updates back to ResInsight + +# export completions +cases = resinsight.project.cases() + +for case in cases: + print("Case name: ", case.name) + print("Case id: ", case.id) + + case.export_well_path_completions( + time_step=0, + well_path_names=["Test Well-1 Y1"], + file_split="UNIFIED_FILE", + include_perforations=True, + # Replace the following with a valid path + custom_file_name="f:/scratch/2023-11-02/myfile.myext", + ) diff --git a/GrpcInterface/Python/rips/contour_map.py b/GrpcInterface/Python/rips/contour_map.py index 6d4e9d3db3..9aeb6bb5a6 100644 --- a/GrpcInterface/Python/rips/contour_map.py +++ b/GrpcInterface/Python/rips/contour_map.py @@ -1,6 +1,7 @@ """ ResInsight 3d contour map module """ + import Commands_pb2 from .pdmobject import add_method diff --git a/GrpcInterface/Python/rips/instance.py b/GrpcInterface/Python/rips/instance.py index 225e1ec9bf..1f6f7b0f70 100644 --- a/GrpcInterface/Python/rips/instance.py +++ b/GrpcInterface/Python/rips/instance.py @@ -285,9 +285,9 @@ def _check_connection_and_version( raise Exception( "Error: Wrong Version of ResInsight at ", location, - self.version_string(), + "Executable : " + self.version_string(), " ", - self.client_version_string(), + "rips : " + self.client_version_string(), ) def __version_message(self) -> App_pb2.Version: diff --git a/GrpcInterface/Python/rips/pdmobject.py b/GrpcInterface/Python/rips/pdmobject.py index 877a2ccb4b..73b2724b07 100644 --- a/GrpcInterface/Python/rips/pdmobject.py +++ b/GrpcInterface/Python/rips/pdmobject.py @@ -511,3 +511,13 @@ def update(self) -> None: raise Exception( "Object is not connected to GRPC service so cannot update ResInsight" ) + + def delete(self) -> None: + """Delete object in ResInsight""" + self.__copy_to_pb2() + if self._pdm_object_stub is not None: + self._pdm_object_stub.DeleteExistingPdmObject(self._pb2_object) + else: + raise Exception( + "Object is not connected to GRPC service so cannot update ResInsight" + ) diff --git a/GrpcInterface/Python/rips/plot.py b/GrpcInterface/Python/rips/plot.py index da41c5ebdd..4b464420db 100644 --- a/GrpcInterface/Python/rips/plot.py +++ b/GrpcInterface/Python/rips/plot.py @@ -1,6 +1,7 @@ """ ResInsight 2d plot module """ + import Commands_pb2 from .pdmobject import add_method diff --git a/GrpcInterface/Python/rips/simulation_well.py b/GrpcInterface/Python/rips/simulation_well.py index abe100d70f..7c29d1c4e0 100644 --- a/GrpcInterface/Python/rips/simulation_well.py +++ b/GrpcInterface/Python/rips/simulation_well.py @@ -1,6 +1,7 @@ """ ResInsight SimulationWell """ + import grpc import SimulationWell_pb2 diff --git a/GrpcInterface/Python/rips/tests/test_object_lifetime.py b/GrpcInterface/Python/rips/tests/test_object_lifetime.py new file mode 100644 index 0000000000..1175a002b8 --- /dev/null +++ b/GrpcInterface/Python/rips/tests/test_object_lifetime.py @@ -0,0 +1,27 @@ +import sys +import os + +sys.path.insert(1, os.path.join(sys.path[0], "../../")) +import rips + + +def test_well_path(rips_instance, initialize_test): + well_path_coll = rips_instance.project.descendants(rips.WellPathCollection)[0] + assert len(well_path_coll.well_paths()) is 0 + + well_path = well_path_coll.add_new_object(rips.ModeledWellPath) + well_path2 = well_path_coll.add_new_object(rips.ModeledWellPath) + assert len(well_path_coll.well_paths()) is 2 + + well_path.delete() + assert len(well_path_coll.well_paths()) is 1 + + try: + # Delete again should throw exception + well_path.delete() + assert False + except Exception: + assert True + + well_path2.delete() + assert len(well_path_coll.well_paths()) is 0 diff --git a/GrpcInterface/RiaGrpcApplicationInterface.cpp b/GrpcInterface/RiaGrpcApplicationInterface.cpp index 410ec00ffb..70f97ecc3a 100644 --- a/GrpcInterface/RiaGrpcApplicationInterface.cpp +++ b/GrpcInterface/RiaGrpcApplicationInterface.cpp @@ -21,6 +21,7 @@ #include "cvfProgramOptions.h" +#include #include //-------------------------------------------------------------------------------------------------- diff --git a/GrpcInterface/RiaGrpcCallbacks.h b/GrpcInterface/RiaGrpcCallbacks.h index faebbb56cf..bb7254a15c 100644 --- a/GrpcInterface/RiaGrpcCallbacks.h +++ b/GrpcInterface/RiaGrpcCallbacks.h @@ -33,8 +33,6 @@ using grpc::ServerCompletionQueue; using grpc::ServerContext; using grpc::Status; -class RiaGrpcServiceInterface; - //================================================================================================== // // Base class for all gRPC-callbacks @@ -83,7 +81,7 @@ class RiaGrpcServiceCallback : public RiaGrpcCallbackInterface { public: RiaGrpcServiceCallback( ServiceT* service ); - ~RiaGrpcServiceCallback(); + ~RiaGrpcServiceCallback() override; QString name() const override; const RequestT& request() const; @@ -127,7 +125,7 @@ class RiaGrpcUnaryCallback : public RiaGrpcServiceCallbackporosity_model() ); - RimCase* rimCase = RiaGrpcServiceInterface::findCase( m_request->case_request().id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( m_request->case_request().id() ); m_eclipseCase = dynamic_cast( rimCase ); if ( !m_eclipseCase ) @@ -191,7 +191,7 @@ const std::vector& RiaActiveCellInfoStateHandler::reservoirCells() cons //-------------------------------------------------------------------------------------------------- grpc::Status RiaActiveCellInfoStateHandler::assignReply( rips::CellInfoArray* reply ) { - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::CellInfo ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::CellInfo ) ); size_t indexInPackage = 0u; reply->mutable_data()->Reserve( (int)packageSize ); @@ -259,7 +259,7 @@ void RiaActiveCellInfoStateHandler::assignCellCenter( rips::Vec3d* //-------------------------------------------------------------------------------------------------- grpc::Status RiaActiveCellInfoStateHandler::assignCellCentersReply( rips::CellCenters* reply ) { - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::Vec3d ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::Vec3d ) ); size_t indexInPackage = 0u; reply->mutable_centers()->Reserve( (int)packageSize ); for ( ; indexInPackage < packageSize && m_currentCellIdx < m_activeCellInfo->reservoirCellCount(); ++indexInPackage ) @@ -332,7 +332,7 @@ void RiaActiveCellInfoStateHandler::assignCellCorners( rips::CellCorners* //-------------------------------------------------------------------------------------------------- Status RiaActiveCellInfoStateHandler::assignCellCornersReply( rips::CellCornersArray* reply ) { - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::CellCorners ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::CellCorners ) ); size_t indexInPackage = 0u; reply->mutable_cells()->Reserve( (int)packageSize ); for ( ; indexInPackage < packageSize && m_currentCellIdx < m_activeCellInfo->reservoirCellCount(); ++indexInPackage ) @@ -363,7 +363,7 @@ grpc::Status RiaGrpcCaseService::GetGridCount( grpc::ServerContext* context, const rips::CaseRequest* request, rips::GridCount* reply ) { - RimCase* rimCase = findCase( request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->id() ); RimEclipseCase* eclipseCase = dynamic_cast( rimCase ); if ( eclipseCase ) @@ -382,7 +382,7 @@ grpc::Status RiaGrpcCaseService::GetCellCount( grpc::ServerContext* cont const rips::CellInfoRequest* request, rips::CellCount* reply ) { - RimCase* rimCase = findCase( request->case_request().id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->case_request().id() ); RimEclipseCase* eclipseCase = dynamic_cast( rimCase ); if ( eclipseCase ) @@ -403,7 +403,7 @@ grpc::Status RiaGrpcCaseService::GetTimeSteps( grpc::ServerContext* context, const rips::CaseRequest* request, rips::TimeStepDates* reply ) { - RimCase* rimCase = findCase( request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->id() ); if ( rimCase ) { @@ -430,7 +430,7 @@ grpc::Status RiaGrpcCaseService::GetDaysSinceStart( grpc::ServerContext* con const rips::CaseRequest* request, rips::DaysSinceStart* reply ) { - RimCase* rimCase = findCase( request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->id() ); RimEclipseCase* eclipseCase = dynamic_cast( rimCase ); if ( eclipseCase ) @@ -466,7 +466,7 @@ grpc::Status RiaGrpcCaseService::GetDaysSinceStart( grpc::ServerContext* con grpc::Status RiaGrpcCaseService::GetCaseInfo( grpc::ServerContext* context, const rips::CaseRequest* request, rips::CaseInfo* reply ) { - RimCase* rimCase = findCase( request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->id() ); if ( rimCase ) { qint64 caseId = rimCase->caseId(); @@ -490,7 +490,7 @@ grpc::Status RiaGrpcCaseService::GetPdmObject( grpc::ServerContext* context, const rips::CaseRequest* request, rips::PdmObject* reply ) { - RimCase* rimCase = findCase( request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->id() ); if ( rimCase ) { copyPdmObjectFromCafToRips( rimCase, reply ); @@ -549,7 +549,7 @@ Status RiaSelectedCellsStateHandler::init( const rips::CaseRequest* request ) CAF_ASSERT( request ); m_request = request; - RimCase* rimCase = RiaGrpcServiceInterface::findCase( m_request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( m_request->id() ); m_eclipseCase = dynamic_cast( rimCase ); if ( !m_eclipseCase ) @@ -624,7 +624,7 @@ grpc::Status RiaSelectedCellsStateHandler::assignReply( rips::SelectedCells* rep } } - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::SelectedCell ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::SelectedCell ) ); size_t indexInPackage = 0u; reply->mutable_cells()->Reserve( (int)packageSize ); for ( ; indexInPackage < packageSize && m_currentItem < eclipseItems.size(); ++indexInPackage ) @@ -667,7 +667,7 @@ grpc::Status RiaGrpcCaseService::GetReservoirBoundingBox( grpc::ServerContext* const rips::CaseRequest* request, rips::BoundingBox* reply ) { - RimCase* rimCase = findCase( request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->id() ); if ( rimCase ) { cvf::BoundingBox boundingBox = rimCase->reservoirBoundingBox(); @@ -689,7 +689,7 @@ grpc::Status RiaGrpcCaseService::GetCoarseningInfoArray( grpc::ServerContext* const rips::CaseRequest* request, rips::CoarseningInfoArray* reply ) { - RimEclipseCase* rimCase = dynamic_cast( findCase( request->id() ) ); + RimEclipseCase* rimCase = dynamic_cast( RiaGrpcHelper::findCase( request->id() ) ); if ( rimCase && rimCase->eclipseCaseData() && rimCase->eclipseCaseData()->mainGrid() ) { for ( size_t gridIdx = 0; gridIdx < rimCase->eclipseCaseData()->gridCount(); gridIdx++ ) diff --git a/GrpcInterface/RiaGrpcCaseService.h b/GrpcInterface/RiaGrpcCaseService.h index f7fcb50c35..f21b3ef29c 100644 --- a/GrpcInterface/RiaGrpcCaseService.h +++ b/GrpcInterface/RiaGrpcCaseService.h @@ -43,7 +43,7 @@ class RiuEclipseSelectionItem; //================================================================================================== class RiaActiveCellInfoStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaActiveCellInfoStateHandler(); @@ -84,7 +84,7 @@ class RiaActiveCellInfoStateHandler //================================================================================================== class RiaSelectedCellsStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaSelectedCellsStateHandler(); @@ -109,7 +109,7 @@ class RiaGrpcCaseService final : public rips::Case::AsyncService, public RiaGrpc { public: grpc::Status - GetGridCount( grpc::ServerContext* context, const rips::CaseRequest* request, rips::GridCount* reply ) override; + GetGridCount( grpc::ServerContext* context, const rips::CaseRequest* request, rips::GridCount* reply ) override; grpc::Status GetCellCount( grpc::ServerContext* context, const rips::CellInfoRequest* request, rips::CellCount* reply ) override; @@ -121,7 +121,7 @@ class RiaGrpcCaseService final : public rips::Case::AsyncService, public RiaGrpc rips::DaysSinceStart* reply ) override; grpc::Status GetCaseInfo( grpc::ServerContext* context, const rips::CaseRequest* request, rips::CaseInfo* reply ) override; grpc::Status - GetPdmObject( grpc::ServerContext* context, const rips::CaseRequest* request, rips::PdmObject* reply ) override; + GetPdmObject( grpc::ServerContext* context, const rips::CaseRequest* request, rips::PdmObject* reply ) override; grpc::Status GetCellInfoForActiveCells( grpc::ServerContext* context, const rips::CellInfoRequest* request, rips::CellInfoArray* reply, diff --git a/GrpcInterface/RiaGrpcCommandService.cpp b/GrpcInterface/RiaGrpcCommandService.cpp index a668b130aa..2f3be12f44 100644 --- a/GrpcInterface/RiaGrpcCommandService.cpp +++ b/GrpcInterface/RiaGrpcCommandService.cpp @@ -45,7 +45,7 @@ using namespace google::protobuf; //-------------------------------------------------------------------------------------------------- grpc::Status RiaGrpcCommandService::Execute( grpc::ServerContext* context, const CommandParams* request, CommandReply* reply ) { - auto requestDescriptor = request->GetDescriptor(); + auto requestDescriptor = rips::CommandParams::GetDescriptor(); CommandParams::ParamsCase paramsCase = request->params_case(); if ( paramsCase != CommandParams::PARAMS_NOT_SET ) @@ -379,7 +379,7 @@ void RiaGrpcCommandService::assignResultToReply( const caf::PdmObject* result, C QString resultType = result->classKeyword(); - auto replyDescriptor = reply->GetDescriptor(); + auto replyDescriptor = rips::CommandReply::GetDescriptor(); auto oneofDescriptor = replyDescriptor->FindOneofByName( "result" ); const FieldDescriptor* matchingOneOf = nullptr; for ( int fieldIndex = 0; fieldIndex < oneofDescriptor->field_count(); ++fieldIndex ) @@ -393,7 +393,7 @@ void RiaGrpcCommandService::assignResultToReply( const caf::PdmObject* result, C } CAF_ASSERT( matchingOneOf ); - Message* message = reply->GetReflection()->MutableMessage( reply, matchingOneOf ); + Message* message = rips::CommandReply::GetReflection()->MutableMessage( reply, matchingOneOf ); CAF_ASSERT( message ); auto resultDescriptor = message->GetDescriptor(); diff --git a/GrpcInterface/RiaGrpcCommandService.h b/GrpcInterface/RiaGrpcCommandService.h index 4b3fef61c8..3b7edcf134 100644 --- a/GrpcInterface/RiaGrpcCommandService.h +++ b/GrpcInterface/RiaGrpcCommandService.h @@ -49,7 +49,7 @@ class RiaGrpcCommandService : public rips::Commands::AsyncService, public RiaGrp { public: grpc::Status - Execute( grpc::ServerContext* context, const rips::CommandParams* request, rips::CommandReply* reply ) override; + Execute( grpc::ServerContext* context, const rips::CommandParams* request, rips::CommandReply* reply ) override; std::vector createCallbacks() override; private: diff --git a/GrpcInterface/RiaGrpcGridService.cpp b/GrpcInterface/RiaGrpcGridService.cpp index 9855ea9ece..8601428591 100644 --- a/GrpcInterface/RiaGrpcGridService.cpp +++ b/GrpcInterface/RiaGrpcGridService.cpp @@ -47,7 +47,7 @@ grpc::Status RiaCellCenterStateHandler::init( const rips::GridRequest* request ) CAF_ASSERT( request ); m_request = request; - RimCase* rimCase = RiaGrpcServiceInterface::findCase( m_request->case_request().id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( m_request->case_request().id() ); m_eclipseCase = dynamic_cast( rimCase ); if ( !m_eclipseCase ) @@ -71,7 +71,7 @@ grpc::Status RiaCellCenterStateHandler::init( const rips::GridRequest* request ) //-------------------------------------------------------------------------------------------------- grpc::Status RiaCellCenterStateHandler::assignReply( rips::CellCenters* reply ) { - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::Vec3d ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::Vec3d ) ); size_t indexInPackage = 0u; reply->mutable_centers()->Reserve( (int)packageSize ); for ( ; indexInPackage < packageSize && m_currentCellIdx < m_grid->cellCount(); ++indexInPackage ) @@ -98,7 +98,7 @@ grpc::Status RiaCellCenterStateHandler::assignReply( rips::CellCenters* reply ) //-------------------------------------------------------------------------------------------------- grpc::Status RiaCellCenterStateHandler::assignCornersReply( rips::CellCornersArray* reply ) { - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::CellCorners ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::CellCorners ) ); size_t indexInPackage = 0u; reply->mutable_cells()->Reserve( (int)packageSize ); @@ -137,7 +137,7 @@ grpc::Status RiaGrpcGridService::GetDimensions( grpc::ServerContext* context const rips::GridRequest* request, rips::GridDimensions* reply ) { - RimCase* rimCase = findCase( request->case_request().id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( request->case_request().id() ); RimEclipseCase* eclipseCase = dynamic_cast( rimCase ); if ( eclipseCase ) diff --git a/GrpcInterface/RiaGrpcGridService.h b/GrpcInterface/RiaGrpcGridService.h index 93f3af5f6e..a3bf1f657d 100644 --- a/GrpcInterface/RiaGrpcGridService.h +++ b/GrpcInterface/RiaGrpcGridService.h @@ -40,7 +40,7 @@ class GridDimensions; //================================================================================================== class RiaCellCenterStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaCellCenterStateHandler(); diff --git a/GrpcInterface/RiaGrpcHelper.cpp b/GrpcInterface/RiaGrpcHelper.cpp index 8de881cd04..2775706663 100644 --- a/GrpcInterface/RiaGrpcHelper.cpp +++ b/GrpcInterface/RiaGrpcHelper.cpp @@ -15,8 +15,18 @@ // for more details. // ////////////////////////////////////////////////////////////////////////////////// + #include "RiaGrpcHelper.h" +#include "RiaApplication.h" +#include "RimCase.h" +#include "RimCommandRouter.h" +#include "RimProject.h" + +#include "PdmObject.pb.h" + +#include "cafPdmObjectScriptingCapabilityRegister.h" + //-------------------------------------------------------------------------------------------------- /// Convert internal ResInsight representation of cells with negative depth to positive depth. //-------------------------------------------------------------------------------------------------- @@ -35,3 +45,63 @@ void RiaGrpcHelper::setCornerValues( rips::Vec3d* out, const cvf::Vec3d& in ) out->set_y( in.y() ); out->set_z( in.z() ); } + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::PdmObject* RiaGrpcHelper::findCafObjectFromRipsObject( const rips::PdmObject& ripsObject ) +{ + QString scriptClassName = QString::fromStdString( ripsObject.class_keyword() ); + uint64_t address = ripsObject.address(); + return findCafObjectFromScriptNameAndAddress( scriptClassName, address ); +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +caf::PdmObject* RiaGrpcHelper::findCafObjectFromScriptNameAndAddress( const QString& scriptClassName, uint64_t address ) +{ + QString classKeyword = caf::PdmObjectScriptingCapabilityRegister::classKeywordFromScriptClassName( scriptClassName ); + + if ( classKeyword == RimCommandRouter::classKeywordStatic() ) return RiaApplication::instance()->commandRouter(); + + RimProject* project = RimProject::current(); + std::vector objectsOfCurrentClass; + + project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass ); + + caf::PdmObject* matchingObject = nullptr; + for ( caf::PdmObject* testObject : objectsOfCurrentClass ) + { + if ( reinterpret_cast( testObject ) == address ) + { + matchingObject = testObject; + } + } + return matchingObject; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +size_t RiaGrpcHelper::numberOfDataUnitsInPackage( size_t dataUnitSize, size_t packageByteCount /*= 64 * 1024u */ ) +{ + size_t dataUnitCount = packageByteCount / dataUnitSize; + return dataUnitCount; +} + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +RimCase* RiaGrpcHelper::findCase( int caseId ) +{ + std::vector cases = RimProject::current()->allGridCases(); + for ( RimCase* rimCase : cases ) + { + if ( caseId == rimCase->caseId() ) + { + return rimCase; + } + } + return nullptr; +} diff --git a/GrpcInterface/RiaGrpcHelper.h b/GrpcInterface/RiaGrpcHelper.h index 4f29389fef..b027876fd6 100644 --- a/GrpcInterface/RiaGrpcHelper.h +++ b/GrpcInterface/RiaGrpcHelper.h @@ -21,6 +21,20 @@ #include "cvfVector3.h" +#include + +class RimCase; + +namespace caf +{ +class PdmObject; +} + +namespace rips +{ +class PdmObject; +} + //================================================================================================== // // Various gRPC helper methods @@ -31,4 +45,10 @@ class RiaGrpcHelper public: static void convertVec3dToPositiveDepth( cvf::Vec3d* vec ); static void setCornerValues( rips::Vec3d* out, const cvf::Vec3d& in ); + + static caf::PdmObject* findCafObjectFromRipsObject( const rips::PdmObject& ripsObject ); + static caf::PdmObject* findCafObjectFromScriptNameAndAddress( const QString& scriptClassName, uint64_t address ); + + static size_t numberOfDataUnitsInPackage( size_t dataUnitSize, size_t packageByteCount = 64 * 1024u ); + static RimCase* findCase( int caseId ); }; diff --git a/GrpcInterface/RiaGrpcNNCPropertiesService.cpp b/GrpcInterface/RiaGrpcNNCPropertiesService.cpp index 7554d42052..4ffcf58c52 100644 --- a/GrpcInterface/RiaGrpcNNCPropertiesService.cpp +++ b/GrpcInterface/RiaGrpcNNCPropertiesService.cpp @@ -19,6 +19,7 @@ #include "RiaGrpcCallbacks.h" #include "RiaGrpcCaseService.h" +#include "RiaGrpcHelper.h" #include "RigCaseCellResultsData.h" #include "RigEclipseCaseData.h" @@ -55,7 +56,7 @@ grpc::Status RiaNNCConnectionsStateHandler::init( const rips::CaseRequest* reque CAF_ASSERT( request ); m_request = request; - RimCase* rimCase = RiaGrpcServiceInterface::findCase( m_request->id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( m_request->id() ); m_eclipseCase = dynamic_cast( rimCase ); if ( !( m_eclipseCase && m_eclipseCase->eclipseCaseData() && m_eclipseCase->eclipseCaseData()->mainGrid() ) ) @@ -93,7 +94,7 @@ grpc::Status RiaNNCConnectionsStateHandler::assignReply( rips::NNCConnections* r const RigConnectionContainer& connections = mainGrid->nncData()->allConnections(); size_t connectionCount = connections.size(); - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( rips::NNCConnection ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( rips::NNCConnection ) ); size_t indexInPackage = 0u; reply->mutable_connections()->Reserve( (int)packageSize ); for ( ; indexInPackage < packageSize && m_currentIdx < connectionCount; ++indexInPackage ) @@ -147,7 +148,7 @@ grpc::Status RiaNNCValuesStateHandler::init( const rips::NNCValuesRequest* reque CAF_ASSERT( request ); m_request = request; - RimCase* rimCase = RiaGrpcServiceInterface::findCase( m_request->case_id() ); + RimCase* rimCase = RiaGrpcHelper::findCase( m_request->case_id() ); m_eclipseCase = dynamic_cast( rimCase ); if ( !( m_eclipseCase && m_eclipseCase->eclipseCaseData() && m_eclipseCase->eclipseCaseData()->mainGrid() ) ) @@ -204,7 +205,7 @@ grpc::Status RiaNNCValuesStateHandler::assignReply( rips::NNCValues* reply ) } size_t connectionCount = connections.size(); - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( double ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( double ) ); size_t indexInPackage = 0u; reply->mutable_values()->Reserve( (int)packageSize ); for ( ; indexInPackage < packageSize && m_currentIdx < connectionCount; ++indexInPackage ) @@ -238,7 +239,7 @@ grpc::Status RiaGrpcNNCPropertiesService::GetAvailableNNCProperties( grpc::Serve const CaseRequest* request, AvailableNNCProperties* reply ) { - RimEclipseCase* eclipseCase = dynamic_cast( RiaGrpcServiceInterface::findCase( request->id() ) ); + RimEclipseCase* eclipseCase = dynamic_cast( RiaGrpcHelper::findCase( request->id() ) ); if ( eclipseCase && eclipseCase->eclipseCaseData() && eclipseCase->eclipseCaseData()->mainGrid() ) { RigNNCData* nncData = eclipseCase->eclipseCaseData()->mainGrid()->nncData(); @@ -332,7 +333,7 @@ std::vector* getOrCreateConnectionScalarResultByName( RigNNCData* nncDat grpc::Status RiaNNCInputValuesStateHandler::init( const NNCValuesInputRequest* request ) { int caseId = request->case_id(); - m_eclipseCase = dynamic_cast( RiaGrpcServiceInterface::findCase( caseId ) ); + m_eclipseCase = dynamic_cast( RiaGrpcHelper::findCase( caseId ) ); if ( m_eclipseCase && m_eclipseCase->eclipseCaseData() && m_eclipseCase->eclipseCaseData()->mainGrid() ) { @@ -341,7 +342,7 @@ grpc::Status RiaNNCInputValuesStateHandler::init( const NNCValuesInputRequest* r m_timeStep = request->time_step(); m_propertyName = QString::fromStdString( request->property_name() ); - RigNNCData* nncData = m_eclipseCase->eclipseCaseData()->mainGrid()->nncData(); + RigNNCData* nncData = m_eclipseCase->eclipseCaseData()->mainGrid()->nncData(); std::vector* resultsToAdd = getOrCreateConnectionScalarResultByName( nncData, m_propertyName, m_timeStep ); if ( !resultsToAdd ) { diff --git a/GrpcInterface/RiaGrpcNNCPropertiesService.h b/GrpcInterface/RiaGrpcNNCPropertiesService.h index cf863e32dc..de5ac7d283 100644 --- a/GrpcInterface/RiaGrpcNNCPropertiesService.h +++ b/GrpcInterface/RiaGrpcNNCPropertiesService.h @@ -34,7 +34,7 @@ class RimEclipseCase; //================================================================================================== class RiaNNCConnectionsStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaNNCConnectionsStateHandler(); @@ -54,7 +54,7 @@ class RiaNNCConnectionsStateHandler //================================================================================================== class RiaNNCValuesStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaNNCValuesStateHandler(); @@ -76,7 +76,7 @@ class RiaNNCValuesStateHandler class RiaNNCInputValuesStateHandler { public: - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaNNCInputValuesStateHandler( bool t = true ); diff --git a/GrpcInterface/RiaGrpcPdmObjectService.cpp b/GrpcInterface/RiaGrpcPdmObjectService.cpp index 84d4478084..de2a0aff45 100644 --- a/GrpcInterface/RiaGrpcPdmObjectService.cpp +++ b/GrpcInterface/RiaGrpcPdmObjectService.cpp @@ -15,12 +15,13 @@ // for more details. // ////////////////////////////////////////////////////////////////////////////////// + #include "RiaGrpcPdmObjectService.h" #include "RiaApplication.h" #include "RiaGrpcCallbacks.h" +#include "RiaGrpcHelper.h" -#include "ProjectDataModelCommands/CommandRouter/RimCommandRouter.h" #include "Rim3dView.h" #include "RimEclipseResultDefinition.h" #include "RimProject.h" @@ -168,7 +169,7 @@ RiaPdmObjectMethodStateHandler::RiaPdmObjectMethodStateHandler( bool clientToSer Status RiaPdmObjectMethodStateHandler::init( const rips::PdmObjectGetterRequest* request ) { CAF_ASSERT( !m_clientToServerStreamer ); - m_fieldOwner = RiaGrpcPdmObjectService::findCafObjectFromRipsObject( request->object() ); + m_fieldOwner = RiaGrpcHelper::findCafObjectFromRipsObject( request->object() ); QString fieldName = QString::fromStdString( request->method() ); std::vector fields = m_fieldOwner->fields(); @@ -220,7 +221,7 @@ Status RiaPdmObjectMethodStateHandler::init( const rips::PdmObjectSetterChunk* c CAF_ASSERT( chunk->has_set_request() ); auto setRequest = chunk->set_request(); auto methodRequest = setRequest.request(); - m_fieldOwner = RiaGrpcPdmObjectService::findCafObjectFromRipsObject( methodRequest.object() ); + m_fieldOwner = RiaGrpcHelper::findCafObjectFromRipsObject( methodRequest.object() ); QString fieldName = QString::fromStdString( methodRequest.method() ); int valueCount = setRequest.data_count(); @@ -230,30 +231,28 @@ Status RiaPdmObjectMethodStateHandler::init( const rips::PdmObjectSetterChunk* c auto scriptability = field->capability(); if ( scriptability && scriptability->scriptFieldName() == fieldName ) { - caf::PdmProxyFieldHandle* proxyField = dynamic_cast( field ); + auto* proxyField = dynamic_cast( field ); if ( proxyField ) { m_proxyField = proxyField; if ( dynamic_cast>*>( field ) ) { - m_dataHolder.reset( new DataHolder>( std::vector( valueCount ) ) ); + m_dataHolder = std::make_unique>>( std::vector( valueCount ) ); return grpc::Status::OK; } - else if ( dynamic_cast>*>( field ) ) + if ( dynamic_cast>*>( field ) ) { - m_dataHolder.reset( new DataHolder>( std::vector( valueCount ) ) ); + m_dataHolder = std::make_unique>>( std::vector( valueCount ) ); return grpc::Status::OK; } - else if ( dynamic_cast>*>( field ) ) + if ( dynamic_cast>*>( field ) ) { - m_dataHolder.reset( new DataHolder>( std::vector( valueCount ) ) ); + m_dataHolder = std::make_unique>>( std::vector( valueCount ) ); return grpc::Status::OK; } - else - { - CAF_ASSERT( false && "The proxy field data type is not yet supported for streaming fields" ); - } + + CAF_ASSERT( false && "The proxy field data type is not yet supported for streaming fields" ); } } } @@ -266,7 +265,7 @@ Status RiaPdmObjectMethodStateHandler::init( const rips::PdmObjectSetterChunk* c Status RiaPdmObjectMethodStateHandler::assignReply( rips::PdmObjectGetterReply* reply ) { CAF_ASSERT( m_dataHolder ); - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( m_dataHolder->dataSizeOf() ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( m_dataHolder->dataSizeOf() ); size_t indexInPackage = 0u; m_dataHolder->reserveReplyStorage( reply ); @@ -377,7 +376,7 @@ grpc::Status RiaGrpcPdmObjectService::GetDescendantPdmObjects( grpc::ServerConte const rips::PdmDescendantObjectRequest* request, rips::PdmObjectArray* reply ) { - auto matchingObject = findCafObjectFromRipsObject( request->object() ); + auto matchingObject = RiaGrpcHelper::findCafObjectFromRipsObject( request->object() ); if ( matchingObject ) { @@ -402,7 +401,7 @@ grpc::Status RiaGrpcPdmObjectService::GetChildPdmObjects( grpc::ServerContext* const rips::PdmChildObjectRequest* request, rips::PdmObjectArray* reply ) { - auto matchingObject = findCafObjectFromRipsObject( request->object() ); + auto matchingObject = RiaGrpcHelper::findCafObjectFromRipsObject( request->object() ); if ( matchingObject ) { QString fieldName = QString::fromStdString( request->child_field() ); @@ -433,7 +432,7 @@ grpc::Status RiaGrpcPdmObjectService::UpdateExistingPdmObject( grpc::ServerConte const rips::PdmObject* request, rips::Empty* response ) { - auto matchingObject = findCafObjectFromRipsObject( *request ); + auto matchingObject = RiaGrpcHelper::findCafObjectFromRipsObject( *request ); if ( matchingObject ) { @@ -459,6 +458,36 @@ grpc::Status RiaGrpcPdmObjectService::UpdateExistingPdmObject( grpc::ServerConte return grpc::Status( grpc::NOT_FOUND, "PdmObject not found" ); } +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +grpc::Status RiaGrpcPdmObjectService::DeleteExistingPdmObject( grpc::ServerContext* context, + const rips::PdmObject* request, + rips::Empty* response ) +{ + auto matchingObject = RiaGrpcHelper::findCafObjectFromRipsObject( *request ); + + if ( matchingObject && matchingObject->parentField() ) + { + auto parentField = matchingObject->parentField(); + parentField->removeChild( matchingObject ); + + auto obj = parentField->ownerObject(); + if ( obj && obj->uiCapability() ) + { + std::vector referringObjects; + + obj->onChildDeleted( nullptr, referringObjects ); + obj->uiCapability()->updateAllRequiredEditors(); + } + + delete matchingObject; + + return grpc::Status::OK; + } + return grpc::Status( grpc::NOT_FOUND, "PdmObject not found" ); +} + //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- @@ -466,7 +495,7 @@ grpc::Status RiaGrpcPdmObjectService::CreateChildPdmObject( grpc::ServerContext* const rips::CreatePdmChildObjectRequest* request, rips::PdmObject* reply ) { - auto matchingObject = findCafObjectFromRipsObject( request->object() ); + auto matchingObject = RiaGrpcHelper::findCafObjectFromRipsObject( request->object() ); if ( matchingObject ) { @@ -517,7 +546,7 @@ grpc::Status RiaGrpcPdmObjectService::CallPdmObjectMethod( grpc::ServerContext* const rips::PdmObjectMethodRequest* request, rips::PdmObject* reply ) { - auto matchingObject = findCafObjectFromRipsObject( request->object() ); + auto matchingObject = RiaGrpcHelper::findCafObjectFromRipsObject( request->object() ); if ( matchingObject ) { QString methodKeyword = QString::fromStdString( request->method() ); @@ -538,15 +567,13 @@ grpc::Status RiaGrpcPdmObjectService::CallPdmObjectMethod( grpc::ServerContext* } return grpc::Status::OK; } - else - { - if ( method->isNullptrValidResult() ) - { - return grpc::Status::OK; - } - return grpc::Status( grpc::NOT_FOUND, "No result returned from Method" ); + if ( method->isNullptrValidResult() ) + { + return grpc::Status::OK; } + + return grpc::Status( grpc::NOT_FOUND, "No result returned from Method" ); } return grpc::Status( grpc::NOT_FOUND, "Could not find Method" ); } @@ -571,6 +598,9 @@ std::vector RiaGrpcPdmObjectService::createCallbacks( new RiaGrpcUnaryCallback( this, &Self::UpdateExistingPdmObject, &Self::RequestUpdateExistingPdmObject ), + new RiaGrpcUnaryCallback( this, + &Self::DeleteExistingPdmObject, + &Self::RequestDeleteExistingPdmObject ), new RiaGrpcUnaryCallback( this, &Self::CreateChildPdmObject, &Self::RequestCreateChildPdmObject ), @@ -596,41 +626,5 @@ std::vector RiaGrpcPdmObjectService::createCallbacks( }; } -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -caf::PdmObject* RiaGrpcPdmObjectService::findCafObjectFromRipsObject( const rips::PdmObject& ripsObject ) -{ - QString scriptClassName = QString::fromStdString( ripsObject.class_keyword() ); - uint64_t address = ripsObject.address(); - return findCafObjectFromScriptNameAndAddress( scriptClassName, address ); -} - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -caf::PdmObject* RiaGrpcPdmObjectService::findCafObjectFromScriptNameAndAddress( const QString& scriptClassName, - uint64_t address ) -{ - QString classKeyword = caf::PdmObjectScriptingCapabilityRegister::classKeywordFromScriptClassName( scriptClassName ); - - if ( classKeyword == RimCommandRouter::classKeywordStatic() ) return RiaApplication::instance()->commandRouter(); - - RimProject* project = RimProject::current(); - std::vector objectsOfCurrentClass; - - project->descendantsIncludingThisFromClassKeyword( classKeyword, objectsOfCurrentClass ); - - caf::PdmObject* matchingObject = nullptr; - for ( caf::PdmObject* testObject : objectsOfCurrentClass ) - { - if ( reinterpret_cast( testObject ) == address ) - { - matchingObject = testObject; - } - } - return matchingObject; -} - static bool RiaGrpcPdmObjectService_init = RiaGrpcServiceFactory::instance()->registerCreator( typeid( RiaGrpcPdmObjectService ).hash_code() ); diff --git a/GrpcInterface/RiaGrpcPdmObjectService.h b/GrpcInterface/RiaGrpcPdmObjectService.h index 2b41195f39..3fae39cb4c 100644 --- a/GrpcInterface/RiaGrpcPdmObjectService.h +++ b/GrpcInterface/RiaGrpcPdmObjectService.h @@ -17,10 +17,10 @@ ////////////////////////////////////////////////////////////////////////////////// #pragma once -#include "PdmObject.grpc.pb.h" #include "RiaGrpcServiceInterface.h" -#include +#include "PdmObject.grpc.pb.h" + #include namespace caf @@ -30,7 +30,7 @@ class PdmProxyFieldHandle; struct AbstractDataHolder { - virtual ~AbstractDataHolder() = default; + virtual ~AbstractDataHolder() = default; virtual size_t dataCount() const = 0; virtual size_t dataSizeOf() const = 0; virtual void reserveReplyStorage( rips::PdmObjectGetterReply* reply ) const = 0; @@ -47,7 +47,7 @@ struct AbstractDataHolder //================================================================================================== class RiaPdmObjectMethodStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: RiaPdmObjectMethodStateHandler( bool clientToServerStreamer = false ); @@ -79,9 +79,11 @@ class RiaGrpcPdmObjectService final : public rips::PdmObjectService::AsyncServic grpc::Status GetAncestorPdmObject( grpc::ServerContext* context, const rips::PdmParentObjectRequest* request, rips::PdmObject* reply ) override; + grpc::Status GetDescendantPdmObjects( grpc::ServerContext* context, const rips::PdmDescendantObjectRequest* request, rips::PdmObjectArray* reply ) override; + grpc::Status GetChildPdmObjects( grpc::ServerContext* context, const rips::PdmChildObjectRequest* request, rips::PdmObjectArray* reply ) override; @@ -94,20 +96,23 @@ class RiaGrpcPdmObjectService final : public rips::PdmObjectService::AsyncServic const rips::PdmObject* request, rips::Empty* response ) override; + grpc::Status DeleteExistingPdmObject( grpc::ServerContext* context, + const rips::PdmObject* request, + rips::Empty* response ) override; + grpc::Status CallPdmObjectGetter( grpc::ServerContext* context, const rips::PdmObjectGetterRequest* request, rips::PdmObjectGetterReply* reply, RiaPdmObjectMethodStateHandler* stateHandler ); + grpc::Status CallPdmObjectSetter( grpc::ServerContext* context, const rips::PdmObjectSetterChunk* chunk, rips::ClientToServerStreamReply* reply, RiaPdmObjectMethodStateHandler* stateHandler ); + grpc::Status CallPdmObjectMethod( grpc::ServerContext* context, const rips::PdmObjectMethodRequest* request, rips::PdmObject* reply ) override; std::vector createCallbacks() override; - - static caf::PdmObject* findCafObjectFromRipsObject( const rips::PdmObject& ripsObject ); - static caf::PdmObject* findCafObjectFromScriptNameAndAddress( const QString& scriptClassName, uint64_t address ); }; diff --git a/GrpcInterface/RiaGrpcProjectService.h b/GrpcInterface/RiaGrpcProjectService.h index 1a33b9f543..fbb7b1e283 100644 --- a/GrpcInterface/RiaGrpcProjectService.h +++ b/GrpcInterface/RiaGrpcProjectService.h @@ -42,7 +42,7 @@ class RiaGrpcProjectService final : public rips::Project::AsyncService, public R grpc::Status GetSelectedCases( grpc::ServerContext* context, const rips::Empty* request, rips::CaseInfoArray* reply ) override; grpc::Status - GetAllCaseGroups( grpc::ServerContext* context, const rips::Empty* request, rips::CaseGroups* reply ) override; + GetAllCaseGroups( grpc::ServerContext* context, const rips::Empty* request, rips::CaseGroups* reply ) override; grpc::Status GetAllCases( grpc::ServerContext* context, const rips::Empty* request, rips::CaseInfoArray* reply ) override; grpc::Status GetCasesInGroup( grpc::ServerContext* context, const rips::CaseGroup* request, diff --git a/GrpcInterface/RiaGrpcPropertiesService.cpp b/GrpcInterface/RiaGrpcPropertiesService.cpp index 2236a5bd21..469ab22124 100644 --- a/GrpcInterface/RiaGrpcPropertiesService.cpp +++ b/GrpcInterface/RiaGrpcPropertiesService.cpp @@ -19,6 +19,7 @@ #include "RiaGrpcCallbacks.h" #include "RiaGrpcCaseService.h" +#include "RiaGrpcHelper.h" #include "RigActiveCellInfo.h" #include "RigActiveCellsResultAccessor.h" @@ -52,7 +53,7 @@ using namespace rips; class RiaCellResultsStateHandler { - typedef grpc::Status Status; + using Status = grpc::Status; public: //-------------------------------------------------------------------------------------------------- @@ -83,7 +84,7 @@ class RiaCellResultsStateHandler Status init( const PropertyRequest* request ) { int caseId = request->case_request().id(); - m_eclipseCase = dynamic_cast( RiaGrpcServiceInterface::findCase( caseId ) ); + m_eclipseCase = dynamic_cast( RiaGrpcHelper::findCase( caseId ) ); if ( m_eclipseCase ) { @@ -147,7 +148,7 @@ class RiaCellResultsStateHandler Status assignStreamReply( PropertyChunk* reply ) { // How many data units will fit into one stream package? - const size_t packageSize = RiaGrpcServiceInterface::numberOfDataUnitsInPackage( sizeof( double ) ); + const size_t packageSize = RiaGrpcHelper::numberOfDataUnitsInPackage( sizeof( double ) ); size_t indexInPackage = 0u; reply->mutable_values()->Reserve( (int)packageSize ); @@ -405,7 +406,7 @@ grpc::Status RiaGrpcPropertiesService::GetAvailableProperties( grpc::ServerConte AvailableProperties* reply ) { int caseId = request->case_request().id(); - RimEclipseCase* eclipseCase = dynamic_cast( RiaGrpcServiceInterface::findCase( caseId ) ); + RimEclipseCase* eclipseCase = dynamic_cast( RiaGrpcHelper::findCase( caseId ) ); if ( eclipseCase ) { auto porosityModel = static_cast( request->porosity_model() ); diff --git a/GrpcInterface/RiaGrpcServiceInterface.cpp b/GrpcInterface/RiaGrpcServiceInterface.cpp index 76c4bddddf..5b87695944 100644 --- a/GrpcInterface/RiaGrpcServiceInterface.cpp +++ b/GrpcInterface/RiaGrpcServiceInterface.cpp @@ -19,7 +19,6 @@ #include "RiaGrpcServiceInterface.h" #include "RiaLogging.h" -#include "RimCase.h" #include "RimProject.h" #include "cafPdmAbstractFieldScriptingCapability.h" @@ -39,32 +38,6 @@ #include #include -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -RimCase* RiaGrpcServiceInterface::findCase( int caseId ) -{ - std::vector cases = RimProject::current()->allGridCases(); - for ( RimCase* rimCase : cases ) - { - if ( caseId == rimCase->caseId() ) - { - return rimCase; - } - } - return nullptr; -} - -//-------------------------------------------------------------------------------------------------- -/// Find the number of data items that will fit in the given bytes. -/// The default argument for numBytesWantedInPackage is meant to be a sensible size for GRPC. -//-------------------------------------------------------------------------------------------------- -size_t RiaGrpcServiceInterface::numberOfDataUnitsInPackage( size_t dataUnitSize, size_t packageByteCount /*= 64 * 1024u*/ ) -{ - size_t dataUnitCount = packageByteCount / dataUnitSize; - return dataUnitCount; -} - //-------------------------------------------------------------------------------------------------- /// //-------------------------------------------------------------------------------------------------- diff --git a/GrpcInterface/RiaGrpcServiceInterface.h b/GrpcInterface/RiaGrpcServiceInterface.h index 465733f86c..579fc65b0d 100644 --- a/GrpcInterface/RiaGrpcServiceInterface.h +++ b/GrpcInterface/RiaGrpcServiceInterface.h @@ -22,7 +22,6 @@ #include class RiaGrpcCallbackInterface; -class RimCase; namespace caf { @@ -52,18 +51,11 @@ class RiaGrpcServiceInterface public: virtual std::vector createCallbacks() = 0; virtual ~RiaGrpcServiceInterface() = default; - static RimCase* findCase( int caseId ); - static size_t numberOfDataUnitsInPackage( size_t dataUnitSize, size_t packageByteCount = 64 * 1024u ); +protected: static void copyPdmObjectFromCafToRips( const caf::PdmObjectHandle* source, rips::PdmObject* destination ); static void copyPdmObjectFromRipsToCaf( const rips::PdmObject* source, caf::PdmObjectHandle* destination ); - static bool assignFieldValue( const QString& stringValue, - caf::PdmFieldHandle* field, - QVariant* oldValue, - QVariant* newValue, - caf::PdmScriptIOMessages* messages ); - static caf::PdmObjectHandle* emplaceChildField( caf::PdmObject* parent, const QString& fieldKeyword, const QString& keywordForClassToCreate ); @@ -71,7 +63,13 @@ class RiaGrpcServiceInterface const QString& keywordForClassToCreate ); static caf::PdmObjectHandle* emplaceChildArrayField( caf::PdmChildArrayFieldHandle* childArrayField, const QString& keywordForClassToCreate ); + + static bool assignFieldValue( const QString& stringValue, + caf::PdmFieldHandle* field, + QVariant* oldValue, + QVariant* newValue, + caf::PdmScriptIOMessages* messages ); }; #include "cafFactory.h" -typedef caf::Factory RiaGrpcServiceFactory; +using RiaGrpcServiceFactory = caf::Factory; diff --git a/GrpcInterface/RiaGrpcSimulationWellService.cpp b/GrpcInterface/RiaGrpcSimulationWellService.cpp index 180cefda6e..761a38d46a 100644 --- a/GrpcInterface/RiaGrpcSimulationWellService.cpp +++ b/GrpcInterface/RiaGrpcSimulationWellService.cpp @@ -18,6 +18,7 @@ #include "RiaGrpcSimulationWellService.h" #include "RiaGrpcCallbacks.h" +#include "RiaGrpcHelper.h" #include "RigEclipseCaseData.h" #include "RigGridBase.h" @@ -40,7 +41,7 @@ grpc::Status RiaGrpcSimulationWellService::GetSimulationWellStatus( grpc::Server rips::SimulationWellStatus* reply ) { - RimEclipseCase* eclipseCase = dynamic_cast( findCase( request->case_id() ) ); + RimEclipseCase* eclipseCase = dynamic_cast( RiaGrpcHelper::findCase( request->case_id() ) ); if ( !eclipseCase ) { return grpc::Status( grpc::NOT_FOUND, "Case not found" ); @@ -91,7 +92,7 @@ grpc::Status RiaGrpcSimulationWellService::GetSimulationWellCells( grpc::ServerC const rips::SimulationWellRequest* request, rips::SimulationWellCellInfoArray* reply ) { - RimEclipseCase* eclipseCase = dynamic_cast( findCase( request->case_id() ) ); + RimEclipseCase* eclipseCase = dynamic_cast( RiaGrpcHelper::findCase( request->case_id() ) ); if ( !eclipseCase ) { return grpc::Status( grpc::NOT_FOUND, "Case not found" ); diff --git a/OctavePlugin/riGetActiveCellInfo.cpp b/OctavePlugin/riGetActiveCellInfo.cpp index 8b389d0704..9b8e07744d 100644 --- a/OctavePlugin/riGetActiveCellInfo.cpp +++ b/OctavePlugin/riGetActiveCellInfo.cpp @@ -63,7 +63,12 @@ void getActiveCellInfo(int32NDArray& activeCellInfo, const QString &hostName, qu return; } +#if OCTAVE_MAJOR_VERSION > 6 + auto internalMatrixData = (qint32*)activeCellInfo.fortran_vec(); +#else qint32* internalMatrixData = (qint32*)activeCellInfo.fortran_vec()->mex_get_data(); +#endif + QStringList errorMessages; if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), columnCount * byteCountForOneTimestep, errorMessages)) { diff --git a/OctavePlugin/riGetSelectedCells.cpp b/OctavePlugin/riGetSelectedCells.cpp index 6c5783f3fa..157549ac5e 100644 --- a/OctavePlugin/riGetSelectedCells.cpp +++ b/OctavePlugin/riGetSelectedCells.cpp @@ -63,7 +63,12 @@ void getSelectedCells(int32NDArray& selectedCellInfo, const QString &hostName, q return; } +#if OCTAVE_MAJOR_VERSION > 6 + auto internalMatrixData = (qint32*)selectedCellInfo.fortran_vec(); +#else qint32* internalMatrixData = (qint32*)selectedCellInfo.fortran_vec()->mex_get_data(); +#endif + QStringList errorMessages; if (!RiaSocketDataTransfer::readBlockDataFromSocket(&socket, (char*)(internalMatrixData), columnCount * byteCountForOneTimestep, errorMessages)) { diff --git a/OctavePlugin/riSetActiveCellProperty.cpp b/OctavePlugin/riSetActiveCellProperty.cpp index 370af8e39f..91edf8f9cd 100644 --- a/OctavePlugin/riSetActiveCellProperty.cpp +++ b/OctavePlugin/riSetActiveCellProperty.cpp @@ -54,7 +54,11 @@ void setEclipseProperty(const Matrix& propertyFrames, const QString &hostName, q socketStream << (qint64)(timeStepCount); socketStream << (qint64)timeStepByteCount; +#if OCTAVE_MAJOR_VERSION > 6 + auto internalData = propertyFrames.data(); +#else const double* internalData = propertyFrames.fortran_vec(); +#endif QStringList errorMessages; if (!RiaSocketDataTransfer::writeBlockDataToSocket(&socket, (const char *)internalData, timeStepByteCount*timeStepCount, errorMessages)) @@ -135,15 +139,6 @@ DEFUN_DLD (riSetActiveCellProperty, args, nargout, Matrix propertyFrames = args(0).matrix_value(); - if (error_state) - { - error("riSetActiveCellProperty: The supplied first argument is not a valid Matrix"); - print_usage(); - - return octave_value_list (); - } - - dim_vector mxDims = propertyFrames.dims(); if (mxDims.length() != 2) { diff --git a/OctavePlugin/riSetGridProperty.cpp b/OctavePlugin/riSetGridProperty.cpp index 199f68bcf6..9a77e17173 100644 --- a/OctavePlugin/riSetGridProperty.cpp +++ b/OctavePlugin/riSetGridProperty.cpp @@ -71,7 +71,11 @@ void setEclipseProperty(const NDArray& propertyFrames, const QString &hostName, socketStream << (qint64)(timeStepCount); socketStream << (qint64)singleTimeStepByteCount; +#if OCTAVE_MAJOR_VERSION > 6 + auto internalData = propertyFrames.data(); +#else const double* internalData = propertyFrames.fortran_vec(); +#endif QStringList errorMessages; if (!RiaSocketDataTransfer::writeBlockDataToSocket(&socket, (const char *)internalData, timeStepCount*singleTimeStepByteCount, errorMessages)) @@ -155,14 +159,6 @@ DEFUN_DLD (riSetGridProperty, args, nargout, NDArray propertyFrames = args(0).array_value(); - if (error_state) - { - error("riSetGridProperty: The supplied first argument is not a valid Matrix"); - print_usage(); - - return octave_value_list (); - } - dim_vector mxDims = propertyFrames.dims(); if (!(mxDims.length() == 3 || mxDims.length() == 4)) diff --git a/OctavePlugin/riSetNNCProperty.cpp b/OctavePlugin/riSetNNCProperty.cpp index 0660ba75cc..f58e7f56e6 100644 --- a/OctavePlugin/riSetNNCProperty.cpp +++ b/OctavePlugin/riSetNNCProperty.cpp @@ -135,14 +135,6 @@ DEFUN_DLD (riSetNNCProperty, args, nargout, Matrix propertyFrames = args(0).matrix_value(); - if (error_state) - { - error("riSetNNCProperty: The supplied first argument is not a valid Matrix"); - print_usage(); - - return octave_value_list (); - } - dim_vector mxDims = propertyFrames.dims(); if (mxDims.length() != 2) diff --git a/ResInsightVersion.cmake b/ResInsightVersion.cmake index 1c5132da43..b7fdbae98b 100644 --- a/ResInsightVersion.cmake +++ b/ResInsightVersion.cmake @@ -1,17 +1,17 @@ -set(RESINSIGHT_MAJOR_VERSION 2023) -set(RESINSIGHT_MINOR_VERSION 12) +set(RESINSIGHT_MAJOR_VERSION 2024) +set(RESINSIGHT_MINOR_VERSION 03) set(RESINSIGHT_PATCH_VERSION 0) # Opional text with no restrictions #set(RESINSIGHT_VERSION_TEXT "-dev") -#set(RESINSIGHT_VERSION_TEXT "-RC_03") +#set(RESINSIGHT_VERSION_TEXT "-RC_05") # Optional text # Must be unique and increasing within one combination of major/minor/patch version # The uniqueness of this text is independent of RESINSIGHT_VERSION_TEXT # Format of text must be ".xx" -#set(RESINSIGHT_DEV_VERSION ".11") +#set(RESINSIGHT_DEV_VERSION ".24") # https://github.com/CRAVA/crava/tree/master/libs/nrlib set(NRLIB_GITHUB_SHA "ba35d4359882f1c6f5e9dc30eb95fe52af50fd6f") diff --git a/ThirdParty/custom-opm-common/custom-opm-parser-tests/CMakeLists.txt b/ThirdParty/custom-opm-common/custom-opm-parser-tests/CMakeLists.txt index 86f36e8611..250ee97d26 100644 --- a/ThirdParty/custom-opm-common/custom-opm-parser-tests/CMakeLists.txt +++ b/ThirdParty/custom-opm-common/custom-opm-parser-tests/CMakeLists.txt @@ -1,16 +1,25 @@ -cmake_minimum_required (VERSION 2.8.12) project ( opm-parser-tests ) +include(FetchContent) +FetchContent_Declare( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.11.0 +) +FetchContent_MakeAvailable(googletest) + +set(THREADS_PREFER_PTHREAD_FLAG ON) + +set( PROJECT_FILES opm-parser-BasicTest.cpp ) + +# add the executable +add_executable (${PROJECT_NAME} ${PROJECT_FILES} ) + # Languages and global compiler settings -if(CMAKE_VERSION VERSION_LESS 3.8) - message(WARNING "CMake version does not support c++17, guessing -std=c++17") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17") -else() - set(CMAKE_CXX_STANDARD 17) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - set(CMAKE_CXX_EXTENSIONS OFF) -endif() +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) if (MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) # VS 2017 : Disable warnings from from gtest code, using deprecated code related to TR1 @@ -21,38 +30,16 @@ CONFIGURE_FILE( ${CMAKE_CURRENT_LIST_DIR}/OpmTestDataDirectory.h.cmake ${CMAKE_BINARY_DIR}/Generated/OpmTestDataDirectory.h ) -include_directories ( - ${CMAKE_CURRENT_SOURCE_DIR}/../.. - ${CMAKE_BINARY_DIR}/Generated -# ${CMAKE_CURRENT_SOURCE_DIR}/../opm-parser - -# ${CMAKE_CURRENT_SOURCE_DIR}/../../custom-opm-common/opm-common - - # ${ERT_INCLUDE_DIRS} - - # ${Boost_INCLUDE_DIRS} -) - -set( PROJECT_FILES - - opm-parser_UnitTests.cpp - ../../gtest/gtest-all.cc - - opm-parser-BasicTest.cpp -) - -# add the executable -add_executable (${PROJECT_NAME} - ${PROJECT_FILES} -) - -source_group("" FILES ${PROJECT_FILES}) +target_include_directories (${PROJECT_NAME} PUBLIC ${CMAKE_BINARY_DIR}/Generated ) target_link_libraries ( ${PROJECT_NAME} custom-opm-common + GTest::gtest_main ) # Add dependency of Shlwapi.lib for Windows platforms if (MSVC) target_link_libraries(${PROJECT_NAME} Shlwapi) -endif() \ No newline at end of file +endif() + +add_test(NAME ${PROJECT_NAME} COMMAND ${PROJECT_NAME}) \ No newline at end of file diff --git a/ThirdParty/custom-opm-common/custom-opm-parser-tests/opm-parser_UnitTests.cpp b/ThirdParty/custom-opm-common/custom-opm-parser-tests/opm-parser_UnitTests.cpp deleted file mode 100644 index 9fb2e675fb..0000000000 --- a/ThirdParty/custom-opm-common/custom-opm-parser-tests/opm-parser_UnitTests.cpp +++ /dev/null @@ -1,20 +0,0 @@ - - -#include "gtest/gtest.h" -#include -#include -#include - -//-------------------------------------------------------------------------------------------------- -/// -//-------------------------------------------------------------------------------------------------- -int main(int argc, char **argv) -{ - testing::InitGoogleTest(&argc, argv); - int result = RUN_ALL_TESTS(); - - char text[5]; - std::cin.getline(text, 5); - - return result; -} \ No newline at end of file diff --git a/ThirdParty/custom-opm-common/opm-common b/ThirdParty/custom-opm-common/opm-common index 046ed00ac6..a76421efff 160000 --- a/ThirdParty/custom-opm-common/opm-common +++ b/ThirdParty/custom-opm-common/opm-common @@ -1 +1 @@ -Subproject commit 046ed00ac67c5991768de21913ca2ef497ddb9cf +Subproject commit a76421efffb45ae42831a5a5a8cc7e2bddbf5b8e diff --git a/ThirdParty/gtest/gtest-all.cc b/ThirdParty/gtest/gtest-all.cc deleted file mode 100644 index cef5397fde..0000000000 --- a/ThirdParty/gtest/gtest-all.cc +++ /dev/null @@ -1,11824 +0,0 @@ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// Google C++ Testing and Mocking Framework (Google Test) -// -// Sometimes it's desirable to build Google Test by compiling a single file. -// This file serves this purpose. - -// This line ensures that gtest.h can be compiled on its own, even -// when it's fused. -#include "gtest/gtest.h" - -// The following lines pull in the real gtest *.cc files. -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// The Google C++ Testing and Mocking Framework (Google Test) - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// Utilities for testing Google Test itself and code that uses Google Test -// (e.g. frameworks built on top of Google Test). - -// GOOGLETEST_CM0004 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ -#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ - - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -namespace testing { - -// This helper class can be used to mock out Google Test failure reporting -// so that we can test Google Test or code that builds on Google Test. -// -// An object of this class appends a TestPartResult object to the -// TestPartResultArray object given in the constructor whenever a Google Test -// failure is reported. It can either intercept only failures that are -// generated in the same thread that created this object or it can intercept -// all generated failures. The scope of this mock object can be controlled with -// the second argument to the two arguments constructor. -class GTEST_API_ ScopedFakeTestPartResultReporter - : public TestPartResultReporterInterface { - public: - // The two possible mocking modes of this object. - enum InterceptMode { - INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. - INTERCEPT_ALL_THREADS // Intercepts all failures. - }; - - // The c'tor sets this object as the test part result reporter used - // by Google Test. The 'result' parameter specifies where to report the - // results. This reporter will only catch failures generated in the current - // thread. DEPRECATED - explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); - - // Same as above, but you can choose the interception scope of this object. - ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, - TestPartResultArray* result); - - // The d'tor restores the previous test part result reporter. - ~ScopedFakeTestPartResultReporter() override; - - // Appends the TestPartResult object to the TestPartResultArray - // received in the constructor. - // - // This method is from the TestPartResultReporterInterface - // interface. - void ReportTestPartResult(const TestPartResult& result) override; - - private: - void Init(); - - const InterceptMode intercept_mode_; - TestPartResultReporterInterface* old_reporter_; - TestPartResultArray* const result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); -}; - -namespace internal { - -// A helper class for implementing EXPECT_FATAL_FAILURE() and -// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given -// TestPartResultArray contains exactly one failure that has the given -// type and contains the given substring. If that's not the case, a -// non-fatal failure will be generated. -class GTEST_API_ SingleFailureChecker { - public: - // The constructor remembers the arguments. - SingleFailureChecker(const TestPartResultArray* results, - TestPartResult::Type type, const std::string& substr); - ~SingleFailureChecker(); - private: - const TestPartResultArray* const results_; - const TestPartResult::Type type_; - const std::string substr_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); -}; - -} // namespace internal - -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -// A set of macros for testing Google Test assertions or code that's expected -// to generate Google Test fatal failures. It verifies that the given -// statement will cause exactly one fatal Google Test failure with 'substr' -// being part of the failure message. -// -// There are two different versions of this macro. EXPECT_FATAL_FAILURE only -// affects and considers failures generated in the current thread and -// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. -// -// The verification of the assertion is done correctly even when the statement -// throws an exception or aborts the current function. -// -// Known restrictions: -// - 'statement' cannot reference local non-static variables or -// non-static members of the current object. -// - 'statement' cannot return a value. -// - You cannot stream a failure message to this macro. -// -// Note that even though the implementations of the following two -// macros are much alike, we cannot refactor them to use a common -// helper macro, due to some peculiarity in how the preprocessor -// works. The AcceptsMacroThatExpandsToUnprotectedComma test in -// gtest_unittest.cc will fail to compile if we do that. -#define EXPECT_FATAL_FAILURE(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ - } while (::testing::internal::AlwaysFalse()) - -#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do { \ - class GTestExpectFatalFailureHelper {\ - public:\ - static void Execute() { statement; }\ - };\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ALL_THREADS, >est_failures);\ - GTestExpectFatalFailureHelper::Execute();\ - }\ - } while (::testing::internal::AlwaysFalse()) - -// A macro for testing Google Test assertions or code that's expected to -// generate Google Test non-fatal failures. It asserts that the given -// statement will cause exactly one non-fatal Google Test failure with 'substr' -// being part of the failure message. -// -// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only -// affects and considers failures generated in the current thread and -// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. -// -// 'statement' is allowed to reference local variables and members of -// the current object. -// -// The verification of the assertion is done correctly even when the statement -// throws an exception or aborts the current function. -// -// Known restrictions: -// - You cannot stream a failure message to this macro. -// -// Note that even though the implementations of the following two -// macros are much alike, we cannot refactor them to use a common -// helper macro, due to some peculiarity in how the preprocessor -// works. If we do that, the code won't compile when the user gives -// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that -// expands to code containing an unprotected comma. The -// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc -// catches that. -// -// For the same reason, we have to write -// if (::testing::internal::AlwaysTrue()) { statement; } -// instead of -// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) -// to avoid an MSVC warning on unreachable code. -#define EXPECT_NONFATAL_FAILURE(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter:: \ - INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ - } while (::testing::internal::AlwaysFalse()) - -#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ - do {\ - ::testing::TestPartResultArray gtest_failures;\ - ::testing::internal::SingleFailureChecker gtest_checker(\ - >est_failures, ::testing::TestPartResult::kNonFatalFailure, \ - (substr));\ - {\ - ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ - ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ - >est_failures);\ - if (::testing::internal::AlwaysTrue()) { statement; }\ - }\ - } while (::testing::internal::AlwaysFalse()) - -#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include // NOLINT -#include -#include - -#if GTEST_OS_LINUX - -# define GTEST_HAS_GETTIMEOFDAY_ 1 - -# include // NOLINT -# include // NOLINT -# include // NOLINT -// Declares vsnprintf(). This header is not available on Windows. -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include - -#elif GTEST_OS_ZOS -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT - -// On z/OS we additionally need strings.h for strcasecmp. -# include // NOLINT - -#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. - -# include // NOLINT -# undef min - -#elif GTEST_OS_WINDOWS // We are on Windows proper. - -# include // NOLINT -# undef min - -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT - -# if GTEST_OS_WINDOWS_MINGW -// MinGW has gettimeofday() but not _ftime64(). -# define GTEST_HAS_GETTIMEOFDAY_ 1 -# include // NOLINT -# endif // GTEST_OS_WINDOWS_MINGW - -#else - -// Assume other platforms have gettimeofday(). -# define GTEST_HAS_GETTIMEOFDAY_ 1 - -// cpplint thinks that the header is already included, so we want to -// silence it. -# include // NOLINT -# include // NOLINT - -#endif // GTEST_OS_LINUX - -#if GTEST_HAS_EXCEPTIONS -# include -#endif - -#if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT -# include // NOLINT -# include // NOLINT -#endif - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Utility functions and classes used by the Google C++ testing framework.// -// This file contains purely Google Test's internal implementation. Please -// DO NOT #INCLUDE IT IN A USER PROGRAM. - -#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ -#define GTEST_SRC_GTEST_INTERNAL_INL_H_ - -#ifndef _WIN32_WCE -# include -#endif // !_WIN32_WCE -#include -#include // For strtoll/_strtoul64/malloc/free. -#include // For memmove. - -#include -#include -#include -#include - - -#if GTEST_CAN_STREAM_RESULTS_ -# include // NOLINT -# include // NOLINT -#endif - -#if GTEST_OS_WINDOWS -# include // NOLINT -#endif // GTEST_OS_WINDOWS - - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -namespace testing { - -// Declares the flags. -// -// We don't want the users to modify this flag in the code, but want -// Google Test's own unit tests to be able to access it. Therefore we -// declare it here as opposed to in gtest.h. -GTEST_DECLARE_bool_(death_test_use_fork); - -namespace internal { - -// The value of GetTestTypeId() as seen from within the Google Test -// library. This is solely for testing GetTestTypeId(). -GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; - -// Names of the flags (needed for parsing Google Test flags). -const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; -const char kBreakOnFailureFlag[] = "break_on_failure"; -const char kCatchExceptionsFlag[] = "catch_exceptions"; -const char kColorFlag[] = "color"; -const char kFilterFlag[] = "filter"; -const char kListTestsFlag[] = "list_tests"; -const char kOutputFlag[] = "output"; -const char kPrintTimeFlag[] = "print_time"; -const char kPrintUTF8Flag[] = "print_utf8"; -const char kRandomSeedFlag[] = "random_seed"; -const char kRepeatFlag[] = "repeat"; -const char kShuffleFlag[] = "shuffle"; -const char kStackTraceDepthFlag[] = "stack_trace_depth"; -const char kStreamResultToFlag[] = "stream_result_to"; -const char kThrowOnFailureFlag[] = "throw_on_failure"; -const char kFlagfileFlag[] = "flagfile"; - -// A valid random seed must be in [1, kMaxRandomSeed]. -const int kMaxRandomSeed = 99999; - -// g_help_flag is true if and only if the --help flag or an equivalent form -// is specified on the command line. -GTEST_API_ extern bool g_help_flag; - -// Returns the current time in milliseconds. -GTEST_API_ TimeInMillis GetTimeInMillis(); - -// Returns true if and only if Google Test should use colors in the output. -GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); - -// Formats the given time in milliseconds as seconds. -GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); - -// Converts the given time in milliseconds to a date string in the ISO 8601 -// format, without the timezone information. N.B.: due to the use the -// non-reentrant localtime() function, this function is not thread safe. Do -// not use it in any code that can be called from multiple threads. -GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); - -// Parses a string for an Int32 flag, in the form of "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -GTEST_API_ bool ParseInt32Flag( - const char* str, const char* flag, Int32* value); - -// Returns a random seed in range [1, kMaxRandomSeed] based on the -// given --gtest_random_seed flag value. -inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { - const unsigned int raw_seed = (random_seed_flag == 0) ? - static_cast(GetTimeInMillis()) : - static_cast(random_seed_flag); - - // Normalizes the actual seed to range [1, kMaxRandomSeed] such that - // it's easy to type. - const int normalized_seed = - static_cast((raw_seed - 1U) % - static_cast(kMaxRandomSeed)) + 1; - return normalized_seed; -} - -// Returns the first valid random seed after 'seed'. The behavior is -// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is -// considered to be 1. -inline int GetNextRandomSeed(int seed) { - GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) - << "Invalid random seed " << seed << " - must be in [1, " - << kMaxRandomSeed << "]."; - const int next_seed = seed + 1; - return (next_seed > kMaxRandomSeed) ? 1 : next_seed; -} - -// This class saves the values of all Google Test flags in its c'tor, and -// restores them in its d'tor. -class GTestFlagSaver { - public: - // The c'tor. - GTestFlagSaver() { - also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); - break_on_failure_ = GTEST_FLAG(break_on_failure); - catch_exceptions_ = GTEST_FLAG(catch_exceptions); - color_ = GTEST_FLAG(color); - death_test_style_ = GTEST_FLAG(death_test_style); - death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); - filter_ = GTEST_FLAG(filter); - internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); - list_tests_ = GTEST_FLAG(list_tests); - output_ = GTEST_FLAG(output); - print_time_ = GTEST_FLAG(print_time); - print_utf8_ = GTEST_FLAG(print_utf8); - random_seed_ = GTEST_FLAG(random_seed); - repeat_ = GTEST_FLAG(repeat); - shuffle_ = GTEST_FLAG(shuffle); - stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); - stream_result_to_ = GTEST_FLAG(stream_result_to); - throw_on_failure_ = GTEST_FLAG(throw_on_failure); - } - - // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. - ~GTestFlagSaver() { - GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; - GTEST_FLAG(break_on_failure) = break_on_failure_; - GTEST_FLAG(catch_exceptions) = catch_exceptions_; - GTEST_FLAG(color) = color_; - GTEST_FLAG(death_test_style) = death_test_style_; - GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; - GTEST_FLAG(filter) = filter_; - GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; - GTEST_FLAG(list_tests) = list_tests_; - GTEST_FLAG(output) = output_; - GTEST_FLAG(print_time) = print_time_; - GTEST_FLAG(print_utf8) = print_utf8_; - GTEST_FLAG(random_seed) = random_seed_; - GTEST_FLAG(repeat) = repeat_; - GTEST_FLAG(shuffle) = shuffle_; - GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; - GTEST_FLAG(stream_result_to) = stream_result_to_; - GTEST_FLAG(throw_on_failure) = throw_on_failure_; - } - - private: - // Fields for saving the original values of flags. - bool also_run_disabled_tests_; - bool break_on_failure_; - bool catch_exceptions_; - std::string color_; - std::string death_test_style_; - bool death_test_use_fork_; - std::string filter_; - std::string internal_run_death_test_; - bool list_tests_; - std::string output_; - bool print_time_; - bool print_utf8_; - internal::Int32 random_seed_; - internal::Int32 repeat_; - bool shuffle_; - internal::Int32 stack_trace_depth_; - std::string stream_result_to_; - bool throw_on_failure_; -} GTEST_ATTRIBUTE_UNUSED_; - -// Converts a Unicode code point to a narrow string in UTF-8 encoding. -// code_point parameter is of type UInt32 because wchar_t may not be -// wide enough to contain a code point. -// If the code_point is not a valid Unicode code point -// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted -// to "(Invalid Unicode 0xXXXXXXXX)". -GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); - -// Converts a wide string to a narrow string in UTF-8 encoding. -// The wide string is assumed to have the following encoding: -// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) -// UTF-32 if sizeof(wchar_t) == 4 (on Linux) -// Parameter str points to a null-terminated wide string. -// Parameter num_chars may additionally limit the number -// of wchar_t characters processed. -1 is used when the entire string -// should be processed. -// If the string contains code points that are not valid Unicode code points -// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding -// and contains invalid UTF-16 surrogate pairs, values in those pairs -// will be encoded as individual Unicode characters from Basic Normal Plane. -GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); - -// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file -// if the variable is present. If a file already exists at this location, this -// function will write over it. If the variable is present, but the file cannot -// be created, prints an error and exits. -void WriteToShardStatusFileIfNeeded(); - -// Checks whether sharding is enabled by examining the relevant -// environment variable values. If the variables are present, -// but inconsistent (e.g., shard_index >= total_shards), prints -// an error and exits. If in_subprocess_for_death_test, sharding is -// disabled because it must only be applied to the original test -// process. Otherwise, we could filter out death tests we intended to execute. -GTEST_API_ bool ShouldShard(const char* total_shards_str, - const char* shard_index_str, - bool in_subprocess_for_death_test); - -// Parses the environment variable var as an Int32. If it is unset, -// returns default_val. If it is not an Int32, prints an error and -// and aborts. -GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); - -// Given the total number of shards, the shard index, and the test id, -// returns true if and only if the test should be run on this shard. The test id -// is some arbitrary but unique non-negative integer assigned to each test -// method. Assumes that 0 <= shard_index < total_shards. -GTEST_API_ bool ShouldRunTestOnShard( - int total_shards, int shard_index, int test_id); - -// STL container utilities. - -// Returns the number of elements in the given container that satisfy -// the given predicate. -template -inline int CountIf(const Container& c, Predicate predicate) { - // Implemented as an explicit loop since std::count_if() in libCstd on - // Solaris has a non-standard signature. - int count = 0; - for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { - if (predicate(*it)) - ++count; - } - return count; -} - -// Applies a function/functor to each element in the container. -template -void ForEach(const Container& c, Functor functor) { - std::for_each(c.begin(), c.end(), functor); -} - -// Returns the i-th element of the vector, or default_value if i is not -// in range [0, v.size()). -template -inline E GetElementOr(const std::vector& v, int i, E default_value) { - return (i < 0 || i >= static_cast(v.size())) ? default_value - : v[static_cast(i)]; -} - -// Performs an in-place shuffle of a range of the vector's elements. -// 'begin' and 'end' are element indices as an STL-style range; -// i.e. [begin, end) are shuffled, where 'end' == size() means to -// shuffle to the end of the vector. -template -void ShuffleRange(internal::Random* random, int begin, int end, - std::vector* v) { - const int size = static_cast(v->size()); - GTEST_CHECK_(0 <= begin && begin <= size) - << "Invalid shuffle range start " << begin << ": must be in range [0, " - << size << "]."; - GTEST_CHECK_(begin <= end && end <= size) - << "Invalid shuffle range finish " << end << ": must be in range [" - << begin << ", " << size << "]."; - - // Fisher-Yates shuffle, from - // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle - for (int range_width = end - begin; range_width >= 2; range_width--) { - const int last_in_range = begin + range_width - 1; - const int selected = - begin + - static_cast(random->Generate(static_cast(range_width))); - std::swap((*v)[static_cast(selected)], - (*v)[static_cast(last_in_range)]); - } -} - -// Performs an in-place shuffle of the vector's elements. -template -inline void Shuffle(internal::Random* random, std::vector* v) { - ShuffleRange(random, 0, static_cast(v->size()), v); -} - -// A function for deleting an object. Handy for being used as a -// functor. -template -static void Delete(T* x) { - delete x; -} - -// A predicate that checks the key of a TestProperty against a known key. -// -// TestPropertyKeyIs is copyable. -class TestPropertyKeyIs { - public: - // Constructor. - // - // TestPropertyKeyIs has NO default constructor. - explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} - - // Returns true if and only if the test name of test property matches on key_. - bool operator()(const TestProperty& test_property) const { - return test_property.key() == key_; - } - - private: - std::string key_; -}; - -// Class UnitTestOptions. -// -// This class contains functions for processing options the user -// specifies when running the tests. It has only static members. -// -// In most cases, the user can specify an option using either an -// environment variable or a command line flag. E.g. you can set the -// test filter using either GTEST_FILTER or --gtest_filter. If both -// the variable and the flag are present, the latter overrides the -// former. -class GTEST_API_ UnitTestOptions { - public: - // Functions for processing the gtest_output flag. - - // Returns the output format, or "" for normal printed output. - static std::string GetOutputFormat(); - - // Returns the absolute path of the requested output file, or the - // default (test_detail.xml in the original working directory) if - // none was explicitly specified. - static std::string GetAbsolutePathToOutputFile(); - - // Functions for processing the gtest_filter flag. - - // Returns true if and only if the wildcard pattern matches the string. - // The first ':' or '\0' character in pattern marks the end of it. - // - // This recursive algorithm isn't very efficient, but is clear and - // works well enough for matching test names, which are short. - static bool PatternMatchesString(const char *pattern, const char *str); - - // Returns true if and only if the user-specified filter matches the test - // suite name and the test name. - static bool FilterMatchesTest(const std::string& test_suite_name, - const std::string& test_name); - -#if GTEST_OS_WINDOWS - // Function for supporting the gtest_catch_exception flag. - - // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the - // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. - // This function is useful as an __except condition. - static int GTestShouldProcessSEH(DWORD exception_code); -#endif // GTEST_OS_WINDOWS - - // Returns true if "name" matches the ':' separated list of glob-style - // filters in "filter". - static bool MatchesFilter(const std::string& name, const char* filter); -}; - -// Returns the current application's name, removing directory path if that -// is present. Used by UnitTestOptions::GetOutputFile. -GTEST_API_ FilePath GetCurrentExecutableName(); - -// The role interface for getting the OS stack trace as a string. -class OsStackTraceGetterInterface { - public: - OsStackTraceGetterInterface() {} - virtual ~OsStackTraceGetterInterface() {} - - // Returns the current OS stack trace as an std::string. Parameters: - // - // max_depth - the maximum number of stack frames to be included - // in the trace. - // skip_count - the number of top frames to be skipped; doesn't count - // against max_depth. - virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0; - - // UponLeavingGTest() should be called immediately before Google Test calls - // user code. It saves some information about the current stack that - // CurrentStackTrace() will use to find and hide Google Test stack frames. - virtual void UponLeavingGTest() = 0; - - // This string is inserted in place of stack frames that are part of - // Google Test's implementation. - static const char* const kElidedFramesMarker; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); -}; - -// A working implementation of the OsStackTraceGetterInterface interface. -class OsStackTraceGetter : public OsStackTraceGetterInterface { - public: - OsStackTraceGetter() {} - - std::string CurrentStackTrace(int max_depth, int skip_count) override; - void UponLeavingGTest() override; - - private: -#if GTEST_HAS_ABSL - Mutex mutex_; // Protects all internal state. - - // We save the stack frame below the frame that calls user code. - // We do this because the address of the frame immediately below - // the user code changes between the call to UponLeavingGTest() - // and any calls to the stack trace code from within the user code. - void* caller_frame_ = nullptr; -#endif // GTEST_HAS_ABSL - - GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); -}; - -// Information about a Google Test trace point. -struct TraceInfo { - const char* file; - int line; - std::string message; -}; - -// This is the default global test part result reporter used in UnitTestImpl. -// This class should only be used by UnitTestImpl. -class DefaultGlobalTestPartResultReporter - : public TestPartResultReporterInterface { - public: - explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); - // Implements the TestPartResultReporterInterface. Reports the test part - // result in the current test. - void ReportTestPartResult(const TestPartResult& result) override; - - private: - UnitTestImpl* const unit_test_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); -}; - -// This is the default per thread test part result reporter used in -// UnitTestImpl. This class should only be used by UnitTestImpl. -class DefaultPerThreadTestPartResultReporter - : public TestPartResultReporterInterface { - public: - explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); - // Implements the TestPartResultReporterInterface. The implementation just - // delegates to the current global test part result reporter of *unit_test_. - void ReportTestPartResult(const TestPartResult& result) override; - - private: - UnitTestImpl* const unit_test_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); -}; - -// The private implementation of the UnitTest class. We don't protect -// the methods under a mutex, as this class is not accessible by a -// user and the UnitTest class that delegates work to this class does -// proper locking. -class GTEST_API_ UnitTestImpl { - public: - explicit UnitTestImpl(UnitTest* parent); - virtual ~UnitTestImpl(); - - // There are two different ways to register your own TestPartResultReporter. - // You can register your own repoter to listen either only for test results - // from the current thread or for results from all threads. - // By default, each per-thread test result repoter just passes a new - // TestPartResult to the global test result reporter, which registers the - // test part result for the currently running test. - - // Returns the global test part result reporter. - TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); - - // Sets the global test part result reporter. - void SetGlobalTestPartResultReporter( - TestPartResultReporterInterface* reporter); - - // Returns the test part result reporter for the current thread. - TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); - - // Sets the test part result reporter for the current thread. - void SetTestPartResultReporterForCurrentThread( - TestPartResultReporterInterface* reporter); - - // Gets the number of successful test suites. - int successful_test_suite_count() const; - - // Gets the number of failed test suites. - int failed_test_suite_count() const; - - // Gets the number of all test suites. - int total_test_suite_count() const; - - // Gets the number of all test suites that contain at least one test - // that should run. - int test_suite_to_run_count() const; - - // Gets the number of successful tests. - int successful_test_count() const; - - // Gets the number of skipped tests. - int skipped_test_count() const; - - // Gets the number of failed tests. - int failed_test_count() const; - - // Gets the number of disabled tests that will be reported in the XML report. - int reportable_disabled_test_count() const; - - // Gets the number of disabled tests. - int disabled_test_count() const; - - // Gets the number of tests to be printed in the XML report. - int reportable_test_count() const; - - // Gets the number of all tests. - int total_test_count() const; - - // Gets the number of tests that should run. - int test_to_run_count() const; - - // Gets the time of the test program start, in ms from the start of the - // UNIX epoch. - TimeInMillis start_timestamp() const { return start_timestamp_; } - - // Gets the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Returns true if and only if the unit test passed (i.e. all test suites - // passed). - bool Passed() const { return !Failed(); } - - // Returns true if and only if the unit test failed (i.e. some test suite - // failed or something outside of all tests failed). - bool Failed() const { - return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed(); - } - - // Gets the i-th test suite among all the test suites. i can range from 0 to - // total_test_suite_count() - 1. If i is not in that range, returns NULL. - const TestSuite* GetTestSuite(int i) const { - const int index = GetElementOr(test_suite_indices_, i, -1); - return index < 0 ? nullptr : test_suites_[static_cast(i)]; - } - - // Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - const TestCase* GetTestCase(int i) const { return GetTestSuite(i); } -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Gets the i-th test suite among all the test suites. i can range from 0 to - // total_test_suite_count() - 1. If i is not in that range, returns NULL. - TestSuite* GetMutableSuiteCase(int i) { - const int index = GetElementOr(test_suite_indices_, i, -1); - return index < 0 ? nullptr : test_suites_[static_cast(index)]; - } - - // Provides access to the event listener list. - TestEventListeners* listeners() { return &listeners_; } - - // Returns the TestResult for the test that's currently running, or - // the TestResult for the ad hoc test if no test is running. - TestResult* current_test_result(); - - // Returns the TestResult for the ad hoc test. - const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } - - // Sets the OS stack trace getter. - // - // Does nothing if the input and the current OS stack trace getter - // are the same; otherwise, deletes the old getter and makes the - // input the current getter. - void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); - - // Returns the current OS stack trace getter if it is not NULL; - // otherwise, creates an OsStackTraceGetter, makes it the current - // getter, and returns it. - OsStackTraceGetterInterface* os_stack_trace_getter(); - - // Returns the current OS stack trace as an std::string. - // - // The maximum number of stack frames to be included is specified by - // the gtest_stack_trace_depth flag. The skip_count parameter - // specifies the number of top frames to be skipped, which doesn't - // count against the number of frames to be included. - // - // For example, if Foo() calls Bar(), which in turn calls - // CurrentOsStackTraceExceptTop(1), Foo() will be included in the - // trace but Bar() and CurrentOsStackTraceExceptTop() won't. - std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; - - // Finds and returns a TestSuite with the given name. If one doesn't - // exist, creates one and returns it. - // - // Arguments: - // - // test_suite_name: name of the test suite - // type_param: the name of the test's type parameter, or NULL if - // this is not a typed or a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test suite - // tear_down_tc: pointer to the function that tears down the test suite - TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param, - internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc); - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - TestCase* GetTestCase(const char* test_case_name, const char* type_param, - internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc) { - return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc); - } -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Adds a TestInfo to the unit test. - // - // Arguments: - // - // set_up_tc: pointer to the function that sets up the test suite - // tear_down_tc: pointer to the function that tears down the test suite - // test_info: the TestInfo object - void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc, - TestInfo* test_info) { - // In order to support thread-safe death tests, we need to - // remember the original working directory when the test program - // was first invoked. We cannot do this in RUN_ALL_TESTS(), as - // the user may have changed the current directory before calling - // RUN_ALL_TESTS(). Therefore we capture the current directory in - // AddTestInfo(), which is called to register a TEST or TEST_F - // before main() is reached. - if (original_working_dir_.IsEmpty()) { - original_working_dir_.Set(FilePath::GetCurrentDir()); - GTEST_CHECK_(!original_working_dir_.IsEmpty()) - << "Failed to get the current working directory."; - } - - GetTestSuite(test_info->test_suite_name(), test_info->type_param(), - set_up_tc, tear_down_tc) - ->AddTestInfo(test_info); - } - - // Returns ParameterizedTestSuiteRegistry object used to keep track of - // value-parameterized tests and instantiate and register them. - internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() { - return parameterized_test_registry_; - } - - // Sets the TestSuite object for the test that's currently running. - void set_current_test_suite(TestSuite* a_current_test_suite) { - current_test_suite_ = a_current_test_suite; - } - - // Sets the TestInfo object for the test that's currently running. If - // current_test_info is NULL, the assertion results will be stored in - // ad_hoc_test_result_. - void set_current_test_info(TestInfo* a_current_test_info) { - current_test_info_ = a_current_test_info; - } - - // Registers all parameterized tests defined using TEST_P and - // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter - // combination. This method can be called more then once; it has guards - // protecting from registering the tests more then once. If - // value-parameterized tests are disabled, RegisterParameterizedTests is - // present but does nothing. - void RegisterParameterizedTests(); - - // Runs all tests in this UnitTest object, prints the result, and - // returns true if all tests are successful. If any exception is - // thrown during a test, this test is considered to be failed, but - // the rest of the tests will still be run. - bool RunAllTests(); - - // Clears the results of all tests, except the ad hoc tests. - void ClearNonAdHocTestResult() { - ForEach(test_suites_, TestSuite::ClearTestSuiteResult); - } - - // Clears the results of ad-hoc test assertions. - void ClearAdHocTestResult() { - ad_hoc_test_result_.Clear(); - } - - // Adds a TestProperty to the current TestResult object when invoked in a - // context of a test or a test suite, or to the global property set. If the - // result already contains a property with the same key, the value will be - // updated. - void RecordProperty(const TestProperty& test_property); - - enum ReactionToSharding { - HONOR_SHARDING_PROTOCOL, - IGNORE_SHARDING_PROTOCOL - }; - - // Matches the full name of each test against the user-specified - // filter to decide whether the test should run, then records the - // result in each TestSuite and TestInfo object. - // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests - // based on sharding variables in the environment. - // Returns the number of tests that should run. - int FilterTests(ReactionToSharding shard_tests); - - // Prints the names of the tests matching the user-specified filter flag. - void ListTestsMatchingFilter(); - - const TestSuite* current_test_suite() const { return current_test_suite_; } - TestInfo* current_test_info() { return current_test_info_; } - const TestInfo* current_test_info() const { return current_test_info_; } - - // Returns the vector of environments that need to be set-up/torn-down - // before/after the tests are run. - std::vector& environments() { return environments_; } - - // Getters for the per-thread Google Test trace stack. - std::vector& gtest_trace_stack() { - return *(gtest_trace_stack_.pointer()); - } - const std::vector& gtest_trace_stack() const { - return gtest_trace_stack_.get(); - } - -#if GTEST_HAS_DEATH_TEST - void InitDeathTestSubprocessControlInfo() { - internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); - } - // Returns a pointer to the parsed --gtest_internal_run_death_test - // flag, or NULL if that flag was not specified. - // This information is useful only in a death test child process. - // Must not be called before a call to InitGoogleTest. - const InternalRunDeathTestFlag* internal_run_death_test_flag() const { - return internal_run_death_test_flag_.get(); - } - - // Returns a pointer to the current death test factory. - internal::DeathTestFactory* death_test_factory() { - return death_test_factory_.get(); - } - - void SuppressTestEventsIfInSubprocess(); - - friend class ReplaceDeathTestFactory; -#endif // GTEST_HAS_DEATH_TEST - - // Initializes the event listener performing XML output as specified by - // UnitTestOptions. Must not be called before InitGoogleTest. - void ConfigureXmlOutput(); - -#if GTEST_CAN_STREAM_RESULTS_ - // Initializes the event listener for streaming test results to a socket. - // Must not be called before InitGoogleTest. - void ConfigureStreamingOutput(); -#endif - - // Performs initialization dependent upon flag values obtained in - // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to - // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest - // this function is also called from RunAllTests. Since this function can be - // called more than once, it has to be idempotent. - void PostFlagParsingInit(); - - // Gets the random seed used at the start of the current test iteration. - int random_seed() const { return random_seed_; } - - // Gets the random number generator. - internal::Random* random() { return &random_; } - - // Shuffles all test suites, and the tests within each test suite, - // making sure that death tests are still run first. - void ShuffleTests(); - - // Restores the test suites and tests to their order before the first shuffle. - void UnshuffleTests(); - - // Returns the value of GTEST_FLAG(catch_exceptions) at the moment - // UnitTest::Run() starts. - bool catch_exceptions() const { return catch_exceptions_; } - - private: - friend class ::testing::UnitTest; - - // Used by UnitTest::Run() to capture the state of - // GTEST_FLAG(catch_exceptions) at the moment it starts. - void set_catch_exceptions(bool value) { catch_exceptions_ = value; } - - // The UnitTest object that owns this implementation object. - UnitTest* const parent_; - - // The working directory when the first TEST() or TEST_F() was - // executed. - internal::FilePath original_working_dir_; - - // The default test part result reporters. - DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; - DefaultPerThreadTestPartResultReporter - default_per_thread_test_part_result_reporter_; - - // Points to (but doesn't own) the global test part result reporter. - TestPartResultReporterInterface* global_test_part_result_repoter_; - - // Protects read and write access to global_test_part_result_reporter_. - internal::Mutex global_test_part_result_reporter_mutex_; - - // Points to (but doesn't own) the per-thread test part result reporter. - internal::ThreadLocal - per_thread_test_part_result_reporter_; - - // The vector of environments that need to be set-up/torn-down - // before/after the tests are run. - std::vector environments_; - - // The vector of TestSuites in their original order. It owns the - // elements in the vector. - std::vector test_suites_; - - // Provides a level of indirection for the test suite list to allow - // easy shuffling and restoring the test suite order. The i-th - // element of this vector is the index of the i-th test suite in the - // shuffled order. - std::vector test_suite_indices_; - - // ParameterizedTestRegistry object used to register value-parameterized - // tests. - internal::ParameterizedTestSuiteRegistry parameterized_test_registry_; - - // Indicates whether RegisterParameterizedTests() has been called already. - bool parameterized_tests_registered_; - - // Index of the last death test suite registered. Initially -1. - int last_death_test_suite_; - - // This points to the TestSuite for the currently running test. It - // changes as Google Test goes through one test suite after another. - // When no test is running, this is set to NULL and Google Test - // stores assertion results in ad_hoc_test_result_. Initially NULL. - TestSuite* current_test_suite_; - - // This points to the TestInfo for the currently running test. It - // changes as Google Test goes through one test after another. When - // no test is running, this is set to NULL and Google Test stores - // assertion results in ad_hoc_test_result_. Initially NULL. - TestInfo* current_test_info_; - - // Normally, a user only writes assertions inside a TEST or TEST_F, - // or inside a function called by a TEST or TEST_F. Since Google - // Test keeps track of which test is current running, it can - // associate such an assertion with the test it belongs to. - // - // If an assertion is encountered when no TEST or TEST_F is running, - // Google Test attributes the assertion result to an imaginary "ad hoc" - // test, and records the result in ad_hoc_test_result_. - TestResult ad_hoc_test_result_; - - // The list of event listeners that can be used to track events inside - // Google Test. - TestEventListeners listeners_; - - // The OS stack trace getter. Will be deleted when the UnitTest - // object is destructed. By default, an OsStackTraceGetter is used, - // but the user can set this field to use a custom getter if that is - // desired. - OsStackTraceGetterInterface* os_stack_trace_getter_; - - // True if and only if PostFlagParsingInit() has been called. - bool post_flag_parse_init_performed_; - - // The random number seed used at the beginning of the test run. - int random_seed_; - - // Our random number generator. - internal::Random random_; - - // The time of the test program start, in ms from the start of the - // UNIX epoch. - TimeInMillis start_timestamp_; - - // How long the test took to run, in milliseconds. - TimeInMillis elapsed_time_; - -#if GTEST_HAS_DEATH_TEST - // The decomposed components of the gtest_internal_run_death_test flag, - // parsed when RUN_ALL_TESTS is called. - std::unique_ptr internal_run_death_test_flag_; - std::unique_ptr death_test_factory_; -#endif // GTEST_HAS_DEATH_TEST - - // A per-thread stack of traces created by the SCOPED_TRACE() macro. - internal::ThreadLocal > gtest_trace_stack_; - - // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() - // starts. - bool catch_exceptions_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); -}; // class UnitTestImpl - -// Convenience function for accessing the global UnitTest -// implementation object. -inline UnitTestImpl* GetUnitTestImpl() { - return UnitTest::GetInstance()->impl(); -} - -#if GTEST_USES_SIMPLE_RE - -// Internal helper functions for implementing the simple regular -// expression matcher. -GTEST_API_ bool IsInSet(char ch, const char* str); -GTEST_API_ bool IsAsciiDigit(char ch); -GTEST_API_ bool IsAsciiPunct(char ch); -GTEST_API_ bool IsRepeat(char ch); -GTEST_API_ bool IsAsciiWhiteSpace(char ch); -GTEST_API_ bool IsAsciiWordChar(char ch); -GTEST_API_ bool IsValidEscape(char ch); -GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); -GTEST_API_ bool ValidateRegex(const char* regex); -GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); -GTEST_API_ bool MatchRepetitionAndRegexAtHead( - bool escaped, char ch, char repeat, const char* regex, const char* str); -GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); - -#endif // GTEST_USES_SIMPLE_RE - -// Parses the command line for Google Test flags, without initializing -// other parts of Google Test. -GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); -GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); - -#if GTEST_HAS_DEATH_TEST - -// Returns the message describing the last system error, regardless of the -// platform. -GTEST_API_ std::string GetLastErrnoDescription(); - -// Attempts to parse a string into a positive integer pointed to by the -// number parameter. Returns true if that is possible. -// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use -// it here. -template -bool ParseNaturalNumber(const ::std::string& str, Integer* number) { - // Fail fast if the given string does not begin with a digit; - // this bypasses strtoXXX's "optional leading whitespace and plus - // or minus sign" semantics, which are undesirable here. - if (str.empty() || !IsDigit(str[0])) { - return false; - } - errno = 0; - - char* end; - // BiggestConvertible is the largest integer type that system-provided - // string-to-number conversion routines can return. - -# if GTEST_OS_WINDOWS && !defined(__GNUC__) - - // MSVC and C++ Builder define __int64 instead of the standard long long. - typedef unsigned __int64 BiggestConvertible; - const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); - -# else - - typedef unsigned long long BiggestConvertible; // NOLINT - const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); - -# endif // GTEST_OS_WINDOWS && !defined(__GNUC__) - - const bool parse_success = *end == '\0' && errno == 0; - - GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); - - const Integer result = static_cast(parsed); - if (parse_success && static_cast(result) == parsed) { - *number = result; - return true; - } - return false; -} -#endif // GTEST_HAS_DEATH_TEST - -// TestResult contains some private methods that should be hidden from -// Google Test user but are required for testing. This class allow our tests -// to access them. -// -// This class is supplied only for the purpose of testing Google Test's own -// constructs. Do not use it in user tests, either directly or indirectly. -class TestResultAccessor { - public: - static void RecordProperty(TestResult* test_result, - const std::string& xml_element, - const TestProperty& property) { - test_result->RecordProperty(xml_element, property); - } - - static void ClearTestPartResults(TestResult* test_result) { - test_result->ClearTestPartResults(); - } - - static const std::vector& test_part_results( - const TestResult& test_result) { - return test_result.test_part_results(); - } -}; - -#if GTEST_CAN_STREAM_RESULTS_ - -// Streams test results to the given port on the given host machine. -class StreamingListener : public EmptyTestEventListener { - public: - // Abstract base class for writing strings to a socket. - class AbstractSocketWriter { - public: - virtual ~AbstractSocketWriter() {} - - // Sends a string to the socket. - virtual void Send(const std::string& message) = 0; - - // Closes the socket. - virtual void CloseConnection() {} - - // Sends a string and a newline to the socket. - void SendLn(const std::string& message) { Send(message + "\n"); } - }; - - // Concrete class for actually writing strings to a socket. - class SocketWriter : public AbstractSocketWriter { - public: - SocketWriter(const std::string& host, const std::string& port) - : sockfd_(-1), host_name_(host), port_num_(port) { - MakeConnection(); - } - - ~SocketWriter() override { - if (sockfd_ != -1) - CloseConnection(); - } - - // Sends a string to the socket. - void Send(const std::string& message) override { - GTEST_CHECK_(sockfd_ != -1) - << "Send() can be called only when there is a connection."; - - const auto len = static_cast(message.length()); - if (write(sockfd_, message.c_str(), len) != static_cast(len)) { - GTEST_LOG_(WARNING) - << "stream_result_to: failed to stream to " - << host_name_ << ":" << port_num_; - } - } - - private: - // Creates a client socket and connects to the server. - void MakeConnection(); - - // Closes the socket. - void CloseConnection() override { - GTEST_CHECK_(sockfd_ != -1) - << "CloseConnection() can be called only when there is a connection."; - - close(sockfd_); - sockfd_ = -1; - } - - int sockfd_; // socket file descriptor - const std::string host_name_; - const std::string port_num_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); - }; // class SocketWriter - - // Escapes '=', '&', '%', and '\n' characters in str as "%xx". - static std::string UrlEncode(const char* str); - - StreamingListener(const std::string& host, const std::string& port) - : socket_writer_(new SocketWriter(host, port)) { - Start(); - } - - explicit StreamingListener(AbstractSocketWriter* socket_writer) - : socket_writer_(socket_writer) { Start(); } - - void OnTestProgramStart(const UnitTest& /* unit_test */) override { - SendLn("event=TestProgramStart"); - } - - void OnTestProgramEnd(const UnitTest& unit_test) override { - // Note that Google Test current only report elapsed time for each - // test iteration, not for the entire test program. - SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); - - // Notify the streaming server to stop. - socket_writer_->CloseConnection(); - } - - void OnTestIterationStart(const UnitTest& /* unit_test */, - int iteration) override { - SendLn("event=TestIterationStart&iteration=" + - StreamableToString(iteration)); - } - - void OnTestIterationEnd(const UnitTest& unit_test, - int /* iteration */) override { - SendLn("event=TestIterationEnd&passed=" + - FormatBool(unit_test.Passed()) + "&elapsed_time=" + - StreamableToString(unit_test.elapsed_time()) + "ms"); - } - - // Note that "event=TestCaseStart" is a wire format and has to remain - // "case" for compatibilty - void OnTestCaseStart(const TestCase& test_case) override { - SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); - } - - // Note that "event=TestCaseEnd" is a wire format and has to remain - // "case" for compatibilty - void OnTestCaseEnd(const TestCase& test_case) override { - SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + - "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + - "ms"); - } - - void OnTestStart(const TestInfo& test_info) override { - SendLn(std::string("event=TestStart&name=") + test_info.name()); - } - - void OnTestEnd(const TestInfo& test_info) override { - SendLn("event=TestEnd&passed=" + - FormatBool((test_info.result())->Passed()) + - "&elapsed_time=" + - StreamableToString((test_info.result())->elapsed_time()) + "ms"); - } - - void OnTestPartResult(const TestPartResult& test_part_result) override { - const char* file_name = test_part_result.file_name(); - if (file_name == nullptr) file_name = ""; - SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + - "&line=" + StreamableToString(test_part_result.line_number()) + - "&message=" + UrlEncode(test_part_result.message())); - } - - private: - // Sends the given message and a newline to the socket. - void SendLn(const std::string& message) { socket_writer_->SendLn(message); } - - // Called at the start of streaming to notify the receiver what - // protocol we are using. - void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } - - std::string FormatBool(bool value) { return value ? "1" : "0"; } - - const std::unique_ptr socket_writer_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); -}; // class StreamingListener - -#endif // GTEST_CAN_STREAM_RESULTS_ - -} // namespace internal -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ - -#if GTEST_OS_WINDOWS -# define vsnprintf _vsnprintf -#endif // GTEST_OS_WINDOWS - -#if GTEST_OS_MAC -#ifndef GTEST_OS_IOS -#include -#endif -#endif - -#if GTEST_HAS_ABSL -#include "absl/debugging/failure_signal_handler.h" -#include "absl/debugging/stacktrace.h" -#include "absl/debugging/symbolize.h" -#include "absl/strings/str_cat.h" -#endif // GTEST_HAS_ABSL - -namespace testing { - -using internal::CountIf; -using internal::ForEach; -using internal::GetElementOr; -using internal::Shuffle; - -// Constants. - -// A test whose test suite name or test name matches this filter is -// disabled and not run. -static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; - -// A test suite whose name matches this filter is considered a death -// test suite and will be run before test suites whose name doesn't -// match this filter. -static const char kDeathTestSuiteFilter[] = "*DeathTest:*DeathTest/*"; - -// A test filter that matches everything. -static const char kUniversalFilter[] = "*"; - -// The default output format. -static const char kDefaultOutputFormat[] = "xml"; -// The default output file. -static const char kDefaultOutputFile[] = "test_detail"; - -// The environment variable name for the test shard index. -static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; -// The environment variable name for the total number of test shards. -static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; -// The environment variable name for the test shard status file. -static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; - -namespace internal { - -// The text used in failure messages to indicate the start of the -// stack trace. -const char kStackTraceMarker[] = "\nStack trace:\n"; - -// g_help_flag is true if and only if the --help flag or an equivalent form -// is specified on the command line. -bool g_help_flag = false; - -// Utilty function to Open File for Writing -static FILE* OpenFileForWriting(const std::string& output_file) { - FILE* fileout = nullptr; - FilePath output_file_path(output_file); - FilePath output_dir(output_file_path.RemoveFileName()); - - if (output_dir.CreateDirectoriesRecursively()) { - fileout = posix::FOpen(output_file.c_str(), "w"); - } - if (fileout == nullptr) { - GTEST_LOG_(FATAL) << "Unable to open file \"" << output_file << "\""; - } - return fileout; -} - -} // namespace internal - -// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY -// environment variable. -static const char* GetDefaultFilter() { - const char* const testbridge_test_only = - internal::posix::GetEnv("TESTBRIDGE_TEST_ONLY"); - if (testbridge_test_only != nullptr) { - return testbridge_test_only; - } - return kUniversalFilter; -} - -GTEST_DEFINE_bool_( - also_run_disabled_tests, - internal::BoolFromGTestEnv("also_run_disabled_tests", false), - "Run disabled tests too, in addition to the tests normally being run."); - -GTEST_DEFINE_bool_( - break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), - "True if and only if a failed assertion should be a debugger " - "break-point."); - -GTEST_DEFINE_bool_(catch_exceptions, - internal::BoolFromGTestEnv("catch_exceptions", true), - "True if and only if " GTEST_NAME_ - " should catch exceptions and treat them as test failures."); - -GTEST_DEFINE_string_( - color, - internal::StringFromGTestEnv("color", "auto"), - "Whether to use colors in the output. Valid values: yes, no, " - "and auto. 'auto' means to use colors if the output is " - "being sent to a terminal and the TERM environment variable " - "is set to a terminal type that supports colors."); - -GTEST_DEFINE_string_( - filter, - internal::StringFromGTestEnv("filter", GetDefaultFilter()), - "A colon-separated list of glob (not regex) patterns " - "for filtering the tests to run, optionally followed by a " - "'-' and a : separated list of negative patterns (tests to " - "exclude). A test is run if it matches one of the positive " - "patterns and does not match any of the negative patterns."); - -GTEST_DEFINE_bool_( - install_failure_signal_handler, - internal::BoolFromGTestEnv("install_failure_signal_handler", false), - "If true and supported on the current platform, " GTEST_NAME_ " should " - "install a signal handler that dumps debugging information when fatal " - "signals are raised."); - -GTEST_DEFINE_bool_(list_tests, false, - "List all tests without running them."); - -// The net priority order after flag processing is thus: -// --gtest_output command line flag -// GTEST_OUTPUT environment variable -// XML_OUTPUT_FILE environment variable -// '' -GTEST_DEFINE_string_( - output, - internal::StringFromGTestEnv("output", - internal::OutputFlagAlsoCheckEnvVar().c_str()), - "A format (defaults to \"xml\" but can be specified to be \"json\"), " - "optionally followed by a colon and an output file name or directory. " - "A directory is indicated by a trailing pathname separator. " - "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " - "If a directory is specified, output files will be created " - "within that directory, with file-names based on the test " - "executable's name and, if necessary, made unique by adding " - "digits."); - -GTEST_DEFINE_bool_(print_time, internal::BoolFromGTestEnv("print_time", true), - "True if and only if " GTEST_NAME_ - " should display elapsed time in text output."); - -GTEST_DEFINE_bool_(print_utf8, internal::BoolFromGTestEnv("print_utf8", true), - "True if and only if " GTEST_NAME_ - " prints UTF8 characters as text."); - -GTEST_DEFINE_int32_( - random_seed, - internal::Int32FromGTestEnv("random_seed", 0), - "Random number seed to use when shuffling test orders. Must be in range " - "[1, 99999], or 0 to use a seed based on the current time."); - -GTEST_DEFINE_int32_( - repeat, - internal::Int32FromGTestEnv("repeat", 1), - "How many times to repeat each test. Specify a negative number " - "for repeating forever. Useful for shaking out flaky tests."); - -GTEST_DEFINE_bool_(show_internal_stack_frames, false, - "True if and only if " GTEST_NAME_ - " should include internal stack frames when " - "printing test failure stack traces."); - -GTEST_DEFINE_bool_(shuffle, internal::BoolFromGTestEnv("shuffle", false), - "True if and only if " GTEST_NAME_ - " should randomize tests' order on every run."); - -GTEST_DEFINE_int32_( - stack_trace_depth, - internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), - "The maximum number of stack frames to print when an " - "assertion fails. The valid range is 0 through 100, inclusive."); - -GTEST_DEFINE_string_( - stream_result_to, - internal::StringFromGTestEnv("stream_result_to", ""), - "This flag specifies the host name and the port number on which to stream " - "test results. Example: \"localhost:555\". The flag is effective only on " - "Linux."); - -GTEST_DEFINE_bool_( - throw_on_failure, - internal::BoolFromGTestEnv("throw_on_failure", false), - "When this flag is specified, a failed assertion will throw an exception " - "if exceptions are enabled or exit the program with a non-zero code " - "otherwise. For use with an external test framework."); - -#if GTEST_USE_OWN_FLAGFILE_FLAG_ -GTEST_DEFINE_string_( - flagfile, - internal::StringFromGTestEnv("flagfile", ""), - "This flag specifies the flagfile to read command-line flags from."); -#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ - -namespace internal { - -// Generates a random number from [0, range), using a Linear -// Congruential Generator (LCG). Crashes if 'range' is 0 or greater -// than kMaxRange. -UInt32 Random::Generate(UInt32 range) { - // These constants are the same as are used in glibc's rand(3). - // Use wider types than necessary to prevent unsigned overflow diagnostics. - state_ = static_cast(1103515245ULL*state_ + 12345U) % kMaxRange; - - GTEST_CHECK_(range > 0) - << "Cannot generate a number in the range [0, 0)."; - GTEST_CHECK_(range <= kMaxRange) - << "Generation of a number in [0, " << range << ") was requested, " - << "but this can only generate numbers in [0, " << kMaxRange << ")."; - - // Converting via modulus introduces a bit of downward bias, but - // it's simple, and a linear congruential generator isn't too good - // to begin with. - return state_ % range; -} - -// GTestIsInitialized() returns true if and only if the user has initialized -// Google Test. Useful for catching the user mistake of not initializing -// Google Test before calling RUN_ALL_TESTS(). -static bool GTestIsInitialized() { return GetArgvs().size() > 0; } - -// Iterates over a vector of TestSuites, keeping a running sum of the -// results of calling a given int-returning method on each. -// Returns the sum. -static int SumOverTestSuiteList(const std::vector& case_list, - int (TestSuite::*method)() const) { - int sum = 0; - for (size_t i = 0; i < case_list.size(); i++) { - sum += (case_list[i]->*method)(); - } - return sum; -} - -// Returns true if and only if the test suite passed. -static bool TestSuitePassed(const TestSuite* test_suite) { - return test_suite->should_run() && test_suite->Passed(); -} - -// Returns true if and only if the test suite failed. -static bool TestSuiteFailed(const TestSuite* test_suite) { - return test_suite->should_run() && test_suite->Failed(); -} - -// Returns true if and only if test_suite contains at least one test that -// should run. -static bool ShouldRunTestSuite(const TestSuite* test_suite) { - return test_suite->should_run(); -} - -// AssertHelper constructor. -AssertHelper::AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message) - : data_(new AssertHelperData(type, file, line, message)) { -} - -AssertHelper::~AssertHelper() { - delete data_; -} - -// Message assignment, for assertion streaming support. -void AssertHelper::operator=(const Message& message) const { - UnitTest::GetInstance()-> - AddTestPartResult(data_->type, data_->file, data_->line, - AppendUserMessage(data_->message, message), - UnitTest::GetInstance()->impl() - ->CurrentOsStackTraceExceptTop(1) - // Skips the stack frame for this function itself. - ); // NOLINT -} - -// A copy of all command line arguments. Set by InitGoogleTest(). -static ::std::vector g_argvs; - -::std::vector GetArgvs() { -#if defined(GTEST_CUSTOM_GET_ARGVS_) - // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or - // ::string. This code converts it to the appropriate type. - const auto& custom = GTEST_CUSTOM_GET_ARGVS_(); - return ::std::vector(custom.begin(), custom.end()); -#else // defined(GTEST_CUSTOM_GET_ARGVS_) - return g_argvs; -#endif // defined(GTEST_CUSTOM_GET_ARGVS_) -} - -// Returns the current application's name, removing directory path if that -// is present. -FilePath GetCurrentExecutableName() { - FilePath result; - -#if GTEST_OS_WINDOWS || GTEST_OS_OS2 - result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); -#else - result.Set(FilePath(GetArgvs()[0])); -#endif // GTEST_OS_WINDOWS - - return result.RemoveDirectoryName(); -} - -// Functions for processing the gtest_output flag. - -// Returns the output format, or "" for normal printed output. -std::string UnitTestOptions::GetOutputFormat() { - const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); - const char* const colon = strchr(gtest_output_flag, ':'); - return (colon == nullptr) - ? std::string(gtest_output_flag) - : std::string(gtest_output_flag, - static_cast(colon - gtest_output_flag)); -} - -// Returns the name of the requested output file, or the default if none -// was explicitly specified. -std::string UnitTestOptions::GetAbsolutePathToOutputFile() { - const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); - - std::string format = GetOutputFormat(); - if (format.empty()) - format = std::string(kDefaultOutputFormat); - - const char* const colon = strchr(gtest_output_flag, ':'); - if (colon == nullptr) - return internal::FilePath::MakeFileName( - internal::FilePath( - UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(kDefaultOutputFile), 0, - format.c_str()).string(); - - internal::FilePath output_name(colon + 1); - if (!output_name.IsAbsolutePath()) - output_name = internal::FilePath::ConcatPaths( - internal::FilePath(UnitTest::GetInstance()->original_working_dir()), - internal::FilePath(colon + 1)); - - if (!output_name.IsDirectory()) - return output_name.string(); - - internal::FilePath result(internal::FilePath::GenerateUniqueFileName( - output_name, internal::GetCurrentExecutableName(), - GetOutputFormat().c_str())); - return result.string(); -} - -// Returns true if and only if the wildcard pattern matches the string. -// The first ':' or '\0' character in pattern marks the end of it. -// -// This recursive algorithm isn't very efficient, but is clear and -// works well enough for matching test names, which are short. -bool UnitTestOptions::PatternMatchesString(const char *pattern, - const char *str) { - switch (*pattern) { - case '\0': - case ':': // Either ':' or '\0' marks the end of the pattern. - return *str == '\0'; - case '?': // Matches any single character. - return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); - case '*': // Matches any string (possibly empty) of characters. - return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || - PatternMatchesString(pattern + 1, str); - default: // Non-special character. Matches itself. - return *pattern == *str && - PatternMatchesString(pattern + 1, str + 1); - } -} - -bool UnitTestOptions::MatchesFilter( - const std::string& name, const char* filter) { - const char *cur_pattern = filter; - for (;;) { - if (PatternMatchesString(cur_pattern, name.c_str())) { - return true; - } - - // Finds the next pattern in the filter. - cur_pattern = strchr(cur_pattern, ':'); - - // Returns if no more pattern can be found. - if (cur_pattern == nullptr) { - return false; - } - - // Skips the pattern separater (the ':' character). - cur_pattern++; - } -} - -// Returns true if and only if the user-specified filter matches the test -// suite name and the test name. -bool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name, - const std::string& test_name) { - const std::string& full_name = test_suite_name + "." + test_name.c_str(); - - // Split --gtest_filter at '-', if there is one, to separate into - // positive filter and negative filter portions - const char* const p = GTEST_FLAG(filter).c_str(); - const char* const dash = strchr(p, '-'); - std::string positive; - std::string negative; - if (dash == nullptr) { - positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter - negative = ""; - } else { - positive = std::string(p, dash); // Everything up to the dash - negative = std::string(dash + 1); // Everything after the dash - if (positive.empty()) { - // Treat '-test1' as the same as '*-test1' - positive = kUniversalFilter; - } - } - - // A filter is a colon-separated list of patterns. It matches a - // test if any pattern in it matches the test. - return (MatchesFilter(full_name, positive.c_str()) && - !MatchesFilter(full_name, negative.c_str())); -} - -#if GTEST_HAS_SEH -// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the -// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. -// This function is useful as an __except condition. -int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { - // Google Test should handle a SEH exception if: - // 1. the user wants it to, AND - // 2. this is not a breakpoint exception, AND - // 3. this is not a C++ exception (VC++ implements them via SEH, - // apparently). - // - // SEH exception code for C++ exceptions. - // (see http://support.microsoft.com/kb/185294 for more information). - const DWORD kCxxExceptionCode = 0xe06d7363; - - bool should_handle = true; - - if (!GTEST_FLAG(catch_exceptions)) - should_handle = false; - else if (exception_code == EXCEPTION_BREAKPOINT) - should_handle = false; - else if (exception_code == kCxxExceptionCode) - should_handle = false; - - return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; -} -#endif // GTEST_HAS_SEH - -} // namespace internal - -// The c'tor sets this object as the test part result reporter used by -// Google Test. The 'result' parameter specifies where to report the -// results. Intercepts only failures from the current thread. -ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( - TestPartResultArray* result) - : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), - result_(result) { - Init(); -} - -// The c'tor sets this object as the test part result reporter used by -// Google Test. The 'result' parameter specifies where to report the -// results. -ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( - InterceptMode intercept_mode, TestPartResultArray* result) - : intercept_mode_(intercept_mode), - result_(result) { - Init(); -} - -void ScopedFakeTestPartResultReporter::Init() { - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - if (intercept_mode_ == INTERCEPT_ALL_THREADS) { - old_reporter_ = impl->GetGlobalTestPartResultReporter(); - impl->SetGlobalTestPartResultReporter(this); - } else { - old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); - impl->SetTestPartResultReporterForCurrentThread(this); - } -} - -// The d'tor restores the test part result reporter used by Google Test -// before. -ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - if (intercept_mode_ == INTERCEPT_ALL_THREADS) { - impl->SetGlobalTestPartResultReporter(old_reporter_); - } else { - impl->SetTestPartResultReporterForCurrentThread(old_reporter_); - } -} - -// Increments the test part result count and remembers the result. -// This method is from the TestPartResultReporterInterface interface. -void ScopedFakeTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - result_->Append(result); -} - -namespace internal { - -// Returns the type ID of ::testing::Test. We should always call this -// instead of GetTypeId< ::testing::Test>() to get the type ID of -// testing::Test. This is to work around a suspected linker bug when -// using Google Test as a framework on Mac OS X. The bug causes -// GetTypeId< ::testing::Test>() to return different values depending -// on whether the call is from the Google Test framework itself or -// from user test code. GetTestTypeId() is guaranteed to always -// return the same value, as it always calls GetTypeId<>() from the -// gtest.cc, which is within the Google Test framework. -TypeId GetTestTypeId() { - return GetTypeId(); -} - -// The value of GetTestTypeId() as seen from within the Google Test -// library. This is solely for testing GetTestTypeId(). -extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); - -// This predicate-formatter checks that 'results' contains a test part -// failure of the given type and that the failure message contains the -// given substring. -static AssertionResult HasOneFailure(const char* /* results_expr */, - const char* /* type_expr */, - const char* /* substr_expr */, - const TestPartResultArray& results, - TestPartResult::Type type, - const std::string& substr) { - const std::string expected(type == TestPartResult::kFatalFailure ? - "1 fatal failure" : - "1 non-fatal failure"); - Message msg; - if (results.size() != 1) { - msg << "Expected: " << expected << "\n" - << " Actual: " << results.size() << " failures"; - for (int i = 0; i < results.size(); i++) { - msg << "\n" << results.GetTestPartResult(i); - } - return AssertionFailure() << msg; - } - - const TestPartResult& r = results.GetTestPartResult(0); - if (r.type() != type) { - return AssertionFailure() << "Expected: " << expected << "\n" - << " Actual:\n" - << r; - } - - if (strstr(r.message(), substr.c_str()) == nullptr) { - return AssertionFailure() << "Expected: " << expected << " containing \"" - << substr << "\"\n" - << " Actual:\n" - << r; - } - - return AssertionSuccess(); -} - -// The constructor of SingleFailureChecker remembers where to look up -// test part results, what type of failure we expect, and what -// substring the failure message should contain. -SingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results, - TestPartResult::Type type, - const std::string& substr) - : results_(results), type_(type), substr_(substr) {} - -// The destructor of SingleFailureChecker verifies that the given -// TestPartResultArray contains exactly one failure that has the given -// type and contains the given substring. If that's not the case, a -// non-fatal failure will be generated. -SingleFailureChecker::~SingleFailureChecker() { - EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); -} - -DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} - -void DefaultGlobalTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - unit_test_->current_test_result()->AddTestPartResult(result); - unit_test_->listeners()->repeater()->OnTestPartResult(result); -} - -DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( - UnitTestImpl* unit_test) : unit_test_(unit_test) {} - -void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( - const TestPartResult& result) { - unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); -} - -// Returns the global test part result reporter. -TestPartResultReporterInterface* -UnitTestImpl::GetGlobalTestPartResultReporter() { - internal::MutexLock lock(&global_test_part_result_reporter_mutex_); - return global_test_part_result_repoter_; -} - -// Sets the global test part result reporter. -void UnitTestImpl::SetGlobalTestPartResultReporter( - TestPartResultReporterInterface* reporter) { - internal::MutexLock lock(&global_test_part_result_reporter_mutex_); - global_test_part_result_repoter_ = reporter; -} - -// Returns the test part result reporter for the current thread. -TestPartResultReporterInterface* -UnitTestImpl::GetTestPartResultReporterForCurrentThread() { - return per_thread_test_part_result_reporter_.get(); -} - -// Sets the test part result reporter for the current thread. -void UnitTestImpl::SetTestPartResultReporterForCurrentThread( - TestPartResultReporterInterface* reporter) { - per_thread_test_part_result_reporter_.set(reporter); -} - -// Gets the number of successful test suites. -int UnitTestImpl::successful_test_suite_count() const { - return CountIf(test_suites_, TestSuitePassed); -} - -// Gets the number of failed test suites. -int UnitTestImpl::failed_test_suite_count() const { - return CountIf(test_suites_, TestSuiteFailed); -} - -// Gets the number of all test suites. -int UnitTestImpl::total_test_suite_count() const { - return static_cast(test_suites_.size()); -} - -// Gets the number of all test suites that contain at least one test -// that should run. -int UnitTestImpl::test_suite_to_run_count() const { - return CountIf(test_suites_, ShouldRunTestSuite); -} - -// Gets the number of successful tests. -int UnitTestImpl::successful_test_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count); -} - -// Gets the number of skipped tests. -int UnitTestImpl::skipped_test_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count); -} - -// Gets the number of failed tests. -int UnitTestImpl::failed_test_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count); -} - -// Gets the number of disabled tests that will be reported in the XML report. -int UnitTestImpl::reportable_disabled_test_count() const { - return SumOverTestSuiteList(test_suites_, - &TestSuite::reportable_disabled_test_count); -} - -// Gets the number of disabled tests. -int UnitTestImpl::disabled_test_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count); -} - -// Gets the number of tests to be printed in the XML report. -int UnitTestImpl::reportable_test_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count); -} - -// Gets the number of all tests. -int UnitTestImpl::total_test_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count); -} - -// Gets the number of tests that should run. -int UnitTestImpl::test_to_run_count() const { - return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count); -} - -// Returns the current OS stack trace as an std::string. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// CurrentOsStackTraceExceptTop(1), Foo() will be included in the -// trace but Bar() and CurrentOsStackTraceExceptTop() won't. -std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { - return os_stack_trace_getter()->CurrentStackTrace( - static_cast(GTEST_FLAG(stack_trace_depth)), - skip_count + 1 - // Skips the user-specified number of frames plus this function - // itself. - ); // NOLINT -} - -// Returns the current time in milliseconds. -TimeInMillis GetTimeInMillis() { -#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) - // Difference between 1970-01-01 and 1601-01-01 in milliseconds. - // http://analogous.blogspot.com/2005/04/epoch.html - const TimeInMillis kJavaEpochToWinFileTimeDelta = - static_cast(116444736UL) * 100000UL; - const DWORD kTenthMicrosInMilliSecond = 10000; - - SYSTEMTIME now_systime; - FILETIME now_filetime; - ULARGE_INTEGER now_int64; - GetSystemTime(&now_systime); - if (SystemTimeToFileTime(&now_systime, &now_filetime)) { - now_int64.LowPart = now_filetime.dwLowDateTime; - now_int64.HighPart = now_filetime.dwHighDateTime; - now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - - kJavaEpochToWinFileTimeDelta; - return now_int64.QuadPart; - } - return 0; -#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ - __timeb64 now; - - // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 - // (deprecated function) there. - GTEST_DISABLE_MSC_DEPRECATED_PUSH_() - _ftime64(&now); - GTEST_DISABLE_MSC_DEPRECATED_POP_() - - return static_cast(now.time) * 1000 + now.millitm; -#elif GTEST_HAS_GETTIMEOFDAY_ - struct timeval now; - gettimeofday(&now, nullptr); - return static_cast(now.tv_sec) * 1000 + now.tv_usec / 1000; -#else -# error "Don't know how to get the current time on your system." -#endif -} - -// Utilities - -// class String. - -#if GTEST_OS_WINDOWS_MOBILE -// Creates a UTF-16 wide string from the given ANSI string, allocating -// memory using new. The caller is responsible for deleting the return -// value using delete[]. Returns the wide string, or NULL if the -// input is NULL. -LPCWSTR String::AnsiToUtf16(const char* ansi) { - if (!ansi) return nullptr; - const int length = strlen(ansi); - const int unicode_length = - MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0); - WCHAR* unicode = new WCHAR[unicode_length + 1]; - MultiByteToWideChar(CP_ACP, 0, ansi, length, - unicode, unicode_length); - unicode[unicode_length] = 0; - return unicode; -} - -// Creates an ANSI string from the given wide string, allocating -// memory using new. The caller is responsible for deleting the return -// value using delete[]. Returns the ANSI string, or NULL if the -// input is NULL. -const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { - if (!utf16_str) return nullptr; - const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr, - 0, nullptr, nullptr); - char* ansi = new char[ansi_length + 1]; - WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr, - nullptr); - ansi[ansi_length] = 0; - return ansi; -} - -#endif // GTEST_OS_WINDOWS_MOBILE - -// Compares two C strings. Returns true if and only if they have the same -// content. -// -// Unlike strcmp(), this function can handle NULL argument(s). A NULL -// C string is considered different to any non-NULL C string, -// including the empty string. -bool String::CStringEquals(const char * lhs, const char * rhs) { - if (lhs == nullptr) return rhs == nullptr; - - if (rhs == nullptr) return false; - - return strcmp(lhs, rhs) == 0; -} - -#if GTEST_HAS_STD_WSTRING - -// Converts an array of wide chars to a narrow string using the UTF-8 -// encoding, and streams the result to the given Message object. -static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, - Message* msg) { - for (size_t i = 0; i != length; ) { // NOLINT - if (wstr[i] != L'\0') { - *msg << WideStringToUtf8(wstr + i, static_cast(length - i)); - while (i != length && wstr[i] != L'\0') - i++; - } else { - *msg << '\0'; - i++; - } - } -} - -#endif // GTEST_HAS_STD_WSTRING - -void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest) { - ::std::vector< ::std::string> parsed; - ::std::string::size_type pos = 0; - while (::testing::internal::AlwaysTrue()) { - const ::std::string::size_type colon = str.find(delimiter, pos); - if (colon == ::std::string::npos) { - parsed.push_back(str.substr(pos)); - break; - } else { - parsed.push_back(str.substr(pos, colon - pos)); - pos = colon + 1; - } - } - dest->swap(parsed); -} - -} // namespace internal - -// Constructs an empty Message. -// We allocate the stringstream separately because otherwise each use of -// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's -// stack frame leading to huge stack frames in some cases; gcc does not reuse -// the stack space. -Message::Message() : ss_(new ::std::stringstream) { - // By default, we want there to be enough precision when printing - // a double to a Message. - *ss_ << std::setprecision(std::numeric_limits::digits10 + 2); -} - -// These two overloads allow streaming a wide C string to a Message -// using the UTF-8 encoding. -Message& Message::operator <<(const wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); -} -Message& Message::operator <<(wchar_t* wide_c_str) { - return *this << internal::String::ShowWideCString(wide_c_str); -} - -#if GTEST_HAS_STD_WSTRING -// Converts the given wide string to a narrow string using the UTF-8 -// encoding, and streams the result to this Message object. -Message& Message::operator <<(const ::std::wstring& wstr) { - internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); - return *this; -} -#endif // GTEST_HAS_STD_WSTRING - -// Gets the text streamed to this object so far as an std::string. -// Each '\0' character in the buffer is replaced with "\\0". -std::string Message::GetString() const { - return internal::StringStreamToString(ss_.get()); -} - -// AssertionResult constructors. -// Used in EXPECT_TRUE/FALSE(assertion_result). -AssertionResult::AssertionResult(const AssertionResult& other) - : success_(other.success_), - message_(other.message_.get() != nullptr - ? new ::std::string(*other.message_) - : static_cast< ::std::string*>(nullptr)) {} - -// Swaps two AssertionResults. -void AssertionResult::swap(AssertionResult& other) { - using std::swap; - swap(success_, other.success_); - swap(message_, other.message_); -} - -// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. -AssertionResult AssertionResult::operator!() const { - AssertionResult negation(!success_); - if (message_.get() != nullptr) negation << *message_; - return negation; -} - -// Makes a successful assertion result. -AssertionResult AssertionSuccess() { - return AssertionResult(true); -} - -// Makes a failed assertion result. -AssertionResult AssertionFailure() { - return AssertionResult(false); -} - -// Makes a failed assertion result with the given failure message. -// Deprecated; use AssertionFailure() << message. -AssertionResult AssertionFailure(const Message& message) { - return AssertionFailure() << message; -} - -namespace internal { - -namespace edit_distance { -std::vector CalculateOptimalEdits(const std::vector& left, - const std::vector& right) { - std::vector > costs( - left.size() + 1, std::vector(right.size() + 1)); - std::vector > best_move( - left.size() + 1, std::vector(right.size() + 1)); - - // Populate for empty right. - for (size_t l_i = 0; l_i < costs.size(); ++l_i) { - costs[l_i][0] = static_cast(l_i); - best_move[l_i][0] = kRemove; - } - // Populate for empty left. - for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { - costs[0][r_i] = static_cast(r_i); - best_move[0][r_i] = kAdd; - } - - for (size_t l_i = 0; l_i < left.size(); ++l_i) { - for (size_t r_i = 0; r_i < right.size(); ++r_i) { - if (left[l_i] == right[r_i]) { - // Found a match. Consume it. - costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; - best_move[l_i + 1][r_i + 1] = kMatch; - continue; - } - - const double add = costs[l_i + 1][r_i]; - const double remove = costs[l_i][r_i + 1]; - const double replace = costs[l_i][r_i]; - if (add < remove && add < replace) { - costs[l_i + 1][r_i + 1] = add + 1; - best_move[l_i + 1][r_i + 1] = kAdd; - } else if (remove < add && remove < replace) { - costs[l_i + 1][r_i + 1] = remove + 1; - best_move[l_i + 1][r_i + 1] = kRemove; - } else { - // We make replace a little more expensive than add/remove to lower - // their priority. - costs[l_i + 1][r_i + 1] = replace + 1.00001; - best_move[l_i + 1][r_i + 1] = kReplace; - } - } - } - - // Reconstruct the best path. We do it in reverse order. - std::vector best_path; - for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { - EditType move = best_move[l_i][r_i]; - best_path.push_back(move); - l_i -= move != kAdd; - r_i -= move != kRemove; - } - std::reverse(best_path.begin(), best_path.end()); - return best_path; -} - -namespace { - -// Helper class to convert string into ids with deduplication. -class InternalStrings { - public: - size_t GetId(const std::string& str) { - IdMap::iterator it = ids_.find(str); - if (it != ids_.end()) return it->second; - size_t id = ids_.size(); - return ids_[str] = id; - } - - private: - typedef std::map IdMap; - IdMap ids_; -}; - -} // namespace - -std::vector CalculateOptimalEdits( - const std::vector& left, - const std::vector& right) { - std::vector left_ids, right_ids; - { - InternalStrings intern_table; - for (size_t i = 0; i < left.size(); ++i) { - left_ids.push_back(intern_table.GetId(left[i])); - } - for (size_t i = 0; i < right.size(); ++i) { - right_ids.push_back(intern_table.GetId(right[i])); - } - } - return CalculateOptimalEdits(left_ids, right_ids); -} - -namespace { - -// Helper class that holds the state for one hunk and prints it out to the -// stream. -// It reorders adds/removes when possible to group all removes before all -// adds. It also adds the hunk header before printint into the stream. -class Hunk { - public: - Hunk(size_t left_start, size_t right_start) - : left_start_(left_start), - right_start_(right_start), - adds_(), - removes_(), - common_() {} - - void PushLine(char edit, const char* line) { - switch (edit) { - case ' ': - ++common_; - FlushEdits(); - hunk_.push_back(std::make_pair(' ', line)); - break; - case '-': - ++removes_; - hunk_removes_.push_back(std::make_pair('-', line)); - break; - case '+': - ++adds_; - hunk_adds_.push_back(std::make_pair('+', line)); - break; - } - } - - void PrintTo(std::ostream* os) { - PrintHeader(os); - FlushEdits(); - for (std::list >::const_iterator it = - hunk_.begin(); - it != hunk_.end(); ++it) { - *os << it->first << it->second << "\n"; - } - } - - bool has_edits() const { return adds_ || removes_; } - - private: - void FlushEdits() { - hunk_.splice(hunk_.end(), hunk_removes_); - hunk_.splice(hunk_.end(), hunk_adds_); - } - - // Print a unified diff header for one hunk. - // The format is - // "@@ -, +, @@" - // where the left/right parts are omitted if unnecessary. - void PrintHeader(std::ostream* ss) const { - *ss << "@@ "; - if (removes_) { - *ss << "-" << left_start_ << "," << (removes_ + common_); - } - if (removes_ && adds_) { - *ss << " "; - } - if (adds_) { - *ss << "+" << right_start_ << "," << (adds_ + common_); - } - *ss << " @@\n"; - } - - size_t left_start_, right_start_; - size_t adds_, removes_, common_; - std::list > hunk_, hunk_adds_, hunk_removes_; -}; - -} // namespace - -// Create a list of diff hunks in Unified diff format. -// Each hunk has a header generated by PrintHeader above plus a body with -// lines prefixed with ' ' for no change, '-' for deletion and '+' for -// addition. -// 'context' represents the desired unchanged prefix/suffix around the diff. -// If two hunks are close enough that their contexts overlap, then they are -// joined into one hunk. -std::string CreateUnifiedDiff(const std::vector& left, - const std::vector& right, - size_t context) { - const std::vector edits = CalculateOptimalEdits(left, right); - - size_t l_i = 0, r_i = 0, edit_i = 0; - std::stringstream ss; - while (edit_i < edits.size()) { - // Find first edit. - while (edit_i < edits.size() && edits[edit_i] == kMatch) { - ++l_i; - ++r_i; - ++edit_i; - } - - // Find the first line to include in the hunk. - const size_t prefix_context = std::min(l_i, context); - Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); - for (size_t i = prefix_context; i > 0; --i) { - hunk.PushLine(' ', left[l_i - i].c_str()); - } - - // Iterate the edits until we found enough suffix for the hunk or the input - // is over. - size_t n_suffix = 0; - for (; edit_i < edits.size(); ++edit_i) { - if (n_suffix >= context) { - // Continue only if the next hunk is very close. - auto it = edits.begin() + static_cast(edit_i); - while (it != edits.end() && *it == kMatch) ++it; - if (it == edits.end() || - static_cast(it - edits.begin()) - edit_i >= context) { - // There is no next edit or it is too far away. - break; - } - } - - EditType edit = edits[edit_i]; - // Reset count when a non match is found. - n_suffix = edit == kMatch ? n_suffix + 1 : 0; - - if (edit == kMatch || edit == kRemove || edit == kReplace) { - hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); - } - if (edit == kAdd || edit == kReplace) { - hunk.PushLine('+', right[r_i].c_str()); - } - - // Advance indices, depending on edit type. - l_i += edit != kAdd; - r_i += edit != kRemove; - } - - if (!hunk.has_edits()) { - // We are done. We don't want this hunk. - break; - } - - hunk.PrintTo(&ss); - } - return ss.str(); -} - -} // namespace edit_distance - -namespace { - -// The string representation of the values received in EqFailure() are already -// escaped. Split them on escaped '\n' boundaries. Leave all other escaped -// characters the same. -std::vector SplitEscapedString(const std::string& str) { - std::vector lines; - size_t start = 0, end = str.size(); - if (end > 2 && str[0] == '"' && str[end - 1] == '"') { - ++start; - --end; - } - bool escaped = false; - for (size_t i = start; i + 1 < end; ++i) { - if (escaped) { - escaped = false; - if (str[i] == 'n') { - lines.push_back(str.substr(start, i - start - 1)); - start = i + 1; - } - } else { - escaped = str[i] == '\\'; - } - } - lines.push_back(str.substr(start, end - start)); - return lines; -} - -} // namespace - -// Constructs and returns the message for an equality assertion -// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. -// -// The first four parameters are the expressions used in the assertion -// and their values, as strings. For example, for ASSERT_EQ(foo, bar) -// where foo is 5 and bar is 6, we have: -// -// lhs_expression: "foo" -// rhs_expression: "bar" -// lhs_value: "5" -// rhs_value: "6" -// -// The ignoring_case parameter is true if and only if the assertion is a -// *_STRCASEEQ*. When it's true, the string "Ignoring case" will -// be inserted into the message. -AssertionResult EqFailure(const char* lhs_expression, - const char* rhs_expression, - const std::string& lhs_value, - const std::string& rhs_value, - bool ignoring_case) { - Message msg; - msg << "Expected equality of these values:"; - msg << "\n " << lhs_expression; - if (lhs_value != lhs_expression) { - msg << "\n Which is: " << lhs_value; - } - msg << "\n " << rhs_expression; - if (rhs_value != rhs_expression) { - msg << "\n Which is: " << rhs_value; - } - - if (ignoring_case) { - msg << "\nIgnoring case"; - } - - if (!lhs_value.empty() && !rhs_value.empty()) { - const std::vector lhs_lines = - SplitEscapedString(lhs_value); - const std::vector rhs_lines = - SplitEscapedString(rhs_value); - if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { - msg << "\nWith diff:\n" - << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); - } - } - - return AssertionFailure() << msg; -} - -// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value) { - const char* actual_message = assertion_result.message(); - Message msg; - msg << "Value of: " << expression_text - << "\n Actual: " << actual_predicate_value; - if (actual_message[0] != '\0') - msg << " (" << actual_message << ")"; - msg << "\nExpected: " << expected_predicate_value; - return msg.GetString(); -} - -// Helper function for implementing ASSERT_NEAR. -AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error) { - const double diff = fabs(val1 - val2); - if (diff <= abs_error) return AssertionSuccess(); - - return AssertionFailure() - << "The difference between " << expr1 << " and " << expr2 - << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" - << expr1 << " evaluates to " << val1 << ",\n" - << expr2 << " evaluates to " << val2 << ", and\n" - << abs_error_expr << " evaluates to " << abs_error << "."; -} - - -// Helper template for implementing FloatLE() and DoubleLE(). -template -AssertionResult FloatingPointLE(const char* expr1, - const char* expr2, - RawType val1, - RawType val2) { - // Returns success if val1 is less than val2, - if (val1 < val2) { - return AssertionSuccess(); - } - - // or if val1 is almost equal to val2. - const FloatingPoint lhs(val1), rhs(val2); - if (lhs.AlmostEquals(rhs)) { - return AssertionSuccess(); - } - - // Note that the above two checks will both fail if either val1 or - // val2 is NaN, as the IEEE floating-point standard requires that - // any predicate involving a NaN must return false. - - ::std::stringstream val1_ss; - val1_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << val1; - - ::std::stringstream val2_ss; - val2_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << val2; - - return AssertionFailure() - << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" - << " Actual: " << StringStreamToString(&val1_ss) << " vs " - << StringStreamToString(&val2_ss); -} - -} // namespace internal - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2) { - return internal::FloatingPointLE(expr1, expr2, val1, val2); -} - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2) { - return internal::FloatingPointLE(expr1, expr2, val1, val2); -} - -namespace internal { - -// The helper function for {ASSERT|EXPECT}_EQ with int or enum -// arguments. -AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs) { - if (lhs == rhs) { - return AssertionSuccess(); - } - - return EqFailure(lhs_expression, - rhs_expression, - FormatForComparisonFailureMessage(lhs, rhs), - FormatForComparisonFailureMessage(rhs, lhs), - false); -} - -// A macro for implementing the helper functions needed to implement -// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here -// just to avoid copy-and-paste of similar code. -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - BiggestInt val1, BiggestInt val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return AssertionFailure() \ - << "Expected: (" << expr1 << ") " #op " (" << expr2\ - << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ - << " vs " << FormatForComparisonFailureMessage(val2, val1);\ - }\ -} - -// Implements the helper function for {ASSERT|EXPECT}_NE with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(NE, !=) -// Implements the helper function for {ASSERT|EXPECT}_LE with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(LE, <=) -// Implements the helper function for {ASSERT|EXPECT}_LT with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(LT, < ) -// Implements the helper function for {ASSERT|EXPECT}_GE with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(GE, >=) -// Implements the helper function for {ASSERT|EXPECT}_GT with int or -// enum arguments. -GTEST_IMPL_CMP_HELPER_(GT, > ) - -#undef GTEST_IMPL_CMP_HELPER_ - -// The helper function for {ASSERT|EXPECT}_STREQ. -AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, - const char* rhs) { - if (String::CStringEquals(lhs, rhs)) { - return AssertionSuccess(); - } - - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); -} - -// The helper function for {ASSERT|EXPECT}_STRCASEEQ. -AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, - const char* rhs_expression, - const char* lhs, - const char* rhs) { - if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { - return AssertionSuccess(); - } - - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - true); -} - -// The helper function for {ASSERT|EXPECT}_STRNE. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2) { - if (!String::CStringEquals(s1, s2)) { - return AssertionSuccess(); - } else { - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; - } -} - -// The helper function for {ASSERT|EXPECT}_STRCASENE. -AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2) { - if (!String::CaseInsensitiveCStringEquals(s1, s2)) { - return AssertionSuccess(); - } else { - return AssertionFailure() - << "Expected: (" << s1_expression << ") != (" - << s2_expression << ") (ignoring case), actual: \"" - << s1 << "\" vs \"" << s2 << "\""; - } -} - -} // namespace internal - -namespace { - -// Helper functions for implementing IsSubString() and IsNotSubstring(). - -// This group of overloaded functions return true if and only if needle -// is a substring of haystack. NULL is considered a substring of -// itself only. - -bool IsSubstringPred(const char* needle, const char* haystack) { - if (needle == nullptr || haystack == nullptr) return needle == haystack; - - return strstr(haystack, needle) != nullptr; -} - -bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { - if (needle == nullptr || haystack == nullptr) return needle == haystack; - - return wcsstr(haystack, needle) != nullptr; -} - -// StringType here can be either ::std::string or ::std::wstring. -template -bool IsSubstringPred(const StringType& needle, - const StringType& haystack) { - return haystack.find(needle) != StringType::npos; -} - -// This function implements either IsSubstring() or IsNotSubstring(), -// depending on the value of the expected_to_be_substring parameter. -// StringType here can be const char*, const wchar_t*, ::std::string, -// or ::std::wstring. -template -AssertionResult IsSubstringImpl( - bool expected_to_be_substring, - const char* needle_expr, const char* haystack_expr, - const StringType& needle, const StringType& haystack) { - if (IsSubstringPred(needle, haystack) == expected_to_be_substring) - return AssertionSuccess(); - - const bool is_wide_string = sizeof(needle[0]) > 1; - const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; - return AssertionFailure() - << "Value of: " << needle_expr << "\n" - << " Actual: " << begin_string_quote << needle << "\"\n" - << "Expected: " << (expected_to_be_substring ? "" : "not ") - << "a substring of " << haystack_expr << "\n" - << "Which is: " << begin_string_quote << haystack << "\""; -} - -} // namespace - -// IsSubstring() and IsNotSubstring() check whether needle is a -// substring of haystack (NULL is considered a substring of itself -// only), and return an appropriate error message when they fail. - -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} - -#if GTEST_HAS_STD_WSTRING -AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { - return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); -} - -AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack) { - return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); -} -#endif // GTEST_HAS_STD_WSTRING - -namespace internal { - -#if GTEST_OS_WINDOWS - -namespace { - -// Helper function for IsHRESULT{SuccessFailure} predicates -AssertionResult HRESULTFailureHelper(const char* expr, - const char* expected, - long hr) { // NOLINT -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE - - // Windows CE doesn't support FormatMessage. - const char error_text[] = ""; - -# else - - // Looks up the human-readable system message for the HRESULT code - // and since we're not passing any params to FormatMessage, we don't - // want inserts expanded. - const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS; - const DWORD kBufSize = 4096; - // Gets the system's human readable message string for this HRESULT. - char error_text[kBufSize] = { '\0' }; - DWORD message_length = ::FormatMessageA(kFlags, - 0, // no source, we're asking system - static_cast(hr), // the error - 0, // no line width restrictions - error_text, // output buffer - kBufSize, // buf size - nullptr); // no arguments for inserts - // Trims tailing white space (FormatMessage leaves a trailing CR-LF) - for (; message_length && IsSpace(error_text[message_length - 1]); - --message_length) { - error_text[message_length - 1] = '\0'; - } - -# endif // GTEST_OS_WINDOWS_MOBILE - - const std::string error_hex("0x" + String::FormatHexInt(hr)); - return ::testing::AssertionFailure() - << "Expected: " << expr << " " << expected << ".\n" - << " Actual: " << error_hex << " " << error_text << "\n"; -} - -} // namespace - -AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT - if (SUCCEEDED(hr)) { - return AssertionSuccess(); - } - return HRESULTFailureHelper(expr, "succeeds", hr); -} - -AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT - if (FAILED(hr)) { - return AssertionSuccess(); - } - return HRESULTFailureHelper(expr, "fails", hr); -} - -#endif // GTEST_OS_WINDOWS - -// Utility functions for encoding Unicode text (wide strings) in -// UTF-8. - -// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8 -// like this: -// -// Code-point length Encoding -// 0 - 7 bits 0xxxxxxx -// 8 - 11 bits 110xxxxx 10xxxxxx -// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx -// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - -// The maximum code-point a one-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint1 = (static_cast(1) << 7) - 1; - -// The maximum code-point a two-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint2 = (static_cast(1) << (5 + 6)) - 1; - -// The maximum code-point a three-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint3 = (static_cast(1) << (4 + 2*6)) - 1; - -// The maximum code-point a four-byte UTF-8 sequence can represent. -const UInt32 kMaxCodePoint4 = (static_cast(1) << (3 + 3*6)) - 1; - -// Chops off the n lowest bits from a bit pattern. Returns the n -// lowest bits. As a side effect, the original bit pattern will be -// shifted to the right by n bits. -inline UInt32 ChopLowBits(UInt32* bits, int n) { - const UInt32 low_bits = *bits & ((static_cast(1) << n) - 1); - *bits >>= n; - return low_bits; -} - -// Converts a Unicode code point to a narrow string in UTF-8 encoding. -// code_point parameter is of type UInt32 because wchar_t may not be -// wide enough to contain a code point. -// If the code_point is not a valid Unicode code point -// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted -// to "(Invalid Unicode 0xXXXXXXXX)". -std::string CodePointToUtf8(UInt32 code_point) { - if (code_point > kMaxCodePoint4) { - return "(Invalid Unicode 0x" + String::FormatHexUInt32(code_point) + ")"; - } - - char str[5]; // Big enough for the largest valid code point. - if (code_point <= kMaxCodePoint1) { - str[1] = '\0'; - str[0] = static_cast(code_point); // 0xxxxxxx - } else if (code_point <= kMaxCodePoint2) { - str[2] = '\0'; - str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[0] = static_cast(0xC0 | code_point); // 110xxxxx - } else if (code_point <= kMaxCodePoint3) { - str[3] = '\0'; - str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[0] = static_cast(0xE0 | code_point); // 1110xxxx - } else { // code_point <= kMaxCodePoint4 - str[4] = '\0'; - str[3] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[2] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[1] = static_cast(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx - str[0] = static_cast(0xF0 | code_point); // 11110xxx - } - return str; -} - -// The following two functions only make sense if the system -// uses UTF-16 for wide string encoding. All supported systems -// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16. - -// Determines if the arguments constitute UTF-16 surrogate pair -// and thus should be combined into a single Unicode code point -// using CreateCodePointFromUtf16SurrogatePair. -inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { - return sizeof(wchar_t) == 2 && - (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; -} - -// Creates a Unicode code point from UTF16 surrogate pair. -inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, - wchar_t second) { - const auto first_u = static_cast(first); - const auto second_u = static_cast(second); - const UInt32 mask = (1 << 10) - 1; - return (sizeof(wchar_t) == 2) - ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000 - : - // This function should not be called when the condition is - // false, but we provide a sensible default in case it is. - first_u; -} - -// Converts a wide string to a narrow string in UTF-8 encoding. -// The wide string is assumed to have the following encoding: -// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin) -// UTF-32 if sizeof(wchar_t) == 4 (on Linux) -// Parameter str points to a null-terminated wide string. -// Parameter num_chars may additionally limit the number -// of wchar_t characters processed. -1 is used when the entire string -// should be processed. -// If the string contains code points that are not valid Unicode code points -// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output -// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding -// and contains invalid UTF-16 surrogate pairs, values in those pairs -// will be encoded as individual Unicode characters from Basic Normal Plane. -std::string WideStringToUtf8(const wchar_t* str, int num_chars) { - if (num_chars == -1) - num_chars = static_cast(wcslen(str)); - - ::std::stringstream stream; - for (int i = 0; i < num_chars; ++i) { - UInt32 unicode_code_point; - - if (str[i] == L'\0') { - break; - } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { - unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], - str[i + 1]); - i++; - } else { - unicode_code_point = static_cast(str[i]); - } - - stream << CodePointToUtf8(unicode_code_point); - } - return StringStreamToString(&stream); -} - -// Converts a wide C string to an std::string using the UTF-8 encoding. -// NULL will be converted to "(null)". -std::string String::ShowWideCString(const wchar_t * wide_c_str) { - if (wide_c_str == nullptr) return "(null)"; - - return internal::WideStringToUtf8(wide_c_str, -1); -} - -// Compares two wide C strings. Returns true if and only if they have the -// same content. -// -// Unlike wcscmp(), this function can handle NULL argument(s). A NULL -// C string is considered different to any non-NULL C string, -// including the empty string. -bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { - if (lhs == nullptr) return rhs == nullptr; - - if (rhs == nullptr) return false; - - return wcscmp(lhs, rhs) == 0; -} - -// Helper function for *_STREQ on wide strings. -AssertionResult CmpHelperSTREQ(const char* lhs_expression, - const char* rhs_expression, - const wchar_t* lhs, - const wchar_t* rhs) { - if (String::WideCStringEquals(lhs, rhs)) { - return AssertionSuccess(); - } - - return EqFailure(lhs_expression, - rhs_expression, - PrintToString(lhs), - PrintToString(rhs), - false); -} - -// Helper function for *_STRNE on wide strings. -AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2) { - if (!String::WideCStringEquals(s1, s2)) { - return AssertionSuccess(); - } - - return AssertionFailure() << "Expected: (" << s1_expression << ") != (" - << s2_expression << "), actual: " - << PrintToString(s1) - << " vs " << PrintToString(s2); -} - -// Compares two C strings, ignoring case. Returns true if and only if they have -// the same content. -// -// Unlike strcasecmp(), this function can handle NULL argument(s). A -// NULL C string is considered different to any non-NULL C string, -// including the empty string. -bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { - if (lhs == nullptr) return rhs == nullptr; - if (rhs == nullptr) return false; - return posix::StrCaseCmp(lhs, rhs) == 0; -} - -// Compares two wide C strings, ignoring case. Returns true if and only if they -// have the same content. -// -// Unlike wcscasecmp(), this function can handle NULL argument(s). -// A NULL C string is considered different to any non-NULL wide C string, -// including the empty string. -// NB: The implementations on different platforms slightly differ. -// On windows, this method uses _wcsicmp which compares according to LC_CTYPE -// environment variable. On GNU platform this method uses wcscasecmp -// which compares according to LC_CTYPE category of the current locale. -// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the -// current locale. -bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs) { - if (lhs == nullptr) return rhs == nullptr; - - if (rhs == nullptr) return false; - -#if GTEST_OS_WINDOWS - return _wcsicmp(lhs, rhs) == 0; -#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID - return wcscasecmp(lhs, rhs) == 0; -#else - // Android, Mac OS X and Cygwin don't define wcscasecmp. - // Other unknown OSes may not define it either. - wint_t left, right; - do { - left = towlower(static_cast(*lhs++)); - right = towlower(static_cast(*rhs++)); - } while (left && left == right); - return left == right; -#endif // OS selector -} - -// Returns true if and only if str ends with the given suffix, ignoring case. -// Any string is considered to end with an empty suffix. -bool String::EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix) { - const size_t str_len = str.length(); - const size_t suffix_len = suffix.length(); - return (str_len >= suffix_len) && - CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, - suffix.c_str()); -} - -// Formats an int value as "%02d". -std::string String::FormatIntWidth2(int value) { - std::stringstream ss; - ss << std::setfill('0') << std::setw(2) << value; - return ss.str(); -} - -// Formats an int value as "%X". -std::string String::FormatHexUInt32(UInt32 value) { - std::stringstream ss; - ss << std::hex << std::uppercase << value; - return ss.str(); -} - -// Formats an int value as "%X". -std::string String::FormatHexInt(int value) { - return FormatHexUInt32(static_cast(value)); -} - -// Formats a byte as "%02X". -std::string String::FormatByte(unsigned char value) { - std::stringstream ss; - ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase - << static_cast(value); - return ss.str(); -} - -// Converts the buffer in a stringstream to an std::string, converting NUL -// bytes to "\\0" along the way. -std::string StringStreamToString(::std::stringstream* ss) { - const ::std::string& str = ss->str(); - const char* const start = str.c_str(); - const char* const end = start + str.length(); - - std::string result; - result.reserve(static_cast(2 * (end - start))); - for (const char* ch = start; ch != end; ++ch) { - if (*ch == '\0') { - result += "\\0"; // Replaces NUL with "\\0"; - } else { - result += *ch; - } - } - - return result; -} - -// Appends the user-supplied message to the Google-Test-generated message. -std::string AppendUserMessage(const std::string& gtest_msg, - const Message& user_msg) { - // Appends the user message if it's non-empty. - const std::string user_msg_string = user_msg.GetString(); - if (user_msg_string.empty()) { - return gtest_msg; - } - - return gtest_msg + "\n" + user_msg_string; -} - -} // namespace internal - -// class TestResult - -// Creates an empty TestResult. -TestResult::TestResult() - : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {} - -// D'tor. -TestResult::~TestResult() { -} - -// Returns the i-th test part result among all the results. i can -// range from 0 to total_part_count() - 1. If i is not in that range, -// aborts the program. -const TestPartResult& TestResult::GetTestPartResult(int i) const { - if (i < 0 || i >= total_part_count()) - internal::posix::Abort(); - return test_part_results_.at(static_cast(i)); -} - -// Returns the i-th test property. i can range from 0 to -// test_property_count() - 1. If i is not in that range, aborts the -// program. -const TestProperty& TestResult::GetTestProperty(int i) const { - if (i < 0 || i >= test_property_count()) - internal::posix::Abort(); - return test_properties_.at(static_cast(i)); -} - -// Clears the test part results. -void TestResult::ClearTestPartResults() { - test_part_results_.clear(); -} - -// Adds a test part result to the list. -void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { - test_part_results_.push_back(test_part_result); -} - -// Adds a test property to the list. If a property with the same key as the -// supplied property is already represented, the value of this test_property -// replaces the old value for that key. -void TestResult::RecordProperty(const std::string& xml_element, - const TestProperty& test_property) { - if (!ValidateTestProperty(xml_element, test_property)) { - return; - } - internal::MutexLock lock(&test_properites_mutex_); - const std::vector::iterator property_with_matching_key = - std::find_if(test_properties_.begin(), test_properties_.end(), - internal::TestPropertyKeyIs(test_property.key())); - if (property_with_matching_key == test_properties_.end()) { - test_properties_.push_back(test_property); - return; - } - property_with_matching_key->SetValue(test_property.value()); -} - -// The list of reserved attributes used in the element of XML -// output. -static const char* const kReservedTestSuitesAttributes[] = { - "disabled", - "errors", - "failures", - "name", - "random_seed", - "tests", - "time", - "timestamp" -}; - -// The list of reserved attributes used in the element of XML -// output. -static const char* const kReservedTestSuiteAttributes[] = { - "disabled", "errors", "failures", "name", "tests", "time", "timestamp"}; - -// The list of reserved attributes used in the element of XML output. -static const char* const kReservedTestCaseAttributes[] = { - "classname", "name", "status", "time", "type_param", - "value_param", "file", "line"}; - -// Use a slightly different set for allowed output to ensure existing tests can -// still RecordProperty("result") or "RecordProperty(timestamp") -static const char* const kReservedOutputTestCaseAttributes[] = { - "classname", "name", "status", "time", "type_param", - "value_param", "file", "line", "result", "timestamp"}; - -template -std::vector ArrayAsVector(const char* const (&array)[kSize]) { - return std::vector(array, array + kSize); -} - -static std::vector GetReservedAttributesForElement( - const std::string& xml_element) { - if (xml_element == "testsuites") { - return ArrayAsVector(kReservedTestSuitesAttributes); - } else if (xml_element == "testsuite") { - return ArrayAsVector(kReservedTestSuiteAttributes); - } else if (xml_element == "testcase") { - return ArrayAsVector(kReservedTestCaseAttributes); - } else { - GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; - } - // This code is unreachable but some compilers may not realizes that. - return std::vector(); -} - -// TODO(jdesprez): Merge the two getReserved attributes once skip is improved -static std::vector GetReservedOutputAttributesForElement( - const std::string& xml_element) { - if (xml_element == "testsuites") { - return ArrayAsVector(kReservedTestSuitesAttributes); - } else if (xml_element == "testsuite") { - return ArrayAsVector(kReservedTestSuiteAttributes); - } else if (xml_element == "testcase") { - return ArrayAsVector(kReservedOutputTestCaseAttributes); - } else { - GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; - } - // This code is unreachable but some compilers may not realizes that. - return std::vector(); -} - -static std::string FormatWordList(const std::vector& words) { - Message word_list; - for (size_t i = 0; i < words.size(); ++i) { - if (i > 0 && words.size() > 2) { - word_list << ", "; - } - if (i == words.size() - 1) { - word_list << "and "; - } - word_list << "'" << words[i] << "'"; - } - return word_list.GetString(); -} - -static bool ValidateTestPropertyName( - const std::string& property_name, - const std::vector& reserved_names) { - if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != - reserved_names.end()) { - ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name - << " (" << FormatWordList(reserved_names) - << " are reserved by " << GTEST_NAME_ << ")"; - return false; - } - return true; -} - -// Adds a failure if the key is a reserved attribute of the element named -// xml_element. Returns true if the property is valid. -bool TestResult::ValidateTestProperty(const std::string& xml_element, - const TestProperty& test_property) { - return ValidateTestPropertyName(test_property.key(), - GetReservedAttributesForElement(xml_element)); -} - -// Clears the object. -void TestResult::Clear() { - test_part_results_.clear(); - test_properties_.clear(); - death_test_count_ = 0; - elapsed_time_ = 0; -} - -// Returns true off the test part was skipped. -static bool TestPartSkipped(const TestPartResult& result) { - return result.skipped(); -} - -// Returns true if and only if the test was skipped. -bool TestResult::Skipped() const { - return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0; -} - -// Returns true if and only if the test failed. -bool TestResult::Failed() const { - for (int i = 0; i < total_part_count(); ++i) { - if (GetTestPartResult(i).failed()) - return true; - } - return false; -} - -// Returns true if and only if the test part fatally failed. -static bool TestPartFatallyFailed(const TestPartResult& result) { - return result.fatally_failed(); -} - -// Returns true if and only if the test fatally failed. -bool TestResult::HasFatalFailure() const { - return CountIf(test_part_results_, TestPartFatallyFailed) > 0; -} - -// Returns true if and only if the test part non-fatally failed. -static bool TestPartNonfatallyFailed(const TestPartResult& result) { - return result.nonfatally_failed(); -} - -// Returns true if and only if the test has a non-fatal failure. -bool TestResult::HasNonfatalFailure() const { - return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; -} - -// Gets the number of all test parts. This is the sum of the number -// of successful test parts and the number of failed test parts. -int TestResult::total_part_count() const { - return static_cast(test_part_results_.size()); -} - -// Returns the number of the test properties. -int TestResult::test_property_count() const { - return static_cast(test_properties_.size()); -} - -// class Test - -// Creates a Test object. - -// The c'tor saves the states of all flags. -Test::Test() - : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { -} - -// The d'tor restores the states of all flags. The actual work is -// done by the d'tor of the gtest_flag_saver_ field, and thus not -// visible here. -Test::~Test() { -} - -// Sets up the test fixture. -// -// A sub-class may override this. -void Test::SetUp() { -} - -// Tears down the test fixture. -// -// A sub-class may override this. -void Test::TearDown() { -} - -// Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const std::string& key, const std::string& value) { - UnitTest::GetInstance()->RecordProperty(key, value); -} - -// Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const std::string& key, int value) { - Message value_message; - value_message << value; - RecordProperty(key, value_message.GetString().c_str()); -} - -namespace internal { - -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const std::string& message) { - // This function is a friend of UnitTest and as such has access to - // AddTestPartResult. - UnitTest::GetInstance()->AddTestPartResult( - result_type, - nullptr, // No info about the source file where the exception occurred. - -1, // We have no info on which line caused the exception. - message, - ""); // No stack trace, either. -} - -} // namespace internal - -// Google Test requires all tests in the same test suite to use the same test -// fixture class. This function checks if the current test has the -// same fixture class as the first test in the current test suite. If -// yes, it returns true; otherwise it generates a Google Test failure and -// returns false. -bool Test::HasSameFixtureClass() { - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - const TestSuite* const test_suite = impl->current_test_suite(); - - // Info about the first test in the current test suite. - const TestInfo* const first_test_info = test_suite->test_info_list()[0]; - const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; - const char* const first_test_name = first_test_info->name(); - - // Info about the current test. - const TestInfo* const this_test_info = impl->current_test_info(); - const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; - const char* const this_test_name = this_test_info->name(); - - if (this_fixture_id != first_fixture_id) { - // Is the first test defined using TEST? - const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); - // Is this test defined using TEST? - const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); - - if (first_is_TEST || this_is_TEST) { - // Both TEST and TEST_F appear in same test suite, which is incorrect. - // Tell the user how to fix this. - - // Gets the name of the TEST and the name of the TEST_F. Note - // that first_is_TEST and this_is_TEST cannot both be true, as - // the fixture IDs are different for the two tests. - const char* const TEST_name = - first_is_TEST ? first_test_name : this_test_name; - const char* const TEST_F_name = - first_is_TEST ? this_test_name : first_test_name; - - ADD_FAILURE() - << "All tests in the same test suite must use the same test fixture\n" - << "class, so mixing TEST_F and TEST in the same test suite is\n" - << "illegal. In test suite " << this_test_info->test_suite_name() - << ",\n" - << "test " << TEST_F_name << " is defined using TEST_F but\n" - << "test " << TEST_name << " is defined using TEST. You probably\n" - << "want to change the TEST to TEST_F or move it to another test\n" - << "case."; - } else { - // Two fixture classes with the same name appear in two different - // namespaces, which is not allowed. Tell the user how to fix this. - ADD_FAILURE() - << "All tests in the same test suite must use the same test fixture\n" - << "class. However, in test suite " - << this_test_info->test_suite_name() << ",\n" - << "you defined test " << first_test_name << " and test " - << this_test_name << "\n" - << "using two different test fixture classes. This can happen if\n" - << "the two classes are from different namespaces or translation\n" - << "units and have the same name. You should probably rename one\n" - << "of the classes to put the tests into different test suites."; - } - return false; - } - - return true; -} - -#if GTEST_HAS_SEH - -// Adds an "exception thrown" fatal failure to the current test. This -// function returns its result via an output parameter pointer because VC++ -// prohibits creation of objects with destructors on stack in functions -// using __try (see error C2712). -static std::string* FormatSehExceptionMessage(DWORD exception_code, - const char* location) { - Message message; - message << "SEH exception with code 0x" << std::setbase(16) << - exception_code << std::setbase(10) << " thrown in " << location << "."; - - return new std::string(message.GetString()); -} - -#endif // GTEST_HAS_SEH - -namespace internal { - -#if GTEST_HAS_EXCEPTIONS - -// Adds an "exception thrown" fatal failure to the current test. -static std::string FormatCxxExceptionMessage(const char* description, - const char* location) { - Message message; - if (description != nullptr) { - message << "C++ exception with description \"" << description << "\""; - } else { - message << "Unknown C++ exception"; - } - message << " thrown in " << location << "."; - - return message.GetString(); -} - -static std::string PrintTestPartResultToString( - const TestPartResult& test_part_result); - -GoogleTestFailureException::GoogleTestFailureException( - const TestPartResult& failure) - : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} - -#endif // GTEST_HAS_EXCEPTIONS - -// We put these helper functions in the internal namespace as IBM's xlC -// compiler rejects the code if they were declared static. - -// Runs the given method and handles SEH exceptions it throws, when -// SEH is supported; returns the 0-value for type Result in case of an -// SEH exception. (Microsoft compilers cannot handle SEH and C++ -// exceptions in the same function. Therefore, we provide a separate -// wrapper function for handling SEH exceptions.) -template -Result HandleSehExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { -#if GTEST_HAS_SEH - __try { - return (object->*method)(); - } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT - GetExceptionCode())) { - // We create the exception message on the heap because VC++ prohibits - // creation of objects with destructors on stack in functions using __try - // (see error C2712). - std::string* exception_message = FormatSehExceptionMessage( - GetExceptionCode(), location); - internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, - *exception_message); - delete exception_message; - return static_cast(0); - } -#else - (void)location; - return (object->*method)(); -#endif // GTEST_HAS_SEH -} - -// Runs the given method and catches and reports C++ and/or SEH-style -// exceptions, if they are supported; returns the 0-value for type -// Result in case of an SEH exception. -template -Result HandleExceptionsInMethodIfSupported( - T* object, Result (T::*method)(), const char* location) { - // NOTE: The user code can affect the way in which Google Test handles - // exceptions by setting GTEST_FLAG(catch_exceptions), but only before - // RUN_ALL_TESTS() starts. It is technically possible to check the flag - // after the exception is caught and either report or re-throw the - // exception based on the flag's value: - // - // try { - // // Perform the test method. - // } catch (...) { - // if (GTEST_FLAG(catch_exceptions)) - // // Report the exception as failure. - // else - // throw; // Re-throws the original exception. - // } - // - // However, the purpose of this flag is to allow the program to drop into - // the debugger when the exception is thrown. On most platforms, once the - // control enters the catch block, the exception origin information is - // lost and the debugger will stop the program at the point of the - // re-throw in this function -- instead of at the point of the original - // throw statement in the code under test. For this reason, we perform - // the check early, sacrificing the ability to affect Google Test's - // exception handling in the method where the exception is thrown. - if (internal::GetUnitTestImpl()->catch_exceptions()) { -#if GTEST_HAS_EXCEPTIONS - try { - return HandleSehExceptionsInMethodIfSupported(object, method, location); - } catch (const AssertionException&) { // NOLINT - // This failure was reported already. - } catch (const internal::GoogleTestFailureException&) { // NOLINT - // This exception type can only be thrown by a failed Google - // Test assertion with the intention of letting another testing - // framework catch it. Therefore we just re-throw it. - throw; - } catch (const std::exception& e) { // NOLINT - internal::ReportFailureInUnknownLocation( - TestPartResult::kFatalFailure, - FormatCxxExceptionMessage(e.what(), location)); - } catch (...) { // NOLINT - internal::ReportFailureInUnknownLocation( - TestPartResult::kFatalFailure, - FormatCxxExceptionMessage(nullptr, location)); - } - return static_cast(0); -#else - return HandleSehExceptionsInMethodIfSupported(object, method, location); -#endif // GTEST_HAS_EXCEPTIONS - } else { - return (object->*method)(); - } -} - -} // namespace internal - -// Runs the test and updates the test result. -void Test::Run() { - if (!HasSameFixtureClass()) return; - - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); - // We will run the test only if SetUp() was successful and didn't call - // GTEST_SKIP(). - if (!HasFatalFailure() && !IsSkipped()) { - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TestBody, "the test body"); - } - - // However, we want to clean up as much as possible. Hence we will - // always call TearDown(), even if SetUp() or the test body has - // failed. - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &Test::TearDown, "TearDown()"); -} - -// Returns true if and only if the current test has a fatal failure. -bool Test::HasFatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); -} - -// Returns true if and only if the current test has a non-fatal failure. -bool Test::HasNonfatalFailure() { - return internal::GetUnitTestImpl()->current_test_result()-> - HasNonfatalFailure(); -} - -// Returns true if and only if the current test was skipped. -bool Test::IsSkipped() { - return internal::GetUnitTestImpl()->current_test_result()->Skipped(); -} - -// class TestInfo - -// Constructs a TestInfo object. It assumes ownership of the test factory -// object. -TestInfo::TestInfo(const std::string& a_test_suite_name, - const std::string& a_name, const char* a_type_param, - const char* a_value_param, - internal::CodeLocation a_code_location, - internal::TypeId fixture_class_id, - internal::TestFactoryBase* factory) - : test_suite_name_(a_test_suite_name), - name_(a_name), - type_param_(a_type_param ? new std::string(a_type_param) : nullptr), - value_param_(a_value_param ? new std::string(a_value_param) : nullptr), - location_(a_code_location), - fixture_class_id_(fixture_class_id), - should_run_(false), - is_disabled_(false), - matches_filter_(false), - factory_(factory), - result_() {} - -// Destructs a TestInfo object. -TestInfo::~TestInfo() { delete factory_; } - -namespace internal { - -// Creates a new TestInfo object and registers it with Google Test; -// returns the created object. -// -// Arguments: -// -// test_suite_name: name of the test suite -// name: name of the test -// type_param: the name of the test's type parameter, or NULL if -// this is not a typed or a type-parameterized test. -// value_param: text representation of the test's value parameter, -// or NULL if this is not a value-parameterized test. -// code_location: code location where the test is defined -// fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test suite -// tear_down_tc: pointer to the function that tears down the test suite -// factory: pointer to the factory that creates a test object. -// The newly created TestInfo instance will assume -// ownership of the factory object. -TestInfo* MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, - const char* value_param, CodeLocation code_location, - TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, - TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) { - TestInfo* const test_info = - new TestInfo(test_suite_name, name, type_param, value_param, - code_location, fixture_class_id, factory); - GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); - return test_info; -} - -void ReportInvalidTestSuiteType(const char* test_suite_name, - CodeLocation code_location) { - Message errors; - errors - << "Attempted redefinition of test suite " << test_suite_name << ".\n" - << "All tests in the same test suite must use the same test fixture\n" - << "class. However, in test suite " << test_suite_name << ", you tried\n" - << "to define a test using a fixture class different from the one\n" - << "used earlier. This can happen if the two fixture classes are\n" - << "from different namespaces and have the same name. You should\n" - << "probably rename one of the classes to put the tests into different\n" - << "test suites."; - - GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(), - code_location.line) - << " " << errors.GetString(); -} -} // namespace internal - -namespace { - -// A predicate that checks the test name of a TestInfo against a known -// value. -// -// This is used for implementation of the TestSuite class only. We put -// it in the anonymous namespace to prevent polluting the outer -// namespace. -// -// TestNameIs is copyable. -class TestNameIs { - public: - // Constructor. - // - // TestNameIs has NO default constructor. - explicit TestNameIs(const char* name) - : name_(name) {} - - // Returns true if and only if the test name of test_info matches name_. - bool operator()(const TestInfo * test_info) const { - return test_info && test_info->name() == name_; - } - - private: - std::string name_; -}; - -} // namespace - -namespace internal { - -// This method expands all parameterized tests registered with macros TEST_P -// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those. -// This will be done just once during the program runtime. -void UnitTestImpl::RegisterParameterizedTests() { - if (!parameterized_tests_registered_) { - parameterized_test_registry_.RegisterTests(); - parameterized_tests_registered_ = true; - } -} - -} // namespace internal - -// Creates the test object, runs it, records its result, and then -// deletes it. -void TestInfo::Run() { - if (!should_run_) return; - - // Tells UnitTest where to store test result. - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_info(this); - - TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); - - // Notifies the unit test event listeners that a test is about to start. - repeater->OnTestStart(*this); - - const TimeInMillis start = internal::GetTimeInMillis(); - - impl->os_stack_trace_getter()->UponLeavingGTest(); - - // Creates the test object. - Test* const test = internal::HandleExceptionsInMethodIfSupported( - factory_, &internal::TestFactoryBase::CreateTest, - "the test fixture's constructor"); - - // Runs the test if the constructor didn't generate a fatal failure or invoke - // GTEST_SKIP(). - // Note that the object will not be null - if (!Test::HasFatalFailure() && !Test::IsSkipped()) { - // This doesn't throw as all user code that can throw are wrapped into - // exception handling code. - test->Run(); - } - - if (test != nullptr) { - // Deletes the test object. - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - test, &Test::DeleteSelf_, "the test fixture's destructor"); - } - - result_.set_start_timestamp(start); - result_.set_elapsed_time(internal::GetTimeInMillis() - start); - - // Notifies the unit test event listener that a test has just finished. - repeater->OnTestEnd(*this); - - // Tells UnitTest to stop associating assertion results to this - // test. - impl->set_current_test_info(nullptr); -} - -// class TestSuite - -// Gets the number of successful tests in this test suite. -int TestSuite::successful_test_count() const { - return CountIf(test_info_list_, TestPassed); -} - -// Gets the number of successful tests in this test suite. -int TestSuite::skipped_test_count() const { - return CountIf(test_info_list_, TestSkipped); -} - -// Gets the number of failed tests in this test suite. -int TestSuite::failed_test_count() const { - return CountIf(test_info_list_, TestFailed); -} - -// Gets the number of disabled tests that will be reported in the XML report. -int TestSuite::reportable_disabled_test_count() const { - return CountIf(test_info_list_, TestReportableDisabled); -} - -// Gets the number of disabled tests in this test suite. -int TestSuite::disabled_test_count() const { - return CountIf(test_info_list_, TestDisabled); -} - -// Gets the number of tests to be printed in the XML report. -int TestSuite::reportable_test_count() const { - return CountIf(test_info_list_, TestReportable); -} - -// Get the number of tests in this test suite that should run. -int TestSuite::test_to_run_count() const { - return CountIf(test_info_list_, ShouldRunTest); -} - -// Gets the number of all tests. -int TestSuite::total_test_count() const { - return static_cast(test_info_list_.size()); -} - -// Creates a TestSuite with the given name. -// -// Arguments: -// -// name: name of the test suite -// a_type_param: the name of the test suite's type parameter, or NULL if -// this is not a typed or a type-parameterized test suite. -// set_up_tc: pointer to the function that sets up the test suite -// tear_down_tc: pointer to the function that tears down the test suite -TestSuite::TestSuite(const char* a_name, const char* a_type_param, - internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc) - : name_(a_name), - type_param_(a_type_param ? new std::string(a_type_param) : nullptr), - set_up_tc_(set_up_tc), - tear_down_tc_(tear_down_tc), - should_run_(false), - start_timestamp_(0), - elapsed_time_(0) {} - -// Destructor of TestSuite. -TestSuite::~TestSuite() { - // Deletes every Test in the collection. - ForEach(test_info_list_, internal::Delete); -} - -// Returns the i-th test among all the tests. i can range from 0 to -// total_test_count() - 1. If i is not in that range, returns NULL. -const TestInfo* TestSuite::GetTestInfo(int i) const { - const int index = GetElementOr(test_indices_, i, -1); - return index < 0 ? nullptr : test_info_list_[static_cast(index)]; -} - -// Returns the i-th test among all the tests. i can range from 0 to -// total_test_count() - 1. If i is not in that range, returns NULL. -TestInfo* TestSuite::GetMutableTestInfo(int i) { - const int index = GetElementOr(test_indices_, i, -1); - return index < 0 ? nullptr : test_info_list_[static_cast(index)]; -} - -// Adds a test to this test suite. Will delete the test upon -// destruction of the TestSuite object. -void TestSuite::AddTestInfo(TestInfo* test_info) { - test_info_list_.push_back(test_info); - test_indices_.push_back(static_cast(test_indices_.size())); -} - -// Runs every test in this TestSuite. -void TestSuite::Run() { - if (!should_run_) return; - - internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); - impl->set_current_test_suite(this); - - TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); - - // Call both legacy and the new API - repeater->OnTestSuiteStart(*this); -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI - repeater->OnTestCaseStart(*this); -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI - - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &TestSuite::RunSetUpTestSuite, "SetUpTestSuite()"); - - start_timestamp_ = internal::GetTimeInMillis(); - for (int i = 0; i < total_test_count(); i++) { - GetMutableTestInfo(i)->Run(); - } - elapsed_time_ = internal::GetTimeInMillis() - start_timestamp_; - - impl->os_stack_trace_getter()->UponLeavingGTest(); - internal::HandleExceptionsInMethodIfSupported( - this, &TestSuite::RunTearDownTestSuite, "TearDownTestSuite()"); - - // Call both legacy and the new API - repeater->OnTestSuiteEnd(*this); -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI - repeater->OnTestCaseEnd(*this); -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI - - impl->set_current_test_suite(nullptr); -} - -// Clears the results of all tests in this test suite. -void TestSuite::ClearResult() { - ad_hoc_test_result_.Clear(); - ForEach(test_info_list_, TestInfo::ClearTestResult); -} - -// Shuffles the tests in this test suite. -void TestSuite::ShuffleTests(internal::Random* random) { - Shuffle(random, &test_indices_); -} - -// Restores the test order to before the first shuffle. -void TestSuite::UnshuffleTests() { - for (size_t i = 0; i < test_indices_.size(); i++) { - test_indices_[i] = static_cast(i); - } -} - -// Formats a countable noun. Depending on its quantity, either the -// singular form or the plural form is used. e.g. -// -// FormatCountableNoun(1, "formula", "formuli") returns "1 formula". -// FormatCountableNoun(5, "book", "books") returns "5 books". -static std::string FormatCountableNoun(int count, - const char * singular_form, - const char * plural_form) { - return internal::StreamableToString(count) + " " + - (count == 1 ? singular_form : plural_form); -} - -// Formats the count of tests. -static std::string FormatTestCount(int test_count) { - return FormatCountableNoun(test_count, "test", "tests"); -} - -// Formats the count of test suites. -static std::string FormatTestSuiteCount(int test_suite_count) { - return FormatCountableNoun(test_suite_count, "test suite", "test suites"); -} - -// Converts a TestPartResult::Type enum to human-friendly string -// representation. Both kNonFatalFailure and kFatalFailure are translated -// to "Failure", as the user usually doesn't care about the difference -// between the two when viewing the test result. -static const char * TestPartResultTypeToString(TestPartResult::Type type) { - switch (type) { - case TestPartResult::kSkip: - return "Skipped"; - case TestPartResult::kSuccess: - return "Success"; - - case TestPartResult::kNonFatalFailure: - case TestPartResult::kFatalFailure: -#ifdef _MSC_VER - return "error: "; -#else - return "Failure\n"; -#endif - default: - return "Unknown result type"; - } -} - -namespace internal { - -// Prints a TestPartResult to an std::string. -static std::string PrintTestPartResultToString( - const TestPartResult& test_part_result) { - return (Message() - << internal::FormatFileLocation(test_part_result.file_name(), - test_part_result.line_number()) - << " " << TestPartResultTypeToString(test_part_result.type()) - << test_part_result.message()).GetString(); -} - -// Prints a TestPartResult. -static void PrintTestPartResult(const TestPartResult& test_part_result) { - const std::string& result = - PrintTestPartResultToString(test_part_result); - printf("%s\n", result.c_str()); - fflush(stdout); - // If the test program runs in Visual Studio or a debugger, the - // following statements add the test part result message to the Output - // window such that the user can double-click on it to jump to the - // corresponding source code location; otherwise they do nothing. -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - // We don't call OutputDebugString*() on Windows Mobile, as printing - // to stdout is done by OutputDebugString() there already - we don't - // want the same message printed twice. - ::OutputDebugStringA(result.c_str()); - ::OutputDebugStringA("\n"); -#endif -} - -// class PrettyUnitTestResultPrinter -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW - -// Returns the character attribute for the given color. -static WORD GetColorAttribute(GTestColor color) { - switch (color) { - case COLOR_RED: return FOREGROUND_RED; - case COLOR_GREEN: return FOREGROUND_GREEN; - case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; - default: return 0; - } -} - -static int GetBitOffset(WORD color_mask) { - if (color_mask == 0) return 0; - - int bitOffset = 0; - while ((color_mask & 1) == 0) { - color_mask >>= 1; - ++bitOffset; - } - return bitOffset; -} - -static WORD GetNewColor(GTestColor color, WORD old_color_attrs) { - // Let's reuse the BG - static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | - BACKGROUND_RED | BACKGROUND_INTENSITY; - static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | - FOREGROUND_RED | FOREGROUND_INTENSITY; - const WORD existing_bg = old_color_attrs & background_mask; - - WORD new_color = - GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY; - static const int bg_bitOffset = GetBitOffset(background_mask); - static const int fg_bitOffset = GetBitOffset(foreground_mask); - - if (((new_color & background_mask) >> bg_bitOffset) == - ((new_color & foreground_mask) >> fg_bitOffset)) { - new_color ^= FOREGROUND_INTENSITY; // invert intensity - } - return new_color; -} - -#else - -// Returns the ANSI color code for the given color. COLOR_DEFAULT is -// an invalid input. -static const char* GetAnsiColorCode(GTestColor color) { - switch (color) { - case COLOR_RED: return "1"; - case COLOR_GREEN: return "2"; - case COLOR_YELLOW: return "3"; - default: - return nullptr; - } -} - -#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - -// Returns true if and only if Google Test should use colors in the output. -bool ShouldUseColor(bool stdout_is_tty) { - const char* const gtest_color = GTEST_FLAG(color).c_str(); - - if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW - // On Windows the TERM variable is usually not set, but the - // console there does support colors. - return stdout_is_tty; -#else - // On non-Windows platforms, we rely on the TERM variable. - const char* const term = posix::GetEnv("TERM"); - const bool term_supports_color = - String::CStringEquals(term, "xterm") || - String::CStringEquals(term, "xterm-color") || - String::CStringEquals(term, "xterm-256color") || - String::CStringEquals(term, "screen") || - String::CStringEquals(term, "screen-256color") || - String::CStringEquals(term, "tmux") || - String::CStringEquals(term, "tmux-256color") || - String::CStringEquals(term, "rxvt-unicode") || - String::CStringEquals(term, "rxvt-unicode-256color") || - String::CStringEquals(term, "linux") || - String::CStringEquals(term, "cygwin"); - return stdout_is_tty && term_supports_color; -#endif // GTEST_OS_WINDOWS - } - - return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || - String::CaseInsensitiveCStringEquals(gtest_color, "true") || - String::CaseInsensitiveCStringEquals(gtest_color, "t") || - String::CStringEquals(gtest_color, "1"); - // We take "yes", "true", "t", and "1" as meaning "yes". If the - // value is neither one of these nor "auto", we treat it as "no" to - // be conservative. -} - -// Helpers for printing colored strings to stdout. Note that on Windows, we -// cannot simply emit special characters and have the terminal change colors. -// This routine must actually emit the characters rather than return a string -// that would be colored when printed, as can be done on Linux. -void ColoredPrintf(GTestColor color, const char* fmt, ...) { - va_list args; - va_start(args, fmt); - -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \ - GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM) - const bool use_color = AlwaysFalse(); -#else - static const bool in_color_mode = - ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); - const bool use_color = in_color_mode && (color != COLOR_DEFAULT); -#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS - - if (!use_color) { - vprintf(fmt, args); - va_end(args); - return; - } - -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ - !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW - const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); - - // Gets the current text color. - CONSOLE_SCREEN_BUFFER_INFO buffer_info; - GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); - const WORD old_color_attrs = buffer_info.wAttributes; - const WORD new_color = GetNewColor(color, old_color_attrs); - - // We need to flush the stream buffers into the console before each - // SetConsoleTextAttribute call lest it affect the text that is already - // printed but has not yet reached the console. - fflush(stdout); - SetConsoleTextAttribute(stdout_handle, new_color); - - vprintf(fmt, args); - - fflush(stdout); - // Restores the text color. - SetConsoleTextAttribute(stdout_handle, old_color_attrs); -#else - printf("\033[0;3%sm", GetAnsiColorCode(color)); - vprintf(fmt, args); - printf("\033[m"); // Resets the terminal to default. -#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE - va_end(args); -} - -// Text printed in Google Test's text output and --gtest_list_tests -// output to label the type parameter and value parameter for a test. -static const char kTypeParamLabel[] = "TypeParam"; -static const char kValueParamLabel[] = "GetParam()"; - -static void PrintFullTestCommentIfPresent(const TestInfo& test_info) { - const char* const type_param = test_info.type_param(); - const char* const value_param = test_info.value_param(); - - if (type_param != nullptr || value_param != nullptr) { - printf(", where "); - if (type_param != nullptr) { - printf("%s = %s", kTypeParamLabel, type_param); - if (value_param != nullptr) printf(" and "); - } - if (value_param != nullptr) { - printf("%s = %s", kValueParamLabel, value_param); - } - } -} - -// This class implements the TestEventListener interface. -// -// Class PrettyUnitTestResultPrinter is copyable. -class PrettyUnitTestResultPrinter : public TestEventListener { - public: - PrettyUnitTestResultPrinter() {} - static void PrintTestName(const char* test_suite, const char* test) { - printf("%s.%s", test_suite, test); - } - - // The following methods override what's in the TestEventListener class. - void OnTestProgramStart(const UnitTest& /*unit_test*/) override {} - void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; - void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; - void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestCaseStart(const TestCase& test_case) override; -#else - void OnTestSuiteStart(const TestSuite& test_suite) override; -#endif // OnTestCaseStart - - void OnTestStart(const TestInfo& test_info) override; - - void OnTestPartResult(const TestPartResult& result) override; - void OnTestEnd(const TestInfo& test_info) override; -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestCaseEnd(const TestCase& test_case) override; -#else - void OnTestSuiteEnd(const TestSuite& test_suite) override; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; - void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} - void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; - void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {} - - private: - static void PrintFailedTests(const UnitTest& unit_test); - static void PrintSkippedTests(const UnitTest& unit_test); -}; - - // Fired before each iteration of tests starts. -void PrettyUnitTestResultPrinter::OnTestIterationStart( - const UnitTest& unit_test, int iteration) { - if (GTEST_FLAG(repeat) != 1) - printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); - - const char* const filter = GTEST_FLAG(filter).c_str(); - - // Prints the filter if it's not *. This reminds the user that some - // tests may be skipped. - if (!String::CStringEquals(filter, kUniversalFilter)) { - ColoredPrintf(COLOR_YELLOW, - "Note: %s filter = %s\n", GTEST_NAME_, filter); - } - - if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { - const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); - ColoredPrintf(COLOR_YELLOW, - "Note: This is test shard %d of %s.\n", - static_cast(shard_index) + 1, - internal::posix::GetEnv(kTestTotalShards)); - } - - if (GTEST_FLAG(shuffle)) { - ColoredPrintf(COLOR_YELLOW, - "Note: Randomizing tests' orders with a seed of %d .\n", - unit_test.random_seed()); - } - - ColoredPrintf(COLOR_GREEN, "[==========] "); - printf("Running %s from %s.\n", - FormatTestCount(unit_test.test_to_run_count()).c_str(), - FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); - fflush(stdout); -} - -void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( - const UnitTest& /*unit_test*/) { - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("Global test environment set-up.\n"); - fflush(stdout); -} - -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { - const std::string counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s", counts.c_str(), test_case.name()); - if (test_case.type_param() == nullptr) { - printf("\n"); - } else { - printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); - } - fflush(stdout); -} -#else -void PrettyUnitTestResultPrinter::OnTestSuiteStart( - const TestSuite& test_suite) { - const std::string counts = - FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s", counts.c_str(), test_suite.name()); - if (test_suite.type_param() == nullptr) { - printf("\n"); - } else { - printf(", where %s = %s\n", kTypeParamLabel, test_suite.type_param()); - } - fflush(stdout); -} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { - ColoredPrintf(COLOR_GREEN, "[ RUN ] "); - PrintTestName(test_info.test_suite_name(), test_info.name()); - printf("\n"); - fflush(stdout); -} - -// Called after an assertion failure. -void PrettyUnitTestResultPrinter::OnTestPartResult( - const TestPartResult& result) { - switch (result.type()) { - // If the test part succeeded, or was skipped, - // we don't need to do anything. - case TestPartResult::kSkip: - case TestPartResult::kSuccess: - return; - default: - // Print failure message from the assertion - // (e.g. expected this and got that). - PrintTestPartResult(result); - fflush(stdout); - } -} - -void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { - if (test_info.result()->Passed()) { - ColoredPrintf(COLOR_GREEN, "[ OK ] "); - } else if (test_info.result()->Skipped()) { - ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); - } else { - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - } - PrintTestName(test_info.test_suite_name(), test_info.name()); - if (test_info.result()->Failed()) - PrintFullTestCommentIfPresent(test_info); - - if (GTEST_FLAG(print_time)) { - printf(" (%s ms)\n", internal::StreamableToString( - test_info.result()->elapsed_time()).c_str()); - } else { - printf("\n"); - } - fflush(stdout); -} - -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { - if (!GTEST_FLAG(print_time)) return; - - const std::string counts = - FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), - internal::StreamableToString(test_case.elapsed_time()).c_str()); - fflush(stdout); -} -#else -void PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) { - if (!GTEST_FLAG(print_time)) return; - - const std::string counts = - FormatCountableNoun(test_suite.test_to_run_count(), "test", "tests"); - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_suite.name(), - internal::StreamableToString(test_suite.elapsed_time()).c_str()); - fflush(stdout); -} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( - const UnitTest& /*unit_test*/) { - ColoredPrintf(COLOR_GREEN, "[----------] "); - printf("Global test environment tear-down\n"); - fflush(stdout); -} - -// Internal helper for printing the list of failed tests. -void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { - const int failed_test_count = unit_test.failed_test_count(); - if (failed_test_count == 0) { - return; - } - - for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { - const TestSuite& test_suite = *unit_test.GetTestSuite(i); - if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) { - continue; - } - for (int j = 0; j < test_suite.total_test_count(); ++j) { - const TestInfo& test_info = *test_suite.GetTestInfo(j); - if (!test_info.should_run() || !test_info.result()->Failed()) { - continue; - } - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - printf("%s.%s", test_suite.name(), test_info.name()); - PrintFullTestCommentIfPresent(test_info); - printf("\n"); - } - } -} - -// Internal helper for printing the list of skipped tests. -void PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) { - const int skipped_test_count = unit_test.skipped_test_count(); - if (skipped_test_count == 0) { - return; - } - - for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { - const TestSuite& test_suite = *unit_test.GetTestSuite(i); - if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) { - continue; - } - for (int j = 0; j < test_suite.total_test_count(); ++j) { - const TestInfo& test_info = *test_suite.GetTestInfo(j); - if (!test_info.should_run() || !test_info.result()->Skipped()) { - continue; - } - ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); - printf("%s.%s", test_suite.name(), test_info.name()); - printf("\n"); - } - } -} - -void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { - ColoredPrintf(COLOR_GREEN, "[==========] "); - printf("%s from %s ran.", - FormatTestCount(unit_test.test_to_run_count()).c_str(), - FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str()); - if (GTEST_FLAG(print_time)) { - printf(" (%s ms total)", - internal::StreamableToString(unit_test.elapsed_time()).c_str()); - } - printf("\n"); - ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); - printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); - - const int skipped_test_count = unit_test.skipped_test_count(); - if (skipped_test_count > 0) { - ColoredPrintf(COLOR_GREEN, "[ SKIPPED ] "); - printf("%s, listed below:\n", FormatTestCount(skipped_test_count).c_str()); - PrintSkippedTests(unit_test); - } - - int num_failures = unit_test.failed_test_count(); - if (!unit_test.Passed()) { - const int failed_test_count = unit_test.failed_test_count(); - ColoredPrintf(COLOR_RED, "[ FAILED ] "); - printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); - PrintFailedTests(unit_test); - printf("\n%2d FAILED %s\n", num_failures, - num_failures == 1 ? "TEST" : "TESTS"); - } - - int num_disabled = unit_test.reportable_disabled_test_count(); - if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { - if (!num_failures) { - printf("\n"); // Add a spacer if no FAILURE banner is displayed. - } - ColoredPrintf(COLOR_YELLOW, - " YOU HAVE %d DISABLED %s\n\n", - num_disabled, - num_disabled == 1 ? "TEST" : "TESTS"); - } - // Ensure that Google Test output is printed before, e.g., heapchecker output. - fflush(stdout); -} - -// End PrettyUnitTestResultPrinter - -// class TestEventRepeater -// -// This class forwards events to other event listeners. -class TestEventRepeater : public TestEventListener { - public: - TestEventRepeater() : forwarding_enabled_(true) {} - ~TestEventRepeater() override; - void Append(TestEventListener *listener); - TestEventListener* Release(TestEventListener* listener); - - // Controls whether events will be forwarded to listeners_. Set to false - // in death test child processes. - bool forwarding_enabled() const { return forwarding_enabled_; } - void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } - - void OnTestProgramStart(const UnitTest& unit_test) override; - void OnTestIterationStart(const UnitTest& unit_test, int iteration) override; - void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override; - void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override; -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestCaseStart(const TestSuite& parameter) override; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestSuiteStart(const TestSuite& parameter) override; - void OnTestStart(const TestInfo& test_info) override; - void OnTestPartResult(const TestPartResult& result) override; - void OnTestEnd(const TestInfo& test_info) override; -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestCaseEnd(const TestCase& parameter) override; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestSuiteEnd(const TestSuite& parameter) override; - void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override; - void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override; - void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; - void OnTestProgramEnd(const UnitTest& unit_test) override; - - private: - // Controls whether events will be forwarded to listeners_. Set to false - // in death test child processes. - bool forwarding_enabled_; - // The list of listeners that receive events. - std::vector listeners_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); -}; - -TestEventRepeater::~TestEventRepeater() { - ForEach(listeners_, Delete); -} - -void TestEventRepeater::Append(TestEventListener *listener) { - listeners_.push_back(listener); -} - -TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { - for (size_t i = 0; i < listeners_.size(); ++i) { - if (listeners_[i] == listener) { - listeners_.erase(listeners_.begin() + static_cast(i)); - return listener; - } - } - - return nullptr; -} - -// Since most methods are very similar, use macros to reduce boilerplate. -// This defines a member that forwards the call to all listeners. -#define GTEST_REPEATER_METHOD_(Name, Type) \ -void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (size_t i = 0; i < listeners_.size(); i++) { \ - listeners_[i]->Name(parameter); \ - } \ - } \ -} -// This defines a member that forwards the call to all listeners in reverse -// order. -#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ - void TestEventRepeater::Name(const Type& parameter) { \ - if (forwarding_enabled_) { \ - for (size_t i = listeners_.size(); i != 0; i--) { \ - listeners_[i - 1]->Name(parameter); \ - } \ - } \ - } - -GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) -GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -GTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite) -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -GTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite) -GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) -GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) -GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) -GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) -GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) -GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite) -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -GTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite) -GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) - -#undef GTEST_REPEATER_METHOD_ -#undef GTEST_REVERSE_REPEATER_METHOD_ - -void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, - int iteration) { - if (forwarding_enabled_) { - for (size_t i = 0; i < listeners_.size(); i++) { - listeners_[i]->OnTestIterationStart(unit_test, iteration); - } - } -} - -void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, - int iteration) { - if (forwarding_enabled_) { - for (size_t i = listeners_.size(); i > 0; i--) { - listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration); - } - } -} - -// End TestEventRepeater - -// This class generates an XML output file. -class XmlUnitTestResultPrinter : public EmptyTestEventListener { - public: - explicit XmlUnitTestResultPrinter(const char* output_file); - - void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; - void ListTestsMatchingFilter(const std::vector& test_suites); - - // Prints an XML summary of all unit tests. - static void PrintXmlTestsList(std::ostream* stream, - const std::vector& test_suites); - - private: - // Is c a whitespace character that is normalized to a space character - // when it appears in an XML attribute value? - static bool IsNormalizableWhitespace(char c) { - return c == 0x9 || c == 0xA || c == 0xD; - } - - // May c appear in a well-formed XML document? - static bool IsValidXmlCharacter(char c) { - return IsNormalizableWhitespace(c) || c >= 0x20; - } - - // Returns an XML-escaped copy of the input string str. If - // is_attribute is true, the text is meant to appear as an attribute - // value, and normalizable whitespace is preserved by replacing it - // with character references. - static std::string EscapeXml(const std::string& str, bool is_attribute); - - // Returns the given string with all characters invalid in XML removed. - static std::string RemoveInvalidXmlCharacters(const std::string& str); - - // Convenience wrapper around EscapeXml when str is an attribute value. - static std::string EscapeXmlAttribute(const std::string& str) { - return EscapeXml(str, true); - } - - // Convenience wrapper around EscapeXml when str is not an attribute value. - static std::string EscapeXmlText(const char* str) { - return EscapeXml(str, false); - } - - // Verifies that the given attribute belongs to the given element and - // streams the attribute as XML. - static void OutputXmlAttribute(std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value); - - // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. - static void OutputXmlCDataSection(::std::ostream* stream, const char* data); - - // Streams an XML representation of a TestInfo object. - static void OutputXmlTestInfo(::std::ostream* stream, - const char* test_suite_name, - const TestInfo& test_info); - - // Prints an XML representation of a TestSuite object - static void PrintXmlTestSuite(::std::ostream* stream, - const TestSuite& test_suite); - - // Prints an XML summary of unit_test to output stream out. - static void PrintXmlUnitTest(::std::ostream* stream, - const UnitTest& unit_test); - - // Produces a string representing the test properties in a result as space - // delimited XML attributes based on the property key="value" pairs. - // When the std::string is not empty, it includes a space at the beginning, - // to delimit this attribute from prior attributes. - static std::string TestPropertiesAsXmlAttributes(const TestResult& result); - - // Streams an XML representation of the test properties of a TestResult - // object. - static void OutputXmlTestProperties(std::ostream* stream, - const TestResult& result); - - // The output file. - const std::string output_file_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); -}; - -// Creates a new XmlUnitTestResultPrinter. -XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) - : output_file_(output_file) { - if (output_file_.empty()) { - GTEST_LOG_(FATAL) << "XML output file may not be null"; - } -} - -// Called after the unit test ends. -void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { - FILE* xmlout = OpenFileForWriting(output_file_); - std::stringstream stream; - PrintXmlUnitTest(&stream, unit_test); - fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); - fclose(xmlout); -} - -void XmlUnitTestResultPrinter::ListTestsMatchingFilter( - const std::vector& test_suites) { - FILE* xmlout = OpenFileForWriting(output_file_); - std::stringstream stream; - PrintXmlTestsList(&stream, test_suites); - fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); - fclose(xmlout); -} - -// Returns an XML-escaped copy of the input string str. If is_attribute -// is true, the text is meant to appear as an attribute value, and -// normalizable whitespace is preserved by replacing it with character -// references. -// -// Invalid XML characters in str, if any, are stripped from the output. -// It is expected that most, if not all, of the text processed by this -// module will consist of ordinary English text. -// If this module is ever modified to produce version 1.1 XML output, -// most invalid characters can be retained using character references. -std::string XmlUnitTestResultPrinter::EscapeXml( - const std::string& str, bool is_attribute) { - Message m; - - for (size_t i = 0; i < str.size(); ++i) { - const char ch = str[i]; - switch (ch) { - case '<': - m << "<"; - break; - case '>': - m << ">"; - break; - case '&': - m << "&"; - break; - case '\'': - if (is_attribute) - m << "'"; - else - m << '\''; - break; - case '"': - if (is_attribute) - m << """; - else - m << '"'; - break; - default: - if (IsValidXmlCharacter(ch)) { - if (is_attribute && IsNormalizableWhitespace(ch)) - m << "&#x" << String::FormatByte(static_cast(ch)) - << ";"; - else - m << ch; - } - break; - } - } - - return m.GetString(); -} - -// Returns the given string with all characters invalid in XML removed. -// Currently invalid characters are dropped from the string. An -// alternative is to replace them with certain characters such as . or ?. -std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( - const std::string& str) { - std::string output; - output.reserve(str.size()); - for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) - if (IsValidXmlCharacter(*it)) - output.push_back(*it); - - return output; -} - -// The following routines generate an XML representation of a UnitTest -// object. -// GOOGLETEST_CM0009 DO NOT DELETE -// -// This is how Google Test concepts map to the DTD: -// -// <-- corresponds to a UnitTest object -// <-- corresponds to a TestSuite object -// <-- corresponds to a TestInfo object -// ... -// ... -// ... -// <-- individual assertion failures -// -// -// - -// Formats the given time in milliseconds as seconds. -std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { - ::std::stringstream ss; - ss << (static_cast(ms) * 1e-3); - return ss.str(); -} - -static bool PortableLocaltime(time_t seconds, struct tm* out) { -#if defined(_MSC_VER) - return localtime_s(out, &seconds) == 0; -#elif defined(__MINGW32__) || defined(__MINGW64__) - // MINGW provides neither localtime_r nor localtime_s, but uses - // Windows' localtime(), which has a thread-local tm buffer. - struct tm* tm_ptr = localtime(&seconds); // NOLINT - if (tm_ptr == nullptr) return false; - *out = *tm_ptr; - return true; -#else - return localtime_r(&seconds, out) != nullptr; -#endif -} - -// Converts the given epoch time in milliseconds to a date string in the ISO -// 8601 format, without the timezone information. -std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { - struct tm time_struct; - if (!PortableLocaltime(static_cast(ms / 1000), &time_struct)) - return ""; - // YYYY-MM-DDThh:mm:ss - return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec); -} - -// Streams an XML CDATA section, escaping invalid CDATA sequences as needed. -void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, - const char* data) { - const char* segment = data; - *stream << ""); - if (next_segment != nullptr) { - stream->write( - segment, static_cast(next_segment - segment)); - *stream << "]]>]]>"); - } else { - *stream << segment; - break; - } - } - *stream << "]]>"; -} - -void XmlUnitTestResultPrinter::OutputXmlAttribute( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value) { - const std::vector& allowed_names = - GetReservedOutputAttributesForElement(element_name); - - GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) - << "Attribute " << name << " is not allowed for element <" << element_name - << ">."; - - *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; -} - -// Prints an XML representation of a TestInfo object. -void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, - const char* test_suite_name, - const TestInfo& test_info) { - const TestResult& result = *test_info.result(); - const std::string kTestsuite = "testcase"; - - if (test_info.is_in_another_shard()) { - return; - } - - *stream << " \n"; - return; - } - - OutputXmlAttribute(stream, kTestsuite, "status", - test_info.should_run() ? "run" : "notrun"); - OutputXmlAttribute(stream, kTestsuite, "result", - test_info.should_run() - ? (result.Skipped() ? "skipped" : "completed") - : "suppressed"); - OutputXmlAttribute(stream, kTestsuite, "time", - FormatTimeInMillisAsSeconds(result.elapsed_time())); - OutputXmlAttribute( - stream, kTestsuite, "timestamp", - FormatEpochTimeInMillisAsIso8601(result.start_timestamp())); - OutputXmlAttribute(stream, kTestsuite, "classname", test_suite_name); - - int failures = 0; - for (int i = 0; i < result.total_part_count(); ++i) { - const TestPartResult& part = result.GetTestPartResult(i); - if (part.failed()) { - if (++failures == 1) { - *stream << ">\n"; - } - const std::string location = - internal::FormatCompilerIndependentFileLocation(part.file_name(), - part.line_number()); - const std::string summary = location + "\n" + part.summary(); - *stream << " "; - const std::string detail = location + "\n" + part.message(); - OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); - *stream << "\n"; - } - } - - if (failures == 0 && result.test_property_count() == 0) { - *stream << " />\n"; - } else { - if (failures == 0) { - *stream << ">\n"; - } - OutputXmlTestProperties(stream, result); - *stream << " \n"; - } -} - -// Prints an XML representation of a TestSuite object -void XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream, - const TestSuite& test_suite) { - const std::string kTestsuite = "testsuite"; - *stream << " <" << kTestsuite; - OutputXmlAttribute(stream, kTestsuite, "name", test_suite.name()); - OutputXmlAttribute(stream, kTestsuite, "tests", - StreamableToString(test_suite.reportable_test_count())); - if (!GTEST_FLAG(list_tests)) { - OutputXmlAttribute(stream, kTestsuite, "failures", - StreamableToString(test_suite.failed_test_count())); - OutputXmlAttribute( - stream, kTestsuite, "disabled", - StreamableToString(test_suite.reportable_disabled_test_count())); - OutputXmlAttribute(stream, kTestsuite, "errors", "0"); - OutputXmlAttribute(stream, kTestsuite, "time", - FormatTimeInMillisAsSeconds(test_suite.elapsed_time())); - OutputXmlAttribute( - stream, kTestsuite, "timestamp", - FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp())); - *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result()); - } - *stream << ">\n"; - for (int i = 0; i < test_suite.total_test_count(); ++i) { - if (test_suite.GetTestInfo(i)->is_reportable()) - OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); - } - *stream << " \n"; -} - -// Prints an XML summary of unit_test to output stream out. -void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, - const UnitTest& unit_test) { - const std::string kTestsuites = "testsuites"; - - *stream << "\n"; - *stream << "<" << kTestsuites; - - OutputXmlAttribute(stream, kTestsuites, "tests", - StreamableToString(unit_test.reportable_test_count())); - OutputXmlAttribute(stream, kTestsuites, "failures", - StreamableToString(unit_test.failed_test_count())); - OutputXmlAttribute( - stream, kTestsuites, "disabled", - StreamableToString(unit_test.reportable_disabled_test_count())); - OutputXmlAttribute(stream, kTestsuites, "errors", "0"); - OutputXmlAttribute(stream, kTestsuites, "time", - FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); - OutputXmlAttribute( - stream, kTestsuites, "timestamp", - FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); - - if (GTEST_FLAG(shuffle)) { - OutputXmlAttribute(stream, kTestsuites, "random_seed", - StreamableToString(unit_test.random_seed())); - } - *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); - - OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); - *stream << ">\n"; - - for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { - if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) - PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i)); - } - *stream << "\n"; -} - -void XmlUnitTestResultPrinter::PrintXmlTestsList( - std::ostream* stream, const std::vector& test_suites) { - const std::string kTestsuites = "testsuites"; - - *stream << "\n"; - *stream << "<" << kTestsuites; - - int total_tests = 0; - for (auto test_suite : test_suites) { - total_tests += test_suite->total_test_count(); - } - OutputXmlAttribute(stream, kTestsuites, "tests", - StreamableToString(total_tests)); - OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); - *stream << ">\n"; - - for (auto test_suite : test_suites) { - PrintXmlTestSuite(stream, *test_suite); - } - *stream << "\n"; -} - -// Produces a string representing the test properties in a result as space -// delimited XML attributes based on the property key="value" pairs. -std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( - const TestResult& result) { - Message attributes; - for (int i = 0; i < result.test_property_count(); ++i) { - const TestProperty& property = result.GetTestProperty(i); - attributes << " " << property.key() << "=" - << "\"" << EscapeXmlAttribute(property.value()) << "\""; - } - return attributes.GetString(); -} - -void XmlUnitTestResultPrinter::OutputXmlTestProperties( - std::ostream* stream, const TestResult& result) { - const std::string kProperties = "properties"; - const std::string kProperty = "property"; - - if (result.test_property_count() <= 0) { - return; - } - - *stream << "<" << kProperties << ">\n"; - for (int i = 0; i < result.test_property_count(); ++i) { - const TestProperty& property = result.GetTestProperty(i); - *stream << "<" << kProperty; - *stream << " name=\"" << EscapeXmlAttribute(property.key()) << "\""; - *stream << " value=\"" << EscapeXmlAttribute(property.value()) << "\""; - *stream << "/>\n"; - } - *stream << "\n"; -} - -// End XmlUnitTestResultPrinter - -// This class generates an JSON output file. -class JsonUnitTestResultPrinter : public EmptyTestEventListener { - public: - explicit JsonUnitTestResultPrinter(const char* output_file); - - void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override; - - // Prints an JSON summary of all unit tests. - static void PrintJsonTestList(::std::ostream* stream, - const std::vector& test_suites); - - private: - // Returns an JSON-escaped copy of the input string str. - static std::string EscapeJson(const std::string& str); - - //// Verifies that the given attribute belongs to the given element and - //// streams the attribute as JSON. - static void OutputJsonKey(std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value, - const std::string& indent, - bool comma = true); - static void OutputJsonKey(std::ostream* stream, - const std::string& element_name, - const std::string& name, - int value, - const std::string& indent, - bool comma = true); - - // Streams a JSON representation of a TestInfo object. - static void OutputJsonTestInfo(::std::ostream* stream, - const char* test_suite_name, - const TestInfo& test_info); - - // Prints a JSON representation of a TestSuite object - static void PrintJsonTestSuite(::std::ostream* stream, - const TestSuite& test_suite); - - // Prints a JSON summary of unit_test to output stream out. - static void PrintJsonUnitTest(::std::ostream* stream, - const UnitTest& unit_test); - - // Produces a string representing the test properties in a result as - // a JSON dictionary. - static std::string TestPropertiesAsJson(const TestResult& result, - const std::string& indent); - - // The output file. - const std::string output_file_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(JsonUnitTestResultPrinter); -}; - -// Creates a new JsonUnitTestResultPrinter. -JsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file) - : output_file_(output_file) { - if (output_file_.empty()) { - GTEST_LOG_(FATAL) << "JSON output file may not be null"; - } -} - -void JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, - int /*iteration*/) { - FILE* jsonout = OpenFileForWriting(output_file_); - std::stringstream stream; - PrintJsonUnitTest(&stream, unit_test); - fprintf(jsonout, "%s", StringStreamToString(&stream).c_str()); - fclose(jsonout); -} - -// Returns an JSON-escaped copy of the input string str. -std::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) { - Message m; - - for (size_t i = 0; i < str.size(); ++i) { - const char ch = str[i]; - switch (ch) { - case '\\': - case '"': - case '/': - m << '\\' << ch; - break; - case '\b': - m << "\\b"; - break; - case '\t': - m << "\\t"; - break; - case '\n': - m << "\\n"; - break; - case '\f': - m << "\\f"; - break; - case '\r': - m << "\\r"; - break; - default: - if (ch < ' ') { - m << "\\u00" << String::FormatByte(static_cast(ch)); - } else { - m << ch; - } - break; - } - } - - return m.GetString(); -} - -// The following routines generate an JSON representation of a UnitTest -// object. - -// Formats the given time in milliseconds as seconds. -static std::string FormatTimeInMillisAsDuration(TimeInMillis ms) { - ::std::stringstream ss; - ss << (static_cast(ms) * 1e-3) << "s"; - return ss.str(); -} - -// Converts the given epoch time in milliseconds to a date string in the -// RFC3339 format, without the timezone information. -static std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) { - struct tm time_struct; - if (!PortableLocaltime(static_cast(ms / 1000), &time_struct)) - return ""; - // YYYY-MM-DDThh:mm:ss - return StreamableToString(time_struct.tm_year + 1900) + "-" + - String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + - String::FormatIntWidth2(time_struct.tm_mday) + "T" + - String::FormatIntWidth2(time_struct.tm_hour) + ":" + - String::FormatIntWidth2(time_struct.tm_min) + ":" + - String::FormatIntWidth2(time_struct.tm_sec) + "Z"; -} - -static inline std::string Indent(size_t width) { - return std::string(width, ' '); -} - -void JsonUnitTestResultPrinter::OutputJsonKey( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - const std::string& value, - const std::string& indent, - bool comma) { - const std::vector& allowed_names = - GetReservedOutputAttributesForElement(element_name); - - GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) - << "Key \"" << name << "\" is not allowed for value \"" << element_name - << "\"."; - - *stream << indent << "\"" << name << "\": \"" << EscapeJson(value) << "\""; - if (comma) - *stream << ",\n"; -} - -void JsonUnitTestResultPrinter::OutputJsonKey( - std::ostream* stream, - const std::string& element_name, - const std::string& name, - int value, - const std::string& indent, - bool comma) { - const std::vector& allowed_names = - GetReservedOutputAttributesForElement(element_name); - - GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != - allowed_names.end()) - << "Key \"" << name << "\" is not allowed for value \"" << element_name - << "\"."; - - *stream << indent << "\"" << name << "\": " << StreamableToString(value); - if (comma) - *stream << ",\n"; -} - -// Prints a JSON representation of a TestInfo object. -void JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream, - const char* test_suite_name, - const TestInfo& test_info) { - const TestResult& result = *test_info.result(); - const std::string kTestsuite = "testcase"; - const std::string kIndent = Indent(10); - - *stream << Indent(8) << "{\n"; - OutputJsonKey(stream, kTestsuite, "name", test_info.name(), kIndent); - - if (test_info.value_param() != nullptr) { - OutputJsonKey(stream, kTestsuite, "value_param", test_info.value_param(), - kIndent); - } - if (test_info.type_param() != nullptr) { - OutputJsonKey(stream, kTestsuite, "type_param", test_info.type_param(), - kIndent); - } - if (GTEST_FLAG(list_tests)) { - OutputJsonKey(stream, kTestsuite, "file", test_info.file(), kIndent); - OutputJsonKey(stream, kTestsuite, "line", test_info.line(), kIndent, false); - *stream << "\n" << Indent(8) << "}"; - return; - } - - OutputJsonKey(stream, kTestsuite, "status", - test_info.should_run() ? "RUN" : "NOTRUN", kIndent); - OutputJsonKey(stream, kTestsuite, "result", - test_info.should_run() - ? (result.Skipped() ? "SKIPPED" : "COMPLETED") - : "SUPPRESSED", - kIndent); - OutputJsonKey(stream, kTestsuite, "timestamp", - FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()), - kIndent); - OutputJsonKey(stream, kTestsuite, "time", - FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent); - OutputJsonKey(stream, kTestsuite, "classname", test_suite_name, kIndent, - false); - *stream << TestPropertiesAsJson(result, kIndent); - - int failures = 0; - for (int i = 0; i < result.total_part_count(); ++i) { - const TestPartResult& part = result.GetTestPartResult(i); - if (part.failed()) { - *stream << ",\n"; - if (++failures == 1) { - *stream << kIndent << "\"" << "failures" << "\": [\n"; - } - const std::string location = - internal::FormatCompilerIndependentFileLocation(part.file_name(), - part.line_number()); - const std::string message = EscapeJson(location + "\n" + part.message()); - *stream << kIndent << " {\n" - << kIndent << " \"failure\": \"" << message << "\",\n" - << kIndent << " \"type\": \"\"\n" - << kIndent << " }"; - } - } - - if (failures > 0) - *stream << "\n" << kIndent << "]"; - *stream << "\n" << Indent(8) << "}"; -} - -// Prints an JSON representation of a TestSuite object -void JsonUnitTestResultPrinter::PrintJsonTestSuite( - std::ostream* stream, const TestSuite& test_suite) { - const std::string kTestsuite = "testsuite"; - const std::string kIndent = Indent(6); - - *stream << Indent(4) << "{\n"; - OutputJsonKey(stream, kTestsuite, "name", test_suite.name(), kIndent); - OutputJsonKey(stream, kTestsuite, "tests", test_suite.reportable_test_count(), - kIndent); - if (!GTEST_FLAG(list_tests)) { - OutputJsonKey(stream, kTestsuite, "failures", - test_suite.failed_test_count(), kIndent); - OutputJsonKey(stream, kTestsuite, "disabled", - test_suite.reportable_disabled_test_count(), kIndent); - OutputJsonKey(stream, kTestsuite, "errors", 0, kIndent); - OutputJsonKey( - stream, kTestsuite, "timestamp", - FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()), - kIndent); - OutputJsonKey(stream, kTestsuite, "time", - FormatTimeInMillisAsDuration(test_suite.elapsed_time()), - kIndent, false); - *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent) - << ",\n"; - } - - *stream << kIndent << "\"" << kTestsuite << "\": [\n"; - - bool comma = false; - for (int i = 0; i < test_suite.total_test_count(); ++i) { - if (test_suite.GetTestInfo(i)->is_reportable()) { - if (comma) { - *stream << ",\n"; - } else { - comma = true; - } - OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i)); - } - } - *stream << "\n" << kIndent << "]\n" << Indent(4) << "}"; -} - -// Prints a JSON summary of unit_test to output stream out. -void JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream, - const UnitTest& unit_test) { - const std::string kTestsuites = "testsuites"; - const std::string kIndent = Indent(2); - *stream << "{\n"; - - OutputJsonKey(stream, kTestsuites, "tests", unit_test.reportable_test_count(), - kIndent); - OutputJsonKey(stream, kTestsuites, "failures", unit_test.failed_test_count(), - kIndent); - OutputJsonKey(stream, kTestsuites, "disabled", - unit_test.reportable_disabled_test_count(), kIndent); - OutputJsonKey(stream, kTestsuites, "errors", 0, kIndent); - if (GTEST_FLAG(shuffle)) { - OutputJsonKey(stream, kTestsuites, "random_seed", unit_test.random_seed(), - kIndent); - } - OutputJsonKey(stream, kTestsuites, "timestamp", - FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()), - kIndent); - OutputJsonKey(stream, kTestsuites, "time", - FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent, - false); - - *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent) - << ",\n"; - - OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); - *stream << kIndent << "\"" << kTestsuites << "\": [\n"; - - bool comma = false; - for (int i = 0; i < unit_test.total_test_suite_count(); ++i) { - if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) { - if (comma) { - *stream << ",\n"; - } else { - comma = true; - } - PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i)); - } - } - - *stream << "\n" << kIndent << "]\n" << "}\n"; -} - -void JsonUnitTestResultPrinter::PrintJsonTestList( - std::ostream* stream, const std::vector& test_suites) { - const std::string kTestsuites = "testsuites"; - const std::string kIndent = Indent(2); - *stream << "{\n"; - int total_tests = 0; - for (auto test_suite : test_suites) { - total_tests += test_suite->total_test_count(); - } - OutputJsonKey(stream, kTestsuites, "tests", total_tests, kIndent); - - OutputJsonKey(stream, kTestsuites, "name", "AllTests", kIndent); - *stream << kIndent << "\"" << kTestsuites << "\": [\n"; - - for (size_t i = 0; i < test_suites.size(); ++i) { - if (i != 0) { - *stream << ",\n"; - } - PrintJsonTestSuite(stream, *test_suites[i]); - } - - *stream << "\n" - << kIndent << "]\n" - << "}\n"; -} -// Produces a string representing the test properties in a result as -// a JSON dictionary. -std::string JsonUnitTestResultPrinter::TestPropertiesAsJson( - const TestResult& result, const std::string& indent) { - Message attributes; - for (int i = 0; i < result.test_property_count(); ++i) { - const TestProperty& property = result.GetTestProperty(i); - attributes << ",\n" << indent << "\"" << property.key() << "\": " - << "\"" << EscapeJson(property.value()) << "\""; - } - return attributes.GetString(); -} - -// End JsonUnitTestResultPrinter - -#if GTEST_CAN_STREAM_RESULTS_ - -// Checks if str contains '=', '&', '%' or '\n' characters. If yes, -// replaces them by "%xx" where xx is their hexadecimal value. For -// example, replaces "=" with "%3D". This algorithm is O(strlen(str)) -// in both time and space -- important as the input str may contain an -// arbitrarily long test failure message and stack trace. -std::string StreamingListener::UrlEncode(const char* str) { - std::string result; - result.reserve(strlen(str) + 1); - for (char ch = *str; ch != '\0'; ch = *++str) { - switch (ch) { - case '%': - case '=': - case '&': - case '\n': - result.append("%" + String::FormatByte(static_cast(ch))); - break; - default: - result.push_back(ch); - break; - } - } - return result; -} - -void StreamingListener::SocketWriter::MakeConnection() { - GTEST_CHECK_(sockfd_ == -1) - << "MakeConnection() can't be called when there is already a connection."; - - addrinfo hints; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. - hints.ai_socktype = SOCK_STREAM; - addrinfo* servinfo = nullptr; - - // Use the getaddrinfo() to get a linked list of IP addresses for - // the given host name. - const int error_num = getaddrinfo( - host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); - if (error_num != 0) { - GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " - << gai_strerror(error_num); - } - - // Loop through all the results and connect to the first we can. - for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr; - cur_addr = cur_addr->ai_next) { - sockfd_ = socket( - cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); - if (sockfd_ != -1) { - // Connect the client socket to the server socket. - if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { - close(sockfd_); - sockfd_ = -1; - } - } - } - - freeaddrinfo(servinfo); // all done with this structure - - if (sockfd_ == -1) { - GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " - << host_name_ << ":" << port_num_; - } -} - -// End of class Streaming Listener -#endif // GTEST_CAN_STREAM_RESULTS__ - -// class OsStackTraceGetter - -const char* const OsStackTraceGetterInterface::kElidedFramesMarker = - "... " GTEST_NAME_ " internal frames ..."; - -std::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count) - GTEST_LOCK_EXCLUDED_(mutex_) { -#if GTEST_HAS_ABSL - std::string result; - - if (max_depth <= 0) { - return result; - } - - max_depth = std::min(max_depth, kMaxStackTraceDepth); - - std::vector raw_stack(max_depth); - // Skips the frames requested by the caller, plus this function. - const int raw_stack_size = - absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1); - - void* caller_frame = nullptr; - { - MutexLock lock(&mutex_); - caller_frame = caller_frame_; - } - - for (int i = 0; i < raw_stack_size; ++i) { - if (raw_stack[i] == caller_frame && - !GTEST_FLAG(show_internal_stack_frames)) { - // Add a marker to the trace and stop adding frames. - absl::StrAppend(&result, kElidedFramesMarker, "\n"); - break; - } - - char tmp[1024]; - const char* symbol = "(unknown)"; - if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) { - symbol = tmp; - } - - char line[1024]; - snprintf(line, sizeof(line), " %p: %s\n", raw_stack[i], symbol); - result += line; - } - - return result; - -#else // !GTEST_HAS_ABSL - static_cast(max_depth); - static_cast(skip_count); - return ""; -#endif // GTEST_HAS_ABSL -} - -void OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) { -#if GTEST_HAS_ABSL - void* caller_frame = nullptr; - if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) { - caller_frame = nullptr; - } - - MutexLock lock(&mutex_); - caller_frame_ = caller_frame; -#endif // GTEST_HAS_ABSL -} - -// A helper class that creates the premature-exit file in its -// constructor and deletes the file in its destructor. -class ScopedPrematureExitFile { - public: - explicit ScopedPrematureExitFile(const char* premature_exit_filepath) - : premature_exit_filepath_(premature_exit_filepath ? - premature_exit_filepath : "") { - // If a path to the premature-exit file is specified... - if (!premature_exit_filepath_.empty()) { - // create the file with a single "0" character in it. I/O - // errors are ignored as there's nothing better we can do and we - // don't want to fail the test because of this. - FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); - fwrite("0", 1, 1, pfile); - fclose(pfile); - } - } - - ~ScopedPrematureExitFile() { - if (!premature_exit_filepath_.empty()) { - int retval = remove(premature_exit_filepath_.c_str()); - if (retval) { - GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \"" - << premature_exit_filepath_ << "\" with error " - << retval; - } - } - } - - private: - const std::string premature_exit_filepath_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); -}; - -} // namespace internal - -// class TestEventListeners - -TestEventListeners::TestEventListeners() - : repeater_(new internal::TestEventRepeater()), - default_result_printer_(nullptr), - default_xml_generator_(nullptr) {} - -TestEventListeners::~TestEventListeners() { delete repeater_; } - -// Returns the standard listener responsible for the default console -// output. Can be removed from the listeners list to shut down default -// console output. Note that removing this object from the listener list -// with Release transfers its ownership to the user. -void TestEventListeners::Append(TestEventListener* listener) { - repeater_->Append(listener); -} - -// Removes the given event listener from the list and returns it. It then -// becomes the caller's responsibility to delete the listener. Returns -// NULL if the listener is not found in the list. -TestEventListener* TestEventListeners::Release(TestEventListener* listener) { - if (listener == default_result_printer_) - default_result_printer_ = nullptr; - else if (listener == default_xml_generator_) - default_xml_generator_ = nullptr; - return repeater_->Release(listener); -} - -// Returns repeater that broadcasts the TestEventListener events to all -// subscribers. -TestEventListener* TestEventListeners::repeater() { return repeater_; } - -// Sets the default_result_printer attribute to the provided listener. -// The listener is also added to the listener list and previous -// default_result_printer is removed from it and deleted. The listener can -// also be NULL in which case it will not be added to the list. Does -// nothing if the previous and the current listener objects are the same. -void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { - if (default_result_printer_ != listener) { - // It is an error to pass this method a listener that is already in the - // list. - delete Release(default_result_printer_); - default_result_printer_ = listener; - if (listener != nullptr) Append(listener); - } -} - -// Sets the default_xml_generator attribute to the provided listener. The -// listener is also added to the listener list and previous -// default_xml_generator is removed from it and deleted. The listener can -// also be NULL in which case it will not be added to the list. Does -// nothing if the previous and the current listener objects are the same. -void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { - if (default_xml_generator_ != listener) { - // It is an error to pass this method a listener that is already in the - // list. - delete Release(default_xml_generator_); - default_xml_generator_ = listener; - if (listener != nullptr) Append(listener); - } -} - -// Controls whether events will be forwarded by the repeater to the -// listeners in the list. -bool TestEventListeners::EventForwardingEnabled() const { - return repeater_->forwarding_enabled(); -} - -void TestEventListeners::SuppressEventForwarding() { - repeater_->set_forwarding_enabled(false); -} - -// class UnitTest - -// Gets the singleton UnitTest object. The first time this method is -// called, a UnitTest object is constructed and returned. Consecutive -// calls will return the same object. -// -// We don't protect this under mutex_ as a user is not supposed to -// call this before main() starts, from which point on the return -// value will never change. -UnitTest* UnitTest::GetInstance() { - // CodeGear C++Builder insists on a public destructor for the - // default implementation. Use this implementation to keep good OO - // design with private destructor. - -#if defined(__BORLANDC__) - static UnitTest* const instance = new UnitTest; - return instance; -#else - static UnitTest instance; - return &instance; -#endif // defined(__BORLANDC__) -} - -// Gets the number of successful test suites. -int UnitTest::successful_test_suite_count() const { - return impl()->successful_test_suite_count(); -} - -// Gets the number of failed test suites. -int UnitTest::failed_test_suite_count() const { - return impl()->failed_test_suite_count(); -} - -// Gets the number of all test suites. -int UnitTest::total_test_suite_count() const { - return impl()->total_test_suite_count(); -} - -// Gets the number of all test suites that contain at least one test -// that should run. -int UnitTest::test_suite_to_run_count() const { - return impl()->test_suite_to_run_count(); -} - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -int UnitTest::successful_test_case_count() const { - return impl()->successful_test_suite_count(); -} -int UnitTest::failed_test_case_count() const { - return impl()->failed_test_suite_count(); -} -int UnitTest::total_test_case_count() const { - return impl()->total_test_suite_count(); -} -int UnitTest::test_case_to_run_count() const { - return impl()->test_suite_to_run_count(); -} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -// Gets the number of successful tests. -int UnitTest::successful_test_count() const { - return impl()->successful_test_count(); -} - -// Gets the number of skipped tests. -int UnitTest::skipped_test_count() const { - return impl()->skipped_test_count(); -} - -// Gets the number of failed tests. -int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } - -// Gets the number of disabled tests that will be reported in the XML report. -int UnitTest::reportable_disabled_test_count() const { - return impl()->reportable_disabled_test_count(); -} - -// Gets the number of disabled tests. -int UnitTest::disabled_test_count() const { - return impl()->disabled_test_count(); -} - -// Gets the number of tests to be printed in the XML report. -int UnitTest::reportable_test_count() const { - return impl()->reportable_test_count(); -} - -// Gets the number of all tests. -int UnitTest::total_test_count() const { return impl()->total_test_count(); } - -// Gets the number of tests that should run. -int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } - -// Gets the time of the test program start, in ms from the start of the -// UNIX epoch. -internal::TimeInMillis UnitTest::start_timestamp() const { - return impl()->start_timestamp(); -} - -// Gets the elapsed time, in milliseconds. -internal::TimeInMillis UnitTest::elapsed_time() const { - return impl()->elapsed_time(); -} - -// Returns true if and only if the unit test passed (i.e. all test suites -// passed). -bool UnitTest::Passed() const { return impl()->Passed(); } - -// Returns true if and only if the unit test failed (i.e. some test suite -// failed or something outside of all tests failed). -bool UnitTest::Failed() const { return impl()->Failed(); } - -// Gets the i-th test suite among all the test suites. i can range from 0 to -// total_test_suite_count() - 1. If i is not in that range, returns NULL. -const TestSuite* UnitTest::GetTestSuite(int i) const { - return impl()->GetTestSuite(i); -} - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -const TestCase* UnitTest::GetTestCase(int i) const { - return impl()->GetTestCase(i); -} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -// Returns the TestResult containing information on test failures and -// properties logged outside of individual test suites. -const TestResult& UnitTest::ad_hoc_test_result() const { - return *impl()->ad_hoc_test_result(); -} - -// Gets the i-th test suite among all the test suites. i can range from 0 to -// total_test_suite_count() - 1. If i is not in that range, returns NULL. -TestSuite* UnitTest::GetMutableTestSuite(int i) { - return impl()->GetMutableSuiteCase(i); -} - -// Returns the list of event listeners that can be used to track events -// inside Google Test. -TestEventListeners& UnitTest::listeners() { - return *impl()->listeners(); -} - -// Registers and returns a global test environment. When a test -// program is run, all global test environments will be set-up in the -// order they were registered. After all tests in the program have -// finished, all global test environments will be torn-down in the -// *reverse* order they were registered. -// -// The UnitTest object takes ownership of the given environment. -// -// We don't protect this under mutex_, as we only support calling it -// from the main thread. -Environment* UnitTest::AddEnvironment(Environment* env) { - if (env == nullptr) { - return nullptr; - } - - impl_->environments().push_back(env); - return env; -} - -// Adds a TestPartResult to the current TestResult object. All Google Test -// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call -// this to report their results. The user code should use the -// assertion macros instead of calling this directly. -void UnitTest::AddTestPartResult( - TestPartResult::Type result_type, - const char* file_name, - int line_number, - const std::string& message, - const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { - Message msg; - msg << message; - - internal::MutexLock lock(&mutex_); - if (impl_->gtest_trace_stack().size() > 0) { - msg << "\n" << GTEST_NAME_ << " trace:"; - - for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) { - const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; - msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) - << " " << trace.message; - } - } - - if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) { - msg << internal::kStackTraceMarker << os_stack_trace; - } - - const TestPartResult result = TestPartResult( - result_type, file_name, line_number, msg.GetString().c_str()); - impl_->GetTestPartResultReporterForCurrentThread()-> - ReportTestPartResult(result); - - if (result_type != TestPartResult::kSuccess && - result_type != TestPartResult::kSkip) { - // gtest_break_on_failure takes precedence over - // gtest_throw_on_failure. This allows a user to set the latter - // in the code (perhaps in order to use Google Test assertions - // with another testing framework) and specify the former on the - // command line for debugging. - if (GTEST_FLAG(break_on_failure)) { -#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT - // Using DebugBreak on Windows allows gtest to still break into a debugger - // when a failure happens and both the --gtest_break_on_failure and - // the --gtest_catch_exceptions flags are specified. - DebugBreak(); -#elif (!defined(__native_client__)) && \ - ((defined(__clang__) || defined(__GNUC__)) && \ - (defined(__x86_64__) || defined(__i386__))) - // with clang/gcc we can achieve the same effect on x86 by invoking int3 - asm("int3"); -#else - // Dereference nullptr through a volatile pointer to prevent the compiler - // from removing. We use this rather than abort() or __builtin_trap() for - // portability: some debuggers don't correctly trap abort(). - *static_cast(nullptr) = 1; -#endif // GTEST_OS_WINDOWS - } else if (GTEST_FLAG(throw_on_failure)) { -#if GTEST_HAS_EXCEPTIONS - throw internal::GoogleTestFailureException(result); -#else - // We cannot call abort() as it generates a pop-up in debug mode - // that cannot be suppressed in VC 7.1 or below. - exit(1); -#endif - } - } -} - -// Adds a TestProperty to the current TestResult object when invoked from -// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked -// from SetUpTestSuite or TearDownTestSuite, or to the global property set -// when invoked elsewhere. If the result already contains a property with -// the same key, the value will be updated. -void UnitTest::RecordProperty(const std::string& key, - const std::string& value) { - impl_->RecordProperty(TestProperty(key, value)); -} - -// Runs all tests in this UnitTest object and prints the result. -// Returns 0 if successful, or 1 otherwise. -// -// We don't protect this under mutex_, as we only support calling it -// from the main thread. -int UnitTest::Run() { - const bool in_death_test_child_process = - internal::GTEST_FLAG(internal_run_death_test).length() > 0; - - // Google Test implements this protocol for catching that a test - // program exits before returning control to Google Test: - // - // 1. Upon start, Google Test creates a file whose absolute path - // is specified by the environment variable - // TEST_PREMATURE_EXIT_FILE. - // 2. When Google Test has finished its work, it deletes the file. - // - // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before - // running a Google-Test-based test program and check the existence - // of the file at the end of the test execution to see if it has - // exited prematurely. - - // If we are in the child process of a death test, don't - // create/delete the premature exit file, as doing so is unnecessary - // and will confuse the parent process. Otherwise, create/delete - // the file upon entering/leaving this function. If the program - // somehow exits before this function has a chance to return, the - // premature-exit file will be left undeleted, causing a test runner - // that understands the premature-exit-file protocol to report the - // test as having failed. - const internal::ScopedPrematureExitFile premature_exit_file( - in_death_test_child_process - ? nullptr - : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); - - // Captures the value of GTEST_FLAG(catch_exceptions). This value will be - // used for the duration of the program. - impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); - -#if GTEST_OS_WINDOWS - // Either the user wants Google Test to catch exceptions thrown by the - // tests or this is executing in the context of death test child - // process. In either case the user does not want to see pop-up dialogs - // about crashes - they are expected. - if (impl()->catch_exceptions() || in_death_test_child_process) { -# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT - // SetErrorMode doesn't exist on CE. - SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | - SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); -# endif // !GTEST_OS_WINDOWS_MOBILE - -# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE - // Death test children can be terminated with _abort(). On Windows, - // _abort() can show a dialog with a warning message. This forces the - // abort message to go to stderr instead. - _set_error_mode(_OUT_TO_STDERR); -# endif - -# if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE - // In the debug version, Visual Studio pops up a separate dialog - // offering a choice to debug the aborted program. We need to suppress - // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement - // executed. Google Test will notify the user of any unexpected - // failure via stderr. - if (!GTEST_FLAG(break_on_failure)) - _set_abort_behavior( - 0x0, // Clear the following flags: - _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. -# endif - - // In debug mode, the Windows CRT can crash with an assertion over invalid - // input (e.g. passing an invalid file descriptor). The default handling - // for these assertions is to pop up a dialog and wait for user input. - // Instead ask the CRT to dump such assertions to stderr non-interactively. - if (!IsDebuggerPresent()) { - (void)_CrtSetReportMode(_CRT_ASSERT, - _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); - (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); - } - } -#endif // GTEST_OS_WINDOWS - - return internal::HandleExceptionsInMethodIfSupported( - impl(), - &internal::UnitTestImpl::RunAllTests, - "auxiliary test code (environments or event listeners)") ? 0 : 1; -} - -// Returns the working directory when the first TEST() or TEST_F() was -// executed. -const char* UnitTest::original_working_dir() const { - return impl_->original_working_dir_.c_str(); -} - -// Returns the TestSuite object for the test that's currently running, -// or NULL if no test is running. -const TestSuite* UnitTest::current_test_suite() const - GTEST_LOCK_EXCLUDED_(mutex_) { - internal::MutexLock lock(&mutex_); - return impl_->current_test_suite(); -} - -// Legacy API is still available but deprecated -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -const TestCase* UnitTest::current_test_case() const - GTEST_LOCK_EXCLUDED_(mutex_) { - internal::MutexLock lock(&mutex_); - return impl_->current_test_suite(); -} -#endif - -// Returns the TestInfo object for the test that's currently running, -// or NULL if no test is running. -const TestInfo* UnitTest::current_test_info() const - GTEST_LOCK_EXCLUDED_(mutex_) { - internal::MutexLock lock(&mutex_); - return impl_->current_test_info(); -} - -// Returns the random seed used at the start of the current test run. -int UnitTest::random_seed() const { return impl_->random_seed(); } - -// Returns ParameterizedTestSuiteRegistry object used to keep track of -// value-parameterized tests and instantiate and register them. -internal::ParameterizedTestSuiteRegistry& -UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { - return impl_->parameterized_test_registry(); -} - -// Creates an empty UnitTest. -UnitTest::UnitTest() { - impl_ = new internal::UnitTestImpl(this); -} - -// Destructor of UnitTest. -UnitTest::~UnitTest() { - delete impl_; -} - -// Pushes a trace defined by SCOPED_TRACE() on to the per-thread -// Google Test trace stack. -void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) - GTEST_LOCK_EXCLUDED_(mutex_) { - internal::MutexLock lock(&mutex_); - impl_->gtest_trace_stack().push_back(trace); -} - -// Pops a trace from the per-thread Google Test trace stack. -void UnitTest::PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_) { - internal::MutexLock lock(&mutex_); - impl_->gtest_trace_stack().pop_back(); -} - -namespace internal { - -UnitTestImpl::UnitTestImpl(UnitTest* parent) - : parent_(parent), - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) - default_global_test_part_result_reporter_(this), - default_per_thread_test_part_result_reporter_(this), - GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_( - &default_global_test_part_result_reporter_), - per_thread_test_part_result_reporter_( - &default_per_thread_test_part_result_reporter_), - parameterized_test_registry_(), - parameterized_tests_registered_(false), - last_death_test_suite_(-1), - current_test_suite_(nullptr), - current_test_info_(nullptr), - ad_hoc_test_result_(), - os_stack_trace_getter_(nullptr), - post_flag_parse_init_performed_(false), - random_seed_(0), // Will be overridden by the flag before first use. - random_(0), // Will be reseeded before first use. - start_timestamp_(0), - elapsed_time_(0), -#if GTEST_HAS_DEATH_TEST - death_test_factory_(new DefaultDeathTestFactory), -#endif - // Will be overridden by the flag before first use. - catch_exceptions_(false) { - listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); -} - -UnitTestImpl::~UnitTestImpl() { - // Deletes every TestSuite. - ForEach(test_suites_, internal::Delete); - - // Deletes every Environment. - ForEach(environments_, internal::Delete); - - delete os_stack_trace_getter_; -} - -// Adds a TestProperty to the current TestResult object when invoked in a -// context of a test, to current test suite's ad_hoc_test_result when invoke -// from SetUpTestSuite/TearDownTestSuite, or to the global property set -// otherwise. If the result already contains a property with the same key, -// the value will be updated. -void UnitTestImpl::RecordProperty(const TestProperty& test_property) { - std::string xml_element; - TestResult* test_result; // TestResult appropriate for property recording. - - if (current_test_info_ != nullptr) { - xml_element = "testcase"; - test_result = &(current_test_info_->result_); - } else if (current_test_suite_ != nullptr) { - xml_element = "testsuite"; - test_result = &(current_test_suite_->ad_hoc_test_result_); - } else { - xml_element = "testsuites"; - test_result = &ad_hoc_test_result_; - } - test_result->RecordProperty(xml_element, test_property); -} - -#if GTEST_HAS_DEATH_TEST -// Disables event forwarding if the control is currently in a death test -// subprocess. Must not be called before InitGoogleTest. -void UnitTestImpl::SuppressTestEventsIfInSubprocess() { - if (internal_run_death_test_flag_.get() != nullptr) - listeners()->SuppressEventForwarding(); -} -#endif // GTEST_HAS_DEATH_TEST - -// Initializes event listeners performing XML output as specified by -// UnitTestOptions. Must not be called before InitGoogleTest. -void UnitTestImpl::ConfigureXmlOutput() { - const std::string& output_format = UnitTestOptions::GetOutputFormat(); - if (output_format == "xml") { - listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); - } else if (output_format == "json") { - listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); - } else if (output_format != "") { - GTEST_LOG_(WARNING) << "WARNING: unrecognized output format \"" - << output_format << "\" ignored."; - } -} - -#if GTEST_CAN_STREAM_RESULTS_ -// Initializes event listeners for streaming test results in string form. -// Must not be called before InitGoogleTest. -void UnitTestImpl::ConfigureStreamingOutput() { - const std::string& target = GTEST_FLAG(stream_result_to); - if (!target.empty()) { - const size_t pos = target.find(':'); - if (pos != std::string::npos) { - listeners()->Append(new StreamingListener(target.substr(0, pos), - target.substr(pos+1))); - } else { - GTEST_LOG_(WARNING) << "unrecognized streaming target \"" << target - << "\" ignored."; - } - } -} -#endif // GTEST_CAN_STREAM_RESULTS_ - -// Performs initialization dependent upon flag values obtained in -// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to -// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest -// this function is also called from RunAllTests. Since this function can be -// called more than once, it has to be idempotent. -void UnitTestImpl::PostFlagParsingInit() { - // Ensures that this function does not execute more than once. - if (!post_flag_parse_init_performed_) { - post_flag_parse_init_performed_ = true; - -#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) - // Register to send notifications about key process state changes. - listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); -#endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) - -#if GTEST_HAS_DEATH_TEST - InitDeathTestSubprocessControlInfo(); - SuppressTestEventsIfInSubprocess(); -#endif // GTEST_HAS_DEATH_TEST - - // Registers parameterized tests. This makes parameterized tests - // available to the UnitTest reflection API without running - // RUN_ALL_TESTS. - RegisterParameterizedTests(); - - // Configures listeners for XML output. This makes it possible for users - // to shut down the default XML output before invoking RUN_ALL_TESTS. - ConfigureXmlOutput(); - -#if GTEST_CAN_STREAM_RESULTS_ - // Configures listeners for streaming test results to the specified server. - ConfigureStreamingOutput(); -#endif // GTEST_CAN_STREAM_RESULTS_ - -#if GTEST_HAS_ABSL - if (GTEST_FLAG(install_failure_signal_handler)) { - absl::FailureSignalHandlerOptions options; - absl::InstallFailureSignalHandler(options); - } -#endif // GTEST_HAS_ABSL - } -} - -// A predicate that checks the name of a TestSuite against a known -// value. -// -// This is used for implementation of the UnitTest class only. We put -// it in the anonymous namespace to prevent polluting the outer -// namespace. -// -// TestSuiteNameIs is copyable. -class TestSuiteNameIs { - public: - // Constructor. - explicit TestSuiteNameIs(const std::string& name) : name_(name) {} - - // Returns true if and only if the name of test_suite matches name_. - bool operator()(const TestSuite* test_suite) const { - return test_suite != nullptr && - strcmp(test_suite->name(), name_.c_str()) == 0; - } - - private: - std::string name_; -}; - -// Finds and returns a TestSuite with the given name. If one doesn't -// exist, creates one and returns it. It's the CALLER'S -// RESPONSIBILITY to ensure that this function is only called WHEN THE -// TESTS ARE NOT SHUFFLED. -// -// Arguments: -// -// test_suite_name: name of the test suite -// type_param: the name of the test suite's type parameter, or NULL if -// this is not a typed or a type-parameterized test suite. -// set_up_tc: pointer to the function that sets up the test suite -// tear_down_tc: pointer to the function that tears down the test suite -TestSuite* UnitTestImpl::GetTestSuite( - const char* test_suite_name, const char* type_param, - internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc) { - // Can we find a TestSuite with the given name? - const auto test_suite = - std::find_if(test_suites_.rbegin(), test_suites_.rend(), - TestSuiteNameIs(test_suite_name)); - - if (test_suite != test_suites_.rend()) return *test_suite; - - // No. Let's create one. - auto* const new_test_suite = - new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc); - - // Is this a death test suite? - if (internal::UnitTestOptions::MatchesFilter(test_suite_name, - kDeathTestSuiteFilter)) { - // Yes. Inserts the test suite after the last death test suite - // defined so far. This only works when the test suites haven't - // been shuffled. Otherwise we may end up running a death test - // after a non-death test. - ++last_death_test_suite_; - test_suites_.insert(test_suites_.begin() + last_death_test_suite_, - new_test_suite); - } else { - // No. Appends to the end of the list. - test_suites_.push_back(new_test_suite); - } - - test_suite_indices_.push_back(static_cast(test_suite_indices_.size())); - return new_test_suite; -} - -// Helpers for setting up / tearing down the given environment. They -// are for use in the ForEach() function. -static void SetUpEnvironment(Environment* env) { env->SetUp(); } -static void TearDownEnvironment(Environment* env) { env->TearDown(); } - -// Runs all tests in this UnitTest object, prints the result, and -// returns true if all tests are successful. If any exception is -// thrown during a test, the test is considered to be failed, but the -// rest of the tests will still be run. -// -// When parameterized tests are enabled, it expands and registers -// parameterized tests first in RegisterParameterizedTests(). -// All other functions called from RunAllTests() may safely assume that -// parameterized tests are ready to be counted and run. -bool UnitTestImpl::RunAllTests() { - // True if and only if Google Test is initialized before RUN_ALL_TESTS() is - // called. - const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized(); - - // Do not run any test if the --help flag was specified. - if (g_help_flag) - return true; - - // Repeats the call to the post-flag parsing initialization in case the - // user didn't call InitGoogleTest. - PostFlagParsingInit(); - - // Even if sharding is not on, test runners may want to use the - // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding - // protocol. - internal::WriteToShardStatusFileIfNeeded(); - - // True if and only if we are in a subprocess for running a thread-safe-style - // death test. - bool in_subprocess_for_death_test = false; - -#if GTEST_HAS_DEATH_TEST - in_subprocess_for_death_test = - (internal_run_death_test_flag_.get() != nullptr); -# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) - if (in_subprocess_for_death_test) { - GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); - } -# endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) -#endif // GTEST_HAS_DEATH_TEST - - const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, - in_subprocess_for_death_test); - - // Compares the full test names with the filter to decide which - // tests to run. - const bool has_tests_to_run = FilterTests(should_shard - ? HONOR_SHARDING_PROTOCOL - : IGNORE_SHARDING_PROTOCOL) > 0; - - // Lists the tests and exits if the --gtest_list_tests flag was specified. - if (GTEST_FLAG(list_tests)) { - // This must be called *after* FilterTests() has been called. - ListTestsMatchingFilter(); - return true; - } - - random_seed_ = GTEST_FLAG(shuffle) ? - GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; - - // True if and only if at least one test has failed. - bool failed = false; - - TestEventListener* repeater = listeners()->repeater(); - - start_timestamp_ = GetTimeInMillis(); - repeater->OnTestProgramStart(*parent_); - - // How many times to repeat the tests? We don't want to repeat them - // when we are inside the subprocess of a death test. - const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); - // Repeats forever if the repeat count is negative. - const bool gtest_repeat_forever = repeat < 0; - for (int i = 0; gtest_repeat_forever || i != repeat; i++) { - // We want to preserve failures generated by ad-hoc test - // assertions executed before RUN_ALL_TESTS(). - ClearNonAdHocTestResult(); - - const TimeInMillis start = GetTimeInMillis(); - - // Shuffles test suites and tests if requested. - if (has_tests_to_run && GTEST_FLAG(shuffle)) { - random()->Reseed(static_cast(random_seed_)); - // This should be done before calling OnTestIterationStart(), - // such that a test event listener can see the actual test order - // in the event. - ShuffleTests(); - } - - // Tells the unit test event listeners that the tests are about to start. - repeater->OnTestIterationStart(*parent_, i); - - // Runs each test suite if there is at least one test to run. - if (has_tests_to_run) { - // Sets up all environments beforehand. - repeater->OnEnvironmentsSetUpStart(*parent_); - ForEach(environments_, SetUpEnvironment); - repeater->OnEnvironmentsSetUpEnd(*parent_); - - // Runs the tests only if there was no fatal failure or skip triggered - // during global set-up. - if (Test::IsSkipped()) { - // Emit diagnostics when global set-up calls skip, as it will not be - // emitted by default. - TestResult& test_result = - *internal::GetUnitTestImpl()->current_test_result(); - for (int j = 0; j < test_result.total_part_count(); ++j) { - const TestPartResult& test_part_result = - test_result.GetTestPartResult(j); - if (test_part_result.type() == TestPartResult::kSkip) { - const std::string& result = test_part_result.message(); - printf("%s\n", result.c_str()); - } - } - fflush(stdout); - } else if (!Test::HasFatalFailure()) { - for (int test_index = 0; test_index < total_test_suite_count(); - test_index++) { - GetMutableSuiteCase(test_index)->Run(); - } - } - - // Tears down all environments in reverse order afterwards. - repeater->OnEnvironmentsTearDownStart(*parent_); - std::for_each(environments_.rbegin(), environments_.rend(), - TearDownEnvironment); - repeater->OnEnvironmentsTearDownEnd(*parent_); - } - - elapsed_time_ = GetTimeInMillis() - start; - - // Tells the unit test event listener that the tests have just finished. - repeater->OnTestIterationEnd(*parent_, i); - - // Gets the result and clears it. - if (!Passed()) { - failed = true; - } - - // Restores the original test order after the iteration. This - // allows the user to quickly repro a failure that happens in the - // N-th iteration without repeating the first (N - 1) iterations. - // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in - // case the user somehow changes the value of the flag somewhere - // (it's always safe to unshuffle the tests). - UnshuffleTests(); - - if (GTEST_FLAG(shuffle)) { - // Picks a new random seed for each iteration. - random_seed_ = GetNextRandomSeed(random_seed_); - } - } - - repeater->OnTestProgramEnd(*parent_); - - if (!gtest_is_initialized_before_run_all_tests) { - ColoredPrintf( - COLOR_RED, - "\nIMPORTANT NOTICE - DO NOT IGNORE:\n" - "This test program did NOT call " GTEST_INIT_GOOGLE_TEST_NAME_ - "() before calling RUN_ALL_TESTS(). This is INVALID. Soon " GTEST_NAME_ - " will start to enforce the valid usage. " - "Please fix it ASAP, or IT WILL START TO FAIL.\n"); // NOLINT -#if GTEST_FOR_GOOGLE_ - ColoredPrintf(COLOR_RED, - "For more details, see http://wiki/Main/ValidGUnitMain.\n"); -#endif // GTEST_FOR_GOOGLE_ - } - - return !failed; -} - -// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file -// if the variable is present. If a file already exists at this location, this -// function will write over it. If the variable is present, but the file cannot -// be created, prints an error and exits. -void WriteToShardStatusFileIfNeeded() { - const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); - if (test_shard_file != nullptr) { - FILE* const file = posix::FOpen(test_shard_file, "w"); - if (file == nullptr) { - ColoredPrintf(COLOR_RED, - "Could not write to the test shard status file \"%s\" " - "specified by the %s environment variable.\n", - test_shard_file, kTestShardStatusFile); - fflush(stdout); - exit(EXIT_FAILURE); - } - fclose(file); - } -} - -// Checks whether sharding is enabled by examining the relevant -// environment variable values. If the variables are present, -// but inconsistent (i.e., shard_index >= total_shards), prints -// an error and exits. If in_subprocess_for_death_test, sharding is -// disabled because it must only be applied to the original test -// process. Otherwise, we could filter out death tests we intended to execute. -bool ShouldShard(const char* total_shards_env, - const char* shard_index_env, - bool in_subprocess_for_death_test) { - if (in_subprocess_for_death_test) { - return false; - } - - const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); - const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); - - if (total_shards == -1 && shard_index == -1) { - return false; - } else if (total_shards == -1 && shard_index != -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestShardIndex << " = " << shard_index - << ", but have left " << kTestTotalShards << " unset.\n"; - ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); - fflush(stdout); - exit(EXIT_FAILURE); - } else if (total_shards != -1 && shard_index == -1) { - const Message msg = Message() - << "Invalid environment variables: you have " - << kTestTotalShards << " = " << total_shards - << ", but have left " << kTestShardIndex << " unset.\n"; - ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); - fflush(stdout); - exit(EXIT_FAILURE); - } else if (shard_index < 0 || shard_index >= total_shards) { - const Message msg = Message() - << "Invalid environment variables: we require 0 <= " - << kTestShardIndex << " < " << kTestTotalShards - << ", but you have " << kTestShardIndex << "=" << shard_index - << ", " << kTestTotalShards << "=" << total_shards << ".\n"; - ColoredPrintf(COLOR_RED, "%s", msg.GetString().c_str()); - fflush(stdout); - exit(EXIT_FAILURE); - } - - return total_shards > 1; -} - -// Parses the environment variable var as an Int32. If it is unset, -// returns default_val. If it is not an Int32, prints an error -// and aborts. -Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { - const char* str_val = posix::GetEnv(var); - if (str_val == nullptr) { - return default_val; - } - - Int32 result; - if (!ParseInt32(Message() << "The value of environment variable " << var, - str_val, &result)) { - exit(EXIT_FAILURE); - } - return result; -} - -// Given the total number of shards, the shard index, and the test id, -// returns true if and only if the test should be run on this shard. The test id -// is some arbitrary but unique non-negative integer assigned to each test -// method. Assumes that 0 <= shard_index < total_shards. -bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { - return (test_id % total_shards) == shard_index; -} - -// Compares the name of each test with the user-specified filter to -// decide whether the test should be run, then records the result in -// each TestSuite and TestInfo object. -// If shard_tests == true, further filters tests based on sharding -// variables in the environment - see -// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md -// . Returns the number of tests that should run. -int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { - const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestTotalShards, -1) : -1; - const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? - Int32FromEnvOrDie(kTestShardIndex, -1) : -1; - - // num_runnable_tests are the number of tests that will - // run across all shards (i.e., match filter and are not disabled). - // num_selected_tests are the number of tests to be run on - // this shard. - int num_runnable_tests = 0; - int num_selected_tests = 0; - for (auto* test_suite : test_suites_) { - const std::string& test_suite_name = test_suite->name(); - test_suite->set_should_run(false); - - for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { - TestInfo* const test_info = test_suite->test_info_list()[j]; - const std::string test_name(test_info->name()); - // A test is disabled if test suite name or test name matches - // kDisableTestFilter. - const bool is_disabled = internal::UnitTestOptions::MatchesFilter( - test_suite_name, kDisableTestFilter) || - internal::UnitTestOptions::MatchesFilter( - test_name, kDisableTestFilter); - test_info->is_disabled_ = is_disabled; - - const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest( - test_suite_name, test_name); - test_info->matches_filter_ = matches_filter; - - const bool is_runnable = - (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && - matches_filter; - - const bool is_in_another_shard = - shard_tests != IGNORE_SHARDING_PROTOCOL && - !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests); - test_info->is_in_another_shard_ = is_in_another_shard; - const bool is_selected = is_runnable && !is_in_another_shard; - - num_runnable_tests += is_runnable; - num_selected_tests += is_selected; - - test_info->should_run_ = is_selected; - test_suite->set_should_run(test_suite->should_run() || is_selected); - } - } - return num_selected_tests; -} - -// Prints the given C-string on a single line by replacing all '\n' -// characters with string "\\n". If the output takes more than -// max_length characters, only prints the first max_length characters -// and "...". -static void PrintOnOneLine(const char* str, int max_length) { - if (str != nullptr) { - for (int i = 0; *str != '\0'; ++str) { - if (i >= max_length) { - printf("..."); - break; - } - if (*str == '\n') { - printf("\\n"); - i += 2; - } else { - printf("%c", *str); - ++i; - } - } - } -} - -// Prints the names of the tests matching the user-specified filter flag. -void UnitTestImpl::ListTestsMatchingFilter() { - // Print at most this many characters for each type/value parameter. - const int kMaxParamLength = 250; - - for (auto* test_suite : test_suites_) { - bool printed_test_suite_name = false; - - for (size_t j = 0; j < test_suite->test_info_list().size(); j++) { - const TestInfo* const test_info = test_suite->test_info_list()[j]; - if (test_info->matches_filter_) { - if (!printed_test_suite_name) { - printed_test_suite_name = true; - printf("%s.", test_suite->name()); - if (test_suite->type_param() != nullptr) { - printf(" # %s = ", kTypeParamLabel); - // We print the type parameter on a single line to make - // the output easy to parse by a program. - PrintOnOneLine(test_suite->type_param(), kMaxParamLength); - } - printf("\n"); - } - printf(" %s", test_info->name()); - if (test_info->value_param() != nullptr) { - printf(" # %s = ", kValueParamLabel); - // We print the value parameter on a single line to make the - // output easy to parse by a program. - PrintOnOneLine(test_info->value_param(), kMaxParamLength); - } - printf("\n"); - } - } - } - fflush(stdout); - const std::string& output_format = UnitTestOptions::GetOutputFormat(); - if (output_format == "xml" || output_format == "json") { - FILE* fileout = OpenFileForWriting( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str()); - std::stringstream stream; - if (output_format == "xml") { - XmlUnitTestResultPrinter( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) - .PrintXmlTestsList(&stream, test_suites_); - } else if (output_format == "json") { - JsonUnitTestResultPrinter( - UnitTestOptions::GetAbsolutePathToOutputFile().c_str()) - .PrintJsonTestList(&stream, test_suites_); - } - fprintf(fileout, "%s", StringStreamToString(&stream).c_str()); - fclose(fileout); - } -} - -// Sets the OS stack trace getter. -// -// Does nothing if the input and the current OS stack trace getter are -// the same; otherwise, deletes the old getter and makes the input the -// current getter. -void UnitTestImpl::set_os_stack_trace_getter( - OsStackTraceGetterInterface* getter) { - if (os_stack_trace_getter_ != getter) { - delete os_stack_trace_getter_; - os_stack_trace_getter_ = getter; - } -} - -// Returns the current OS stack trace getter if it is not NULL; -// otherwise, creates an OsStackTraceGetter, makes it the current -// getter, and returns it. -OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { - if (os_stack_trace_getter_ == nullptr) { -#ifdef GTEST_OS_STACK_TRACE_GETTER_ - os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; -#else - os_stack_trace_getter_ = new OsStackTraceGetter; -#endif // GTEST_OS_STACK_TRACE_GETTER_ - } - - return os_stack_trace_getter_; -} - -// Returns the most specific TestResult currently running. -TestResult* UnitTestImpl::current_test_result() { - if (current_test_info_ != nullptr) { - return ¤t_test_info_->result_; - } - if (current_test_suite_ != nullptr) { - return ¤t_test_suite_->ad_hoc_test_result_; - } - return &ad_hoc_test_result_; -} - -// Shuffles all test suites, and the tests within each test suite, -// making sure that death tests are still run first. -void UnitTestImpl::ShuffleTests() { - // Shuffles the death test suites. - ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_); - - // Shuffles the non-death test suites. - ShuffleRange(random(), last_death_test_suite_ + 1, - static_cast(test_suites_.size()), &test_suite_indices_); - - // Shuffles the tests inside each test suite. - for (auto& test_suite : test_suites_) { - test_suite->ShuffleTests(random()); - } -} - -// Restores the test suites and tests to their order before the first shuffle. -void UnitTestImpl::UnshuffleTests() { - for (size_t i = 0; i < test_suites_.size(); i++) { - // Unshuffles the tests in each test suite. - test_suites_[i]->UnshuffleTests(); - // Resets the index of each test suite. - test_suite_indices_[i] = static_cast(i); - } -} - -// Returns the current OS stack trace as an std::string. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in -// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, - int skip_count) { - // We pass skip_count + 1 to skip this wrapper function in addition - // to what the user really wants to skip. - return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); -} - -// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to -// suppress unreachable code warnings. -namespace { -class ClassUniqueToAlwaysTrue {}; -} - -bool IsTrue(bool condition) { return condition; } - -bool AlwaysTrue() { -#if GTEST_HAS_EXCEPTIONS - // This condition is always false so AlwaysTrue() never actually throws, - // but it makes the compiler think that it may throw. - if (IsTrue(false)) - throw ClassUniqueToAlwaysTrue(); -#endif // GTEST_HAS_EXCEPTIONS - return true; -} - -// If *pstr starts with the given prefix, modifies *pstr to be right -// past the prefix and returns true; otherwise leaves *pstr unchanged -// and returns false. None of pstr, *pstr, and prefix can be NULL. -bool SkipPrefix(const char* prefix, const char** pstr) { - const size_t prefix_len = strlen(prefix); - if (strncmp(*pstr, prefix, prefix_len) == 0) { - *pstr += prefix_len; - return true; - } - return false; -} - -// Parses a string as a command line flag. The string should have -// the format "--flag=value". When def_optional is true, the "=value" -// part can be omitted. -// -// Returns the value of the flag, or NULL if the parsing failed. -static const char* ParseFlagValue(const char* str, const char* flag, - bool def_optional) { - // str and flag must not be NULL. - if (str == nullptr || flag == nullptr) return nullptr; - - // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. - const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; - const size_t flag_len = flag_str.length(); - if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr; - - // Skips the flag name. - const char* flag_end = str + flag_len; - - // When def_optional is true, it's OK to not have a "=value" part. - if (def_optional && (flag_end[0] == '\0')) { - return flag_end; - } - - // If def_optional is true and there are more characters after the - // flag name, or if def_optional is false, there must be a '=' after - // the flag name. - if (flag_end[0] != '=') return nullptr; - - // Returns the string after "=". - return flag_end + 1; -} - -// Parses a string for a bool flag, in the form of either -// "--flag=value" or "--flag". -// -// In the former case, the value is taken as true as long as it does -// not start with '0', 'f', or 'F'. -// -// In the latter case, the value is taken as true. -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -static bool ParseBoolFlag(const char* str, const char* flag, bool* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, true); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Converts the string value to a bool. - *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); - return true; -} - -// Parses a string for an Int32 flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Sets *value to the value of the flag. - return ParseInt32(Message() << "The value of flag --" << flag, - value_str, value); -} - -// Parses a string for a string flag, in the form of -// "--flag=value". -// -// On success, stores the value of the flag in *value, and returns -// true. On failure, returns false without changing *value. -template -static bool ParseStringFlag(const char* str, const char* flag, String* value) { - // Gets the value of the flag as a string. - const char* const value_str = ParseFlagValue(str, flag, false); - - // Aborts if the parsing failed. - if (value_str == nullptr) return false; - - // Sets *value to the value of the flag. - *value = value_str; - return true; -} - -// Determines whether a string has a prefix that Google Test uses for its -// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. -// If Google Test detects that a command line flag has its prefix but is not -// recognized, it will print its help message. Flags starting with -// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test -// internal flags and do not trigger the help message. -static bool HasGoogleTestFlagPrefix(const char* str) { - return (SkipPrefix("--", &str) || - SkipPrefix("-", &str) || - SkipPrefix("/", &str)) && - !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && - (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || - SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); -} - -// Prints a string containing code-encoded text. The following escape -// sequences can be used in the string to control the text color: -// -// @@ prints a single '@' character. -// @R changes the color to red. -// @G changes the color to green. -// @Y changes the color to yellow. -// @D changes to the default terminal text color. -// -static void PrintColorEncoded(const char* str) { - GTestColor color = COLOR_DEFAULT; // The current color. - - // Conceptually, we split the string into segments divided by escape - // sequences. Then we print one segment at a time. At the end of - // each iteration, the str pointer advances to the beginning of the - // next segment. - for (;;) { - const char* p = strchr(str, '@'); - if (p == nullptr) { - ColoredPrintf(color, "%s", str); - return; - } - - ColoredPrintf(color, "%s", std::string(str, p).c_str()); - - const char ch = p[1]; - str = p + 2; - if (ch == '@') { - ColoredPrintf(color, "@"); - } else if (ch == 'D') { - color = COLOR_DEFAULT; - } else if (ch == 'R') { - color = COLOR_RED; - } else if (ch == 'G') { - color = COLOR_GREEN; - } else if (ch == 'Y') { - color = COLOR_YELLOW; - } else { - --str; - } - } -} - -static const char kColorEncodedHelpMessage[] = -"This program contains tests written using " GTEST_NAME_ ". You can use the\n" -"following command line flags to control its behavior:\n" -"\n" -"Test Selection:\n" -" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" -" List the names of all tests instead of running them. The name of\n" -" TEST(Foo, Bar) is \"Foo.Bar\".\n" -" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" - "[@G-@YNEGATIVE_PATTERNS]@D\n" -" Run only the tests whose name matches one of the positive patterns but\n" -" none of the negative patterns. '?' matches any single character; '*'\n" -" matches any substring; ':' separates two patterns.\n" -" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" -" Run all disabled tests too.\n" -"\n" -"Test Execution:\n" -" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" -" Run the tests repeatedly; use a negative count to repeat forever.\n" -" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" -" Randomize tests' orders on every iteration.\n" -" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" -" Random number seed to use for shuffling test orders (between 1 and\n" -" 99999, or 0 to use a seed based on the current time).\n" -"\n" -"Test Output:\n" -" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" -" Enable/disable colored output. The default is @Gauto@D.\n" -" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" -" Don't print the elapsed time of each test.\n" -" @G--" GTEST_FLAG_PREFIX_ "output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G" - GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" -" Generate a JSON or XML report in the given directory or with the given\n" -" file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\n" -# if GTEST_CAN_STREAM_RESULTS_ -" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" -" Stream test results to the given server.\n" -# endif // GTEST_CAN_STREAM_RESULTS_ -"\n" -"Assertion Behavior:\n" -# if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS -" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" -" Set the default death test style.\n" -# endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS -" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" -" Turn assertion failures into debugger break-points.\n" -" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" -" Turn assertion failures into C++ exceptions for use by an external\n" -" test framework.\n" -" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" -" Do not report exceptions as test failures. Instead, allow them\n" -" to crash the program or throw a pop-up (on Windows).\n" -"\n" -"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " - "the corresponding\n" -"environment variable of a flag (all letters in upper-case). For example, to\n" -"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ - "color=no@D or set\n" -"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" -"\n" -"For more information, please read the " GTEST_NAME_ " documentation at\n" -"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" -"(not one in your own code or tests), please report it to\n" -"@G<" GTEST_DEV_EMAIL_ ">@D.\n"; - -static bool ParseGoogleTestFlag(const char* const arg) { - return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, - >EST_FLAG(also_run_disabled_tests)) || - ParseBoolFlag(arg, kBreakOnFailureFlag, - >EST_FLAG(break_on_failure)) || - ParseBoolFlag(arg, kCatchExceptionsFlag, - >EST_FLAG(catch_exceptions)) || - ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) || - ParseStringFlag(arg, kDeathTestStyleFlag, - >EST_FLAG(death_test_style)) || - ParseBoolFlag(arg, kDeathTestUseFork, - >EST_FLAG(death_test_use_fork)) || - ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) || - ParseStringFlag(arg, kInternalRunDeathTestFlag, - >EST_FLAG(internal_run_death_test)) || - ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) || - ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) || - ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) || - ParseBoolFlag(arg, kPrintUTF8Flag, >EST_FLAG(print_utf8)) || - ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) || - ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) || - ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) || - ParseInt32Flag(arg, kStackTraceDepthFlag, - >EST_FLAG(stack_trace_depth)) || - ParseStringFlag(arg, kStreamResultToFlag, - >EST_FLAG(stream_result_to)) || - ParseBoolFlag(arg, kThrowOnFailureFlag, - >EST_FLAG(throw_on_failure)); -} - -#if GTEST_USE_OWN_FLAGFILE_FLAG_ -static void LoadFlagsFromFile(const std::string& path) { - FILE* flagfile = posix::FOpen(path.c_str(), "r"); - if (!flagfile) { - GTEST_LOG_(FATAL) << "Unable to open file \"" << GTEST_FLAG(flagfile) - << "\""; - } - std::string contents(ReadEntireFile(flagfile)); - posix::FClose(flagfile); - std::vector lines; - SplitString(contents, '\n', &lines); - for (size_t i = 0; i < lines.size(); ++i) { - if (lines[i].empty()) - continue; - if (!ParseGoogleTestFlag(lines[i].c_str())) - g_help_flag = true; - } -} -#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ - -// Parses the command line for Google Test flags, without initializing -// other parts of Google Test. The type parameter CharType can be -// instantiated to either char or wchar_t. -template -void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { - for (int i = 1; i < *argc; i++) { - const std::string arg_string = StreamableToString(argv[i]); - const char* const arg = arg_string.c_str(); - - using internal::ParseBoolFlag; - using internal::ParseInt32Flag; - using internal::ParseStringFlag; - - bool remove_flag = false; - if (ParseGoogleTestFlag(arg)) { - remove_flag = true; -#if GTEST_USE_OWN_FLAGFILE_FLAG_ - } else if (ParseStringFlag(arg, kFlagfileFlag, >EST_FLAG(flagfile))) { - LoadFlagsFromFile(GTEST_FLAG(flagfile)); - remove_flag = true; -#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ - } else if (arg_string == "--help" || arg_string == "-h" || - arg_string == "-?" || arg_string == "/?" || - HasGoogleTestFlagPrefix(arg)) { - // Both help flag and unrecognized Google Test flags (excluding - // internal ones) trigger help display. - g_help_flag = true; - } - - if (remove_flag) { - // Shift the remainder of the argv list left by one. Note - // that argv has (*argc + 1) elements, the last one always being - // NULL. The following loop moves the trailing NULL element as - // well. - for (int j = i; j != *argc; j++) { - argv[j] = argv[j + 1]; - } - - // Decrements the argument count. - (*argc)--; - - // We also need to decrement the iterator as we just removed - // an element. - i--; - } - } - - if (g_help_flag) { - // We print the help here instead of in RUN_ALL_TESTS(), as the - // latter may not be called at all if the user is using Google - // Test with another testing framework. - PrintColorEncoded(kColorEncodedHelpMessage); - } -} - -// Parses the command line for Google Test flags, without initializing -// other parts of Google Test. -void ParseGoogleTestFlagsOnly(int* argc, char** argv) { - ParseGoogleTestFlagsOnlyImpl(argc, argv); - - // Fix the value of *_NSGetArgc() on macOS, but if and only if - // *_NSGetArgv() == argv - // Only applicable to char** version of argv -#if GTEST_OS_MAC -#ifndef GTEST_OS_IOS - if (*_NSGetArgv() == argv) { - *_NSGetArgc() = *argc; - } -#endif -#endif -} -void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { - ParseGoogleTestFlagsOnlyImpl(argc, argv); -} - -// The internal implementation of InitGoogleTest(). -// -// The type parameter CharType can be instantiated to either char or -// wchar_t. -template -void InitGoogleTestImpl(int* argc, CharType** argv) { - // We don't want to run the initialization code twice. - if (GTestIsInitialized()) return; - - if (*argc <= 0) return; - - g_argvs.clear(); - for (int i = 0; i != *argc; i++) { - g_argvs.push_back(StreamableToString(argv[i])); - } - -#if GTEST_HAS_ABSL - absl::InitializeSymbolizer(g_argvs[0].c_str()); -#endif // GTEST_HAS_ABSL - - ParseGoogleTestFlagsOnly(argc, argv); - GetUnitTestImpl()->PostFlagParsingInit(); -} - -} // namespace internal - -// Initializes Google Test. This must be called before calling -// RUN_ALL_TESTS(). In particular, it parses a command line for the -// flags that Google Test recognizes. Whenever a Google Test flag is -// seen, it is removed from argv, and *argc is decremented. -// -// No value is returned. Instead, the Google Test flag variables are -// updated. -// -// Calling the function for the second time has no user-visible effect. -void InitGoogleTest(int* argc, char** argv) { -#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) - GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) - internal::InitGoogleTestImpl(argc, argv); -#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) -} - -// This overloaded version can be used in Windows programs compiled in -// UNICODE mode. -void InitGoogleTest(int* argc, wchar_t** argv) { -#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) - GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) - internal::InitGoogleTestImpl(argc, argv); -#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) -} - -// This overloaded version can be used on Arduino/embedded platforms where -// there is no argc/argv. -void InitGoogleTest() { - // Since Arduino doesn't have a command line, fake out the argc/argv arguments - int argc = 1; - const auto arg0 = "dummy"; - char* argv0 = const_cast(arg0); - char** argv = &argv0; - -#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) - GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv); -#else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) - internal::InitGoogleTestImpl(&argc, argv); -#endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) -} - -std::string TempDir() { -#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_) - return GTEST_CUSTOM_TEMPDIR_FUNCTION_(); -#endif - -#if GTEST_OS_WINDOWS_MOBILE - return "\\temp\\"; -#elif GTEST_OS_WINDOWS - const char* temp_dir = internal::posix::GetEnv("TEMP"); - if (temp_dir == nullptr || temp_dir[0] == '\0') - return "\\temp\\"; - else if (temp_dir[strlen(temp_dir) - 1] == '\\') - return temp_dir; - else - return std::string(temp_dir) + "\\"; -#elif GTEST_OS_LINUX_ANDROID - return "/sdcard/"; -#else - return "/tmp/"; -#endif // GTEST_OS_WINDOWS_MOBILE -} - -// Class ScopedTrace - -// Pushes the given source file location and message onto a per-thread -// trace stack maintained by Google Test. -void ScopedTrace::PushTrace(const char* file, int line, std::string message) { - internal::TraceInfo trace; - trace.file = file; - trace.line = line; - trace.message.swap(message); - - UnitTest::GetInstance()->PushGTestTrace(trace); -} - -// Pops the info pushed by the c'tor. -ScopedTrace::~ScopedTrace() - GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { - UnitTest::GetInstance()->PopGTestTrace(); -} - -} // namespace testing -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// This file implements death tests. - - -#include - - -#if GTEST_HAS_DEATH_TEST - -# if GTEST_OS_MAC -# include -# endif // GTEST_OS_MAC - -# include -# include -# include - -# if GTEST_OS_LINUX -# include -# endif // GTEST_OS_LINUX - -# include - -# if GTEST_OS_WINDOWS -# include -# else -# include -# include -# endif // GTEST_OS_WINDOWS - -# if GTEST_OS_QNX -# include -# endif // GTEST_OS_QNX - -# if GTEST_OS_FUCHSIA -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# endif // GTEST_OS_FUCHSIA - -#endif // GTEST_HAS_DEATH_TEST - - -namespace testing { - -// Constants. - -// The default death test style. -// -// This is defined in internal/gtest-port.h as "fast", but can be overridden by -// a definition in internal/custom/gtest-port.h. The recommended value, which is -// used internally at Google, is "threadsafe". -static const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE; - -GTEST_DEFINE_string_( - death_test_style, - internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), - "Indicates how to run a death test in a forked child process: " - "\"threadsafe\" (child process re-executes the test binary " - "from the beginning, running only the specific death test) or " - "\"fast\" (child process runs the death test immediately " - "after forking)."); - -GTEST_DEFINE_bool_( - death_test_use_fork, - internal::BoolFromGTestEnv("death_test_use_fork", false), - "Instructs to use fork()/_exit() instead of clone() in death tests. " - "Ignored and always uses fork() on POSIX systems where clone() is not " - "implemented. Useful when running under valgrind or similar tools if " - "those do not support clone(). Valgrind 3.3.1 will just fail if " - "it sees an unsupported combination of clone() flags. " - "It is not recommended to use this flag w/o valgrind though it will " - "work in 99% of the cases. Once valgrind is fixed, this flag will " - "most likely be removed."); - -namespace internal { -GTEST_DEFINE_string_( - internal_run_death_test, "", - "Indicates the file, line number, temporal index of " - "the single death test to run, and a file descriptor to " - "which a success code may be sent, all separated by " - "the '|' characters. This flag is specified if and only if the " - "current process is a sub-process launched for running a thread-safe " - "death test. FOR INTERNAL USE ONLY."); -} // namespace internal - -#if GTEST_HAS_DEATH_TEST - -namespace internal { - -// Valid only for fast death tests. Indicates the code is running in the -// child process of a fast style death test. -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA -static bool g_in_fast_death_test_child = false; -# endif - -// Returns a Boolean value indicating whether the caller is currently -// executing in the context of the death test child process. Tools such as -// Valgrind heap checkers may need this to modify their behavior in death -// tests. IMPORTANT: This is an internal utility. Using it may break the -// implementation of death tests. User code MUST NOT use it. -bool InDeathTestChild() { -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA - - // On Windows and Fuchsia, death tests are thread-safe regardless of the value - // of the death_test_style flag. - return !GTEST_FLAG(internal_run_death_test).empty(); - -# else - - if (GTEST_FLAG(death_test_style) == "threadsafe") - return !GTEST_FLAG(internal_run_death_test).empty(); - else - return g_in_fast_death_test_child; -#endif -} - -} // namespace internal - -// ExitedWithCode constructor. -ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { -} - -// ExitedWithCode function-call operator. -bool ExitedWithCode::operator()(int exit_status) const { -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA - - return exit_status == exit_code_; - -# else - - return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; - -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA -} - -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA -// KilledBySignal constructor. -KilledBySignal::KilledBySignal(int signum) : signum_(signum) { -} - -// KilledBySignal function-call operator. -bool KilledBySignal::operator()(int exit_status) const { -# if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) - { - bool result; - if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { - return result; - } - } -# endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) - return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; -} -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA - -namespace internal { - -// Utilities needed for death tests. - -// Generates a textual description of a given exit code, in the format -// specified by wait(2). -static std::string ExitSummary(int exit_code) { - Message m; - -# if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA - - m << "Exited with exit status " << exit_code; - -# else - - if (WIFEXITED(exit_code)) { - m << "Exited with exit status " << WEXITSTATUS(exit_code); - } else if (WIFSIGNALED(exit_code)) { - m << "Terminated by signal " << WTERMSIG(exit_code); - } -# ifdef WCOREDUMP - if (WCOREDUMP(exit_code)) { - m << " (core dumped)"; - } -# endif -# endif // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA - - return m.GetString(); -} - -// Returns true if exit_status describes a process that was terminated -// by a signal, or exited normally with a nonzero exit code. -bool ExitedUnsuccessfully(int exit_status) { - return !ExitedWithCode(0)(exit_status); -} - -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA -// Generates a textual failure message when a death test finds more than -// one thread running, or cannot determine the number of threads, prior -// to executing the given statement. It is the responsibility of the -// caller not to pass a thread_count of 1. -static std::string DeathTestThreadWarning(size_t thread_count) { - Message msg; - msg << "Death tests use fork(), which is unsafe particularly" - << " in a threaded context. For this test, " << GTEST_NAME_ << " "; - if (thread_count == 0) { - msg << "couldn't detect the number of threads."; - } else { - msg << "detected " << thread_count << " threads."; - } - msg << " See " - "https://github.com/google/googletest/blob/master/googletest/docs/" - "advanced.md#death-tests-and-threads" - << " for more explanation and suggested solutions, especially if" - << " this is the last message you see before your test times out."; - return msg.GetString(); -} -# endif // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA - -// Flag characters for reporting a death test that did not die. -static const char kDeathTestLived = 'L'; -static const char kDeathTestReturned = 'R'; -static const char kDeathTestThrew = 'T'; -static const char kDeathTestInternalError = 'I'; - -#if GTEST_OS_FUCHSIA - -// File descriptor used for the pipe in the child process. -static const int kFuchsiaReadPipeFd = 3; - -#endif - -// An enumeration describing all of the possible ways that a death test can -// conclude. DIED means that the process died while executing the test -// code; LIVED means that process lived beyond the end of the test code; -// RETURNED means that the test statement attempted to execute a return -// statement, which is not allowed; THREW means that the test statement -// returned control by throwing an exception. IN_PROGRESS means the test -// has not yet concluded. -enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; - -// Routine for aborting the program which is safe to call from an -// exec-style death test child process, in which case the error -// message is propagated back to the parent process. Otherwise, the -// message is simply printed to stderr. In either case, the program -// then exits with status 1. -static void DeathTestAbort(const std::string& message) { - // On a POSIX system, this function may be called from a threadsafe-style - // death test child process, which operates on a very small stack. Use - // the heap for any additional non-minuscule memory requirements. - const InternalRunDeathTestFlag* const flag = - GetUnitTestImpl()->internal_run_death_test_flag(); - if (flag != nullptr) { - FILE* parent = posix::FDOpen(flag->write_fd(), "w"); - fputc(kDeathTestInternalError, parent); - fprintf(parent, "%s", message.c_str()); - fflush(parent); - _exit(1); - } else { - fprintf(stderr, "%s", message.c_str()); - fflush(stderr); - posix::Abort(); - } -} - -// A replacement for CHECK that calls DeathTestAbort if the assertion -// fails. -# define GTEST_DEATH_TEST_CHECK_(expression) \ - do { \ - if (!::testing::internal::IsTrue(expression)) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression); \ - } \ - } while (::testing::internal::AlwaysFalse()) - -// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for -// evaluating any system call that fulfills two conditions: it must return -// -1 on failure, and set errno to EINTR when it is interrupted and -// should be tried again. The macro expands to a loop that repeatedly -// evaluates the expression as long as it evaluates to -1 and sets -// errno to EINTR. If the expression evaluates to -1 but errno is -// something other than EINTR, DeathTestAbort is called. -# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ - do { \ - int gtest_retval; \ - do { \ - gtest_retval = (expression); \ - } while (gtest_retval == -1 && errno == EINTR); \ - if (gtest_retval == -1) { \ - DeathTestAbort( \ - ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ - + ::testing::internal::StreamableToString(__LINE__) + ": " \ - + #expression + " != -1"); \ - } \ - } while (::testing::internal::AlwaysFalse()) - -// Returns the message describing the last system error in errno. -std::string GetLastErrnoDescription() { - return errno == 0 ? "" : posix::StrError(errno); -} - -// This is called from a death test parent process to read a failure -// message from the death test child process and log it with the FATAL -// severity. On Windows, the message is read from a pipe handle. On other -// platforms, it is read from a file descriptor. -static void FailFromInternalError(int fd) { - Message error; - char buffer[256]; - int num_read; - - do { - while ((num_read = posix::Read(fd, buffer, 255)) > 0) { - buffer[num_read] = '\0'; - error << buffer; - } - } while (num_read == -1 && errno == EINTR); - - if (num_read == 0) { - GTEST_LOG_(FATAL) << error.GetString(); - } else { - const int last_error = errno; - GTEST_LOG_(FATAL) << "Error while reading death test internal: " - << GetLastErrnoDescription() << " [" << last_error << "]"; - } -} - -// Death test constructor. Increments the running death test count -// for the current test. -DeathTest::DeathTest() { - TestInfo* const info = GetUnitTestImpl()->current_test_info(); - if (info == nullptr) { - DeathTestAbort("Cannot run a death test outside of a TEST or " - "TEST_F construct"); - } -} - -// Creates and returns a death test by dispatching to the current -// death test factory. -bool DeathTest::Create(const char* statement, - Matcher matcher, const char* file, - int line, DeathTest** test) { - return GetUnitTestImpl()->death_test_factory()->Create( - statement, std::move(matcher), file, line, test); -} - -const char* DeathTest::LastMessage() { - return last_death_test_message_.c_str(); -} - -void DeathTest::set_last_death_test_message(const std::string& message) { - last_death_test_message_ = message; -} - -std::string DeathTest::last_death_test_message_; - -// Provides cross platform implementation for some death functionality. -class DeathTestImpl : public DeathTest { - protected: - DeathTestImpl(const char* a_statement, Matcher matcher) - : statement_(a_statement), - matcher_(std::move(matcher)), - spawned_(false), - status_(-1), - outcome_(IN_PROGRESS), - read_fd_(-1), - write_fd_(-1) {} - - // read_fd_ is expected to be closed and cleared by a derived class. - ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } - - void Abort(AbortReason reason) override; - bool Passed(bool status_ok) override; - - const char* statement() const { return statement_; } - bool spawned() const { return spawned_; } - void set_spawned(bool is_spawned) { spawned_ = is_spawned; } - int status() const { return status_; } - void set_status(int a_status) { status_ = a_status; } - DeathTestOutcome outcome() const { return outcome_; } - void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } - int read_fd() const { return read_fd_; } - void set_read_fd(int fd) { read_fd_ = fd; } - int write_fd() const { return write_fd_; } - void set_write_fd(int fd) { write_fd_ = fd; } - - // Called in the parent process only. Reads the result code of the death - // test child process via a pipe, interprets it to set the outcome_ - // member, and closes read_fd_. Outputs diagnostics and terminates in - // case of unexpected codes. - void ReadAndInterpretStatusByte(); - - // Returns stderr output from the child process. - virtual std::string GetErrorLogs(); - - private: - // The textual content of the code this object is testing. This class - // doesn't own this string and should not attempt to delete it. - const char* const statement_; - // A matcher that's expected to match the stderr output by the child process. - Matcher matcher_; - // True if the death test child process has been successfully spawned. - bool spawned_; - // The exit status of the child process. - int status_; - // How the death test concluded. - DeathTestOutcome outcome_; - // Descriptor to the read end of the pipe to the child process. It is - // always -1 in the child process. The child keeps its write end of the - // pipe in write_fd_. - int read_fd_; - // Descriptor to the child's write end of the pipe to the parent process. - // It is always -1 in the parent process. The parent keeps its end of the - // pipe in read_fd_. - int write_fd_; -}; - -// Called in the parent process only. Reads the result code of the death -// test child process via a pipe, interprets it to set the outcome_ -// member, and closes read_fd_. Outputs diagnostics and terminates in -// case of unexpected codes. -void DeathTestImpl::ReadAndInterpretStatusByte() { - char flag; - int bytes_read; - - // The read() here blocks until data is available (signifying the - // failure of the death test) or until the pipe is closed (signifying - // its success), so it's okay to call this in the parent before - // the child process has exited. - do { - bytes_read = posix::Read(read_fd(), &flag, 1); - } while (bytes_read == -1 && errno == EINTR); - - if (bytes_read == 0) { - set_outcome(DIED); - } else if (bytes_read == 1) { - switch (flag) { - case kDeathTestReturned: - set_outcome(RETURNED); - break; - case kDeathTestThrew: - set_outcome(THREW); - break; - case kDeathTestLived: - set_outcome(LIVED); - break; - case kDeathTestInternalError: - FailFromInternalError(read_fd()); // Does not return. - break; - default: - GTEST_LOG_(FATAL) << "Death test child process reported " - << "unexpected status byte (" - << static_cast(flag) << ")"; - } - } else { - GTEST_LOG_(FATAL) << "Read from death test child process failed: " - << GetLastErrnoDescription(); - } - GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); - set_read_fd(-1); -} - -std::string DeathTestImpl::GetErrorLogs() { - return GetCapturedStderr(); -} - -// Signals that the death test code which should have exited, didn't. -// Should be called only in a death test child process. -// Writes a status byte to the child's status file descriptor, then -// calls _exit(1). -void DeathTestImpl::Abort(AbortReason reason) { - // The parent process considers the death test to be a failure if - // it finds any data in our pipe. So, here we write a single flag byte - // to the pipe, then exit. - const char status_ch = - reason == TEST_DID_NOT_DIE ? kDeathTestLived : - reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; - - GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); - // We are leaking the descriptor here because on some platforms (i.e., - // when built as Windows DLL), destructors of global objects will still - // run after calling _exit(). On such systems, write_fd_ will be - // indirectly closed from the destructor of UnitTestImpl, causing double - // close if it is also closed here. On debug configurations, double close - // may assert. As there are no in-process buffers to flush here, we are - // relying on the OS to close the descriptor after the process terminates - // when the destructors are not run. - _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) -} - -// Returns an indented copy of stderr output for a death test. -// This makes distinguishing death test output lines from regular log lines -// much easier. -static ::std::string FormatDeathTestOutput(const ::std::string& output) { - ::std::string ret; - for (size_t at = 0; ; ) { - const size_t line_end = output.find('\n', at); - ret += "[ DEATH ] "; - if (line_end == ::std::string::npos) { - ret += output.substr(at); - break; - } - ret += output.substr(at, line_end + 1 - at); - at = line_end + 1; - } - return ret; -} - -// Assesses the success or failure of a death test, using both private -// members which have previously been set, and one argument: -// -// Private data members: -// outcome: An enumeration describing how the death test -// concluded: DIED, LIVED, THREW, or RETURNED. The death test -// fails in the latter three cases. -// status: The exit status of the child process. On *nix, it is in the -// in the format specified by wait(2). On Windows, this is the -// value supplied to the ExitProcess() API or a numeric code -// of the exception that terminated the program. -// matcher_: A matcher that's expected to match the stderr output by the child -// process. -// -// Argument: -// status_ok: true if exit_status is acceptable in the context of -// this particular death test, which fails if it is false -// -// Returns true if and only if all of the above conditions are met. Otherwise, -// the first failing condition, in the order given above, is the one that is -// reported. Also sets the last death test message string. -bool DeathTestImpl::Passed(bool status_ok) { - if (!spawned()) - return false; - - const std::string error_message = GetErrorLogs(); - - bool success = false; - Message buffer; - - buffer << "Death test: " << statement() << "\n"; - switch (outcome()) { - case LIVED: - buffer << " Result: failed to die.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); - break; - case THREW: - buffer << " Result: threw an exception.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); - break; - case RETURNED: - buffer << " Result: illegal return in test statement.\n" - << " Error msg:\n" << FormatDeathTestOutput(error_message); - break; - case DIED: - if (status_ok) { - if (matcher_.Matches(error_message)) { - success = true; - } else { - std::ostringstream stream; - matcher_.DescribeTo(&stream); - buffer << " Result: died but not with expected error.\n" - << " Expected: " << stream.str() << "\n" - << "Actual msg:\n" - << FormatDeathTestOutput(error_message); - } - } else { - buffer << " Result: died but not with expected exit code:\n" - << " " << ExitSummary(status()) << "\n" - << "Actual msg:\n" << FormatDeathTestOutput(error_message); - } - break; - case IN_PROGRESS: - default: - GTEST_LOG_(FATAL) - << "DeathTest::Passed somehow called before conclusion of test"; - } - - DeathTest::set_last_death_test_message(buffer.GetString()); - return success; -} - -# if GTEST_OS_WINDOWS -// WindowsDeathTest implements death tests on Windows. Due to the -// specifics of starting new processes on Windows, death tests there are -// always threadsafe, and Google Test considers the -// --gtest_death_test_style=fast setting to be equivalent to -// --gtest_death_test_style=threadsafe there. -// -// A few implementation notes: Like the Linux version, the Windows -// implementation uses pipes for child-to-parent communication. But due to -// the specifics of pipes on Windows, some extra steps are required: -// -// 1. The parent creates a communication pipe and stores handles to both -// ends of it. -// 2. The parent starts the child and provides it with the information -// necessary to acquire the handle to the write end of the pipe. -// 3. The child acquires the write end of the pipe and signals the parent -// using a Windows event. -// 4. Now the parent can release the write end of the pipe on its side. If -// this is done before step 3, the object's reference count goes down to -// 0 and it is destroyed, preventing the child from acquiring it. The -// parent now has to release it, or read operations on the read end of -// the pipe will not return when the child terminates. -// 5. The parent reads child's output through the pipe (outcome code and -// any possible error messages) from the pipe, and its stderr and then -// determines whether to fail the test. -// -// Note: to distinguish Win32 API calls from the local method and function -// calls, the former are explicitly resolved in the global namespace. -// -class WindowsDeathTest : public DeathTestImpl { - public: - WindowsDeathTest(const char* a_statement, Matcher matcher, - const char* file, int line) - : DeathTestImpl(a_statement, std::move(matcher)), - file_(file), - line_(line) {} - - // All of these virtual functions are inherited from DeathTest. - virtual int Wait(); - virtual TestRole AssumeRole(); - - private: - // The name of the file in which the death test is located. - const char* const file_; - // The line number on which the death test is located. - const int line_; - // Handle to the write end of the pipe to the child process. - AutoHandle write_handle_; - // Child process handle. - AutoHandle child_handle_; - // Event the child process uses to signal the parent that it has - // acquired the handle to the write end of the pipe. After seeing this - // event the parent can release its own handles to make sure its - // ReadFile() calls return when the child terminates. - AutoHandle event_handle_; -}; - -// Waits for the child in a death test to exit, returning its exit -// status, or 0 if no child process exists. As a side effect, sets the -// outcome data member. -int WindowsDeathTest::Wait() { - if (!spawned()) - return 0; - - // Wait until the child either signals that it has acquired the write end - // of the pipe or it dies. - const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; - switch (::WaitForMultipleObjects(2, - wait_handles, - FALSE, // Waits for any of the handles. - INFINITE)) { - case WAIT_OBJECT_0: - case WAIT_OBJECT_0 + 1: - break; - default: - GTEST_DEATH_TEST_CHECK_(false); // Should not get here. - } - - // The child has acquired the write end of the pipe or exited. - // We release the handle on our side and continue. - write_handle_.Reset(); - event_handle_.Reset(); - - ReadAndInterpretStatusByte(); - - // Waits for the child process to exit if it haven't already. This - // returns immediately if the child has already exited, regardless of - // whether previous calls to WaitForMultipleObjects synchronized on this - // handle or not. - GTEST_DEATH_TEST_CHECK_( - WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), - INFINITE)); - DWORD status_code; - GTEST_DEATH_TEST_CHECK_( - ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); - child_handle_.Reset(); - set_status(static_cast(status_code)); - return status(); -} - -// The AssumeRole process for a Windows death test. It creates a child -// process with the same executable as the current process to run the -// death test. The child process is given the --gtest_filter and -// --gtest_internal_run_death_test flags such that it knows to run the -// current death test only. -DeathTest::TestRole WindowsDeathTest::AssumeRole() { - const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const TestInfo* const info = impl->current_test_info(); - const int death_test_index = info->result()->death_test_count(); - - if (flag != nullptr) { - // ParseInternalRunDeathTestFlag() has performed all the necessary - // processing. - set_write_fd(flag->write_fd()); - return EXECUTE_TEST; - } - - // WindowsDeathTest uses an anonymous pipe to communicate results of - // a death test. - SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES), - nullptr, TRUE}; - HANDLE read_handle, write_handle; - GTEST_DEATH_TEST_CHECK_( - ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, - 0) // Default buffer size. - != FALSE); - set_read_fd(::_open_osfhandle(reinterpret_cast(read_handle), - O_RDONLY)); - write_handle_.Reset(write_handle); - event_handle_.Reset(::CreateEvent( - &handles_are_inheritable, - TRUE, // The event will automatically reset to non-signaled state. - FALSE, // The initial state is non-signalled. - nullptr)); // The even is unnamed. - GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr); - const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + - kFilterFlag + "=" + info->test_suite_name() + - "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + - "=" + file_ + "|" + StreamableToString(line_) + "|" + - StreamableToString(death_test_index) + "|" + - StreamableToString(static_cast(::GetCurrentProcessId())) + - // size_t has the same width as pointers on both 32-bit and 64-bit - // Windows platforms. - // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. - "|" + StreamableToString(reinterpret_cast(write_handle)) + - "|" + StreamableToString(reinterpret_cast(event_handle_.Get())); - - char executable_path[_MAX_PATH + 1]; // NOLINT - GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr, - executable_path, - _MAX_PATH)); - - std::string command_line = - std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + - internal_flag + "\""; - - DeathTest::set_last_death_test_message(""); - - CaptureStderr(); - // Flush the log buffers since the log streams are shared with the child. - FlushInfoLog(); - - // The child process will share the standard handles with the parent. - STARTUPINFOA startup_info; - memset(&startup_info, 0, sizeof(STARTUPINFO)); - startup_info.dwFlags = STARTF_USESTDHANDLES; - startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); - startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); - startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); - - PROCESS_INFORMATION process_info; - GTEST_DEATH_TEST_CHECK_( - ::CreateProcessA( - executable_path, const_cast(command_line.c_str()), - nullptr, // Retuned process handle is not inheritable. - nullptr, // Retuned thread handle is not inheritable. - TRUE, // Child inherits all inheritable handles (for write_handle_). - 0x0, // Default creation flags. - nullptr, // Inherit the parent's environment. - UnitTest::GetInstance()->original_working_dir(), &startup_info, - &process_info) != FALSE); - child_handle_.Reset(process_info.hProcess); - ::CloseHandle(process_info.hThread); - set_spawned(true); - return OVERSEE_TEST; -} - -# elif GTEST_OS_FUCHSIA - -class FuchsiaDeathTest : public DeathTestImpl { - public: - FuchsiaDeathTest(const char* a_statement, Matcher matcher, - const char* file, int line) - : DeathTestImpl(a_statement, std::move(matcher)), - file_(file), - line_(line) {} - - // All of these virtual functions are inherited from DeathTest. - int Wait() override; - TestRole AssumeRole() override; - std::string GetErrorLogs() override; - - private: - // The name of the file in which the death test is located. - const char* const file_; - // The line number on which the death test is located. - const int line_; - // The stderr data captured by the child process. - std::string captured_stderr_; - - zx::process child_process_; - zx::channel exception_channel_; - zx::socket stderr_socket_; -}; - -// Utility class for accumulating command-line arguments. -class Arguments { - public: - Arguments() { args_.push_back(nullptr); } - - ~Arguments() { - for (std::vector::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template - void AddArguments(const ::std::vector& arguments) { - for (typename ::std::vector::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { - args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); - } - } - char* const* Argv() { - return &args_[0]; - } - - int size() { - return args_.size() - 1; - } - - private: - std::vector args_; -}; - -// Waits for the child in a death test to exit, returning its exit -// status, or 0 if no child process exists. As a side effect, sets the -// outcome data member. -int FuchsiaDeathTest::Wait() { - const int kProcessKey = 0; - const int kSocketKey = 1; - const int kExceptionKey = 2; - - if (!spawned()) - return 0; - - // Create a port to wait for socket/task/exception events. - zx_status_t status_zx; - zx::port port; - status_zx = zx::port::create(0, &port); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - - // Register to wait for the child process to terminate. - status_zx = child_process_.wait_async( - port, kProcessKey, ZX_PROCESS_TERMINATED, ZX_WAIT_ASYNC_ONCE); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - - // Register to wait for the socket to be readable or closed. - status_zx = stderr_socket_.wait_async( - port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, - ZX_WAIT_ASYNC_ONCE); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - - // Register to wait for an exception. - status_zx = exception_channel_.wait_async( - port, kExceptionKey, ZX_CHANNEL_READABLE, ZX_WAIT_ASYNC_ONCE); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - - bool process_terminated = false; - bool socket_closed = false; - do { - zx_port_packet_t packet = {}; - status_zx = port.wait(zx::time::infinite(), &packet); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - - if (packet.key == kExceptionKey) { - // Process encountered an exception. Kill it directly rather than - // letting other handlers process the event. We will get a kProcessKey - // event when the process actually terminates. - status_zx = child_process_.kill(); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - } else if (packet.key == kProcessKey) { - // Process terminated. - GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); - GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED); - process_terminated = true; - } else if (packet.key == kSocketKey) { - GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type)); - if (packet.signal.observed & ZX_SOCKET_READABLE) { - // Read data from the socket. - constexpr size_t kBufferSize = 1024; - do { - size_t old_length = captured_stderr_.length(); - size_t bytes_read = 0; - captured_stderr_.resize(old_length + kBufferSize); - status_zx = stderr_socket_.read( - 0, &captured_stderr_.front() + old_length, kBufferSize, - &bytes_read); - captured_stderr_.resize(old_length + bytes_read); - } while (status_zx == ZX_OK); - if (status_zx == ZX_ERR_PEER_CLOSED) { - socket_closed = true; - } else { - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT); - status_zx = stderr_socket_.wait_async( - port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, - ZX_WAIT_ASYNC_ONCE); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - } - } else { - GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED); - socket_closed = true; - } - } - } while (!process_terminated && !socket_closed); - - ReadAndInterpretStatusByte(); - - zx_info_process_t buffer; - status_zx = child_process_.get_info( - ZX_INFO_PROCESS, &buffer, sizeof(buffer), nullptr, nullptr); - GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK); - - GTEST_DEATH_TEST_CHECK_(buffer.exited); - set_status(buffer.return_code); - return status(); -} - -// The AssumeRole process for a Fuchsia death test. It creates a child -// process with the same executable as the current process to run the -// death test. The child process is given the --gtest_filter and -// --gtest_internal_run_death_test flags such that it knows to run the -// current death test only. -DeathTest::TestRole FuchsiaDeathTest::AssumeRole() { - const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const TestInfo* const info = impl->current_test_info(); - const int death_test_index = info->result()->death_test_count(); - - if (flag != nullptr) { - // ParseInternalRunDeathTestFlag() has performed all the necessary - // processing. - set_write_fd(kFuchsiaReadPipeFd); - return EXECUTE_TEST; - } - - // Flush the log buffers since the log streams are shared with the child. - FlushInfoLog(); - - // Build the child process command line. - const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + - kFilterFlag + "=" + info->test_suite_name() + - "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" - + file_ + "|" - + StreamableToString(line_) + "|" - + StreamableToString(death_test_index); - Arguments args; - args.AddArguments(GetInjectableArgvs()); - args.AddArgument(filter_flag.c_str()); - args.AddArgument(internal_flag.c_str()); - - // Build the pipe for communication with the child. - zx_status_t status; - zx_handle_t child_pipe_handle; - int child_pipe_fd; - status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - set_read_fd(child_pipe_fd); - - // Set the pipe handle for the child. - fdio_spawn_action_t spawn_actions[2] = {}; - fdio_spawn_action_t* add_handle_action = &spawn_actions[0]; - add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE; - add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd); - add_handle_action->h.handle = child_pipe_handle; - - // Create a socket pair will be used to receive the child process' stderr. - zx::socket stderr_producer_socket; - status = - zx::socket::create(0, &stderr_producer_socket, &stderr_socket_); - GTEST_DEATH_TEST_CHECK_(status >= 0); - int stderr_producer_fd = -1; - status = - fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd); - GTEST_DEATH_TEST_CHECK_(status >= 0); - - // Make the stderr socket nonblocking. - GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0); - - fdio_spawn_action_t* add_stderr_action = &spawn_actions[1]; - add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD; - add_stderr_action->fd.local_fd = stderr_producer_fd; - add_stderr_action->fd.target_fd = STDERR_FILENO; - - // Create a child job. - zx_handle_t child_job = ZX_HANDLE_INVALID; - status = zx_job_create(zx_job_default(), 0, & child_job); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - zx_policy_basic_t policy; - policy.condition = ZX_POL_NEW_ANY; - policy.policy = ZX_POL_ACTION_ALLOW; - status = zx_job_set_policy( - child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC, &policy, 1); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - - // Create an exception channel attached to the |child_job|, to allow - // us to suppress the system default exception handler from firing. - status = - zx_task_create_exception_channel( - child_job, 0, exception_channel_.reset_and_get_address()); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - - // Spawn the child process. - status = fdio_spawn_etc( - child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0], args.Argv(), nullptr, - 2, spawn_actions, child_process_.reset_and_get_address(), nullptr); - GTEST_DEATH_TEST_CHECK_(status == ZX_OK); - - set_spawned(true); - return OVERSEE_TEST; -} - -std::string FuchsiaDeathTest::GetErrorLogs() { - return captured_stderr_; -} - -#else // We are neither on Windows, nor on Fuchsia. - -// ForkingDeathTest provides implementations for most of the abstract -// methods of the DeathTest interface. Only the AssumeRole method is -// left undefined. -class ForkingDeathTest : public DeathTestImpl { - public: - ForkingDeathTest(const char* statement, Matcher matcher); - - // All of these virtual functions are inherited from DeathTest. - int Wait() override; - - protected: - void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } - - private: - // PID of child process during death test; 0 in the child process itself. - pid_t child_pid_; -}; - -// Constructs a ForkingDeathTest. -ForkingDeathTest::ForkingDeathTest(const char* a_statement, - Matcher matcher) - : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {} - -// Waits for the child in a death test to exit, returning its exit -// status, or 0 if no child process exists. As a side effect, sets the -// outcome data member. -int ForkingDeathTest::Wait() { - if (!spawned()) - return 0; - - ReadAndInterpretStatusByte(); - - int status_value; - GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); - set_status(status_value); - return status_value; -} - -// A concrete death test class that forks, then immediately runs the test -// in the child process. -class NoExecDeathTest : public ForkingDeathTest { - public: - NoExecDeathTest(const char* a_statement, Matcher matcher) - : ForkingDeathTest(a_statement, std::move(matcher)) {} - TestRole AssumeRole() override; -}; - -// The AssumeRole process for a fork-and-run death test. It implements a -// straightforward fork, with a simple pipe to transmit the status byte. -DeathTest::TestRole NoExecDeathTest::AssumeRole() { - const size_t thread_count = GetThreadCount(); - if (thread_count != 1) { - GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); - } - - int pipe_fd[2]; - GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); - - DeathTest::set_last_death_test_message(""); - CaptureStderr(); - // When we fork the process below, the log file buffers are copied, but the - // file descriptors are shared. We flush all log files here so that closing - // the file descriptors in the child process doesn't throw off the - // synchronization between descriptors and buffers in the parent process. - // This is as close to the fork as possible to avoid a race condition in case - // there are multiple threads running before the death test, and another - // thread writes to the log file. - FlushInfoLog(); - - const pid_t child_pid = fork(); - GTEST_DEATH_TEST_CHECK_(child_pid != -1); - set_child_pid(child_pid); - if (child_pid == 0) { - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); - set_write_fd(pipe_fd[1]); - // Redirects all logging to stderr in the child process to prevent - // concurrent writes to the log files. We capture stderr in the parent - // process and append the child process' output to a log. - LogToStderr(); - // Event forwarding to the listeners of event listener API mush be shut - // down in death test subprocesses. - GetUnitTestImpl()->listeners()->SuppressEventForwarding(); - g_in_fast_death_test_child = true; - return EXECUTE_TEST; - } else { - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); - set_read_fd(pipe_fd[0]); - set_spawned(true); - return OVERSEE_TEST; - } -} - -// A concrete death test class that forks and re-executes the main -// program from the beginning, with command-line flags set that cause -// only this specific death test to be run. -class ExecDeathTest : public ForkingDeathTest { - public: - ExecDeathTest(const char* a_statement, Matcher matcher, - const char* file, int line) - : ForkingDeathTest(a_statement, std::move(matcher)), - file_(file), - line_(line) {} - TestRole AssumeRole() override; - - private: - static ::std::vector GetArgvsForDeathTestChildProcess() { - ::std::vector args = GetInjectableArgvs(); -# if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) - ::std::vector extra_args = - GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); - args.insert(args.end(), extra_args.begin(), extra_args.end()); -# endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) - return args; - } - // The name of the file in which the death test is located. - const char* const file_; - // The line number on which the death test is located. - const int line_; -}; - -// Utility class for accumulating command-line arguments. -class Arguments { - public: - Arguments() { args_.push_back(nullptr); } - - ~Arguments() { - for (std::vector::iterator i = args_.begin(); i != args_.end(); - ++i) { - free(*i); - } - } - void AddArgument(const char* argument) { - args_.insert(args_.end() - 1, posix::StrDup(argument)); - } - - template - void AddArguments(const ::std::vector& arguments) { - for (typename ::std::vector::const_iterator i = arguments.begin(); - i != arguments.end(); - ++i) { - args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); - } - } - char* const* Argv() { - return &args_[0]; - } - - private: - std::vector args_; -}; - -// A struct that encompasses the arguments to the child process of a -// threadsafe-style death test process. -struct ExecDeathTestArgs { - char* const* argv; // Command-line arguments for the child's call to exec - int close_fd; // File descriptor to close; the read end of a pipe -}; - -# if GTEST_OS_MAC -inline char** GetEnviron() { - // When Google Test is built as a framework on MacOS X, the environ variable - // is unavailable. Apple's documentation (man environ) recommends using - // _NSGetEnviron() instead. - return *_NSGetEnviron(); -} -# else -// Some POSIX platforms expect you to declare environ. extern "C" makes -// it reside in the global namespace. -extern "C" char** environ; -inline char** GetEnviron() { return environ; } -# endif // GTEST_OS_MAC - -# if !GTEST_OS_QNX -// The main function for a threadsafe-style death test child process. -// This function is called in a clone()-ed process and thus must avoid -// any potentially unsafe operations like malloc or libc functions. -static int ExecDeathTestChildMain(void* child_arg) { - ExecDeathTestArgs* const args = static_cast(child_arg); - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); - - // We need to execute the test program in the same environment where - // it was originally invoked. Therefore we change to the original - // working directory first. - const char* const original_dir = - UnitTest::GetInstance()->original_working_dir(); - // We can safely call chdir() as it's a direct system call. - if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); - return EXIT_FAILURE; - } - - // We can safely call execve() as it's a direct system call. We - // cannot use execvp() as it's a libc function and thus potentially - // unsafe. Since execve() doesn't search the PATH, the user must - // invoke the test program via a valid path that contains at least - // one path separator. - execve(args->argv[0], args->argv, GetEnviron()); - DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + - original_dir + " failed: " + - GetLastErrnoDescription()); - return EXIT_FAILURE; -} -# endif // !GTEST_OS_QNX - -# if GTEST_HAS_CLONE -// Two utility routines that together determine the direction the stack -// grows. -// This could be accomplished more elegantly by a single recursive -// function, but we want to guard against the unlikely possibility of -// a smart compiler optimizing the recursion away. -// -// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining -// StackLowerThanAddress into StackGrowsDown, which then doesn't give -// correct answer. -static void StackLowerThanAddress(const void* ptr, - bool* result) GTEST_NO_INLINE_; -// HWAddressSanitizer add a random tag to the MSB of the local variable address, -// making comparison result unpredictable. -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -static void StackLowerThanAddress(const void* ptr, bool* result) { - int dummy; - *result = (&dummy < ptr); -} - -// Make sure AddressSanitizer does not tamper with the stack here. -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -static bool StackGrowsDown() { - int dummy; - bool result; - StackLowerThanAddress(&dummy, &result); - return result; -} -# endif // GTEST_HAS_CLONE - -// Spawns a child process with the same executable as the current process in -// a thread-safe manner and instructs it to run the death test. The -// implementation uses fork(2) + exec. On systems where clone(2) is -// available, it is used instead, being slightly more thread-safe. On QNX, -// fork supports only single-threaded environments, so this function uses -// spawn(2) there instead. The function dies with an error message if -// anything goes wrong. -static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { - ExecDeathTestArgs args = { argv, close_fd }; - pid_t child_pid = -1; - -# if GTEST_OS_QNX - // Obtains the current directory and sets it to be closed in the child - // process. - const int cwd_fd = open(".", O_RDONLY); - GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); - GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); - // We need to execute the test program in the same environment where - // it was originally invoked. Therefore we change to the original - // working directory first. - const char* const original_dir = - UnitTest::GetInstance()->original_working_dir(); - // We can safely call chdir() as it's a direct system call. - if (chdir(original_dir) != 0) { - DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + - GetLastErrnoDescription()); - return EXIT_FAILURE; - } - - int fd_flags; - // Set close_fd to be closed after spawn. - GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); - GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, - fd_flags | FD_CLOEXEC)); - struct inheritance inherit = {0}; - // spawn is a system call. - child_pid = - spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron()); - // Restores the current working directory. - GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); - -# else // GTEST_OS_QNX -# if GTEST_OS_LINUX - // When a SIGPROF signal is received while fork() or clone() are executing, - // the process may hang. To avoid this, we ignore SIGPROF here and re-enable - // it after the call to fork()/clone() is complete. - struct sigaction saved_sigprof_action; - struct sigaction ignore_sigprof_action; - memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); - sigemptyset(&ignore_sigprof_action.sa_mask); - ignore_sigprof_action.sa_handler = SIG_IGN; - GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( - SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); -# endif // GTEST_OS_LINUX - -# if GTEST_HAS_CLONE - const bool use_fork = GTEST_FLAG(death_test_use_fork); - - if (!use_fork) { - static const bool stack_grows_down = StackGrowsDown(); - const auto stack_size = static_cast(getpagesize()); - // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. - void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE, - MAP_ANON | MAP_PRIVATE, -1, 0); - GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); - - // Maximum stack alignment in bytes: For a downward-growing stack, this - // amount is subtracted from size of the stack space to get an address - // that is within the stack space and is aligned on all systems we care - // about. As far as I know there is no ABI with stack alignment greater - // than 64. We assume stack and stack_size already have alignment of - // kMaxStackAlignment. - const size_t kMaxStackAlignment = 64; - void* const stack_top = - static_cast(stack) + - (stack_grows_down ? stack_size - kMaxStackAlignment : 0); - GTEST_DEATH_TEST_CHECK_( - static_cast(stack_size) > kMaxStackAlignment && - reinterpret_cast(stack_top) % kMaxStackAlignment == 0); - - child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); - - GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); - } -# else - const bool use_fork = true; -# endif // GTEST_HAS_CLONE - - if (use_fork && (child_pid = fork()) == 0) { - ExecDeathTestChildMain(&args); - _exit(0); - } -# endif // GTEST_OS_QNX -# if GTEST_OS_LINUX - GTEST_DEATH_TEST_CHECK_SYSCALL_( - sigaction(SIGPROF, &saved_sigprof_action, nullptr)); -# endif // GTEST_OS_LINUX - - GTEST_DEATH_TEST_CHECK_(child_pid != -1); - return child_pid; -} - -// The AssumeRole process for a fork-and-exec death test. It re-executes the -// main program from the beginning, setting the --gtest_filter -// and --gtest_internal_run_death_test flags to cause only the current -// death test to be re-run. -DeathTest::TestRole ExecDeathTest::AssumeRole() { - const UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const TestInfo* const info = impl->current_test_info(); - const int death_test_index = info->result()->death_test_count(); - - if (flag != nullptr) { - set_write_fd(flag->write_fd()); - return EXECUTE_TEST; - } - - int pipe_fd[2]; - GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); - // Clear the close-on-exec flag on the write end of the pipe, lest - // it be closed when the child process does an exec: - GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); - - const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + - kFilterFlag + "=" + info->test_suite_name() + - "." + info->name(); - const std::string internal_flag = - std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" - + file_ + "|" + StreamableToString(line_) + "|" - + StreamableToString(death_test_index) + "|" - + StreamableToString(pipe_fd[1]); - Arguments args; - args.AddArguments(GetArgvsForDeathTestChildProcess()); - args.AddArgument(filter_flag.c_str()); - args.AddArgument(internal_flag.c_str()); - - DeathTest::set_last_death_test_message(""); - - CaptureStderr(); - // See the comment in NoExecDeathTest::AssumeRole for why the next line - // is necessary. - FlushInfoLog(); - - const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); - GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); - set_child_pid(child_pid); - set_read_fd(pipe_fd[0]); - set_spawned(true); - return OVERSEE_TEST; -} - -# endif // !GTEST_OS_WINDOWS - -// Creates a concrete DeathTest-derived class that depends on the -// --gtest_death_test_style flag, and sets the pointer pointed to -// by the "test" argument to its address. If the test should be -// skipped, sets that pointer to NULL. Returns true, unless the -// flag is set to an invalid value. -bool DefaultDeathTestFactory::Create(const char* statement, - Matcher matcher, - const char* file, int line, - DeathTest** test) { - UnitTestImpl* const impl = GetUnitTestImpl(); - const InternalRunDeathTestFlag* const flag = - impl->internal_run_death_test_flag(); - const int death_test_index = impl->current_test_info() - ->increment_death_test_count(); - - if (flag != nullptr) { - if (death_test_index > flag->index()) { - DeathTest::set_last_death_test_message( - "Death test count (" + StreamableToString(death_test_index) - + ") somehow exceeded expected maximum (" - + StreamableToString(flag->index()) + ")"); - return false; - } - - if (!(flag->file() == file && flag->line() == line && - flag->index() == death_test_index)) { - *test = nullptr; - return true; - } - } - -# if GTEST_OS_WINDOWS - - if (GTEST_FLAG(death_test_style) == "threadsafe" || - GTEST_FLAG(death_test_style) == "fast") { - *test = new WindowsDeathTest(statement, std::move(matcher), file, line); - } - -# elif GTEST_OS_FUCHSIA - - if (GTEST_FLAG(death_test_style) == "threadsafe" || - GTEST_FLAG(death_test_style) == "fast") { - *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line); - } - -# else - - if (GTEST_FLAG(death_test_style) == "threadsafe") { - *test = new ExecDeathTest(statement, std::move(matcher), file, line); - } else if (GTEST_FLAG(death_test_style) == "fast") { - *test = new NoExecDeathTest(statement, std::move(matcher)); - } - -# endif // GTEST_OS_WINDOWS - - else { // NOLINT - this is more readable than unbalanced brackets inside #if. - DeathTest::set_last_death_test_message( - "Unknown death test style \"" + GTEST_FLAG(death_test_style) - + "\" encountered"); - return false; - } - - return true; -} - -# if GTEST_OS_WINDOWS -// Recreates the pipe and event handles from the provided parameters, -// signals the event, and returns a file descriptor wrapped around the pipe -// handle. This function is called in the child process only. -static int GetStatusFileDescriptor(unsigned int parent_process_id, - size_t write_handle_as_size_t, - size_t event_handle_as_size_t) { - AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, - FALSE, // Non-inheritable. - parent_process_id)); - if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { - DeathTestAbort("Unable to open parent process " + - StreamableToString(parent_process_id)); - } - - GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); - - const HANDLE write_handle = - reinterpret_cast(write_handle_as_size_t); - HANDLE dup_write_handle; - - // The newly initialized handle is accessible only in the parent - // process. To obtain one accessible within the child, we need to use - // DuplicateHandle. - if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, - ::GetCurrentProcess(), &dup_write_handle, - 0x0, // Requested privileges ignored since - // DUPLICATE_SAME_ACCESS is used. - FALSE, // Request non-inheritable handler. - DUPLICATE_SAME_ACCESS)) { - DeathTestAbort("Unable to duplicate the pipe handle " + - StreamableToString(write_handle_as_size_t) + - " from the parent process " + - StreamableToString(parent_process_id)); - } - - const HANDLE event_handle = reinterpret_cast(event_handle_as_size_t); - HANDLE dup_event_handle; - - if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, - ::GetCurrentProcess(), &dup_event_handle, - 0x0, - FALSE, - DUPLICATE_SAME_ACCESS)) { - DeathTestAbort("Unable to duplicate the event handle " + - StreamableToString(event_handle_as_size_t) + - " from the parent process " + - StreamableToString(parent_process_id)); - } - - const int write_fd = - ::_open_osfhandle(reinterpret_cast(dup_write_handle), O_APPEND); - if (write_fd == -1) { - DeathTestAbort("Unable to convert pipe handle " + - StreamableToString(write_handle_as_size_t) + - " to a file descriptor"); - } - - // Signals the parent that the write end of the pipe has been acquired - // so the parent can release its own write end. - ::SetEvent(dup_event_handle); - - return write_fd; -} -# endif // GTEST_OS_WINDOWS - -// Returns a newly created InternalRunDeathTestFlag object with fields -// initialized from the GTEST_FLAG(internal_run_death_test) flag if -// the flag is specified; otherwise returns NULL. -InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { - if (GTEST_FLAG(internal_run_death_test) == "") return nullptr; - - // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we - // can use it here. - int line = -1; - int index = -1; - ::std::vector< ::std::string> fields; - SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); - int write_fd = -1; - -# if GTEST_OS_WINDOWS - - unsigned int parent_process_id = 0; - size_t write_handle_as_size_t = 0; - size_t event_handle_as_size_t = 0; - - if (fields.size() != 6 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &parent_process_id) - || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) - || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + - GTEST_FLAG(internal_run_death_test)); - } - write_fd = GetStatusFileDescriptor(parent_process_id, - write_handle_as_size_t, - event_handle_as_size_t); - -# elif GTEST_OS_FUCHSIA - - if (fields.size() != 3 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " - + GTEST_FLAG(internal_run_death_test)); - } - -# else - - if (fields.size() != 4 - || !ParseNaturalNumber(fields[1], &line) - || !ParseNaturalNumber(fields[2], &index) - || !ParseNaturalNumber(fields[3], &write_fd)) { - DeathTestAbort("Bad --gtest_internal_run_death_test flag: " - + GTEST_FLAG(internal_run_death_test)); - } - -# endif // GTEST_OS_WINDOWS - - return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); -} - -} // namespace internal - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace testing -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -#include - -#if GTEST_OS_WINDOWS_MOBILE -# include -#elif GTEST_OS_WINDOWS -# include -# include -#else -# include -# include // Some Linux distributions define PATH_MAX here. -#endif // GTEST_OS_WINDOWS_MOBILE - - -#if GTEST_OS_WINDOWS -# define GTEST_PATH_MAX_ _MAX_PATH -#elif defined(PATH_MAX) -# define GTEST_PATH_MAX_ PATH_MAX -#elif defined(_XOPEN_PATH_MAX) -# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX -#else -# define GTEST_PATH_MAX_ _POSIX_PATH_MAX -#endif // GTEST_OS_WINDOWS - -namespace testing { -namespace internal { - -#if GTEST_OS_WINDOWS -// On Windows, '\\' is the standard path separator, but many tools and the -// Windows API also accept '/' as an alternate path separator. Unless otherwise -// noted, a file path can contain either kind of path separators, or a mixture -// of them. -const char kPathSeparator = '\\'; -const char kAlternatePathSeparator = '/'; -const char kAlternatePathSeparatorString[] = "/"; -# if GTEST_OS_WINDOWS_MOBILE -// Windows CE doesn't have a current directory. You should not use -// the current directory in tests on Windows CE, but this at least -// provides a reasonable fallback. -const char kCurrentDirectoryString[] = "\\"; -// Windows CE doesn't define INVALID_FILE_ATTRIBUTES -const DWORD kInvalidFileAttributes = 0xffffffff; -# else -const char kCurrentDirectoryString[] = ".\\"; -# endif // GTEST_OS_WINDOWS_MOBILE -#else -const char kPathSeparator = '/'; -const char kCurrentDirectoryString[] = "./"; -#endif // GTEST_OS_WINDOWS - -// Returns whether the given character is a valid path separator. -static bool IsPathSeparator(char c) { -#if GTEST_HAS_ALT_PATH_SEP_ - return (c == kPathSeparator) || (c == kAlternatePathSeparator); -#else - return c == kPathSeparator; -#endif -} - -// Returns the current working directory, or "" if unsuccessful. -FilePath FilePath::GetCurrentDir() { -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \ - GTEST_OS_WINDOWS_RT || ARDUINO || defined(ESP_PLATFORM) - // These platforms do not have a current directory, so we just return - // something reasonable. - return FilePath(kCurrentDirectoryString); -#elif GTEST_OS_WINDOWS - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; - return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd); -#else - char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; - char* result = getcwd(cwd, sizeof(cwd)); -# if GTEST_OS_NACL - // getcwd will likely fail in NaCl due to the sandbox, so return something - // reasonable. The user may have provided a shim implementation for getcwd, - // however, so fallback only when failure is detected. - return FilePath(result == nullptr ? kCurrentDirectoryString : cwd); -# endif // GTEST_OS_NACL - return FilePath(result == nullptr ? "" : cwd); -#endif // GTEST_OS_WINDOWS_MOBILE -} - -// Returns a copy of the FilePath with the case-insensitive extension removed. -// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns -// FilePath("dir/file"). If a case-insensitive extension is not -// found, returns a copy of the original FilePath. -FilePath FilePath::RemoveExtension(const char* extension) const { - const std::string dot_extension = std::string(".") + extension; - if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { - return FilePath(pathname_.substr( - 0, pathname_.length() - dot_extension.length())); - } - return *this; -} - -// Returns a pointer to the last occurrence of a valid path separator in -// the FilePath. On Windows, for example, both '/' and '\' are valid path -// separators. Returns NULL if no path separator was found. -const char* FilePath::FindLastPathSeparator() const { - const char* const last_sep = strrchr(c_str(), kPathSeparator); -#if GTEST_HAS_ALT_PATH_SEP_ - const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); - // Comparing two pointers of which only one is NULL is undefined. - if (last_alt_sep != nullptr && - (last_sep == nullptr || last_alt_sep > last_sep)) { - return last_alt_sep; - } -#endif - return last_sep; -} - -// Returns a copy of the FilePath with the directory part removed. -// Example: FilePath("path/to/file").RemoveDirectoryName() returns -// FilePath("file"). If there is no directory part ("just_a_file"), it returns -// the FilePath unmodified. If there is no file part ("just_a_dir/") it -// returns an empty FilePath (""). -// On Windows platform, '\' is the path separator, otherwise it is '/'. -FilePath FilePath::RemoveDirectoryName() const { - const char* const last_sep = FindLastPathSeparator(); - return last_sep ? FilePath(last_sep + 1) : *this; -} - -// RemoveFileName returns the directory path with the filename removed. -// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". -// If the FilePath is "a_file" or "/a_file", RemoveFileName returns -// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does -// not have a file, like "just/a/dir/", it returns the FilePath unmodified. -// On Windows platform, '\' is the path separator, otherwise it is '/'. -FilePath FilePath::RemoveFileName() const { - const char* const last_sep = FindLastPathSeparator(); - std::string dir; - if (last_sep) { - dir = std::string(c_str(), static_cast(last_sep + 1 - c_str())); - } else { - dir = kCurrentDirectoryString; - } - return FilePath(dir); -} - -// Helper functions for naming files in a directory for xml output. - -// Given directory = "dir", base_name = "test", number = 0, -// extension = "xml", returns "dir/test.xml". If number is greater -// than zero (e.g., 12), returns "dir/test_12.xml". -// On Windows platform, uses \ as the separator rather than /. -FilePath FilePath::MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, - const char* extension) { - std::string file; - if (number == 0) { - file = base_name.string() + "." + extension; - } else { - file = base_name.string() + "_" + StreamableToString(number) - + "." + extension; - } - return ConcatPaths(directory, FilePath(file)); -} - -// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". -// On Windows, uses \ as the separator rather than /. -FilePath FilePath::ConcatPaths(const FilePath& directory, - const FilePath& relative_path) { - if (directory.IsEmpty()) - return relative_path; - const FilePath dir(directory.RemoveTrailingPathSeparator()); - return FilePath(dir.string() + kPathSeparator + relative_path.string()); -} - -// Returns true if pathname describes something findable in the file-system, -// either a file, directory, or whatever. -bool FilePath::FileOrDirectoryExists() const { -#if GTEST_OS_WINDOWS_MOBILE - LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); - const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; - return attributes != kInvalidFileAttributes; -#else - posix::StatStruct file_stat; - return posix::Stat(pathname_.c_str(), &file_stat) == 0; -#endif // GTEST_OS_WINDOWS_MOBILE -} - -// Returns true if pathname describes a directory in the file-system -// that exists. -bool FilePath::DirectoryExists() const { - bool result = false; -#if GTEST_OS_WINDOWS - // Don't strip off trailing separator if path is a root directory on - // Windows (like "C:\\"). - const FilePath& path(IsRootDirectory() ? *this : - RemoveTrailingPathSeparator()); -#else - const FilePath& path(*this); -#endif - -#if GTEST_OS_WINDOWS_MOBILE - LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); - const DWORD attributes = GetFileAttributes(unicode); - delete [] unicode; - if ((attributes != kInvalidFileAttributes) && - (attributes & FILE_ATTRIBUTE_DIRECTORY)) { - result = true; - } -#else - posix::StatStruct file_stat; - result = posix::Stat(path.c_str(), &file_stat) == 0 && - posix::IsDir(file_stat); -#endif // GTEST_OS_WINDOWS_MOBILE - - return result; -} - -// Returns true if pathname describes a root directory. (Windows has one -// root directory per disk drive.) -bool FilePath::IsRootDirectory() const { -#if GTEST_OS_WINDOWS - return pathname_.length() == 3 && IsAbsolutePath(); -#else - return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); -#endif -} - -// Returns true if pathname describes an absolute path. -bool FilePath::IsAbsolutePath() const { - const char* const name = pathname_.c_str(); -#if GTEST_OS_WINDOWS - return pathname_.length() >= 3 && - ((name[0] >= 'a' && name[0] <= 'z') || - (name[0] >= 'A' && name[0] <= 'Z')) && - name[1] == ':' && - IsPathSeparator(name[2]); -#else - return IsPathSeparator(name[0]); -#endif -} - -// Returns a pathname for a file that does not currently exist. The pathname -// will be directory/base_name.extension or -// directory/base_name_.extension if directory/base_name.extension -// already exists. The number will be incremented until a pathname is found -// that does not already exist. -// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. -// There could be a race condition if two or more processes are calling this -// function at the same time -- they could both pick the same filename. -FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension) { - FilePath full_pathname; - int number = 0; - do { - full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); - } while (full_pathname.FileOrDirectoryExists()); - return full_pathname; -} - -// Returns true if FilePath ends with a path separator, which indicates that -// it is intended to represent a directory. Returns false otherwise. -// This does NOT check that a directory (or file) actually exists. -bool FilePath::IsDirectory() const { - return !pathname_.empty() && - IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); -} - -// Create directories so that path exists. Returns true if successful or if -// the directories already exist; returns false if unable to create directories -// for any reason. -bool FilePath::CreateDirectoriesRecursively() const { - if (!this->IsDirectory()) { - return false; - } - - if (pathname_.length() == 0 || this->DirectoryExists()) { - return true; - } - - const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); - return parent.CreateDirectoriesRecursively() && this->CreateFolder(); -} - -// Create the directory so that path exists. Returns true if successful or -// if the directory already exists; returns false if unable to create the -// directory for any reason, including if the parent directory does not -// exist. Not named "CreateDirectory" because that's a macro on Windows. -bool FilePath::CreateFolder() const { -#if GTEST_OS_WINDOWS_MOBILE - FilePath removed_sep(this->RemoveTrailingPathSeparator()); - LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); - int result = CreateDirectory(unicode, nullptr) ? 0 : -1; - delete [] unicode; -#elif GTEST_OS_WINDOWS - int result = _mkdir(pathname_.c_str()); -#else - int result = mkdir(pathname_.c_str(), 0777); -#endif // GTEST_OS_WINDOWS_MOBILE - - if (result == -1) { - return this->DirectoryExists(); // An error is OK if the directory exists. - } - return true; // No error. -} - -// If input name has a trailing separator character, remove it and return the -// name, otherwise return the name string unmodified. -// On Windows platform, uses \ as the separator, other platforms use /. -FilePath FilePath::RemoveTrailingPathSeparator() const { - return IsDirectory() - ? FilePath(pathname_.substr(0, pathname_.length() - 1)) - : *this; -} - -// Removes any redundant separators that might be in the pathname. -// For example, "bar///foo" becomes "bar/foo". Does not eliminate other -// redundancies that might be in a pathname involving "." or "..". -void FilePath::Normalize() { - if (pathname_.c_str() == nullptr) { - pathname_ = ""; - return; - } - const char* src = pathname_.c_str(); - char* const dest = new char[pathname_.length() + 1]; - char* dest_ptr = dest; - memset(dest_ptr, 0, pathname_.length() + 1); - - while (*src != '\0') { - *dest_ptr = *src; - if (!IsPathSeparator(*src)) { - src++; - } else { -#if GTEST_HAS_ALT_PATH_SEP_ - if (*dest_ptr == kAlternatePathSeparator) { - *dest_ptr = kPathSeparator; - } -#endif - while (IsPathSeparator(*src)) - src++; - } - dest_ptr++; - } - *dest_ptr = '\0'; - pathname_ = dest; - delete[] dest; -} - -} // namespace internal -} // namespace testing -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This file implements just enough of the matcher interface to allow -// EXPECT_DEATH and friends to accept a matcher argument. - - -#include - -namespace testing { - -// Constructs a matcher that matches a const std::string& whose value is -// equal to s. -Matcher::Matcher(const std::string& s) { *this = Eq(s); } - -// Constructs a matcher that matches a const std::string& whose value is -// equal to s. -Matcher::Matcher(const char* s) { - *this = Eq(std::string(s)); -} - -// Constructs a matcher that matches a std::string whose value is equal to -// s. -Matcher::Matcher(const std::string& s) { *this = Eq(s); } - -// Constructs a matcher that matches a std::string whose value is equal to -// s. -Matcher::Matcher(const char* s) { *this = Eq(std::string(s)); } - -#if GTEST_HAS_ABSL -// Constructs a matcher that matches a const absl::string_view& whose value is -// equal to s. -Matcher::Matcher(const std::string& s) { - *this = Eq(s); -} - -// Constructs a matcher that matches a const absl::string_view& whose value is -// equal to s. -Matcher::Matcher(const char* s) { - *this = Eq(std::string(s)); -} - -// Constructs a matcher that matches a const absl::string_view& whose value is -// equal to s. -Matcher::Matcher(absl::string_view s) { - *this = Eq(std::string(s)); -} - -// Constructs a matcher that matches a absl::string_view whose value is equal to -// s. -Matcher::Matcher(const std::string& s) { *this = Eq(s); } - -// Constructs a matcher that matches a absl::string_view whose value is equal to -// s. -Matcher::Matcher(const char* s) { - *this = Eq(std::string(s)); -} - -// Constructs a matcher that matches a absl::string_view whose value is equal to -// s. -Matcher::Matcher(absl::string_view s) { - *this = Eq(std::string(s)); -} -#endif // GTEST_HAS_ABSL - -} // namespace testing -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -#include -#include -#include -#include -#include -#include - -#if GTEST_OS_WINDOWS -# include -# include -# include -# include // Used in ThreadLocal. -# ifdef _MSC_VER -# include -# endif // _MSC_VER -#else -# include -#endif // GTEST_OS_WINDOWS - -#if GTEST_OS_MAC -# include -# include -# include -#endif // GTEST_OS_MAC - -#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD || GTEST_OS_OPENBSD -# include -# if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD -# include -# endif -#endif - -#if GTEST_OS_QNX -# include -# include -# include -#endif // GTEST_OS_QNX - -#if GTEST_OS_AIX -# include -# include -#endif // GTEST_OS_AIX - -#if GTEST_OS_FUCHSIA -# include -# include -#endif // GTEST_OS_FUCHSIA - - -namespace testing { -namespace internal { - -#if defined(_MSC_VER) || defined(__BORLANDC__) -// MSVC and C++Builder do not provide a definition of STDERR_FILENO. -const int kStdOutFileno = 1; -const int kStdErrFileno = 2; -#else -const int kStdOutFileno = STDOUT_FILENO; -const int kStdErrFileno = STDERR_FILENO; -#endif // _MSC_VER - -#if GTEST_OS_LINUX - -namespace { -template -T ReadProcFileField(const std::string& filename, int field) { - std::string dummy; - std::ifstream file(filename.c_str()); - while (field-- > 0) { - file >> dummy; - } - T output = 0; - file >> output; - return output; -} -} // namespace - -// Returns the number of active threads, or 0 when there is an error. -size_t GetThreadCount() { - const std::string filename = - (Message() << "/proc/" << getpid() << "/stat").GetString(); - return ReadProcFileField(filename, 19); -} - -#elif GTEST_OS_MAC - -size_t GetThreadCount() { - const task_t task = mach_task_self(); - mach_msg_type_number_t thread_count; - thread_act_array_t thread_list; - const kern_return_t status = task_threads(task, &thread_list, &thread_count); - if (status == KERN_SUCCESS) { - // task_threads allocates resources in thread_list and we need to free them - // to avoid leaks. - vm_deallocate(task, - reinterpret_cast(thread_list), - sizeof(thread_t) * thread_count); - return static_cast(thread_count); - } else { - return 0; - } -} - -#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \ - GTEST_OS_NETBSD - -#if GTEST_OS_NETBSD -#undef KERN_PROC -#define KERN_PROC KERN_PROC2 -#define kinfo_proc kinfo_proc2 -#endif - -#if GTEST_OS_DRAGONFLY -#define KP_NLWP(kp) (kp.kp_nthreads) -#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD -#define KP_NLWP(kp) (kp.ki_numthreads) -#elif GTEST_OS_NETBSD -#define KP_NLWP(kp) (kp.p_nlwps) -#endif - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -size_t GetThreadCount() { - int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID, - getpid(), -#if GTEST_OS_NETBSD - sizeof(struct kinfo_proc), - 1, -#endif - }; - u_int miblen = sizeof(mib) / sizeof(mib[0]); - struct kinfo_proc info; - size_t size = sizeof(info); - if (sysctl(mib, miblen, &info, &size, NULL, 0)) { - return 0; - } - return static_cast(KP_NLWP(info)); -} -#elif GTEST_OS_OPENBSD - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -size_t GetThreadCount() { - int mib[] = { - CTL_KERN, - KERN_PROC, - KERN_PROC_PID | KERN_PROC_SHOW_THREADS, - getpid(), - sizeof(struct kinfo_proc), - 0, - }; - u_int miblen = sizeof(mib) / sizeof(mib[0]); - - // get number of structs - size_t size; - if (sysctl(mib, miblen, NULL, &size, NULL, 0)) { - return 0; - } - mib[5] = size / mib[4]; - - // populate array of structs - struct kinfo_proc info[mib[5]]; - if (sysctl(mib, miblen, &info, &size, NULL, 0)) { - return 0; - } - - // exclude empty members - int nthreads = 0; - for (int i = 0; i < size / mib[4]; i++) { - if (info[i].p_tid != -1) - nthreads++; - } - return nthreads; -} - -#elif GTEST_OS_QNX - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -size_t GetThreadCount() { - const int fd = open("/proc/self/as", O_RDONLY); - if (fd < 0) { - return 0; - } - procfs_info process_info; - const int status = - devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr); - close(fd); - if (status == EOK) { - return static_cast(process_info.num_threads); - } else { - return 0; - } -} - -#elif GTEST_OS_AIX - -size_t GetThreadCount() { - struct procentry64 entry; - pid_t pid = getpid(); - int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1); - if (status == 1) { - return entry.pi_thcount; - } else { - return 0; - } -} - -#elif GTEST_OS_FUCHSIA - -size_t GetThreadCount() { - int dummy_buffer; - size_t avail; - zx_status_t status = zx_object_get_info( - zx_process_self(), - ZX_INFO_PROCESS_THREADS, - &dummy_buffer, - 0, - nullptr, - &avail); - if (status == ZX_OK) { - return avail; - } else { - return 0; - } -} - -#else - -size_t GetThreadCount() { - // There's no portable way to detect the number of threads, so we just - // return 0 to indicate that we cannot detect it. - return 0; -} - -#endif // GTEST_OS_LINUX - -#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS - -void SleepMilliseconds(int n) { - ::Sleep(static_cast(n)); -} - -AutoHandle::AutoHandle() - : handle_(INVALID_HANDLE_VALUE) {} - -AutoHandle::AutoHandle(Handle handle) - : handle_(handle) {} - -AutoHandle::~AutoHandle() { - Reset(); -} - -AutoHandle::Handle AutoHandle::Get() const { - return handle_; -} - -void AutoHandle::Reset() { - Reset(INVALID_HANDLE_VALUE); -} - -void AutoHandle::Reset(HANDLE handle) { - // Resetting with the same handle we already own is invalid. - if (handle_ != handle) { - if (IsCloseable()) { - ::CloseHandle(handle_); - } - handle_ = handle; - } else { - GTEST_CHECK_(!IsCloseable()) - << "Resetting a valid handle to itself is likely a programmer error " - "and thus not allowed."; - } -} - -bool AutoHandle::IsCloseable() const { - // Different Windows APIs may use either of these values to represent an - // invalid handle. - return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE; -} - -Notification::Notification() - : event_(::CreateEvent(nullptr, // Default security attributes. - TRUE, // Do not reset automatically. - FALSE, // Initially unset. - nullptr)) { // Anonymous event. - GTEST_CHECK_(event_.Get() != nullptr); -} - -void Notification::Notify() { - GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); -} - -void Notification::WaitForNotification() { - GTEST_CHECK_( - ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); -} - -Mutex::Mutex() - : owner_thread_id_(0), - type_(kDynamic), - critical_section_init_phase_(0), - critical_section_(new CRITICAL_SECTION) { - ::InitializeCriticalSection(critical_section_); -} - -Mutex::~Mutex() { - // Static mutexes are leaked intentionally. It is not thread-safe to try - // to clean them up. - if (type_ == kDynamic) { - ::DeleteCriticalSection(critical_section_); - delete critical_section_; - critical_section_ = nullptr; - } -} - -void Mutex::Lock() { - ThreadSafeLazyInit(); - ::EnterCriticalSection(critical_section_); - owner_thread_id_ = ::GetCurrentThreadId(); -} - -void Mutex::Unlock() { - ThreadSafeLazyInit(); - // We don't protect writing to owner_thread_id_ here, as it's the - // caller's responsibility to ensure that the current thread holds the - // mutex when this is called. - owner_thread_id_ = 0; - ::LeaveCriticalSection(critical_section_); -} - -// Does nothing if the current thread holds the mutex. Otherwise, crashes -// with high probability. -void Mutex::AssertHeld() { - ThreadSafeLazyInit(); - GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) - << "The current thread is not holding the mutex @" << this; -} - -namespace { - -#ifdef _MSC_VER -// Use the RAII idiom to flag mem allocs that are intentionally never -// deallocated. The motivation is to silence the false positive mem leaks -// that are reported by the debug version of MS's CRT which can only detect -// if an alloc is missing a matching deallocation. -// Example: -// MemoryIsNotDeallocated memory_is_not_deallocated; -// critical_section_ = new CRITICAL_SECTION; -// -class MemoryIsNotDeallocated -{ - public: - MemoryIsNotDeallocated() : old_crtdbg_flag_(0) { - old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); - // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT - // doesn't report mem leak if there's no matching deallocation. - _CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF); - } - - ~MemoryIsNotDeallocated() { - // Restore the original _CRTDBG_ALLOC_MEM_DF flag - _CrtSetDbgFlag(old_crtdbg_flag_); - } - - private: - int old_crtdbg_flag_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(MemoryIsNotDeallocated); -}; -#endif // _MSC_VER - -} // namespace - -// Initializes owner_thread_id_ and critical_section_ in static mutexes. -void Mutex::ThreadSafeLazyInit() { - // Dynamic mutexes are initialized in the constructor. - if (type_ == kStatic) { - switch ( - ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { - case 0: - // If critical_section_init_phase_ was 0 before the exchange, we - // are the first to test it and need to perform the initialization. - owner_thread_id_ = 0; - { - // Use RAII to flag that following mem alloc is never deallocated. -#ifdef _MSC_VER - MemoryIsNotDeallocated memory_is_not_deallocated; -#endif // _MSC_VER - critical_section_ = new CRITICAL_SECTION; - } - ::InitializeCriticalSection(critical_section_); - // Updates the critical_section_init_phase_ to 2 to signal - // initialization complete. - GTEST_CHECK_(::InterlockedCompareExchange( - &critical_section_init_phase_, 2L, 1L) == - 1L); - break; - case 1: - // Somebody else is already initializing the mutex; spin until they - // are done. - while (::InterlockedCompareExchange(&critical_section_init_phase_, - 2L, - 2L) != 2L) { - // Possibly yields the rest of the thread's time slice to other - // threads. - ::Sleep(0); - } - break; - - case 2: - break; // The mutex is already initialized and ready for use. - - default: - GTEST_CHECK_(false) - << "Unexpected value of critical_section_init_phase_ " - << "while initializing a static mutex."; - } - } -} - -namespace { - -class ThreadWithParamSupport : public ThreadWithParamBase { - public: - static HANDLE CreateThread(Runnable* runnable, - Notification* thread_can_start) { - ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); - DWORD thread_id; - HANDLE thread_handle = ::CreateThread( - nullptr, // Default security. - 0, // Default stack size. - &ThreadWithParamSupport::ThreadMain, - param, // Parameter to ThreadMainStatic - 0x0, // Default creation flags. - &thread_id); // Need a valid pointer for the call to work under Win98. - GTEST_CHECK_(thread_handle != nullptr) - << "CreateThread failed with error " << ::GetLastError() << "."; - if (thread_handle == nullptr) { - delete param; - } - return thread_handle; - } - - private: - struct ThreadMainParam { - ThreadMainParam(Runnable* runnable, Notification* thread_can_start) - : runnable_(runnable), - thread_can_start_(thread_can_start) { - } - std::unique_ptr runnable_; - // Does not own. - Notification* thread_can_start_; - }; - - static DWORD WINAPI ThreadMain(void* ptr) { - // Transfers ownership. - std::unique_ptr param(static_cast(ptr)); - if (param->thread_can_start_ != nullptr) - param->thread_can_start_->WaitForNotification(); - param->runnable_->Run(); - return 0; - } - - // Prohibit instantiation. - ThreadWithParamSupport(); - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); -}; - -} // namespace - -ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, - Notification* thread_can_start) - : thread_(ThreadWithParamSupport::CreateThread(runnable, - thread_can_start)) { -} - -ThreadWithParamBase::~ThreadWithParamBase() { - Join(); -} - -void ThreadWithParamBase::Join() { - GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) - << "Failed to join the thread with error " << ::GetLastError() << "."; -} - -// Maps a thread to a set of ThreadIdToThreadLocals that have values -// instantiated on that thread and notifies them when the thread exits. A -// ThreadLocal instance is expected to persist until all threads it has -// values on have terminated. -class ThreadLocalRegistryImpl { - public: - // Registers thread_local_instance as having value on the current thread. - // Returns a value that can be used to identify the thread from other threads. - static ThreadLocalValueHolderBase* GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance) { - DWORD current_thread = ::GetCurrentThreadId(); - MutexLock lock(&mutex_); - ThreadIdToThreadLocals* const thread_to_thread_locals = - GetThreadLocalsMapLocked(); - ThreadIdToThreadLocals::iterator thread_local_pos = - thread_to_thread_locals->find(current_thread); - if (thread_local_pos == thread_to_thread_locals->end()) { - thread_local_pos = thread_to_thread_locals->insert( - std::make_pair(current_thread, ThreadLocalValues())).first; - StartWatcherThreadFor(current_thread); - } - ThreadLocalValues& thread_local_values = thread_local_pos->second; - ThreadLocalValues::iterator value_pos = - thread_local_values.find(thread_local_instance); - if (value_pos == thread_local_values.end()) { - value_pos = - thread_local_values - .insert(std::make_pair( - thread_local_instance, - std::shared_ptr( - thread_local_instance->NewValueForCurrentThread()))) - .first; - } - return value_pos->second.get(); - } - - static void OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance) { - std::vector > value_holders; - // Clean up the ThreadLocalValues data structure while holding the lock, but - // defer the destruction of the ThreadLocalValueHolderBases. - { - MutexLock lock(&mutex_); - ThreadIdToThreadLocals* const thread_to_thread_locals = - GetThreadLocalsMapLocked(); - for (ThreadIdToThreadLocals::iterator it = - thread_to_thread_locals->begin(); - it != thread_to_thread_locals->end(); - ++it) { - ThreadLocalValues& thread_local_values = it->second; - ThreadLocalValues::iterator value_pos = - thread_local_values.find(thread_local_instance); - if (value_pos != thread_local_values.end()) { - value_holders.push_back(value_pos->second); - thread_local_values.erase(value_pos); - // This 'if' can only be successful at most once, so theoretically we - // could break out of the loop here, but we don't bother doing so. - } - } - } - // Outside the lock, let the destructor for 'value_holders' deallocate the - // ThreadLocalValueHolderBases. - } - - static void OnThreadExit(DWORD thread_id) { - GTEST_CHECK_(thread_id != 0) << ::GetLastError(); - std::vector > value_holders; - // Clean up the ThreadIdToThreadLocals data structure while holding the - // lock, but defer the destruction of the ThreadLocalValueHolderBases. - { - MutexLock lock(&mutex_); - ThreadIdToThreadLocals* const thread_to_thread_locals = - GetThreadLocalsMapLocked(); - ThreadIdToThreadLocals::iterator thread_local_pos = - thread_to_thread_locals->find(thread_id); - if (thread_local_pos != thread_to_thread_locals->end()) { - ThreadLocalValues& thread_local_values = thread_local_pos->second; - for (ThreadLocalValues::iterator value_pos = - thread_local_values.begin(); - value_pos != thread_local_values.end(); - ++value_pos) { - value_holders.push_back(value_pos->second); - } - thread_to_thread_locals->erase(thread_local_pos); - } - } - // Outside the lock, let the destructor for 'value_holders' deallocate the - // ThreadLocalValueHolderBases. - } - - private: - // In a particular thread, maps a ThreadLocal object to its value. - typedef std::map > - ThreadLocalValues; - // Stores all ThreadIdToThreadLocals having values in a thread, indexed by - // thread's ID. - typedef std::map ThreadIdToThreadLocals; - - // Holds the thread id and thread handle that we pass from - // StartWatcherThreadFor to WatcherThreadFunc. - typedef std::pair ThreadIdAndHandle; - - static void StartWatcherThreadFor(DWORD thread_id) { - // The returned handle will be kept in thread_map and closed by - // watcher_thread in WatcherThreadFunc. - HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, - FALSE, - thread_id); - GTEST_CHECK_(thread != nullptr); - // We need to pass a valid thread ID pointer into CreateThread for it - // to work correctly under Win98. - DWORD watcher_thread_id; - HANDLE watcher_thread = ::CreateThread( - nullptr, // Default security. - 0, // Default stack size - &ThreadLocalRegistryImpl::WatcherThreadFunc, - reinterpret_cast(new ThreadIdAndHandle(thread_id, thread)), - CREATE_SUSPENDED, &watcher_thread_id); - GTEST_CHECK_(watcher_thread != nullptr); - // Give the watcher thread the same priority as ours to avoid being - // blocked by it. - ::SetThreadPriority(watcher_thread, - ::GetThreadPriority(::GetCurrentThread())); - ::ResumeThread(watcher_thread); - ::CloseHandle(watcher_thread); - } - - // Monitors exit from a given thread and notifies those - // ThreadIdToThreadLocals about thread termination. - static DWORD WINAPI WatcherThreadFunc(LPVOID param) { - const ThreadIdAndHandle* tah = - reinterpret_cast(param); - GTEST_CHECK_( - ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); - OnThreadExit(tah->first); - ::CloseHandle(tah->second); - delete tah; - return 0; - } - - // Returns map of thread local instances. - static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { - mutex_.AssertHeld(); -#ifdef _MSC_VER - MemoryIsNotDeallocated memory_is_not_deallocated; -#endif // _MSC_VER - static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals(); - return map; - } - - // Protects access to GetThreadLocalsMapLocked() and its return value. - static Mutex mutex_; - // Protects access to GetThreadMapLocked() and its return value. - static Mutex thread_map_mutex_; -}; - -Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); -Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); - -ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance) { - return ThreadLocalRegistryImpl::GetValueOnCurrentThread( - thread_local_instance); -} - -void ThreadLocalRegistry::OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance) { - ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); -} - -#endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS - -#if GTEST_USES_POSIX_RE - -// Implements RE. Currently only needed for death tests. - -RE::~RE() { - if (is_valid_) { - // regfree'ing an invalid regex might crash because the content - // of the regex is undefined. Since the regex's are essentially - // the same, one cannot be valid (or invalid) without the other - // being so too. - regfree(&partial_regex_); - regfree(&full_regex_); - } - free(const_cast(pattern_)); -} - -// Returns true if and only if regular expression re matches the entire str. -bool RE::FullMatch(const char* str, const RE& re) { - if (!re.is_valid_) return false; - - regmatch_t match; - return regexec(&re.full_regex_, str, 1, &match, 0) == 0; -} - -// Returns true if and only if regular expression re matches a substring of -// str (including str itself). -bool RE::PartialMatch(const char* str, const RE& re) { - if (!re.is_valid_) return false; - - regmatch_t match; - return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; -} - -// Initializes an RE from its string representation. -void RE::Init(const char* regex) { - pattern_ = posix::StrDup(regex); - - // Reserves enough bytes to hold the regular expression used for a - // full match. - const size_t full_regex_len = strlen(regex) + 10; - char* const full_pattern = new char[full_regex_len]; - - snprintf(full_pattern, full_regex_len, "^(%s)$", regex); - is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; - // We want to call regcomp(&partial_regex_, ...) even if the - // previous expression returns false. Otherwise partial_regex_ may - // not be properly initialized can may cause trouble when it's - // freed. - // - // Some implementation of POSIX regex (e.g. on at least some - // versions of Cygwin) doesn't accept the empty string as a valid - // regex. We change it to an equivalent form "()" to be safe. - if (is_valid_) { - const char* const partial_regex = (*regex == '\0') ? "()" : regex; - is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; - } - EXPECT_TRUE(is_valid_) - << "Regular expression \"" << regex - << "\" is not a valid POSIX Extended regular expression."; - - delete[] full_pattern; -} - -#elif GTEST_USES_SIMPLE_RE - -// Returns true if and only if ch appears anywhere in str (excluding the -// terminating '\0' character). -bool IsInSet(char ch, const char* str) { - return ch != '\0' && strchr(str, ch) != nullptr; -} - -// Returns true if and only if ch belongs to the given classification. -// Unlike similar functions in , these aren't affected by the -// current locale. -bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } -bool IsAsciiPunct(char ch) { - return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); -} -bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } -bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } -bool IsAsciiWordChar(char ch) { - return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || - ('0' <= ch && ch <= '9') || ch == '_'; -} - -// Returns true if and only if "\\c" is a supported escape sequence. -bool IsValidEscape(char c) { - return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); -} - -// Returns true if and only if the given atom (specified by escaped and -// pattern) matches ch. The result is undefined if the atom is invalid. -bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { - if (escaped) { // "\\p" where p is pattern_char. - switch (pattern_char) { - case 'd': return IsAsciiDigit(ch); - case 'D': return !IsAsciiDigit(ch); - case 'f': return ch == '\f'; - case 'n': return ch == '\n'; - case 'r': return ch == '\r'; - case 's': return IsAsciiWhiteSpace(ch); - case 'S': return !IsAsciiWhiteSpace(ch); - case 't': return ch == '\t'; - case 'v': return ch == '\v'; - case 'w': return IsAsciiWordChar(ch); - case 'W': return !IsAsciiWordChar(ch); - } - return IsAsciiPunct(pattern_char) && pattern_char == ch; - } - - return (pattern_char == '.' && ch != '\n') || pattern_char == ch; -} - -// Helper function used by ValidateRegex() to format error messages. -static std::string FormatRegexSyntaxError(const char* regex, int index) { - return (Message() << "Syntax error at index " << index - << " in simple regular expression \"" << regex << "\": ").GetString(); -} - -// Generates non-fatal failures and returns false if regex is invalid; -// otherwise returns true. -bool ValidateRegex(const char* regex) { - if (regex == nullptr) { - ADD_FAILURE() << "NULL is not a valid simple regular expression."; - return false; - } - - bool is_valid = true; - - // True if and only if ?, *, or + can follow the previous atom. - bool prev_repeatable = false; - for (int i = 0; regex[i]; i++) { - if (regex[i] == '\\') { // An escape sequence - i++; - if (regex[i] == '\0') { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) - << "'\\' cannot appear at the end."; - return false; - } - - if (!IsValidEscape(regex[i])) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) - << "invalid escape sequence \"\\" << regex[i] << "\"."; - is_valid = false; - } - prev_repeatable = true; - } else { // Not an escape sequence. - const char ch = regex[i]; - - if (ch == '^' && i > 0) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'^' can only appear at the beginning."; - is_valid = false; - } else if (ch == '$' && regex[i + 1] != '\0') { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'$' can only appear at the end."; - is_valid = false; - } else if (IsInSet(ch, "()[]{}|")) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' is unsupported."; - is_valid = false; - } else if (IsRepeat(ch) && !prev_repeatable) { - ADD_FAILURE() << FormatRegexSyntaxError(regex, i) - << "'" << ch << "' can only follow a repeatable token."; - is_valid = false; - } - - prev_repeatable = !IsInSet(ch, "^$?*+"); - } - } - - return is_valid; -} - -// Matches a repeated regex atom followed by a valid simple regular -// expression. The regex atom is defined as c if escaped is false, -// or \c otherwise. repeat is the repetition meta character (?, *, -// or +). The behavior is undefined if str contains too many -// characters to be indexable by size_t, in which case the test will -// probably time out anyway. We are fine with this limitation as -// std::string has it too. -bool MatchRepetitionAndRegexAtHead( - bool escaped, char c, char repeat, const char* regex, - const char* str) { - const size_t min_count = (repeat == '+') ? 1 : 0; - const size_t max_count = (repeat == '?') ? 1 : - static_cast(-1) - 1; - // We cannot call numeric_limits::max() as it conflicts with the - // max() macro on Windows. - - for (size_t i = 0; i <= max_count; ++i) { - // We know that the atom matches each of the first i characters in str. - if (i >= min_count && MatchRegexAtHead(regex, str + i)) { - // We have enough matches at the head, and the tail matches too. - // Since we only care about *whether* the pattern matches str - // (as opposed to *how* it matches), there is no need to find a - // greedy match. - return true; - } - if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) - return false; - } - return false; -} - -// Returns true if and only if regex matches a prefix of str. regex must -// be a valid simple regular expression and not start with "^", or the -// result is undefined. -bool MatchRegexAtHead(const char* regex, const char* str) { - if (*regex == '\0') // An empty regex matches a prefix of anything. - return true; - - // "$" only matches the end of a string. Note that regex being - // valid guarantees that there's nothing after "$" in it. - if (*regex == '$') - return *str == '\0'; - - // Is the first thing in regex an escape sequence? - const bool escaped = *regex == '\\'; - if (escaped) - ++regex; - if (IsRepeat(regex[1])) { - // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so - // here's an indirect recursion. It terminates as the regex gets - // shorter in each recursion. - return MatchRepetitionAndRegexAtHead( - escaped, regex[0], regex[1], regex + 2, str); - } else { - // regex isn't empty, isn't "$", and doesn't start with a - // repetition. We match the first atom of regex with the first - // character of str and recurse. - return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && - MatchRegexAtHead(regex + 1, str + 1); - } -} - -// Returns true if and only if regex matches any substring of str. regex must -// be a valid simple regular expression, or the result is undefined. -// -// The algorithm is recursive, but the recursion depth doesn't exceed -// the regex length, so we won't need to worry about running out of -// stack space normally. In rare cases the time complexity can be -// exponential with respect to the regex length + the string length, -// but usually it's must faster (often close to linear). -bool MatchRegexAnywhere(const char* regex, const char* str) { - if (regex == nullptr || str == nullptr) return false; - - if (*regex == '^') - return MatchRegexAtHead(regex + 1, str); - - // A successful match can be anywhere in str. - do { - if (MatchRegexAtHead(regex, str)) - return true; - } while (*str++ != '\0'); - return false; -} - -// Implements the RE class. - -RE::~RE() { - free(const_cast(pattern_)); - free(const_cast(full_pattern_)); -} - -// Returns true if and only if regular expression re matches the entire str. -bool RE::FullMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); -} - -// Returns true if and only if regular expression re matches a substring of -// str (including str itself). -bool RE::PartialMatch(const char* str, const RE& re) { - return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); -} - -// Initializes an RE from its string representation. -void RE::Init(const char* regex) { - pattern_ = full_pattern_ = nullptr; - if (regex != nullptr) { - pattern_ = posix::StrDup(regex); - } - - is_valid_ = ValidateRegex(regex); - if (!is_valid_) { - // No need to calculate the full pattern when the regex is invalid. - return; - } - - const size_t len = strlen(regex); - // Reserves enough bytes to hold the regular expression used for a - // full match: we need space to prepend a '^', append a '$', and - // terminate the string with '\0'. - char* buffer = static_cast(malloc(len + 3)); - full_pattern_ = buffer; - - if (*regex != '^') - *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. - - // We don't use snprintf or strncpy, as they trigger a warning when - // compiled with VC++ 8.0. - memcpy(buffer, regex, len); - buffer += len; - - if (len == 0 || regex[len - 1] != '$') - *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. - - *buffer = '\0'; -} - -#endif // GTEST_USES_POSIX_RE - -const char kUnknownFile[] = "unknown file"; - -// Formats a source file path and a line number as they would appear -// in an error message from the compiler used to compile this code. -GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { - const std::string file_name(file == nullptr ? kUnknownFile : file); - - if (line < 0) { - return file_name + ":"; - } -#ifdef _MSC_VER - return file_name + "(" + StreamableToString(line) + "):"; -#else - return file_name + ":" + StreamableToString(line) + ":"; -#endif // _MSC_VER -} - -// Formats a file location for compiler-independent XML output. -// Although this function is not platform dependent, we put it next to -// FormatFileLocation in order to contrast the two functions. -// Note that FormatCompilerIndependentFileLocation() does NOT append colon -// to the file location it produces, unlike FormatFileLocation(). -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( - const char* file, int line) { - const std::string file_name(file == nullptr ? kUnknownFile : file); - - if (line < 0) - return file_name; - else - return file_name + ":" + StreamableToString(line); -} - -GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) - : severity_(severity) { - const char* const marker = - severity == GTEST_INFO ? "[ INFO ]" : - severity == GTEST_WARNING ? "[WARNING]" : - severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; - GetStream() << ::std::endl << marker << " " - << FormatFileLocation(file, line).c_str() << ": "; -} - -// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. -GTestLog::~GTestLog() { - GetStream() << ::std::endl; - if (severity_ == GTEST_FATAL) { - fflush(stderr); - posix::Abort(); - } -} - -// Disable Microsoft deprecation warnings for POSIX functions called from -// this class (creat, dup, dup2, and close) -GTEST_DISABLE_MSC_DEPRECATED_PUSH_() - -#if GTEST_HAS_STREAM_REDIRECTION - -// Object that captures an output stream (stdout/stderr). -class CapturedStream { - public: - // The ctor redirects the stream to a temporary file. - explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { -# if GTEST_OS_WINDOWS - char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT - char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT - - ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); - const UINT success = ::GetTempFileNameA(temp_dir_path, - "gtest_redir", - 0, // Generate unique file name. - temp_file_path); - GTEST_CHECK_(success != 0) - << "Unable to create a temporary file in " << temp_dir_path; - const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); - GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " - << temp_file_path; - filename_ = temp_file_path; -# else - // There's no guarantee that a test has write access to the current - // directory, so we create the temporary file in the /tmp directory - // instead. We use /tmp on most systems, and /sdcard on Android. - // That's because Android doesn't have /tmp. -# if GTEST_OS_LINUX_ANDROID - // Note: Android applications are expected to call the framework's - // Context.getExternalStorageDirectory() method through JNI to get - // the location of the world-writable SD Card directory. However, - // this requires a Context handle, which cannot be retrieved - // globally from native code. Doing so also precludes running the - // code as part of a regular standalone executable, which doesn't - // run in a Dalvik process (e.g. when running it through 'adb shell'). - // - // The location /data/local/tmp is directly accessible from native code. - // '/sdcard' and other variants cannot be relied on, as they are not - // guaranteed to be mounted, or may have a delay in mounting. - char name_template[] = "/data/local/tmp/gtest_captured_stream.XXXXXX"; -# else - char name_template[] = "/tmp/captured_stream.XXXXXX"; -# endif // GTEST_OS_LINUX_ANDROID - const int captured_fd = mkstemp(name_template); - if (captured_fd == -1) { - GTEST_LOG_(WARNING) - << "Failed to create tmp file " << name_template - << " for test; does the test have access to the /tmp directory?"; - } - filename_ = name_template; -# endif // GTEST_OS_WINDOWS - fflush(nullptr); - dup2(captured_fd, fd_); - close(captured_fd); - } - - ~CapturedStream() { - remove(filename_.c_str()); - } - - std::string GetCapturedString() { - if (uncaptured_fd_ != -1) { - // Restores the original stream. - fflush(nullptr); - dup2(uncaptured_fd_, fd_); - close(uncaptured_fd_); - uncaptured_fd_ = -1; - } - - FILE* const file = posix::FOpen(filename_.c_str(), "r"); - if (file == nullptr) { - GTEST_LOG_(FATAL) << "Failed to open tmp file " << filename_ - << " for capturing stream."; - } - const std::string content = ReadEntireFile(file); - posix::FClose(file); - return content; - } - - private: - const int fd_; // A stream to capture. - int uncaptured_fd_; - // Name of the temporary file holding the stderr output. - ::std::string filename_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); -}; - -GTEST_DISABLE_MSC_DEPRECATED_POP_() - -static CapturedStream* g_captured_stderr = nullptr; -static CapturedStream* g_captured_stdout = nullptr; - -// Starts capturing an output stream (stdout/stderr). -static void CaptureStream(int fd, const char* stream_name, - CapturedStream** stream) { - if (*stream != nullptr) { - GTEST_LOG_(FATAL) << "Only one " << stream_name - << " capturer can exist at a time."; - } - *stream = new CapturedStream(fd); -} - -// Stops capturing the output stream and returns the captured string. -static std::string GetCapturedStream(CapturedStream** captured_stream) { - const std::string content = (*captured_stream)->GetCapturedString(); - - delete *captured_stream; - *captured_stream = nullptr; - - return content; -} - -// Starts capturing stdout. -void CaptureStdout() { - CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); -} - -// Starts capturing stderr. -void CaptureStderr() { - CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); -} - -// Stops capturing stdout and returns the captured string. -std::string GetCapturedStdout() { - return GetCapturedStream(&g_captured_stdout); -} - -// Stops capturing stderr and returns the captured string. -std::string GetCapturedStderr() { - return GetCapturedStream(&g_captured_stderr); -} - -#endif // GTEST_HAS_STREAM_REDIRECTION - - - - - -size_t GetFileSize(FILE* file) { - fseek(file, 0, SEEK_END); - return static_cast(ftell(file)); -} - -std::string ReadEntireFile(FILE* file) { - const size_t file_size = GetFileSize(file); - char* const buffer = new char[file_size]; - - size_t bytes_last_read = 0; // # of bytes read in the last fread() - size_t bytes_read = 0; // # of bytes read so far - - fseek(file, 0, SEEK_SET); - - // Keeps reading the file until we cannot read further or the - // pre-determined file size is reached. - do { - bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); - bytes_read += bytes_last_read; - } while (bytes_last_read > 0 && bytes_read < file_size); - - const std::string content(buffer, bytes_read); - delete[] buffer; - - return content; -} - -#if GTEST_HAS_DEATH_TEST -static const std::vector* g_injected_test_argvs = - nullptr; // Owned. - -std::vector GetInjectableArgvs() { - if (g_injected_test_argvs != nullptr) { - return *g_injected_test_argvs; - } - return GetArgvs(); -} - -void SetInjectableArgvs(const std::vector* new_argvs) { - if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs; - g_injected_test_argvs = new_argvs; -} - -void SetInjectableArgvs(const std::vector& new_argvs) { - SetInjectableArgvs( - new std::vector(new_argvs.begin(), new_argvs.end())); -} - -void ClearInjectableArgvs() { - delete g_injected_test_argvs; - g_injected_test_argvs = nullptr; -} -#endif // GTEST_HAS_DEATH_TEST - -#if GTEST_OS_WINDOWS_MOBILE -namespace posix { -void Abort() { - DebugBreak(); - TerminateProcess(GetCurrentProcess(), 1); -} -} // namespace posix -#endif // GTEST_OS_WINDOWS_MOBILE - -// Returns the name of the environment variable corresponding to the -// given flag. For example, FlagToEnvVar("foo") will return -// "GTEST_FOO" in the open-source version. -static std::string FlagToEnvVar(const char* flag) { - const std::string full_flag = - (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); - - Message env_var; - for (size_t i = 0; i != full_flag.length(); i++) { - env_var << ToUpper(full_flag.c_str()[i]); - } - - return env_var.GetString(); -} - -// Parses 'str' for a 32-bit signed integer. If successful, writes -// the result to *value and returns true; otherwise leaves *value -// unchanged and returns false. -bool ParseInt32(const Message& src_text, const char* str, Int32* value) { - // Parses the environment variable as a decimal integer. - char* end = nullptr; - const long long_value = strtol(str, &end, 10); // NOLINT - - // Has strtol() consumed all characters in the string? - if (*end != '\0') { - // No - an invalid character was encountered. - Message msg; - msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" - << " has value \"" << str << "\".\n"; - printf("%s", msg.GetString().c_str()); - fflush(stdout); - return false; - } - - // Is the parsed value in the range of an Int32? - const Int32 result = static_cast(long_value); - if (long_value == LONG_MAX || long_value == LONG_MIN || - // The parsed value overflows as a long. (strtol() returns - // LONG_MAX or LONG_MIN when the input overflows.) - result != long_value - // The parsed value overflows as an Int32. - ) { - Message msg; - msg << "WARNING: " << src_text - << " is expected to be a 32-bit integer, but actually" - << " has value " << str << ", which overflows.\n"; - printf("%s", msg.GetString().c_str()); - fflush(stdout); - return false; - } - - *value = result; - return true; -} - -// Reads and returns the Boolean environment variable corresponding to -// the given flag; if it's not set, returns default_value. -// -// The value is considered true if and only if it's not "0". -bool BoolFromGTestEnv(const char* flag, bool default_value) { -#if defined(GTEST_GET_BOOL_FROM_ENV_) - return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); -#else - const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = posix::GetEnv(env_var.c_str()); - return string_value == nullptr ? default_value - : strcmp(string_value, "0") != 0; -#endif // defined(GTEST_GET_BOOL_FROM_ENV_) -} - -// Reads and returns a 32-bit integer stored in the environment -// variable corresponding to the given flag; if it isn't set or -// doesn't represent a valid 32-bit integer, returns default_value. -Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { -#if defined(GTEST_GET_INT32_FROM_ENV_) - return GTEST_GET_INT32_FROM_ENV_(flag, default_value); -#else - const std::string env_var = FlagToEnvVar(flag); - const char* const string_value = posix::GetEnv(env_var.c_str()); - if (string_value == nullptr) { - // The environment variable is not set. - return default_value; - } - - Int32 result = default_value; - if (!ParseInt32(Message() << "Environment variable " << env_var, - string_value, &result)) { - printf("The default value %s is used.\n", - (Message() << default_value).GetString().c_str()); - fflush(stdout); - return default_value; - } - - return result; -#endif // defined(GTEST_GET_INT32_FROM_ENV_) -} - -// As a special case for the 'output' flag, if GTEST_OUTPUT is not -// set, we look for XML_OUTPUT_FILE, which is set by the Bazel build -// system. The value of XML_OUTPUT_FILE is a filename without the -// "xml:" prefix of GTEST_OUTPUT. -// Note that this is meant to be called at the call site so it does -// not check that the flag is 'output' -// In essence this checks an env variable called XML_OUTPUT_FILE -// and if it is set we prepend "xml:" to its value, if it not set we return "" -std::string OutputFlagAlsoCheckEnvVar(){ - std::string default_value_for_output_flag = ""; - const char* xml_output_file_env = posix::GetEnv("XML_OUTPUT_FILE"); - if (nullptr != xml_output_file_env) { - default_value_for_output_flag = std::string("xml:") + xml_output_file_env; - } - return default_value_for_output_flag; -} - -// Reads and returns the string environment variable corresponding to -// the given flag; if it's not set, returns default_value. -const char* StringFromGTestEnv(const char* flag, const char* default_value) { -#if defined(GTEST_GET_STRING_FROM_ENV_) - return GTEST_GET_STRING_FROM_ENV_(flag, default_value); -#else - const std::string env_var = FlagToEnvVar(flag); - const char* const value = posix::GetEnv(env_var.c_str()); - return value == nullptr ? default_value : value; -#endif // defined(GTEST_GET_STRING_FROM_ENV_) -} - -} // namespace internal -} // namespace testing -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Test - The Google C++ Testing and Mocking Framework -// -// This file implements a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); -// -// It uses the << operator when possible, and prints the bytes in the -// object otherwise. A user can override its behavior for a class -// type Foo by defining either operator<<(::std::ostream&, const Foo&) -// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that -// defines Foo. - -#include -#include -#include -#include // NOLINT -#include - -namespace testing { - -namespace { - -using ::std::ostream; - -// Prints a segment of bytes in the given object. -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, - size_t count, ostream* os) { - char text[5] = ""; - for (size_t i = 0; i != count; i++) { - const size_t j = start + i; - if (i != 0) { - // Organizes the bytes into groups of 2 for easy parsing by - // human. - if ((j % 2) == 0) - *os << ' '; - else - *os << '-'; - } - GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); - *os << text; - } -} - -// Prints the bytes in the given value to the given ostream. -void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, - ostream* os) { - // Tells the user how big the object is. - *os << count << "-byte object <"; - - const size_t kThreshold = 132; - const size_t kChunkSize = 64; - // If the object size is bigger than kThreshold, we'll have to omit - // some details by printing only the first and the last kChunkSize - // bytes. - if (count < kThreshold) { - PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); - } else { - PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); - *os << " ... "; - // Rounds up to 2-byte boundary. - const size_t resume_pos = (count - kChunkSize + 1)/2*2; - PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); - } - *os << ">"; -} - -} // namespace - -namespace internal2 { - -// Delegates to PrintBytesInObjectToImpl() to print the bytes in the -// given object. The delegation simplifies the implementation, which -// uses the << operator and thus is easier done outside of the -// ::testing::internal namespace, which contains a << operator that -// sometimes conflicts with the one in STL. -void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, - ostream* os) { - PrintBytesInObjectToImpl(obj_bytes, count, os); -} - -} // namespace internal2 - -namespace internal { - -// Depending on the value of a char (or wchar_t), we print it in one -// of three formats: -// - as is if it's a printable ASCII (e.g. 'a', '2', ' '), -// - as a hexadecimal escape sequence (e.g. '\x7F'), or -// - as a special escape sequence (e.g. '\r', '\n'). -enum CharFormat { - kAsIs, - kHexEscape, - kSpecialEscape -}; - -// Returns true if c is a printable ASCII character. We test the -// value of c directly instead of calling isprint(), which is buggy on -// Windows Mobile. -inline bool IsPrintableAscii(wchar_t c) { - return 0x20 <= c && c <= 0x7E; -} - -// Prints a wide or narrow char c as a character literal without the -// quotes, escaping it when necessary; returns how c was formatted. -// The template argument UnsignedChar is the unsigned version of Char, -// which is the type of c. -template -static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { - wchar_t w_c = static_cast(c); - switch (w_c) { - case L'\0': - *os << "\\0"; - break; - case L'\'': - *os << "\\'"; - break; - case L'\\': - *os << "\\\\"; - break; - case L'\a': - *os << "\\a"; - break; - case L'\b': - *os << "\\b"; - break; - case L'\f': - *os << "\\f"; - break; - case L'\n': - *os << "\\n"; - break; - case L'\r': - *os << "\\r"; - break; - case L'\t': - *os << "\\t"; - break; - case L'\v': - *os << "\\v"; - break; - default: - if (IsPrintableAscii(w_c)) { - *os << static_cast(c); - return kAsIs; - } else { - ostream::fmtflags flags = os->flags(); - *os << "\\x" << std::hex << std::uppercase - << static_cast(static_cast(c)); - os->flags(flags); - return kHexEscape; - } - } - return kSpecialEscape; -} - -// Prints a wchar_t c as if it's part of a string literal, escaping it when -// necessary; returns how c was formatted. -static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { - switch (c) { - case L'\'': - *os << "'"; - return kAsIs; - case L'"': - *os << "\\\""; - return kSpecialEscape; - default: - return PrintAsCharLiteralTo(c, os); - } -} - -// Prints a char c as if it's part of a string literal, escaping it when -// necessary; returns how c was formatted. -static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { - return PrintAsStringLiteralTo( - static_cast(static_cast(c)), os); -} - -// Prints a wide or narrow character c and its code. '\0' is printed -// as "'\\0'", other unprintable characters are also properly escaped -// using the standard C++ escape sequence. The template argument -// UnsignedChar is the unsigned version of Char, which is the type of c. -template -void PrintCharAndCodeTo(Char c, ostream* os) { - // First, print c as a literal in the most readable form we can find. - *os << ((sizeof(c) > 1) ? "L'" : "'"); - const CharFormat format = PrintAsCharLiteralTo(c, os); - *os << "'"; - - // To aid user debugging, we also print c's code in decimal, unless - // it's 0 (in which case c was printed as '\\0', making the code - // obvious). - if (c == 0) - return; - *os << " (" << static_cast(c); - - // For more convenience, we print c's code again in hexadecimal, - // unless c was already printed in the form '\x##' or the code is in - // [1, 9]. - if (format == kHexEscape || (1 <= c && c <= 9)) { - // Do nothing. - } else { - *os << ", 0x" << String::FormatHexInt(static_cast(c)); - } - *os << ")"; -} - -void PrintTo(unsigned char c, ::std::ostream* os) { - PrintCharAndCodeTo(c, os); -} -void PrintTo(signed char c, ::std::ostream* os) { - PrintCharAndCodeTo(c, os); -} - -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its code. L'\0' is printed as "L'\\0'". -void PrintTo(wchar_t wc, ostream* os) { - PrintCharAndCodeTo(wc, os); -} - -// Prints the given array of characters to the ostream. CharType must be either -// char or wchar_t. -// The array starts at begin, the length is len, it may include '\0' characters -// and may not be NUL-terminated. -template -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static CharFormat PrintCharsAsStringTo( - const CharType* begin, size_t len, ostream* os) { - const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; - *os << kQuoteBegin; - bool is_previous_hex = false; - CharFormat print_format = kAsIs; - for (size_t index = 0; index < len; ++index) { - const CharType cur = begin[index]; - if (is_previous_hex && IsXDigit(cur)) { - // Previous character is of '\x..' form and this character can be - // interpreted as another hexadecimal digit in its number. Break string to - // disambiguate. - *os << "\" " << kQuoteBegin; - } - is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; - // Remember if any characters required hex escaping. - if (is_previous_hex) { - print_format = kHexEscape; - } - } - *os << "\""; - return print_format; -} - -// Prints a (const) char/wchar_t array of 'len' elements, starting at address -// 'begin'. CharType must be either char or wchar_t. -template -GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -static void UniversalPrintCharArray( - const CharType* begin, size_t len, ostream* os) { - // The code - // const char kFoo[] = "foo"; - // generates an array of 4, not 3, elements, with the last one being '\0'. - // - // Therefore when printing a char array, we don't print the last element if - // it's '\0', such that the output matches the string literal as it's - // written in the source code. - if (len > 0 && begin[len - 1] == '\0') { - PrintCharsAsStringTo(begin, len - 1, os); - return; - } - - // If, however, the last element in the array is not '\0', e.g. - // const char kFoo[] = { 'f', 'o', 'o' }; - // we must print the entire array. We also print a message to indicate - // that the array is not NUL-terminated. - PrintCharsAsStringTo(begin, len, os); - *os << " (no terminating NUL)"; -} - -// Prints a (const) char array of 'len' elements, starting at address 'begin'. -void UniversalPrintArray(const char* begin, size_t len, ostream* os) { - UniversalPrintCharArray(begin, len, os); -} - -// Prints a (const) wchar_t array of 'len' elements, starting at address -// 'begin'. -void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { - UniversalPrintCharArray(begin, len, os); -} - -// Prints the given C string to the ostream. -void PrintTo(const char* s, ostream* os) { - if (s == nullptr) { - *os << "NULL"; - } else { - *os << ImplicitCast_(s) << " pointing to "; - PrintCharsAsStringTo(s, strlen(s), os); - } -} - -// MSVC compiler can be configured to define whar_t as a typedef -// of unsigned short. Defining an overload for const wchar_t* in that case -// would cause pointers to unsigned shorts be printed as wide strings, -// possibly accessing more memory than intended and causing invalid -// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when -// wchar_t is implemented as a native type. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Prints the given wide C string to the ostream. -void PrintTo(const wchar_t* s, ostream* os) { - if (s == nullptr) { - *os << "NULL"; - } else { - *os << ImplicitCast_(s) << " pointing to "; - PrintCharsAsStringTo(s, wcslen(s), os); - } -} -#endif // wchar_t is native - -namespace { - -bool ContainsUnprintableControlCodes(const char* str, size_t length) { - const unsigned char *s = reinterpret_cast(str); - - for (size_t i = 0; i < length; i++) { - unsigned char ch = *s++; - if (std::iscntrl(ch)) { - switch (ch) { - case '\t': - case '\n': - case '\r': - break; - default: - return true; - } - } - } - return false; -} - -bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; } - -bool IsValidUTF8(const char* str, size_t length) { - const unsigned char *s = reinterpret_cast(str); - - for (size_t i = 0; i < length;) { - unsigned char lead = s[i++]; - - if (lead <= 0x7f) { - continue; // single-byte character (ASCII) 0..7F - } - if (lead < 0xc2) { - return false; // trail byte or non-shortest form - } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) { - ++i; // 2-byte character - } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length && - IsUTF8TrailByte(s[i]) && - IsUTF8TrailByte(s[i + 1]) && - // check for non-shortest form and surrogate - (lead != 0xe0 || s[i] >= 0xa0) && - (lead != 0xed || s[i] < 0xa0)) { - i += 2; // 3-byte character - } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length && - IsUTF8TrailByte(s[i]) && - IsUTF8TrailByte(s[i + 1]) && - IsUTF8TrailByte(s[i + 2]) && - // check for non-shortest form - (lead != 0xf0 || s[i] >= 0x90) && - (lead != 0xf4 || s[i] < 0x90)) { - i += 3; // 4-byte character - } else { - return false; - } - } - return true; -} - -void ConditionalPrintAsText(const char* str, size_t length, ostream* os) { - if (!ContainsUnprintableControlCodes(str, length) && - IsValidUTF8(str, length)) { - *os << "\n As Text: \"" << str << "\""; - } -} - -} // anonymous namespace - -void PrintStringTo(const ::std::string& s, ostream* os) { - if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) { - if (GTEST_FLAG(print_utf8)) { - ConditionalPrintAsText(s.data(), s.size(), os); - } - } -} - -#if GTEST_HAS_STD_WSTRING -void PrintWideStringTo(const ::std::wstring& s, ostream* os) { - PrintCharsAsStringTo(s.data(), s.size(), os); -} -#endif // GTEST_HAS_STD_WSTRING - -} // namespace internal - -} // namespace testing -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// The Google C++ Testing and Mocking Framework (Google Test) - - -namespace testing { - -using internal::GetUnitTestImpl; - -// Gets the summary of the failure message by omitting the stack trace -// in it. -std::string TestPartResult::ExtractSummary(const char* message) { - const char* const stack_trace = strstr(message, internal::kStackTraceMarker); - return stack_trace == nullptr ? message : std::string(message, stack_trace); -} - -// Prints a TestPartResult object. -std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { - return os << result.file_name() << ":" << result.line_number() << ": " - << (result.type() == TestPartResult::kSuccess - ? "Success" - : result.type() == TestPartResult::kSkip - ? "Skipped" - : result.type() == TestPartResult::kFatalFailure - ? "Fatal failure" - : "Non-fatal failure") - << ":\n" - << result.message() << std::endl; -} - -// Appends a TestPartResult to the array. -void TestPartResultArray::Append(const TestPartResult& result) { - array_.push_back(result); -} - -// Returns the TestPartResult at the given index (0-based). -const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { - if (index < 0 || index >= size()) { - printf("\nInvalid index (%d) into TestPartResultArray.\n", index); - internal::posix::Abort(); - } - - return array_[static_cast(index)]; -} - -// Returns the number of TestPartResult objects in the array. -int TestPartResultArray::size() const { - return static_cast(array_.size()); -} - -namespace internal { - -HasNewFatalFailureHelper::HasNewFatalFailureHelper() - : has_new_fatal_failure_(false), - original_reporter_(GetUnitTestImpl()-> - GetTestPartResultReporterForCurrentThread()) { - GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); -} - -HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { - GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( - original_reporter_); -} - -void HasNewFatalFailureHelper::ReportTestPartResult( - const TestPartResult& result) { - if (result.fatally_failed()) - has_new_fatal_failure_ = true; - original_reporter_->ReportTestPartResult(result); -} - -} // namespace internal - -} // namespace testing -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - - -namespace testing { -namespace internal { - -#if GTEST_HAS_TYPED_TEST_P - -// Skips to the first non-space char in str. Returns an empty string if str -// contains only whitespace characters. -static const char* SkipSpaces(const char* str) { - while (IsSpace(*str)) - str++; - return str; -} - -static std::vector SplitIntoTestNames(const char* src) { - std::vector name_vec; - src = SkipSpaces(src); - for (; src != nullptr; src = SkipComma(src)) { - name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); - } - return name_vec; -} - -// Verifies that registered_tests match the test names in -// registered_tests_; returns registered_tests if successful, or -// aborts the program otherwise. -const char* TypedTestSuitePState::VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests) { - typedef RegisteredTestsMap::const_iterator RegisteredTestIter; - registered_ = true; - - std::vector name_vec = SplitIntoTestNames(registered_tests); - - Message errors; - - std::set tests; - for (std::vector::const_iterator name_it = name_vec.begin(); - name_it != name_vec.end(); ++name_it) { - const std::string& name = *name_it; - if (tests.count(name) != 0) { - errors << "Test " << name << " is listed more than once.\n"; - continue; - } - - bool found = false; - for (RegisteredTestIter it = registered_tests_.begin(); - it != registered_tests_.end(); - ++it) { - if (name == it->first) { - found = true; - break; - } - } - - if (found) { - tests.insert(name); - } else { - errors << "No test named " << name - << " can be found in this test suite.\n"; - } - } - - for (RegisteredTestIter it = registered_tests_.begin(); - it != registered_tests_.end(); - ++it) { - if (tests.count(it->first) == 0) { - errors << "You forgot to list test " << it->first << ".\n"; - } - } - - const std::string& errors_str = errors.GetString(); - if (errors_str != "") { - fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), - errors_str.c_str()); - fflush(stderr); - posix::Abort(); - } - - return registered_tests; -} - -#endif // GTEST_HAS_TYPED_TEST_P - -} // namespace internal -} // namespace testing diff --git a/ThirdParty/gtest/gtest.h b/ThirdParty/gtest/gtest.h deleted file mode 100644 index df1441aa35..0000000000 --- a/ThirdParty/gtest/gtest.h +++ /dev/null @@ -1,14813 +0,0 @@ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file defines the public API for Google Test. It should be -// included by any test program that uses Google Test. -// -// IMPORTANT NOTE: Due to limitation of the C++ language, we have to -// leave some internal implementation details in this header file. -// They are clearly marked by comments like this: -// -// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -// -// Such code is NOT meant to be used by a user directly, and is subject -// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user -// program! -// -// Acknowledgment: Google Test borrowed the idea of automatic test -// registration from Barthelemy Dagenais' (barthelemy@prologique.com) -// easyUnit framework. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_H_ - -#include -#include -#include -#include -#include -#include - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file declares functions and macros used internally by -// Google Test. They are subject to change without notice. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Low-level types and utilities for porting Google Test to various -// platforms. All macros ending with _ and symbols defined in an -// internal namespace are subject to change without notice. Code -// outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't -// end with _ are part of Google Test's public API and can be used by -// code outside Google Test. -// -// This file is fundamental to Google Test. All other Google Test source -// files are expected to #include this. Therefore, it cannot #include -// any other Google Test header. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ - -// Environment-describing macros -// ----------------------------- -// -// Google Test can be used in many different environments. Macros in -// this section tell Google Test what kind of environment it is being -// used in, such that Google Test can provide environment-specific -// features and implementations. -// -// Google Test tries to automatically detect the properties of its -// environment, so users usually don't need to worry about these -// macros. However, the automatic detection is not perfect. -// Sometimes it's necessary for a user to define some of the following -// macros in the build script to override Google Test's decisions. -// -// If the user doesn't define a macro in the list, Google Test will -// provide a default definition. After this header is #included, all -// macros in this list will be defined to either 1 or 0. -// -// Notes to maintainers: -// - Each macro here is a user-tweakable knob; do not grow the list -// lightly. -// - Use #if to key off these macros. Don't use #ifdef or "#if -// defined(...)", which will not work as these macros are ALWAYS -// defined. -// -// GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) -// is/isn't available. -// GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions -// are enabled. -// GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular -// expressions are/aren't available. -// GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that -// is/isn't available. -// GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't -// enabled. -// GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that -// std::wstring does/doesn't work (Google Test can -// be used where std::wstring is unavailable). -// GTEST_HAS_SEH - Define it to 1/0 to indicate whether the -// compiler supports Microsoft's "Structured -// Exception Handling". -// GTEST_HAS_STREAM_REDIRECTION -// - Define it to 1/0 to indicate whether the -// platform supports I/O stream redirection using -// dup() and dup2(). -// GTEST_LINKED_AS_SHARED_LIBRARY -// - Define to 1 when compiling tests that use -// Google Test as a shared library (known as -// DLL on Windows). -// GTEST_CREATE_SHARED_LIBRARY -// - Define to 1 when compiling Google Test itself -// as a shared library. -// GTEST_DEFAULT_DEATH_TEST_STYLE -// - The default value of --gtest_death_test_style. -// The legacy default has been "fast" in the open -// source version since 2008. The recommended value -// is "threadsafe", and can be set in -// custom/gtest-port.h. - -// Platform-indicating macros -// -------------------------- -// -// Macros indicating the platform on which Google Test is being used -// (a macro is defined to 1 if compiled on the given platform; -// otherwise UNDEFINED -- it's never defined to 0.). Google Test -// defines these macros automatically. Code outside Google Test MUST -// NOT define them. -// -// GTEST_OS_AIX - IBM AIX -// GTEST_OS_CYGWIN - Cygwin -// GTEST_OS_DRAGONFLY - DragonFlyBSD -// GTEST_OS_FREEBSD - FreeBSD -// GTEST_OS_FUCHSIA - Fuchsia -// GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD -// GTEST_OS_HAIKU - Haiku -// GTEST_OS_HPUX - HP-UX -// GTEST_OS_LINUX - Linux -// GTEST_OS_LINUX_ANDROID - Google Android -// GTEST_OS_MAC - Mac OS X -// GTEST_OS_IOS - iOS -// GTEST_OS_NACL - Google Native Client (NaCl) -// GTEST_OS_NETBSD - NetBSD -// GTEST_OS_OPENBSD - OpenBSD -// GTEST_OS_OS2 - OS/2 -// GTEST_OS_QNX - QNX -// GTEST_OS_SOLARIS - Sun Solaris -// GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) -// GTEST_OS_WINDOWS_DESKTOP - Windows Desktop -// GTEST_OS_WINDOWS_MINGW - MinGW -// GTEST_OS_WINDOWS_MOBILE - Windows Mobile -// GTEST_OS_WINDOWS_PHONE - Windows Phone -// GTEST_OS_WINDOWS_RT - Windows Store App/WinRT -// GTEST_OS_ZOS - z/OS -// -// Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the -// most stable support. Since core members of the Google Test project -// don't have access to other platforms, support for them may be less -// stable. If you notice any problems on your platform, please notify -// googletestframework@googlegroups.com (patches for fixing them are -// even more welcome!). -// -// It is possible that none of the GTEST_OS_* macros are defined. - -// Feature-indicating macros -// ------------------------- -// -// Macros indicating which Google Test features are available (a macro -// is defined to 1 if the corresponding feature is supported; -// otherwise UNDEFINED -- it's never defined to 0.). Google Test -// defines these macros automatically. Code outside Google Test MUST -// NOT define them. -// -// These macros are public so that portable tests can be written. -// Such tests typically surround code using a feature with an #if -// which controls that code. For example: -// -// #if GTEST_HAS_DEATH_TEST -// EXPECT_DEATH(DoSomethingDeadly()); -// #endif -// -// GTEST_HAS_DEATH_TEST - death tests -// GTEST_HAS_TYPED_TEST - typed tests -// GTEST_HAS_TYPED_TEST_P - type-parameterized tests -// GTEST_IS_THREADSAFE - Google Test is thread-safe. -// GOOGLETEST_CM0007 DO NOT DELETE -// GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with -// GTEST_HAS_POSIX_RE (see above) which users can -// define themselves. -// GTEST_USES_SIMPLE_RE - our own simple regex is used; -// the above RE\b(s) are mutually exclusive. - -// Misc public macros -// ------------------ -// -// GTEST_FLAG(flag_name) - references the variable corresponding to -// the given Google Test flag. - -// Internal utilities -// ------------------ -// -// The following macros and utilities are for Google Test's INTERNAL -// use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. -// -// Macros for basic C++ coding: -// GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. -// GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a -// variable don't have to be used. -// GTEST_DISALLOW_ASSIGN_ - disables operator=. -// GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. -// GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. -// GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is -// suppressed (constant conditional). -// GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 -// is suppressed. -// -// Synchronization: -// Mutex, MutexLock, ThreadLocal, GetThreadCount() -// - synchronization primitives. -// -// Regular expressions: -// RE - a simple regular expression class using the POSIX -// Extended Regular Expression syntax on UNIX-like platforms -// GOOGLETEST_CM0008 DO NOT DELETE -// or a reduced regular exception syntax on other -// platforms, including Windows. -// Logging: -// GTEST_LOG_() - logs messages at the specified severity level. -// LogToStderr() - directs all log messages to stderr. -// FlushInfoLog() - flushes informational log messages. -// -// Stdout and stderr capturing: -// CaptureStdout() - starts capturing stdout. -// GetCapturedStdout() - stops capturing stdout and returns the captured -// string. -// CaptureStderr() - starts capturing stderr. -// GetCapturedStderr() - stops capturing stderr and returns the captured -// string. -// -// Integer types: -// TypeWithSize - maps an integer to a int type. -// Int32, UInt32, Int64, UInt64, TimeInMillis -// - integers of known sizes. -// BiggestInt - the biggest signed integer type. -// -// Command-line utilities: -// GTEST_DECLARE_*() - declares a flag. -// GTEST_DEFINE_*() - defines a flag. -// GetInjectableArgvs() - returns the command line as a vector of strings. -// -// Environment variable utilities: -// GetEnv() - gets the value of an environment variable. -// BoolFromGTestEnv() - parses a bool environment variable. -// Int32FromGTestEnv() - parses an Int32 environment variable. -// StringFromGTestEnv() - parses a string environment variable. -// -// Deprecation warnings: -// GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as -// deprecated; calling a marked function -// should generate a compiler warning - -#include // for isspace, etc -#include // for ptrdiff_t -#include -#include -#include -#include -#include - -#ifndef _WIN32_WCE -# include -# include -#endif // !_WIN32_WCE - -#if defined __APPLE__ -# include -# include -#endif - -#include // NOLINT -#include // NOLINT -#include // NOLINT -#include // NOLINT -#include -#include -#include // NOLINT - -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file defines the GTEST_OS_* macro. -// It is separate from gtest-port.h so that custom/gtest-port.h can include it. - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ - -// Determines the platform on which Google Test is compiled. -#ifdef __CYGWIN__ -# define GTEST_OS_CYGWIN 1 -# elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__) -# define GTEST_OS_WINDOWS_MINGW 1 -# define GTEST_OS_WINDOWS 1 -#elif defined _WIN32 -# define GTEST_OS_WINDOWS 1 -# ifdef _WIN32_WCE -# define GTEST_OS_WINDOWS_MOBILE 1 -# elif defined(WINAPI_FAMILY) -# include -# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) -# define GTEST_OS_WINDOWS_DESKTOP 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) -# define GTEST_OS_WINDOWS_PHONE 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) -# define GTEST_OS_WINDOWS_RT 1 -# elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE) -# define GTEST_OS_WINDOWS_PHONE 1 -# define GTEST_OS_WINDOWS_TV_TITLE 1 -# else - // WINAPI_FAMILY defined but no known partition matched. - // Default to desktop. -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif -# else -# define GTEST_OS_WINDOWS_DESKTOP 1 -# endif // _WIN32_WCE -#elif defined __OS2__ -# define GTEST_OS_OS2 1 -#elif defined __APPLE__ -# define GTEST_OS_MAC 1 -# if TARGET_OS_IPHONE -# define GTEST_OS_IOS 1 -# endif -#elif defined __DragonFly__ -# define GTEST_OS_DRAGONFLY 1 -#elif defined __FreeBSD__ -# define GTEST_OS_FREEBSD 1 -#elif defined __Fuchsia__ -# define GTEST_OS_FUCHSIA 1 -#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__) -# define GTEST_OS_GNU_KFREEBSD 1 -#elif defined __linux__ -# define GTEST_OS_LINUX 1 -# if defined __ANDROID__ -# define GTEST_OS_LINUX_ANDROID 1 -# endif -#elif defined __MVS__ -# define GTEST_OS_ZOS 1 -#elif defined(__sun) && defined(__SVR4) -# define GTEST_OS_SOLARIS 1 -#elif defined(_AIX) -# define GTEST_OS_AIX 1 -#elif defined(__hpux) -# define GTEST_OS_HPUX 1 -#elif defined __native_client__ -# define GTEST_OS_NACL 1 -#elif defined __NetBSD__ -# define GTEST_OS_NETBSD 1 -#elif defined __OpenBSD__ -# define GTEST_OS_OPENBSD 1 -#elif defined __QNX__ -# define GTEST_OS_QNX 1 -#elif defined(__HAIKU__) -#define GTEST_OS_HAIKU 1 -#endif // __CYGWIN__ - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Injection point for custom user configurations. See README for details -// -// ** Custom implementation starts here ** - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ - -#if !defined(GTEST_DEV_EMAIL_) -# define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" -# define GTEST_FLAG_PREFIX_ "gtest_" -# define GTEST_FLAG_PREFIX_DASH_ "gtest-" -# define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" -# define GTEST_NAME_ "Google Test" -# define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" -#endif // !defined(GTEST_DEV_EMAIL_) - -#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) -# define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" -#endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) - -// Determines the version of gcc that is used to compile this. -#ifdef __GNUC__ -// 40302 means version 4.3.2. -# define GTEST_GCC_VER_ \ - (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) -#endif // __GNUC__ - -// Macros for disabling Microsoft Visual C++ warnings. -// -// GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) -// /* code that triggers warnings C4800 and C4385 */ -// GTEST_DISABLE_MSC_WARNINGS_POP_() -#if defined(_MSC_VER) -# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ - __pragma(warning(push)) \ - __pragma(warning(disable: warnings)) -# define GTEST_DISABLE_MSC_WARNINGS_POP_() \ - __pragma(warning(pop)) -#else -// Not all compilers are MSVC -# define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) -# define GTEST_DISABLE_MSC_WARNINGS_POP_() -#endif - -// Clang on Windows does not understand MSVC's pragma warning. -// We need clang-specific way to disable function deprecation warning. -#ifdef __clang__ -# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") \ - _Pragma("clang diagnostic ignored \"-Wdeprecated-implementations\"") -#define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ - _Pragma("clang diagnostic pop") -#else -# define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \ - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) -# define GTEST_DISABLE_MSC_DEPRECATED_POP_() \ - GTEST_DISABLE_MSC_WARNINGS_POP_() -#endif - -// Brings in definitions for functions used in the testing::internal::posix -// namespace (read, write, close, chdir, isatty, stat). We do not currently -// use them on Windows Mobile. -#if GTEST_OS_WINDOWS -# if !GTEST_OS_WINDOWS_MOBILE -# include -# include -# endif -// In order to avoid having to include , use forward declaration -#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR) -// MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two -// separate (equivalent) structs, instead of using typedef -typedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION; -#else -// Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. -// This assumption is verified by -// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. -typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; -#endif -#else -// This assumes that non-Windows OSes provide unistd.h. For OSes where this -// is not the case, we need to include headers that provide the functions -// mentioned above. -# include -# include -#endif // GTEST_OS_WINDOWS - -#if GTEST_OS_LINUX_ANDROID -// Used to define __ANDROID_API__ matching the target NDK API level. -# include // NOLINT -#endif - -// Defines this to true if and only if Google Test can use POSIX regular -// expressions. -#ifndef GTEST_HAS_POSIX_RE -# if GTEST_OS_LINUX_ANDROID -// On Android, is only available starting with Gingerbread. -# define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) -# else -# define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) -# endif -#endif - -#if GTEST_USES_PCRE -// The appropriate headers have already been included. - -#elif GTEST_HAS_POSIX_RE - -// On some platforms, needs someone to define size_t, and -// won't compile otherwise. We can #include it here as we already -// included , which is guaranteed to define size_t through -// . -# include // NOLINT - -# define GTEST_USES_POSIX_RE 1 - -#elif GTEST_OS_WINDOWS - -// is not available on Windows. Use our own simple regex -// implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#else - -// may not be available on this platform. Use our own -// simple regex implementation instead. -# define GTEST_USES_SIMPLE_RE 1 - -#endif // GTEST_USES_PCRE - -#ifndef GTEST_HAS_EXCEPTIONS -// The user didn't tell us whether exceptions are enabled, so we need -// to figure it out. -# if defined(_MSC_VER) && defined(_CPPUNWIND) -// MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__BORLANDC__) -// C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS -// macro to enable exceptions, so we'll do the same. -// Assumes that exceptions are enabled by default. -# ifndef _HAS_EXCEPTIONS -# define _HAS_EXCEPTIONS 1 -# endif // _HAS_EXCEPTIONS -# define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS -# elif defined(__clang__) -// clang defines __EXCEPTIONS if and only if exceptions are enabled before clang -// 220714, but if and only if cleanups are enabled after that. In Obj-C++ files, -// there can be cleanups for ObjC exceptions which also need cleanups, even if -// C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which -// checks for C++ exceptions starting at clang r206352, but which checked for -// cleanups prior to that. To reliably check for C++ exception availability with -// clang, check for -// __EXCEPTIONS && __has_feature(cxx_exceptions). -# define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) -# elif defined(__GNUC__) && __EXCEPTIONS -// gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__SUNPRO_CC) -// Sun Pro CC supports exceptions. However, there is no compile-time way of -// detecting whether they are enabled or not. Therefore, we assume that -// they are enabled unless the user tells us otherwise. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__IBMCPP__) && __EXCEPTIONS -// xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled. -# define GTEST_HAS_EXCEPTIONS 1 -# elif defined(__HP_aCC) -// Exception handling is in effect by default in HP aCC compiler. It has to -// be turned of by +noeh compiler option if desired. -# define GTEST_HAS_EXCEPTIONS 1 -# else -// For other compilers, we assume exceptions are disabled to be -// conservative. -# define GTEST_HAS_EXCEPTIONS 0 -# endif // defined(_MSC_VER) || defined(__BORLANDC__) -#endif // GTEST_HAS_EXCEPTIONS - -#if !defined(GTEST_HAS_STD_STRING) -// Even though we don't use this macro any longer, we keep it in case -// some clients still depend on it. -# define GTEST_HAS_STD_STRING 1 -#elif !GTEST_HAS_STD_STRING -// The user told us that ::std::string isn't available. -# error "::std::string isn't available." -#endif // !defined(GTEST_HAS_STD_STRING) - -#ifndef GTEST_HAS_STD_WSTRING -// The user didn't tell us whether ::std::wstring is available, so we need -// to figure it out. -// Cygwin 1.7 and below doesn't support ::std::wstring. -// Solaris' libc++ doesn't support it either. Android has -// no support for it at least as recent as Froyo (2.2). -#define GTEST_HAS_STD_WSTRING \ - (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - GTEST_OS_HAIKU)) - -#endif // GTEST_HAS_STD_WSTRING - -// Determines whether RTTI is available. -#ifndef GTEST_HAS_RTTI -// The user didn't tell us whether RTTI is enabled, so we need to -// figure it out. - -# ifdef _MSC_VER - -#ifdef _CPPRTTI // MSVC defines this macro if and only if RTTI is enabled. -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif - -// Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is -// enabled. -# elif defined(__GNUC__) - -# ifdef __GXX_RTTI -// When building against STLport with the Android NDK and with -// -frtti -fno-exceptions, the build fails at link time with undefined -// references to __cxa_bad_typeid. Note sure if STL or toolchain bug, -// so disable RTTI when detected. -# if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ - !defined(__EXCEPTIONS) -# define GTEST_HAS_RTTI 0 -# else -# define GTEST_HAS_RTTI 1 -# endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS -# else -# define GTEST_HAS_RTTI 0 -# endif // __GXX_RTTI - -// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends -// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the -// first version with C++ support. -# elif defined(__clang__) - -# define GTEST_HAS_RTTI __has_feature(cxx_rtti) - -// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if -// both the typeid and dynamic_cast features are present. -# elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) - -# ifdef __RTTI_ALL__ -# define GTEST_HAS_RTTI 1 -# else -# define GTEST_HAS_RTTI 0 -# endif - -# else - -// For all other compilers, we assume RTTI is enabled. -# define GTEST_HAS_RTTI 1 - -# endif // _MSC_VER - -#endif // GTEST_HAS_RTTI - -// It's this header's responsibility to #include when RTTI -// is enabled. -#if GTEST_HAS_RTTI -# include -#endif - -// Determines whether Google Test can use the pthreads library. -#ifndef GTEST_HAS_PTHREAD -// The user didn't tell us explicitly, so we make reasonable assumptions about -// which platforms have pthreads support. -// -// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 -// to your compiler flags. -#define GTEST_HAS_PTHREAD \ - (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX || \ - GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD || \ - GTEST_OS_HAIKU) -#endif // GTEST_HAS_PTHREAD - -#if GTEST_HAS_PTHREAD -// gtest-port.h guarantees to #include when GTEST_HAS_PTHREAD is -// true. -# include // NOLINT - -// For timespec and nanosleep, used below. -# include // NOLINT -#endif - -// Determines whether clone(2) is supported. -// Usually it will only be available on Linux, excluding -// Linux on the Itanium architecture. -// Also see http://linux.die.net/man/2/clone. -#ifndef GTEST_HAS_CLONE -// The user didn't tell us, so we need to figure it out. - -# if GTEST_OS_LINUX && !defined(__ia64__) -# if GTEST_OS_LINUX_ANDROID -// On Android, clone() became available at different API levels for each 32-bit -// architecture. -# if defined(__LP64__) || \ - (defined(__arm__) && __ANDROID_API__ >= 9) || \ - (defined(__mips__) && __ANDROID_API__ >= 12) || \ - (defined(__i386__) && __ANDROID_API__ >= 17) -# define GTEST_HAS_CLONE 1 -# else -# define GTEST_HAS_CLONE 0 -# endif -# else -# define GTEST_HAS_CLONE 1 -# endif -# else -# define GTEST_HAS_CLONE 0 -# endif // GTEST_OS_LINUX && !defined(__ia64__) - -#endif // GTEST_HAS_CLONE - -// Determines whether to support stream redirection. This is used to test -// output correctness and to implement death tests. -#ifndef GTEST_HAS_STREAM_REDIRECTION -// By default, we assume that stream redirection is supported on all -// platforms except known mobile ones. -# if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT -# define GTEST_HAS_STREAM_REDIRECTION 0 -# else -# define GTEST_HAS_STREAM_REDIRECTION 1 -# endif // !GTEST_OS_WINDOWS_MOBILE -#endif // GTEST_HAS_STREAM_REDIRECTION - -// Determines whether to support death tests. -// pops up a dialog window that cannot be suppressed programmatically. -#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ - (GTEST_OS_MAC && !GTEST_OS_IOS) || \ - (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW || \ - GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \ - GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \ - GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU) -# define GTEST_HAS_DEATH_TEST 1 -#endif - -// Determines whether to support type-driven tests. - -// Typed tests need and variadic macros, which GCC, VC++ 8.0, -// Sun Pro CC, IBM Visual Age, and HP aCC support. -#if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \ - defined(__IBMCPP__) || defined(__HP_aCC) -# define GTEST_HAS_TYPED_TEST 1 -# define GTEST_HAS_TYPED_TEST_P 1 -#endif - -// Determines whether the system compiler uses UTF-16 for encoding wide strings. -#define GTEST_WIDE_STRING_USES_UTF16_ \ - (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2) - -// Determines whether test results can be streamed to a socket. -#if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \ - GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD -# define GTEST_CAN_STREAM_RESULTS_ 1 -#endif - -// Defines some utility macros. - -// The GNU compiler emits a warning if nested "if" statements are followed by -// an "else" statement and braces are not used to explicitly disambiguate the -// "else" binding. This leads to problems with code like: -// -// if (gate) -// ASSERT_*(condition) << "Some message"; -// -// The "switch (0) case 0:" idiom is used to suppress this. -#ifdef __INTEL_COMPILER -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ -#else -# define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT -#endif - -// Use this annotation at the end of a struct/class definition to -// prevent the compiler from optimizing away instances that are never -// used. This is useful when all interesting logic happens inside the -// c'tor and / or d'tor. Example: -// -// struct Foo { -// Foo() { ... } -// } GTEST_ATTRIBUTE_UNUSED_; -// -// Also use it after a variable or parameter declaration to tell the -// compiler the variable/parameter does not have to be used. -#if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -#elif defined(__clang__) -# if __has_attribute(unused) -# define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) -# endif -#endif -#ifndef GTEST_ATTRIBUTE_UNUSED_ -# define GTEST_ATTRIBUTE_UNUSED_ -#endif - -// Use this annotation before a function that takes a printf format string. -#if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC) -# if defined(__MINGW_PRINTF_FORMAT) -// MinGW has two different printf implementations. Ensure the format macro -// matches the selected implementation. See -// https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ - __attribute__((__format__(__MINGW_PRINTF_FORMAT, string_index, \ - first_to_check))) -# else -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \ - __attribute__((__format__(__printf__, string_index, first_to_check))) -# endif -#else -# define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) -#endif - - -// A macro to disallow operator= -// This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_ASSIGN_(type) \ - void operator=(type const &) = delete - -// A macro to disallow copy constructor and operator= -// This should be used in the private: declarations for a class. -#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type) \ - type(type const &) = delete; \ - GTEST_DISALLOW_ASSIGN_(type) - -// Tell the compiler to warn about unused return values for functions declared -// with this macro. The macro should be used on function declarations -// following the argument list: -// -// Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; -#if defined(__GNUC__) && !defined(COMPILER_ICC) -# define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) -#else -# define GTEST_MUST_USE_RESULT_ -#endif // __GNUC__ && !COMPILER_ICC - -// MS C++ compiler emits warning when a conditional expression is compile time -// constant. In some contexts this warning is false positive and needs to be -// suppressed. Use the following two macros in such cases: -// -// GTEST_INTENTIONAL_CONST_COND_PUSH_() -// while (true) { -// GTEST_INTENTIONAL_CONST_COND_POP_() -// } -# define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) -# define GTEST_INTENTIONAL_CONST_COND_POP_() \ - GTEST_DISABLE_MSC_WARNINGS_POP_() - -// Determine whether the compiler supports Microsoft's Structured Exception -// Handling. This is supported by several Windows compilers but generally -// does not exist on any other system. -#ifndef GTEST_HAS_SEH -// The user didn't tell us, so we need to figure it out. - -# if defined(_MSC_VER) || defined(__BORLANDC__) -// These two compilers are known to support SEH. -# define GTEST_HAS_SEH 1 -# else -// Assume no SEH. -# define GTEST_HAS_SEH 0 -# endif - -#endif // GTEST_HAS_SEH - -#ifndef GTEST_IS_THREADSAFE - -#define GTEST_IS_THREADSAFE \ - (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ || \ - (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \ - GTEST_HAS_PTHREAD) - -#endif // GTEST_IS_THREADSAFE - -// GTEST_API_ qualifies all symbols that must be exported. The definitions below -// are guarded by #ifndef to give embedders a chance to define GTEST_API_ in -// gtest/internal/custom/gtest-port.h -#ifndef GTEST_API_ - -#ifdef _MSC_VER -# if GTEST_LINKED_AS_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllimport) -# elif GTEST_CREATE_SHARED_LIBRARY -# define GTEST_API_ __declspec(dllexport) -# endif -#elif __GNUC__ >= 4 || defined(__clang__) -# define GTEST_API_ __attribute__((visibility ("default"))) -#endif // _MSC_VER - -#endif // GTEST_API_ - -#ifndef GTEST_API_ -# define GTEST_API_ -#endif // GTEST_API_ - -#ifndef GTEST_DEFAULT_DEATH_TEST_STYLE -# define GTEST_DEFAULT_DEATH_TEST_STYLE "fast" -#endif // GTEST_DEFAULT_DEATH_TEST_STYLE - -#ifdef __GNUC__ -// Ask the compiler to never inline a given function. -# define GTEST_NO_INLINE_ __attribute__((noinline)) -#else -# define GTEST_NO_INLINE_ -#endif - -// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. -#if !defined(GTEST_HAS_CXXABI_H_) -# if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER)) -# define GTEST_HAS_CXXABI_H_ 1 -# else -# define GTEST_HAS_CXXABI_H_ 0 -# endif -#endif - -// A function level attribute to disable checking for use of uninitialized -// memory when built with MemorySanitizer. -#if defined(__clang__) -# if __has_feature(memory_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ - __attribute__((no_sanitize_memory)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -# endif // __has_feature(memory_sanitizer) -#else -# define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ -#endif // __clang__ - -// A function level attribute to disable AddressSanitizer instrumentation. -#if defined(__clang__) -# if __has_feature(address_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ - __attribute__((no_sanitize_address)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -# endif // __has_feature(address_sanitizer) -#else -# define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ -#endif // __clang__ - -// A function level attribute to disable HWAddressSanitizer instrumentation. -#if defined(__clang__) -# if __has_feature(hwaddress_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \ - __attribute__((no_sanitize("hwaddress"))) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -# endif // __has_feature(hwaddress_sanitizer) -#else -# define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ -#endif // __clang__ - -// A function level attribute to disable ThreadSanitizer instrumentation. -#if defined(__clang__) -# if __has_feature(thread_sanitizer) -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ - __attribute__((no_sanitize_thread)) -# else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -# endif // __has_feature(thread_sanitizer) -#else -# define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ -#endif // __clang__ - -namespace testing { - -class Message; - -// Legacy imports for backwards compatibility. -// New code should use std:: names directly. -using std::get; -using std::make_tuple; -using std::tuple; -using std::tuple_element; -using std::tuple_size; - -namespace internal { - -// A secret type that Google Test users don't know about. It has no -// definition on purpose. Therefore it's impossible to create a -// Secret object, which is what we want. -class Secret; - -// The GTEST_COMPILE_ASSERT_ is a legacy macro used to verify that a compile -// time expression is true (in new code, use static_assert instead). For -// example, you could use it to verify the size of a static array: -// -// GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, -// names_incorrect_size); -// -// The second argument to the macro must be a valid C++ identifier. If the -// expression is false, compiler will issue an error containing this identifier. -#define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) - -// Evaluates to the number of elements in 'array'. -#define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) - -// A helper for suppressing warnings on constant condition. It just -// returns 'condition'. -GTEST_API_ bool IsTrue(bool condition); - -// Defines RE. - -#if GTEST_USES_PCRE -// if used, PCRE is injected by custom/gtest-port.h -#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE - -// A simple C++ wrapper for . It uses the POSIX Extended -// Regular Expression syntax. -class GTEST_API_ RE { - public: - // A copy constructor is required by the Standard to initialize object - // references from r-values. - RE(const RE& other) { Init(other.pattern()); } - - // Constructs an RE from a string. - RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT - - RE(const char* regex) { Init(regex); } // NOLINT - ~RE(); - - // Returns the string representation of the regex. - const char* pattern() const { return pattern_; } - - // FullMatch(str, re) returns true if and only if regular expression re - // matches the entire str. - // PartialMatch(str, re) returns true if and only if regular expression re - // matches a substring of str (including str itself). - static bool FullMatch(const ::std::string& str, const RE& re) { - return FullMatch(str.c_str(), re); - } - static bool PartialMatch(const ::std::string& str, const RE& re) { - return PartialMatch(str.c_str(), re); - } - - static bool FullMatch(const char* str, const RE& re); - static bool PartialMatch(const char* str, const RE& re); - - private: - void Init(const char* regex); - const char* pattern_; - bool is_valid_; - -# if GTEST_USES_POSIX_RE - - regex_t full_regex_; // For FullMatch(). - regex_t partial_regex_; // For PartialMatch(). - -# else // GTEST_USES_SIMPLE_RE - - const char* full_pattern_; // For FullMatch(); - -# endif - - GTEST_DISALLOW_ASSIGN_(RE); -}; - -#endif // GTEST_USES_PCRE - -// Formats a source file path and a line number as they would appear -// in an error message from the compiler used to compile this code. -GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); - -// Formats a file location for compiler-independent XML output. -// Although this function is not platform dependent, we put it next to -// FormatFileLocation in order to contrast the two functions. -GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, - int line); - -// Defines logging utilities: -// GTEST_LOG_(severity) - logs messages at the specified severity level. The -// message itself is streamed into the macro. -// LogToStderr() - directs all log messages to stderr. -// FlushInfoLog() - flushes informational log messages. - -enum GTestLogSeverity { - GTEST_INFO, - GTEST_WARNING, - GTEST_ERROR, - GTEST_FATAL -}; - -// Formats log entry severity, provides a stream object for streaming the -// log message, and terminates the message with a newline when going out of -// scope. -class GTEST_API_ GTestLog { - public: - GTestLog(GTestLogSeverity severity, const char* file, int line); - - // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. - ~GTestLog(); - - ::std::ostream& GetStream() { return ::std::cerr; } - - private: - const GTestLogSeverity severity_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); -}; - -#if !defined(GTEST_LOG_) - -# define GTEST_LOG_(severity) \ - ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ - __FILE__, __LINE__).GetStream() - -inline void LogToStderr() {} -inline void FlushInfoLog() { fflush(nullptr); } - -#endif // !defined(GTEST_LOG_) - -#if !defined(GTEST_CHECK_) -// INTERNAL IMPLEMENTATION - DO NOT USE. -// -// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition -// is not satisfied. -// Synopsys: -// GTEST_CHECK_(boolean_condition); -// or -// GTEST_CHECK_(boolean_condition) << "Additional message"; -// -// This checks the condition and if the condition is not satisfied -// it prints message about the condition violation, including the -// condition itself, plus additional message streamed into it, if any, -// and then it aborts the program. It aborts the program irrespective of -// whether it is built in the debug mode or not. -# define GTEST_CHECK_(condition) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::IsTrue(condition)) \ - ; \ - else \ - GTEST_LOG_(FATAL) << "Condition " #condition " failed. " -#endif // !defined(GTEST_CHECK_) - -// An all-mode assert to verify that the given POSIX-style function -// call returns 0 (indicating success). Known limitation: this -// doesn't expand to a balanced 'if' statement, so enclose the macro -// in {} if you need to use it as the only statement in an 'if' -// branch. -#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ - if (const int gtest_error = (posix_call)) \ - GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ - << gtest_error - -// Transforms "T" into "const T&" according to standard reference collapsing -// rules (this is only needed as a backport for C++98 compilers that do not -// support reference collapsing). Specifically, it transforms: -// -// char ==> const char& -// const char ==> const char& -// char& ==> char& -// const char& ==> const char& -// -// Note that the non-const reference will not have "const" added. This is -// standard, and necessary so that "T" can always bind to "const T&". -template -struct ConstRef { typedef const T& type; }; -template -struct ConstRef { typedef T& type; }; - -// The argument T must depend on some template parameters. -#define GTEST_REFERENCE_TO_CONST_(T) \ - typename ::testing::internal::ConstRef::type - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Use ImplicitCast_ as a safe version of static_cast for upcasting in -// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a -// const Foo*). When you use ImplicitCast_, the compiler checks that -// the cast is safe. Such explicit ImplicitCast_s are necessary in -// surprisingly many situations where C++ demands an exact type match -// instead of an argument type convertable to a target type. -// -// The syntax for using ImplicitCast_ is the same as for static_cast: -// -// ImplicitCast_(expr) -// -// ImplicitCast_ would have been part of the C++ standard library, -// but the proposal was submitted too late. It will probably make -// its way into the language in the future. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., implicit_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template -inline To ImplicitCast_(To x) { return x; } - -// When you upcast (that is, cast a pointer from type Foo to type -// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts -// always succeed. When you downcast (that is, cast a pointer from -// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because -// how do you know the pointer is really of type SubclassOfFoo? It -// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, -// when you downcast, you should use this macro. In debug mode, we -// use dynamic_cast<> to double-check the downcast is legal (we die -// if it's not). In normal mode, we do the efficient static_cast<> -// instead. Thus, it's important to test in debug mode to make sure -// the cast is legal! -// This is the only place in the code we should use dynamic_cast<>. -// In particular, you SHOULDN'T be using dynamic_cast<> in order to -// do RTTI (eg code like this: -// if (dynamic_cast(foo)) HandleASubclass1Object(foo); -// if (dynamic_cast(foo)) HandleASubclass2Object(foo); -// You should design the code some other way not to need this. -// -// This relatively ugly name is intentional. It prevents clashes with -// similar functions users may have (e.g., down_cast). The internal -// namespace alone is not enough because the function can be found by ADL. -template // use like this: DownCast_(foo); -inline To DownCast_(From* f) { // so we only accept pointers - // Ensures that To is a sub-type of From *. This test is here only - // for compile-time type checking, and has no overhead in an - // optimized build at run-time, as it will be optimized away - // completely. - GTEST_INTENTIONAL_CONST_COND_PUSH_() - if (false) { - GTEST_INTENTIONAL_CONST_COND_POP_() - const To to = nullptr; - ::testing::internal::ImplicitCast_(to); - } - -#if GTEST_HAS_RTTI - // RTTI: debug mode only! - GTEST_CHECK_(f == nullptr || dynamic_cast(f) != nullptr); -#endif - return static_cast(f); -} - -// Downcasts the pointer of type Base to Derived. -// Derived must be a subclass of Base. The parameter MUST -// point to a class of type Derived, not any subclass of it. -// When RTTI is available, the function performs a runtime -// check to enforce this. -template -Derived* CheckedDowncastToActualType(Base* base) { -#if GTEST_HAS_RTTI - GTEST_CHECK_(typeid(*base) == typeid(Derived)); -#endif - -#if GTEST_HAS_DOWNCAST_ - return ::down_cast(base); -#elif GTEST_HAS_RTTI - return dynamic_cast(base); // NOLINT -#else - return static_cast(base); // Poor man's downcast. -#endif -} - -#if GTEST_HAS_STREAM_REDIRECTION - -// Defines the stderr capturer: -// CaptureStdout - starts capturing stdout. -// GetCapturedStdout - stops capturing stdout and returns the captured string. -// CaptureStderr - starts capturing stderr. -// GetCapturedStderr - stops capturing stderr and returns the captured string. -// -GTEST_API_ void CaptureStdout(); -GTEST_API_ std::string GetCapturedStdout(); -GTEST_API_ void CaptureStderr(); -GTEST_API_ std::string GetCapturedStderr(); - -#endif // GTEST_HAS_STREAM_REDIRECTION -// Returns the size (in bytes) of a file. -GTEST_API_ size_t GetFileSize(FILE* file); - -// Reads the entire content of a file as a string. -GTEST_API_ std::string ReadEntireFile(FILE* file); - -// All command line arguments. -GTEST_API_ std::vector GetArgvs(); - -#if GTEST_HAS_DEATH_TEST - -std::vector GetInjectableArgvs(); -// Deprecated: pass the args vector by value instead. -void SetInjectableArgvs(const std::vector* new_argvs); -void SetInjectableArgvs(const std::vector& new_argvs); -void ClearInjectableArgvs(); - -#endif // GTEST_HAS_DEATH_TEST - -// Defines synchronization primitives. -#if GTEST_IS_THREADSAFE -# if GTEST_HAS_PTHREAD -// Sleeps for (roughly) n milliseconds. This function is only for testing -// Google Test's own constructs. Don't use it in user tests, either -// directly or indirectly. -inline void SleepMilliseconds(int n) { - const timespec time = { - 0, // 0 seconds. - n * 1000L * 1000L, // And n ms. - }; - nanosleep(&time, nullptr); -} -# endif // GTEST_HAS_PTHREAD - -# if GTEST_HAS_NOTIFICATION_ -// Notification has already been imported into the namespace. -// Nothing to do here. - -# elif GTEST_HAS_PTHREAD -// Allows a controller thread to pause execution of newly created -// threads until notified. Instances of this class must be created -// and destroyed in the controller thread. -// -// This class is only for testing Google Test's own constructs. Do not -// use it in user tests, either directly or indirectly. -class Notification { - public: - Notification() : notified_(false) { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr)); - } - ~Notification() { - pthread_mutex_destroy(&mutex_); - } - - // Notifies all threads created with this notification to start. Must - // be called from the controller thread. - void Notify() { - pthread_mutex_lock(&mutex_); - notified_ = true; - pthread_mutex_unlock(&mutex_); - } - - // Blocks until the controller thread notifies. Must be called from a test - // thread. - void WaitForNotification() { - for (;;) { - pthread_mutex_lock(&mutex_); - const bool notified = notified_; - pthread_mutex_unlock(&mutex_); - if (notified) - break; - SleepMilliseconds(10); - } - } - - private: - pthread_mutex_t mutex_; - bool notified_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); -}; - -# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT - -GTEST_API_ void SleepMilliseconds(int n); - -// Provides leak-safe Windows kernel handle ownership. -// Used in death tests and in threading support. -class GTEST_API_ AutoHandle { - public: - // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to - // avoid including in this header file. Including is - // undesirable because it defines a lot of symbols and macros that tend to - // conflict with client code. This assumption is verified by - // WindowsTypesTest.HANDLEIsVoidStar. - typedef void* Handle; - AutoHandle(); - explicit AutoHandle(Handle handle); - - ~AutoHandle(); - - Handle Get() const; - void Reset(); - void Reset(Handle handle); - - private: - // Returns true if and only if the handle is a valid handle object that can be - // closed. - bool IsCloseable() const; - - Handle handle_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); -}; - -// Allows a controller thread to pause execution of newly created -// threads until notified. Instances of this class must be created -// and destroyed in the controller thread. -// -// This class is only for testing Google Test's own constructs. Do not -// use it in user tests, either directly or indirectly. -class GTEST_API_ Notification { - public: - Notification(); - void Notify(); - void WaitForNotification(); - - private: - AutoHandle event_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); -}; -# endif // GTEST_HAS_NOTIFICATION_ - -// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD -// defined, but we don't want to use MinGW's pthreads implementation, which -// has conformance problems with some versions of the POSIX standard. -# if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW - -// As a C-function, ThreadFuncWithCLinkage cannot be templated itself. -// Consequently, it cannot select a correct instantiation of ThreadWithParam -// in order to call its Run(). Introducing ThreadWithParamBase as a -// non-templated base class for ThreadWithParam allows us to bypass this -// problem. -class ThreadWithParamBase { - public: - virtual ~ThreadWithParamBase() {} - virtual void Run() = 0; -}; - -// pthread_create() accepts a pointer to a function type with the C linkage. -// According to the Standard (7.5/1), function types with different linkages -// are different even if they are otherwise identical. Some compilers (for -// example, SunStudio) treat them as different types. Since class methods -// cannot be defined with C-linkage we need to define a free C-function to -// pass into pthread_create(). -extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { - static_cast(thread)->Run(); - return nullptr; -} - -// Helper class for testing Google Test's multi-threading constructs. -// To use it, write: -// -// void ThreadFunc(int param) { /* Do things with param */ } -// Notification thread_can_start; -// ... -// // The thread_can_start parameter is optional; you can supply NULL. -// ThreadWithParam thread(&ThreadFunc, 5, &thread_can_start); -// thread_can_start.Notify(); -// -// These classes are only for testing Google Test's own constructs. Do -// not use them in user tests, either directly or indirectly. -template -class ThreadWithParam : public ThreadWithParamBase { - public: - typedef void UserThreadFunc(T); - - ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) - : func_(func), - param_(param), - thread_can_start_(thread_can_start), - finished_(false) { - ThreadWithParamBase* const base = this; - // The thread can be created only after all fields except thread_ - // have been initialized. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base)); - } - ~ThreadWithParam() override { Join(); } - - void Join() { - if (!finished_) { - GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr)); - finished_ = true; - } - } - - void Run() override { - if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification(); - func_(param_); - } - - private: - UserThreadFunc* const func_; // User-supplied thread function. - const T param_; // User-supplied parameter to the thread function. - // When non-NULL, used to block execution until the controller thread - // notifies. - Notification* const thread_can_start_; - bool finished_; // true if and only if we know that the thread function has - // finished. - pthread_t thread_; // The native thread object. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); -}; -# endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || - // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - -# if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ -// Mutex and ThreadLocal have already been imported into the namespace. -// Nothing to do here. - -# elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT - -// Mutex implements mutex on Windows platforms. It is used in conjunction -// with class MutexLock: -// -// Mutex mutex; -// ... -// MutexLock lock(&mutex); // Acquires the mutex and releases it at the -// // end of the current scope. -// -// A static Mutex *must* be defined or declared using one of the following -// macros: -// GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); -// GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); -// -// (A non-static Mutex is defined/declared in the usual way). -class GTEST_API_ Mutex { - public: - enum MutexType { kStatic = 0, kDynamic = 1 }; - // We rely on kStaticMutex being 0 as it is to what the linker initializes - // type_ in static mutexes. critical_section_ will be initialized lazily - // in ThreadSafeLazyInit(). - enum StaticConstructorSelector { kStaticMutex = 0 }; - - // This constructor intentionally does nothing. It relies on type_ being - // statically initialized to 0 (effectively setting it to kStatic) and on - // ThreadSafeLazyInit() to lazily initialize the rest of the members. - explicit Mutex(StaticConstructorSelector /*dummy*/) {} - - Mutex(); - ~Mutex(); - - void Lock(); - - void Unlock(); - - // Does nothing if the current thread holds the mutex. Otherwise, crashes - // with high probability. - void AssertHeld(); - - private: - // Initializes owner_thread_id_ and critical_section_ in static mutexes. - void ThreadSafeLazyInit(); - - // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503, - // we assume that 0 is an invalid value for thread IDs. - unsigned int owner_thread_id_; - - // For static mutexes, we rely on these members being initialized to zeros - // by the linker. - MutexType type_; - long critical_section_init_phase_; // NOLINT - GTEST_CRITICAL_SECTION* critical_section_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); -}; - -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex - -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) - -// We cannot name this class MutexLock because the ctor declaration would -// conflict with a macro named MutexLock, which is defined on some -// platforms. That macro is used as a defensive measure to prevent against -// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than -// "MutexLock l(&mu)". Hence the typedef trick below. -class GTestMutexLock { - public: - explicit GTestMutexLock(Mutex* mutex) - : mutex_(mutex) { mutex_->Lock(); } - - ~GTestMutexLock() { mutex_->Unlock(); } - - private: - Mutex* const mutex_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); -}; - -typedef GTestMutexLock MutexLock; - -// Base class for ValueHolder. Allows a caller to hold and delete a value -// without knowing its type. -class ThreadLocalValueHolderBase { - public: - virtual ~ThreadLocalValueHolderBase() {} -}; - -// Provides a way for a thread to send notifications to a ThreadLocal -// regardless of its parameter type. -class ThreadLocalBase { - public: - // Creates a new ValueHolder object holding a default value passed to - // this ThreadLocal's constructor and returns it. It is the caller's - // responsibility not to call this when the ThreadLocal instance already - // has a value on the current thread. - virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; - - protected: - ThreadLocalBase() {} - virtual ~ThreadLocalBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); -}; - -// Maps a thread to a set of ThreadLocals that have values instantiated on that -// thread and notifies them when the thread exits. A ThreadLocal instance is -// expected to persist until all threads it has values on have terminated. -class GTEST_API_ ThreadLocalRegistry { - public: - // Registers thread_local_instance as having value on the current thread. - // Returns a value that can be used to identify the thread from other threads. - static ThreadLocalValueHolderBase* GetValueOnCurrentThread( - const ThreadLocalBase* thread_local_instance); - - // Invoked when a ThreadLocal instance is destroyed. - static void OnThreadLocalDestroyed( - const ThreadLocalBase* thread_local_instance); -}; - -class GTEST_API_ ThreadWithParamBase { - public: - void Join(); - - protected: - class Runnable { - public: - virtual ~Runnable() {} - virtual void Run() = 0; - }; - - ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); - virtual ~ThreadWithParamBase(); - - private: - AutoHandle thread_; -}; - -// Helper class for testing Google Test's multi-threading constructs. -template -class ThreadWithParam : public ThreadWithParamBase { - public: - typedef void UserThreadFunc(T); - - ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) - : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { - } - virtual ~ThreadWithParam() {} - - private: - class RunnableImpl : public Runnable { - public: - RunnableImpl(UserThreadFunc* func, T param) - : func_(func), - param_(param) { - } - virtual ~RunnableImpl() {} - virtual void Run() { - func_(param_); - } - - private: - UserThreadFunc* const func_; - const T param_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); - }; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); -}; - -// Implements thread-local storage on Windows systems. -// -// // Thread 1 -// ThreadLocal tl(100); // 100 is the default value for each thread. -// -// // Thread 2 -// tl.set(150); // Changes the value for thread 2 only. -// EXPECT_EQ(150, tl.get()); -// -// // Thread 1 -// EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. -// tl.set(200); -// EXPECT_EQ(200, tl.get()); -// -// The template type argument T must have a public copy constructor. -// In addition, the default ThreadLocal constructor requires T to have -// a public default constructor. -// -// The users of a TheadLocal instance have to make sure that all but one -// threads (including the main one) using that instance have exited before -// destroying it. Otherwise, the per-thread objects managed for them by the -// ThreadLocal instance are not guaranteed to be destroyed on all platforms. -// -// Google Test only uses global ThreadLocal objects. That means they -// will die after main() has returned. Therefore, no per-thread -// object managed by Google Test will be leaked as long as all threads -// using Google Test have exited when main() returns. -template -class ThreadLocal : public ThreadLocalBase { - public: - ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} - explicit ThreadLocal(const T& value) - : default_factory_(new InstanceValueHolderFactory(value)) {} - - ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } - - T* pointer() { return GetOrCreateValue(); } - const T* pointer() const { return GetOrCreateValue(); } - const T& get() const { return *pointer(); } - void set(const T& value) { *pointer() = value; } - - private: - // Holds a value of T. Can be deleted via its base class without the caller - // knowing the type of T. - class ValueHolder : public ThreadLocalValueHolderBase { - public: - ValueHolder() : value_() {} - explicit ValueHolder(const T& value) : value_(value) {} - - T* pointer() { return &value_; } - - private: - T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); - }; - - - T* GetOrCreateValue() const { - return static_cast( - ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); - } - - virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { - return default_factory_->MakeNewHolder(); - } - - class ValueHolderFactory { - public: - ValueHolderFactory() {} - virtual ~ValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const = 0; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); - }; - - class DefaultValueHolderFactory : public ValueHolderFactory { - public: - DefaultValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); - }; - - class InstanceValueHolderFactory : public ValueHolderFactory { - public: - explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { - return new ValueHolder(value_); - } - - private: - const T value_; // The value for each thread. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); - }; - - std::unique_ptr default_factory_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); -}; - -# elif GTEST_HAS_PTHREAD - -// MutexBase and Mutex implement mutex on pthreads-based platforms. -class MutexBase { - public: - // Acquires this mutex. - void Lock() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); - owner_ = pthread_self(); - has_owner_ = true; - } - - // Releases this mutex. - void Unlock() { - // Since the lock is being released the owner_ field should no longer be - // considered valid. We don't protect writing to has_owner_ here, as it's - // the caller's responsibility to ensure that the current thread holds the - // mutex when this is called. - has_owner_ = false; - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); - } - - // Does nothing if the current thread holds the mutex. Otherwise, crashes - // with high probability. - void AssertHeld() const { - GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) - << "The current thread is not holding the mutex @" << this; - } - - // A static mutex may be used before main() is entered. It may even - // be used before the dynamic initialization stage. Therefore we - // must be able to initialize a static mutex object at link time. - // This means MutexBase has to be a POD and its member variables - // have to be public. - public: - pthread_mutex_t mutex_; // The underlying pthread mutex. - // has_owner_ indicates whether the owner_ field below contains a valid thread - // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All - // accesses to the owner_ field should be protected by a check of this field. - // An alternative might be to memset() owner_ to all zeros, but there's no - // guarantee that a zero'd pthread_t is necessarily invalid or even different - // from pthread_self(). - bool has_owner_; - pthread_t owner_; // The thread holding the mutex. -}; - -// Forward-declares a static mutex. -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::MutexBase mutex - -// Defines and statically (i.e. at link time) initializes a static mutex. -// The initialization list here does not explicitly initialize each field, -// instead relying on default initialization for the unspecified fields. In -// particular, the owner_ field (a pthread_t) is not explicitly initialized. -// This allows initialization to work whether pthread_t is a scalar or struct. -// The flag -Wmissing-field-initializers must not be specified for this to work. -#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ - ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0} - -// The Mutex class can only be used for mutexes created at runtime. It -// shares its API with MutexBase otherwise. -class Mutex : public MutexBase { - public: - Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr)); - has_owner_ = false; - } - ~Mutex() { - GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); -}; - -// We cannot name this class MutexLock because the ctor declaration would -// conflict with a macro named MutexLock, which is defined on some -// platforms. That macro is used as a defensive measure to prevent against -// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than -// "MutexLock l(&mu)". Hence the typedef trick below. -class GTestMutexLock { - public: - explicit GTestMutexLock(MutexBase* mutex) - : mutex_(mutex) { mutex_->Lock(); } - - ~GTestMutexLock() { mutex_->Unlock(); } - - private: - MutexBase* const mutex_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); -}; - -typedef GTestMutexLock MutexLock; - -// Helpers for ThreadLocal. - -// pthread_key_create() requires DeleteThreadLocalValue() to have -// C-linkage. Therefore it cannot be templatized to access -// ThreadLocal. Hence the need for class -// ThreadLocalValueHolderBase. -class ThreadLocalValueHolderBase { - public: - virtual ~ThreadLocalValueHolderBase() {} -}; - -// Called by pthread to delete thread-local data stored by -// pthread_setspecific(). -extern "C" inline void DeleteThreadLocalValue(void* value_holder) { - delete static_cast(value_holder); -} - -// Implements thread-local storage on pthreads-based systems. -template -class GTEST_API_ ThreadLocal { - public: - ThreadLocal() - : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} - explicit ThreadLocal(const T& value) - : key_(CreateKey()), - default_factory_(new InstanceValueHolderFactory(value)) {} - - ~ThreadLocal() { - // Destroys the managed object for the current thread, if any. - DeleteThreadLocalValue(pthread_getspecific(key_)); - - // Releases resources associated with the key. This will *not* - // delete managed objects for other threads. - GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); - } - - T* pointer() { return GetOrCreateValue(); } - const T* pointer() const { return GetOrCreateValue(); } - const T& get() const { return *pointer(); } - void set(const T& value) { *pointer() = value; } - - private: - // Holds a value of type T. - class ValueHolder : public ThreadLocalValueHolderBase { - public: - ValueHolder() : value_() {} - explicit ValueHolder(const T& value) : value_(value) {} - - T* pointer() { return &value_; } - - private: - T value_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); - }; - - static pthread_key_t CreateKey() { - pthread_key_t key; - // When a thread exits, DeleteThreadLocalValue() will be called on - // the object managed for that thread. - GTEST_CHECK_POSIX_SUCCESS_( - pthread_key_create(&key, &DeleteThreadLocalValue)); - return key; - } - - T* GetOrCreateValue() const { - ThreadLocalValueHolderBase* const holder = - static_cast(pthread_getspecific(key_)); - if (holder != nullptr) { - return CheckedDowncastToActualType(holder)->pointer(); - } - - ValueHolder* const new_holder = default_factory_->MakeNewHolder(); - ThreadLocalValueHolderBase* const holder_base = new_holder; - GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); - return new_holder->pointer(); - } - - class ValueHolderFactory { - public: - ValueHolderFactory() {} - virtual ~ValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const = 0; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); - }; - - class DefaultValueHolderFactory : public ValueHolderFactory { - public: - DefaultValueHolderFactory() {} - virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); - }; - - class InstanceValueHolderFactory : public ValueHolderFactory { - public: - explicit InstanceValueHolderFactory(const T& value) : value_(value) {} - virtual ValueHolder* MakeNewHolder() const { - return new ValueHolder(value_); - } - - private: - const T value_; // The value for each thread. - - GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); - }; - - // A key pthreads uses for looking up per-thread values. - const pthread_key_t key_; - std::unique_ptr default_factory_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); -}; - -# endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - -#else // GTEST_IS_THREADSAFE - -// A dummy implementation of synchronization primitives (mutex, lock, -// and thread-local variable). Necessary for compiling Google Test where -// mutex is not supported - using Google Test in multiple threads is not -// supported on such platforms. - -class Mutex { - public: - Mutex() {} - void Lock() {} - void Unlock() {} - void AssertHeld() const {} -}; - -# define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ - extern ::testing::internal::Mutex mutex - -# define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex - -// We cannot name this class MutexLock because the ctor declaration would -// conflict with a macro named MutexLock, which is defined on some -// platforms. That macro is used as a defensive measure to prevent against -// inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than -// "MutexLock l(&mu)". Hence the typedef trick below. -class GTestMutexLock { - public: - explicit GTestMutexLock(Mutex*) {} // NOLINT -}; - -typedef GTestMutexLock MutexLock; - -template -class GTEST_API_ ThreadLocal { - public: - ThreadLocal() : value_() {} - explicit ThreadLocal(const T& value) : value_(value) {} - T* pointer() { return &value_; } - const T* pointer() const { return &value_; } - const T& get() const { return value_; } - void set(const T& value) { value_ = value; } - private: - T value_; -}; - -#endif // GTEST_IS_THREADSAFE - -// Returns the number of threads running in the process, or 0 to indicate that -// we cannot detect it. -GTEST_API_ size_t GetThreadCount(); - -template -using bool_constant = std::integral_constant; - -#if GTEST_OS_WINDOWS -# define GTEST_PATH_SEP_ "\\" -# define GTEST_HAS_ALT_PATH_SEP_ 1 -// The biggest signed integer type the compiler supports. -typedef __int64 BiggestInt; -#else -# define GTEST_PATH_SEP_ "/" -# define GTEST_HAS_ALT_PATH_SEP_ 0 -typedef long long BiggestInt; // NOLINT -#endif // GTEST_OS_WINDOWS - -// Utilities for char. - -// isspace(int ch) and friends accept an unsigned char or EOF. char -// may be signed, depending on the compiler (or compiler flags). -// Therefore we need to cast a char to unsigned char before calling -// isspace(), etc. - -inline bool IsAlpha(char ch) { - return isalpha(static_cast(ch)) != 0; -} -inline bool IsAlNum(char ch) { - return isalnum(static_cast(ch)) != 0; -} -inline bool IsDigit(char ch) { - return isdigit(static_cast(ch)) != 0; -} -inline bool IsLower(char ch) { - return islower(static_cast(ch)) != 0; -} -inline bool IsSpace(char ch) { - return isspace(static_cast(ch)) != 0; -} -inline bool IsUpper(char ch) { - return isupper(static_cast(ch)) != 0; -} -inline bool IsXDigit(char ch) { - return isxdigit(static_cast(ch)) != 0; -} -inline bool IsXDigit(wchar_t ch) { - const unsigned char low_byte = static_cast(ch); - return ch == low_byte && isxdigit(low_byte) != 0; -} - -inline char ToLower(char ch) { - return static_cast(tolower(static_cast(ch))); -} -inline char ToUpper(char ch) { - return static_cast(toupper(static_cast(ch))); -} - -inline std::string StripTrailingSpaces(std::string str) { - std::string::iterator it = str.end(); - while (it != str.begin() && IsSpace(*--it)) - it = str.erase(it); - return str; -} - -// The testing::internal::posix namespace holds wrappers for common -// POSIX functions. These wrappers hide the differences between -// Windows/MSVC and POSIX systems. Since some compilers define these -// standard functions as macros, the wrapper cannot have the same name -// as the wrapped function. - -namespace posix { - -// Functions with a different name on Windows. - -#if GTEST_OS_WINDOWS - -typedef struct _stat StatStruct; - -# ifdef __BORLANDC__ -inline int IsATTY(int fd) { return isatty(fd); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return stricmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } -# else // !__BORLANDC__ -# if GTEST_OS_WINDOWS_MOBILE -inline int IsATTY(int /* fd */) { return 0; } -# else -inline int IsATTY(int fd) { return _isatty(fd); } -# endif // GTEST_OS_WINDOWS_MOBILE -inline int StrCaseCmp(const char* s1, const char* s2) { - return _stricmp(s1, s2); -} -inline char* StrDup(const char* src) { return _strdup(src); } -# endif // __BORLANDC__ - -# if GTEST_OS_WINDOWS_MOBILE -inline int FileNo(FILE* file) { return reinterpret_cast(_fileno(file)); } -// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this -// time and thus not defined there. -# else -inline int FileNo(FILE* file) { return _fileno(file); } -inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } -inline int RmDir(const char* dir) { return _rmdir(dir); } -inline bool IsDir(const StatStruct& st) { - return (_S_IFDIR & st.st_mode) != 0; -} -# endif // GTEST_OS_WINDOWS_MOBILE - -#else - -typedef struct stat StatStruct; - -inline int FileNo(FILE* file) { return fileno(file); } -inline int IsATTY(int fd) { return isatty(fd); } -inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } -inline int StrCaseCmp(const char* s1, const char* s2) { - return strcasecmp(s1, s2); -} -inline char* StrDup(const char* src) { return strdup(src); } -inline int RmDir(const char* dir) { return rmdir(dir); } -inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } - -#endif // GTEST_OS_WINDOWS - -// Functions deprecated by MSVC 8.0. - -GTEST_DISABLE_MSC_DEPRECATED_PUSH_() - -inline const char* StrNCpy(char* dest, const char* src, size_t n) { - return strncpy(dest, src, n); -} - -// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and -// StrError() aren't needed on Windows CE at this time and thus not -// defined there. - -#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT -inline int ChDir(const char* dir) { return chdir(dir); } -#endif -inline FILE* FOpen(const char* path, const char* mode) { - return fopen(path, mode); -} -#if !GTEST_OS_WINDOWS_MOBILE -inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { - return freopen(path, mode, stream); -} -inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } -#endif -inline int FClose(FILE* fp) { return fclose(fp); } -#if !GTEST_OS_WINDOWS_MOBILE -inline int Read(int fd, void* buf, unsigned int count) { - return static_cast(read(fd, buf, count)); -} -inline int Write(int fd, const void* buf, unsigned int count) { - return static_cast(write(fd, buf, count)); -} -inline int Close(int fd) { return close(fd); } -inline const char* StrError(int errnum) { return strerror(errnum); } -#endif -inline const char* GetEnv(const char* name) { -#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT - // We are on Windows CE, which has no environment variables. - static_cast(name); // To prevent 'unused argument' warning. - return nullptr; -#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) - // Environment variables which we programmatically clear will be set to the - // empty string rather than unset (NULL). Handle that case. - const char* const env = getenv(name); - return (env != nullptr && env[0] != '\0') ? env : nullptr; -#else - return getenv(name); -#endif -} - -GTEST_DISABLE_MSC_DEPRECATED_POP_() - -#if GTEST_OS_WINDOWS_MOBILE -// Windows CE has no C library. The abort() function is used in -// several places in Google Test. This implementation provides a reasonable -// imitation of standard behaviour. -[[noreturn]] void Abort(); -#else -[[noreturn]] inline void Abort() { abort(); } -#endif // GTEST_OS_WINDOWS_MOBILE - -} // namespace posix - -// MSVC "deprecates" snprintf and issues warnings wherever it is used. In -// order to avoid these warnings, we need to use _snprintf or _snprintf_s on -// MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate -// function in order to achieve that. We use macro definition here because -// snprintf is a variadic function. -#if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE -// MSVC 2005 and above support variadic macros. -# define GTEST_SNPRINTF_(buffer, size, format, ...) \ - _snprintf_s(buffer, size, size, format, __VA_ARGS__) -#elif defined(_MSC_VER) -// Windows CE does not define _snprintf_s -# define GTEST_SNPRINTF_ _snprintf -#else -# define GTEST_SNPRINTF_ snprintf -#endif - -// The maximum number a BiggestInt can represent. This definition -// works no matter BiggestInt is represented in one's complement or -// two's complement. -// -// We cannot rely on numeric_limits in STL, as __int64 and long long -// are not part of standard C++ and numeric_limits doesn't need to be -// defined for them. -const BiggestInt kMaxBiggestInt = - ~(static_cast(1) << (8*sizeof(BiggestInt) - 1)); - -// This template class serves as a compile-time function from size to -// type. It maps a size in bytes to a primitive type with that -// size. e.g. -// -// TypeWithSize<4>::UInt -// -// is typedef-ed to be unsigned int (unsigned integer made up of 4 -// bytes). -// -// Such functionality should belong to STL, but I cannot find it -// there. -// -// Google Test uses this class in the implementation of floating-point -// comparison. -// -// For now it only handles UInt (unsigned int) as that's all Google Test -// needs. Other types can be easily added in the future if need -// arises. -template -class TypeWithSize { - public: - // This prevents the user from using TypeWithSize with incorrect - // values of N. - typedef void UInt; -}; - -// The specialization for size 4. -template <> -class TypeWithSize<4> { - public: - // unsigned int has size 4 in both gcc and MSVC. - // - // As base/basictypes.h doesn't compile on Windows, we cannot use - // uint32, uint64, and etc here. - typedef int Int; - typedef unsigned int UInt; -}; - -// The specialization for size 8. -template <> -class TypeWithSize<8> { - public: -#if GTEST_OS_WINDOWS - typedef __int64 Int; - typedef unsigned __int64 UInt; -#else - typedef long long Int; // NOLINT - typedef unsigned long long UInt; // NOLINT -#endif // GTEST_OS_WINDOWS -}; - -// Integer types of known sizes. -typedef TypeWithSize<4>::Int Int32; -typedef TypeWithSize<4>::UInt UInt32; -typedef TypeWithSize<8>::Int Int64; -typedef TypeWithSize<8>::UInt UInt64; -typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. - -// Utilities for command line flags and environment variables. - -// Macro for referencing flags. -#if !defined(GTEST_FLAG) -# define GTEST_FLAG(name) FLAGS_gtest_##name -#endif // !defined(GTEST_FLAG) - -#if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) -# define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 -#endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) - -#if !defined(GTEST_DECLARE_bool_) -# define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver - -// Macros for declaring flags. -# define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) -# define GTEST_DECLARE_int32_(name) \ - GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) -# define GTEST_DECLARE_string_(name) \ - GTEST_API_ extern ::std::string GTEST_FLAG(name) - -// Macros for defining flags. -# define GTEST_DEFINE_bool_(name, default_val, doc) \ - GTEST_API_ bool GTEST_FLAG(name) = (default_val) -# define GTEST_DEFINE_int32_(name, default_val, doc) \ - GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) -# define GTEST_DEFINE_string_(name, default_val, doc) \ - GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) - -#endif // !defined(GTEST_DECLARE_bool_) - -// Thread annotations -#if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) -# define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) -# define GTEST_LOCK_EXCLUDED_(locks) -#endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) - -// Parses 'str' for a 32-bit signed integer. If successful, writes the result -// to *value and returns true; otherwise leaves *value unchanged and returns -// false. -bool ParseInt32(const Message& src_text, const char* str, Int32* value); - -// Parses a bool/Int32/string from the environment variable -// corresponding to the given Google Test flag. -bool BoolFromGTestEnv(const char* flag, bool default_val); -GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); -std::string OutputFlagAlsoCheckEnvVar(); -const char* StringFromGTestEnv(const char* flag, const char* default_val); - -} // namespace internal -} // namespace testing - -#if !defined(GTEST_INTERNAL_DEPRECATED) - -// Internal Macro to mark an API deprecated, for googletest usage only -// Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or -// GTEST_INTERNAL_DEPRECATED(message) myFunction(); Every usage of -// a deprecated entity will trigger a warning when compiled with -// `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler). -// For msvc /W3 option will need to be used -// Note that for 'other' compilers this macro evaluates to nothing to prevent -// compilations errors. -#if defined(_MSC_VER) -#define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message)) -#elif defined(__GNUC__) -#define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message))) -#else -#define GTEST_INTERNAL_DEPRECATED(message) -#endif - -#endif // !defined(GTEST_INTERNAL_DEPRECATED) - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ - -#if GTEST_OS_LINUX -# include -# include -# include -# include -#endif // GTEST_OS_LINUX - -#if GTEST_HAS_EXCEPTIONS -# include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file defines the Message class. -// -// IMPORTANT NOTE: Due to limitation of the C++ language, we have to -// leave some internal implementation details in this header file. -// They are clearly marked by comments like this: -// -// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -// -// Such code is NOT meant to be used by a user directly, and is subject -// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user -// program! - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ -#define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ - -#include -#include - - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -// Ensures that there is at least one operator<< in the global namespace. -// See Message& operator<<(...) below for why. -void operator<<(const testing::internal::Secret&, int); - -namespace testing { - -// The Message class works like an ostream repeater. -// -// Typical usage: -// -// 1. You stream a bunch of values to a Message object. -// It will remember the text in a stringstream. -// 2. Then you stream the Message object to an ostream. -// This causes the text in the Message to be streamed -// to the ostream. -// -// For example; -// -// testing::Message foo; -// foo << 1 << " != " << 2; -// std::cout << foo; -// -// will print "1 != 2". -// -// Message is not intended to be inherited from. In particular, its -// destructor is not virtual. -// -// Note that stringstream behaves differently in gcc and in MSVC. You -// can stream a NULL char pointer to it in the former, but not in the -// latter (it causes an access violation if you do). The Message -// class hides this difference by treating a NULL char pointer as -// "(null)". -class GTEST_API_ Message { - private: - // The type of basic IO manipulators (endl, ends, and flush) for - // narrow streams. - typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); - - public: - // Constructs an empty Message. - Message(); - - // Copy constructor. - Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT - *ss_ << msg.GetString(); - } - - // Constructs a Message from a C-string. - explicit Message(const char* str) : ss_(new ::std::stringstream) { - *ss_ << str; - } - - // Streams a non-pointer value to this object. - template - inline Message& operator <<(const T& val) { - // Some libraries overload << for STL containers. These - // overloads are defined in the global namespace instead of ::std. - // - // C++'s symbol lookup rule (i.e. Koenig lookup) says that these - // overloads are visible in either the std namespace or the global - // namespace, but not other namespaces, including the testing - // namespace which Google Test's Message class is in. - // - // To allow STL containers (and other types that has a << operator - // defined in the global namespace) to be used in Google Test - // assertions, testing::Message must access the custom << operator - // from the global namespace. With this using declaration, - // overloads of << defined in the global namespace and those - // visible via Koenig lookup are both exposed in this function. - using ::operator <<; - *ss_ << val; - return *this; - } - - // Streams a pointer value to this object. - // - // This function is an overload of the previous one. When you - // stream a pointer to a Message, this definition will be used as it - // is more specialized. (The C++ Standard, section - // [temp.func.order].) If you stream a non-pointer, then the - // previous definition will be used. - // - // The reason for this overload is that streaming a NULL pointer to - // ostream is undefined behavior. Depending on the compiler, you - // may get "0", "(nil)", "(null)", or an access violation. To - // ensure consistent result across compilers, we always treat NULL - // as "(null)". - template - inline Message& operator <<(T* const& pointer) { // NOLINT - if (pointer == nullptr) { - *ss_ << "(null)"; - } else { - *ss_ << pointer; - } - return *this; - } - - // Since the basic IO manipulators are overloaded for both narrow - // and wide streams, we have to provide this specialized definition - // of operator <<, even though its body is the same as the - // templatized version above. Without this definition, streaming - // endl or other basic IO manipulators to Message will confuse the - // compiler. - Message& operator <<(BasicNarrowIoManip val) { - *ss_ << val; - return *this; - } - - // Instead of 1/0, we want to see true/false for bool values. - Message& operator <<(bool b) { - return *this << (b ? "true" : "false"); - } - - // These two overloads allow streaming a wide C string to a Message - // using the UTF-8 encoding. - Message& operator <<(const wchar_t* wide_c_str); - Message& operator <<(wchar_t* wide_c_str); - -#if GTEST_HAS_STD_WSTRING - // Converts the given wide string to a narrow string using the UTF-8 - // encoding, and streams the result to this Message object. - Message& operator <<(const ::std::wstring& wstr); -#endif // GTEST_HAS_STD_WSTRING - - // Gets the text streamed to this object so far as an std::string. - // Each '\0' character in the buffer is replaced with "\\0". - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - std::string GetString() const; - - private: - // We'll hold the text streamed to this object here. - const std::unique_ptr< ::std::stringstream> ss_; - - // We declare (but don't implement) this to prevent the compiler - // from implementing the assignment operator. - void operator=(const Message&); -}; - -// Streams a Message to an ostream. -inline std::ostream& operator <<(std::ostream& os, const Message& sb) { - return os << sb.GetString(); -} - -namespace internal { - -// Converts a streamable value to an std::string. A NULL pointer is -// converted to "(null)". When the input value is a ::string, -// ::std::string, ::wstring, or ::std::wstring object, each NUL -// character in it is replaced with "\\0". -template -std::string StreamableToString(const T& streamable) { - return (Message() << streamable).GetString(); -} - -} // namespace internal -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -#endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Google Test filepath utilities -// -// This header file declares classes and functions used internally by -// Google Test. They are subject to change without notice. -// -// This file is #included in gtest/internal/gtest-internal.h. -// Do not include this header file separately! - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file declares the String class and functions used internally by -// Google Test. They are subject to change without notice. They should not used -// by code external to Google Test. -// -// This header file is #included by gtest-internal.h. -// It should not be #included by other files. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ - -#ifdef __BORLANDC__ -// string.h is not guaranteed to provide strcpy on C++ Builder. -# include -#endif - -#include -#include - - -namespace testing { -namespace internal { - -// String - an abstract class holding static string utilities. -class GTEST_API_ String { - public: - // Static utility methods - - // Clones a 0-terminated C string, allocating memory using new. The - // caller is responsible for deleting the return value using - // delete[]. Returns the cloned string, or NULL if the input is - // NULL. - // - // This is different from strdup() in string.h, which allocates - // memory using malloc(). - static const char* CloneCString(const char* c_str); - -#if GTEST_OS_WINDOWS_MOBILE - // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be - // able to pass strings to Win32 APIs on CE we need to convert them - // to 'Unicode', UTF-16. - - // Creates a UTF-16 wide string from the given ANSI string, allocating - // memory using new. The caller is responsible for deleting the return - // value using delete[]. Returns the wide string, or NULL if the - // input is NULL. - // - // The wide string is created using the ANSI codepage (CP_ACP) to - // match the behaviour of the ANSI versions of Win32 calls and the - // C runtime. - static LPCWSTR AnsiToUtf16(const char* c_str); - - // Creates an ANSI string from the given wide string, allocating - // memory using new. The caller is responsible for deleting the return - // value using delete[]. Returns the ANSI string, or NULL if the - // input is NULL. - // - // The returned string is created using the ANSI codepage (CP_ACP) to - // match the behaviour of the ANSI versions of Win32 calls and the - // C runtime. - static const char* Utf16ToAnsi(LPCWSTR utf16_str); -#endif - - // Compares two C strings. Returns true if and only if they have the same - // content. - // - // Unlike strcmp(), this function can handle NULL argument(s). A - // NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool CStringEquals(const char* lhs, const char* rhs); - - // Converts a wide C string to a String using the UTF-8 encoding. - // NULL will be converted to "(null)". If an error occurred during - // the conversion, "(failed to convert from wide string)" is - // returned. - static std::string ShowWideCString(const wchar_t* wide_c_str); - - // Compares two wide C strings. Returns true if and only if they have the - // same content. - // - // Unlike wcscmp(), this function can handle NULL argument(s). A - // NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); - - // Compares two C strings, ignoring case. Returns true if and only if - // they have the same content. - // - // Unlike strcasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL C string, - // including the empty string. - static bool CaseInsensitiveCStringEquals(const char* lhs, - const char* rhs); - - // Compares two wide C strings, ignoring case. Returns true if and only if - // they have the same content. - // - // Unlike wcscasecmp(), this function can handle NULL argument(s). - // A NULL C string is considered different to any non-NULL wide C string, - // including the empty string. - // NB: The implementations on different platforms slightly differ. - // On windows, this method uses _wcsicmp which compares according to LC_CTYPE - // environment variable. On GNU platform this method uses wcscasecmp - // which compares according to LC_CTYPE category of the current locale. - // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the - // current locale. - static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, - const wchar_t* rhs); - - // Returns true if and only if the given string ends with the given suffix, - // ignoring case. Any string is considered to end with an empty suffix. - static bool EndsWithCaseInsensitive( - const std::string& str, const std::string& suffix); - - // Formats an int value as "%02d". - static std::string FormatIntWidth2(int value); // "%02d" for width == 2 - - // Formats an int value as "%X". - static std::string FormatHexInt(int value); - - // Formats an int value as "%X". - static std::string FormatHexUInt32(UInt32 value); - - // Formats a byte as "%02X". - static std::string FormatByte(unsigned char value); - - private: - String(); // Not meant to be instantiated. -}; // class String - -// Gets the content of the stringstream's buffer as an std::string. Each '\0' -// character in the buffer is replaced with "\\0". -GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -namespace testing { -namespace internal { - -// FilePath - a class for file and directory pathname manipulation which -// handles platform-specific conventions (like the pathname separator). -// Used for helper functions for naming files in a directory for xml output. -// Except for Set methods, all methods are const or static, which provides an -// "immutable value object" -- useful for peace of mind. -// A FilePath with a value ending in a path separator ("like/this/") represents -// a directory, otherwise it is assumed to represent a file. In either case, -// it may or may not represent an actual file or directory in the file system. -// Names are NOT checked for syntax correctness -- no checking for illegal -// characters, malformed paths, etc. - -class GTEST_API_ FilePath { - public: - FilePath() : pathname_("") { } - FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } - - explicit FilePath(const std::string& pathname) : pathname_(pathname) { - Normalize(); - } - - FilePath& operator=(const FilePath& rhs) { - Set(rhs); - return *this; - } - - void Set(const FilePath& rhs) { - pathname_ = rhs.pathname_; - } - - const std::string& string() const { return pathname_; } - const char* c_str() const { return pathname_.c_str(); } - - // Returns the current working directory, or "" if unsuccessful. - static FilePath GetCurrentDir(); - - // Given directory = "dir", base_name = "test", number = 0, - // extension = "xml", returns "dir/test.xml". If number is greater - // than zero (e.g., 12), returns "dir/test_12.xml". - // On Windows platform, uses \ as the separator rather than /. - static FilePath MakeFileName(const FilePath& directory, - const FilePath& base_name, - int number, - const char* extension); - - // Given directory = "dir", relative_path = "test.xml", - // returns "dir/test.xml". - // On Windows, uses \ as the separator rather than /. - static FilePath ConcatPaths(const FilePath& directory, - const FilePath& relative_path); - - // Returns a pathname for a file that does not currently exist. The pathname - // will be directory/base_name.extension or - // directory/base_name_.extension if directory/base_name.extension - // already exists. The number will be incremented until a pathname is found - // that does not already exist. - // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. - // There could be a race condition if two or more processes are calling this - // function at the same time -- they could both pick the same filename. - static FilePath GenerateUniqueFileName(const FilePath& directory, - const FilePath& base_name, - const char* extension); - - // Returns true if and only if the path is "". - bool IsEmpty() const { return pathname_.empty(); } - - // If input name has a trailing separator character, removes it and returns - // the name, otherwise return the name string unmodified. - // On Windows platform, uses \ as the separator, other platforms use /. - FilePath RemoveTrailingPathSeparator() const; - - // Returns a copy of the FilePath with the directory part removed. - // Example: FilePath("path/to/file").RemoveDirectoryName() returns - // FilePath("file"). If there is no directory part ("just_a_file"), it returns - // the FilePath unmodified. If there is no file part ("just_a_dir/") it - // returns an empty FilePath (""). - // On Windows platform, '\' is the path separator, otherwise it is '/'. - FilePath RemoveDirectoryName() const; - - // RemoveFileName returns the directory path with the filename removed. - // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". - // If the FilePath is "a_file" or "/a_file", RemoveFileName returns - // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does - // not have a file, like "just/a/dir/", it returns the FilePath unmodified. - // On Windows platform, '\' is the path separator, otherwise it is '/'. - FilePath RemoveFileName() const; - - // Returns a copy of the FilePath with the case-insensitive extension removed. - // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns - // FilePath("dir/file"). If a case-insensitive extension is not - // found, returns a copy of the original FilePath. - FilePath RemoveExtension(const char* extension) const; - - // Creates directories so that path exists. Returns true if successful or if - // the directories already exist; returns false if unable to create - // directories for any reason. Will also return false if the FilePath does - // not represent a directory (that is, it doesn't end with a path separator). - bool CreateDirectoriesRecursively() const; - - // Create the directory so that path exists. Returns true if successful or - // if the directory already exists; returns false if unable to create the - // directory for any reason, including if the parent directory does not - // exist. Not named "CreateDirectory" because that's a macro on Windows. - bool CreateFolder() const; - - // Returns true if FilePath describes something in the file-system, - // either a file, directory, or whatever, and that something exists. - bool FileOrDirectoryExists() const; - - // Returns true if pathname describes a directory in the file-system - // that exists. - bool DirectoryExists() const; - - // Returns true if FilePath ends with a path separator, which indicates that - // it is intended to represent a directory. Returns false otherwise. - // This does NOT check that a directory (or file) actually exists. - bool IsDirectory() const; - - // Returns true if pathname describes a root directory. (Windows has one - // root directory per disk drive.) - bool IsRootDirectory() const; - - // Returns true if pathname describes an absolute path. - bool IsAbsolutePath() const; - - private: - // Replaces multiple consecutive separators with a single separator. - // For example, "bar///foo" becomes "bar/foo". Does not eliminate other - // redundancies that might be in a pathname involving "." or "..". - // - // A pathname with multiple consecutive separators may occur either through - // user error or as a result of some scripts or APIs that generate a pathname - // with a trailing separator. On other platforms the same API or script - // may NOT generate a pathname with a trailing "/". Then elsewhere that - // pathname may have another "/" and pathname components added to it, - // without checking for the separator already being there. - // The script language and operating system may allow paths like "foo//bar" - // but some of the functions in FilePath will not handle that correctly. In - // particular, RemoveTrailingPathSeparator() only removes one separator, and - // it is called in CreateDirectoriesRecursively() assuming that it will change - // a pathname from directory syntax (trailing separator) to filename syntax. - // - // On Windows this method also replaces the alternate path separator '/' with - // the primary path separator '\\', so that for example "bar\\/\\foo" becomes - // "bar\\foo". - - void Normalize(); - - // Returns a pointer to the last occurence of a valid path separator in - // the FilePath. On Windows, for example, both '/' and '\' are valid path - // separators. Returns NULL if no path separator was found. - const char* FindLastPathSeparator() const; - - std::string pathname_; -}; // class FilePath - -} // namespace internal -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ -// This file was GENERATED by command: -// pump.py gtest-type-util.h.pump -// DO NOT EDIT BY HAND!!! - -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Type utilities needed for implementing typed and type-parameterized -// tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// Currently we support at most 50 types in a list, and at most 50 -// type-parameterized tests in one type-parameterized test suite. -// Please contact googletestframework@googlegroups.com if you need -// more. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - - -// #ifdef __GNUC__ is too general here. It is possible to use gcc without using -// libstdc++ (which is where cxxabi.h comes from). -# if GTEST_HAS_CXXABI_H_ -# include -# elif defined(__HP_aCC) -# include -# endif // GTEST_HASH_CXXABI_H_ - -namespace testing { -namespace internal { - -// Canonicalizes a given name with respect to the Standard C++ Library. -// This handles removing the inline namespace within `std` that is -// used by various standard libraries (e.g., `std::__1`). Names outside -// of namespace std are returned unmodified. -inline std::string CanonicalizeForStdLibVersioning(std::string s) { - static const char prefix[] = "std::__"; - if (s.compare(0, strlen(prefix), prefix) == 0) { - std::string::size_type end = s.find("::", strlen(prefix)); - if (end != s.npos) { - // Erase everything between the initial `std` and the second `::`. - s.erase(strlen("std"), end - strlen("std")); - } - } - return s; -} - -// GetTypeName() returns a human-readable name of type T. -// NB: This function is also used in Google Mock, so don't move it inside of -// the typed-test-only section below. -template -std::string GetTypeName() { -# if GTEST_HAS_RTTI - - const char* const name = typeid(T).name(); -# if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) - int status = 0; - // gcc's implementation of typeid(T).name() mangles the type name, - // so we have to demangle it. -# if GTEST_HAS_CXXABI_H_ - using abi::__cxa_demangle; -# endif // GTEST_HAS_CXXABI_H_ - char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status); - const std::string name_str(status == 0 ? readable_name : name); - free(readable_name); - return CanonicalizeForStdLibVersioning(name_str); -# else - return name; -# endif // GTEST_HAS_CXXABI_H_ || __HP_aCC - -# else - - return ""; - -# endif // GTEST_HAS_RTTI -} - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// A unique type used as the default value for the arguments of class -// template Types. This allows us to simulate variadic templates -// (e.g. Types, Type, and etc), which C++ doesn't -// support directly. -struct None {}; - -// The following family of struct and struct templates are used to -// represent type lists. In particular, TypesN -// represents a type list with N types (T1, T2, ..., and TN) in it. -// Except for Types0, every struct in the family has two member types: -// Head for the first type in the list, and Tail for the rest of the -// list. - -// The empty type list. -struct Types0 {}; - -// Type lists of length 1, 2, 3, and so on. - -template -struct Types1 { - typedef T1 Head; - typedef Types0 Tail; -}; -template -struct Types2 { - typedef T1 Head; - typedef Types1 Tail; -}; - -template -struct Types3 { - typedef T1 Head; - typedef Types2 Tail; -}; - -template -struct Types4 { - typedef T1 Head; - typedef Types3 Tail; -}; - -template -struct Types5 { - typedef T1 Head; - typedef Types4 Tail; -}; - -template -struct Types6 { - typedef T1 Head; - typedef Types5 Tail; -}; - -template -struct Types7 { - typedef T1 Head; - typedef Types6 Tail; -}; - -template -struct Types8 { - typedef T1 Head; - typedef Types7 Tail; -}; - -template -struct Types9 { - typedef T1 Head; - typedef Types8 Tail; -}; - -template -struct Types10 { - typedef T1 Head; - typedef Types9 Tail; -}; - -template -struct Types11 { - typedef T1 Head; - typedef Types10 Tail; -}; - -template -struct Types12 { - typedef T1 Head; - typedef Types11 Tail; -}; - -template -struct Types13 { - typedef T1 Head; - typedef Types12 Tail; -}; - -template -struct Types14 { - typedef T1 Head; - typedef Types13 Tail; -}; - -template -struct Types15 { - typedef T1 Head; - typedef Types14 Tail; -}; - -template -struct Types16 { - typedef T1 Head; - typedef Types15 Tail; -}; - -template -struct Types17 { - typedef T1 Head; - typedef Types16 Tail; -}; - -template -struct Types18 { - typedef T1 Head; - typedef Types17 Tail; -}; - -template -struct Types19 { - typedef T1 Head; - typedef Types18 Tail; -}; - -template -struct Types20 { - typedef T1 Head; - typedef Types19 Tail; -}; - -template -struct Types21 { - typedef T1 Head; - typedef Types20 Tail; -}; - -template -struct Types22 { - typedef T1 Head; - typedef Types21 Tail; -}; - -template -struct Types23 { - typedef T1 Head; - typedef Types22 Tail; -}; - -template -struct Types24 { - typedef T1 Head; - typedef Types23 Tail; -}; - -template -struct Types25 { - typedef T1 Head; - typedef Types24 Tail; -}; - -template -struct Types26 { - typedef T1 Head; - typedef Types25 Tail; -}; - -template -struct Types27 { - typedef T1 Head; - typedef Types26 Tail; -}; - -template -struct Types28 { - typedef T1 Head; - typedef Types27 Tail; -}; - -template -struct Types29 { - typedef T1 Head; - typedef Types28 Tail; -}; - -template -struct Types30 { - typedef T1 Head; - typedef Types29 Tail; -}; - -template -struct Types31 { - typedef T1 Head; - typedef Types30 Tail; -}; - -template -struct Types32 { - typedef T1 Head; - typedef Types31 Tail; -}; - -template -struct Types33 { - typedef T1 Head; - typedef Types32 Tail; -}; - -template -struct Types34 { - typedef T1 Head; - typedef Types33 Tail; -}; - -template -struct Types35 { - typedef T1 Head; - typedef Types34 Tail; -}; - -template -struct Types36 { - typedef T1 Head; - typedef Types35 Tail; -}; - -template -struct Types37 { - typedef T1 Head; - typedef Types36 Tail; -}; - -template -struct Types38 { - typedef T1 Head; - typedef Types37 Tail; -}; - -template -struct Types39 { - typedef T1 Head; - typedef Types38 Tail; -}; - -template -struct Types40 { - typedef T1 Head; - typedef Types39 Tail; -}; - -template -struct Types41 { - typedef T1 Head; - typedef Types40 Tail; -}; - -template -struct Types42 { - typedef T1 Head; - typedef Types41 Tail; -}; - -template -struct Types43 { - typedef T1 Head; - typedef Types42 Tail; -}; - -template -struct Types44 { - typedef T1 Head; - typedef Types43 Tail; -}; - -template -struct Types45 { - typedef T1 Head; - typedef Types44 Tail; -}; - -template -struct Types46 { - typedef T1 Head; - typedef Types45 Tail; -}; - -template -struct Types47 { - typedef T1 Head; - typedef Types46 Tail; -}; - -template -struct Types48 { - typedef T1 Head; - typedef Types47 Tail; -}; - -template -struct Types49 { - typedef T1 Head; - typedef Types48 Tail; -}; - -template -struct Types50 { - typedef T1 Head; - typedef Types49 Tail; -}; - - -} // namespace internal - -// We don't want to require the users to write TypesN<...> directly, -// as that would require them to count the length. Types<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Types -// will appear as Types in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Types, and Google Test will translate -// that to TypesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Types template. -template -struct Types { - typedef internal::Types50 type; -}; - -template <> -struct Types { - typedef internal::Types0 type; -}; -template -struct Types { - typedef internal::Types1 type; -}; -template -struct Types { - typedef internal::Types2 type; -}; -template -struct Types { - typedef internal::Types3 type; -}; -template -struct Types { - typedef internal::Types4 type; -}; -template -struct Types { - typedef internal::Types5 type; -}; -template -struct Types { - typedef internal::Types6 type; -}; -template -struct Types { - typedef internal::Types7 type; -}; -template -struct Types { - typedef internal::Types8 type; -}; -template -struct Types { - typedef internal::Types9 type; -}; -template -struct Types { - typedef internal::Types10 type; -}; -template -struct Types { - typedef internal::Types11 type; -}; -template -struct Types { - typedef internal::Types12 type; -}; -template -struct Types { - typedef internal::Types13 type; -}; -template -struct Types { - typedef internal::Types14 type; -}; -template -struct Types { - typedef internal::Types15 type; -}; -template -struct Types { - typedef internal::Types16 type; -}; -template -struct Types { - typedef internal::Types17 type; -}; -template -struct Types { - typedef internal::Types18 type; -}; -template -struct Types { - typedef internal::Types19 type; -}; -template -struct Types { - typedef internal::Types20 type; -}; -template -struct Types { - typedef internal::Types21 type; -}; -template -struct Types { - typedef internal::Types22 type; -}; -template -struct Types { - typedef internal::Types23 type; -}; -template -struct Types { - typedef internal::Types24 type; -}; -template -struct Types { - typedef internal::Types25 type; -}; -template -struct Types { - typedef internal::Types26 type; -}; -template -struct Types { - typedef internal::Types27 type; -}; -template -struct Types { - typedef internal::Types28 type; -}; -template -struct Types { - typedef internal::Types29 type; -}; -template -struct Types { - typedef internal::Types30 type; -}; -template -struct Types { - typedef internal::Types31 type; -}; -template -struct Types { - typedef internal::Types32 type; -}; -template -struct Types { - typedef internal::Types33 type; -}; -template -struct Types { - typedef internal::Types34 type; -}; -template -struct Types { - typedef internal::Types35 type; -}; -template -struct Types { - typedef internal::Types36 type; -}; -template -struct Types { - typedef internal::Types37 type; -}; -template -struct Types { - typedef internal::Types38 type; -}; -template -struct Types { - typedef internal::Types39 type; -}; -template -struct Types { - typedef internal::Types40 type; -}; -template -struct Types { - typedef internal::Types41 type; -}; -template -struct Types { - typedef internal::Types42 type; -}; -template -struct Types { - typedef internal::Types43 type; -}; -template -struct Types { - typedef internal::Types44 type; -}; -template -struct Types { - typedef internal::Types45 type; -}; -template -struct Types { - typedef internal::Types46 type; -}; -template -struct Types { - typedef internal::Types47 type; -}; -template -struct Types { - typedef internal::Types48 type; -}; -template -struct Types { - typedef internal::Types49 type; -}; - -namespace internal { - -# define GTEST_TEMPLATE_ template class - -// The template "selector" struct TemplateSel is used to -// represent Tmpl, which must be a class template with one type -// parameter, as a type. TemplateSel::Bind::type is defined -// as the type Tmpl. This allows us to actually instantiate the -// template "selected" by TemplateSel. -// -// This trick is necessary for simulating typedef for class templates, -// which C++ doesn't support directly. -template -struct TemplateSel { - template - struct Bind { - typedef Tmpl type; - }; -}; - -# define GTEST_BIND_(TmplSel, T) \ - TmplSel::template Bind::type - -// A unique struct template used as the default value for the -// arguments of class template Templates. This allows us to simulate -// variadic templates (e.g. Templates, Templates, -// and etc), which C++ doesn't support directly. -template -struct NoneT {}; - -// The following family of struct and struct templates are used to -// represent template lists. In particular, TemplatesN represents a list of N templates (T1, T2, ..., and TN). Except -// for Templates0, every struct in the family has two member types: -// Head for the selector of the first template in the list, and Tail -// for the rest of the list. - -// The empty template list. -struct Templates0 {}; - -// Template lists of length 1, 2, 3, and so on. - -template -struct Templates1 { - typedef TemplateSel Head; - typedef Templates0 Tail; -}; -template -struct Templates2 { - typedef TemplateSel Head; - typedef Templates1 Tail; -}; - -template -struct Templates3 { - typedef TemplateSel Head; - typedef Templates2 Tail; -}; - -template -struct Templates4 { - typedef TemplateSel Head; - typedef Templates3 Tail; -}; - -template -struct Templates5 { - typedef TemplateSel Head; - typedef Templates4 Tail; -}; - -template -struct Templates6 { - typedef TemplateSel Head; - typedef Templates5 Tail; -}; - -template -struct Templates7 { - typedef TemplateSel Head; - typedef Templates6 Tail; -}; - -template -struct Templates8 { - typedef TemplateSel Head; - typedef Templates7 Tail; -}; - -template -struct Templates9 { - typedef TemplateSel Head; - typedef Templates8 Tail; -}; - -template -struct Templates10 { - typedef TemplateSel Head; - typedef Templates9 Tail; -}; - -template -struct Templates11 { - typedef TemplateSel Head; - typedef Templates10 Tail; -}; - -template -struct Templates12 { - typedef TemplateSel Head; - typedef Templates11 Tail; -}; - -template -struct Templates13 { - typedef TemplateSel Head; - typedef Templates12 Tail; -}; - -template -struct Templates14 { - typedef TemplateSel Head; - typedef Templates13 Tail; -}; - -template -struct Templates15 { - typedef TemplateSel Head; - typedef Templates14 Tail; -}; - -template -struct Templates16 { - typedef TemplateSel Head; - typedef Templates15 Tail; -}; - -template -struct Templates17 { - typedef TemplateSel Head; - typedef Templates16 Tail; -}; - -template -struct Templates18 { - typedef TemplateSel Head; - typedef Templates17 Tail; -}; - -template -struct Templates19 { - typedef TemplateSel Head; - typedef Templates18 Tail; -}; - -template -struct Templates20 { - typedef TemplateSel Head; - typedef Templates19 Tail; -}; - -template -struct Templates21 { - typedef TemplateSel Head; - typedef Templates20 Tail; -}; - -template -struct Templates22 { - typedef TemplateSel Head; - typedef Templates21 Tail; -}; - -template -struct Templates23 { - typedef TemplateSel Head; - typedef Templates22 Tail; -}; - -template -struct Templates24 { - typedef TemplateSel Head; - typedef Templates23 Tail; -}; - -template -struct Templates25 { - typedef TemplateSel Head; - typedef Templates24 Tail; -}; - -template -struct Templates26 { - typedef TemplateSel Head; - typedef Templates25 Tail; -}; - -template -struct Templates27 { - typedef TemplateSel Head; - typedef Templates26 Tail; -}; - -template -struct Templates28 { - typedef TemplateSel Head; - typedef Templates27 Tail; -}; - -template -struct Templates29 { - typedef TemplateSel Head; - typedef Templates28 Tail; -}; - -template -struct Templates30 { - typedef TemplateSel Head; - typedef Templates29 Tail; -}; - -template -struct Templates31 { - typedef TemplateSel Head; - typedef Templates30 Tail; -}; - -template -struct Templates32 { - typedef TemplateSel Head; - typedef Templates31 Tail; -}; - -template -struct Templates33 { - typedef TemplateSel Head; - typedef Templates32 Tail; -}; - -template -struct Templates34 { - typedef TemplateSel Head; - typedef Templates33 Tail; -}; - -template -struct Templates35 { - typedef TemplateSel Head; - typedef Templates34 Tail; -}; - -template -struct Templates36 { - typedef TemplateSel Head; - typedef Templates35 Tail; -}; - -template -struct Templates37 { - typedef TemplateSel Head; - typedef Templates36 Tail; -}; - -template -struct Templates38 { - typedef TemplateSel Head; - typedef Templates37 Tail; -}; - -template -struct Templates39 { - typedef TemplateSel Head; - typedef Templates38 Tail; -}; - -template -struct Templates40 { - typedef TemplateSel Head; - typedef Templates39 Tail; -}; - -template -struct Templates41 { - typedef TemplateSel Head; - typedef Templates40 Tail; -}; - -template -struct Templates42 { - typedef TemplateSel Head; - typedef Templates41 Tail; -}; - -template -struct Templates43 { - typedef TemplateSel Head; - typedef Templates42 Tail; -}; - -template -struct Templates44 { - typedef TemplateSel Head; - typedef Templates43 Tail; -}; - -template -struct Templates45 { - typedef TemplateSel Head; - typedef Templates44 Tail; -}; - -template -struct Templates46 { - typedef TemplateSel Head; - typedef Templates45 Tail; -}; - -template -struct Templates47 { - typedef TemplateSel Head; - typedef Templates46 Tail; -}; - -template -struct Templates48 { - typedef TemplateSel Head; - typedef Templates47 Tail; -}; - -template -struct Templates49 { - typedef TemplateSel Head; - typedef Templates48 Tail; -}; - -template -struct Templates50 { - typedef TemplateSel Head; - typedef Templates49 Tail; -}; - - -// We don't want to require the users to write TemplatesN<...> directly, -// as that would require them to count the length. Templates<...> is much -// easier to write, but generates horrible messages when there is a -// compiler error, as gcc insists on printing out each template -// argument, even if it has the default value (this means Templates -// will appear as Templates in the compiler -// errors). -// -// Our solution is to combine the best part of the two approaches: a -// user would write Templates, and Google Test will translate -// that to TemplatesN internally to make error messages -// readable. The translation is done by the 'type' member of the -// Templates template. -template -struct Templates { - typedef Templates50 type; -}; - -template <> -struct Templates { - typedef Templates0 type; -}; -template -struct Templates { - typedef Templates1 type; -}; -template -struct Templates { - typedef Templates2 type; -}; -template -struct Templates { - typedef Templates3 type; -}; -template -struct Templates { - typedef Templates4 type; -}; -template -struct Templates { - typedef Templates5 type; -}; -template -struct Templates { - typedef Templates6 type; -}; -template -struct Templates { - typedef Templates7 type; -}; -template -struct Templates { - typedef Templates8 type; -}; -template -struct Templates { - typedef Templates9 type; -}; -template -struct Templates { - typedef Templates10 type; -}; -template -struct Templates { - typedef Templates11 type; -}; -template -struct Templates { - typedef Templates12 type; -}; -template -struct Templates { - typedef Templates13 type; -}; -template -struct Templates { - typedef Templates14 type; -}; -template -struct Templates { - typedef Templates15 type; -}; -template -struct Templates { - typedef Templates16 type; -}; -template -struct Templates { - typedef Templates17 type; -}; -template -struct Templates { - typedef Templates18 type; -}; -template -struct Templates { - typedef Templates19 type; -}; -template -struct Templates { - typedef Templates20 type; -}; -template -struct Templates { - typedef Templates21 type; -}; -template -struct Templates { - typedef Templates22 type; -}; -template -struct Templates { - typedef Templates23 type; -}; -template -struct Templates { - typedef Templates24 type; -}; -template -struct Templates { - typedef Templates25 type; -}; -template -struct Templates { - typedef Templates26 type; -}; -template -struct Templates { - typedef Templates27 type; -}; -template -struct Templates { - typedef Templates28 type; -}; -template -struct Templates { - typedef Templates29 type; -}; -template -struct Templates { - typedef Templates30 type; -}; -template -struct Templates { - typedef Templates31 type; -}; -template -struct Templates { - typedef Templates32 type; -}; -template -struct Templates { - typedef Templates33 type; -}; -template -struct Templates { - typedef Templates34 type; -}; -template -struct Templates { - typedef Templates35 type; -}; -template -struct Templates { - typedef Templates36 type; -}; -template -struct Templates { - typedef Templates37 type; -}; -template -struct Templates { - typedef Templates38 type; -}; -template -struct Templates { - typedef Templates39 type; -}; -template -struct Templates { - typedef Templates40 type; -}; -template -struct Templates { - typedef Templates41 type; -}; -template -struct Templates { - typedef Templates42 type; -}; -template -struct Templates { - typedef Templates43 type; -}; -template -struct Templates { - typedef Templates44 type; -}; -template -struct Templates { - typedef Templates45 type; -}; -template -struct Templates { - typedef Templates46 type; -}; -template -struct Templates { - typedef Templates47 type; -}; -template -struct Templates { - typedef Templates48 type; -}; -template -struct Templates { - typedef Templates49 type; -}; - -// The TypeList template makes it possible to use either a single type -// or a Types<...> list in TYPED_TEST_SUITE() and -// INSTANTIATE_TYPED_TEST_SUITE_P(). - -template -struct TypeList { - typedef Types1 type; -}; - -template -struct TypeList > { - typedef typename Types::type type; -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ - -// Due to C++ preprocessor weirdness, we need double indirection to -// concatenate two tokens when one of them is __LINE__. Writing -// -// foo ## __LINE__ -// -// will result in the token foo__LINE__, instead of foo followed by -// the current line number. For more details, see -// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 -#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) -#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar - -// Stringifies its argument. -#define GTEST_STRINGIFY_(name) #name - -namespace proto2 { class Message; } - -namespace testing { - -// Forward declarations. - -class AssertionResult; // Result of an assertion. -class Message; // Represents a failure message. -class Test; // Represents a test. -class TestInfo; // Information about a test. -class TestPartResult; // Result of a test part. -class UnitTest; // A collection of test suites. - -template -::std::string PrintToString(const T& value); - -namespace internal { - -struct TraceInfo; // Information about a trace point. -class TestInfoImpl; // Opaque implementation of TestInfo -class UnitTestImpl; // Opaque implementation of UnitTest - -// The text used in failure messages to indicate the start of the -// stack trace. -GTEST_API_ extern const char kStackTraceMarker[]; - -// An IgnoredValue object can be implicitly constructed from ANY value. -class IgnoredValue { - struct Sink {}; - public: - // This constructor template allows any value to be implicitly - // converted to IgnoredValue. The object has no data member and - // doesn't try to remember anything about the argument. We - // deliberately omit the 'explicit' keyword in order to allow the - // conversion to be implicit. - // Disable the conversion if T already has a magical conversion operator. - // Otherwise we get ambiguity. - template ::value, - int>::type = 0> - IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) -}; - -// Appends the user-supplied message to the Google-Test-generated message. -GTEST_API_ std::string AppendUserMessage( - const std::string& gtest_msg, const Message& user_msg); - -#if GTEST_HAS_EXCEPTIONS - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4275 \ -/* an exported class was derived from a class that was not exported */) - -// This exception is thrown by (and only by) a failed Google Test -// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions -// are enabled). We derive it from std::runtime_error, which is for -// errors presumably detectable only at run time. Since -// std::runtime_error inherits from std::exception, many testing -// frameworks know how to extract and print the message inside it. -class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { - public: - explicit GoogleTestFailureException(const TestPartResult& failure); -}; - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4275 - -#endif // GTEST_HAS_EXCEPTIONS - -namespace edit_distance { -// Returns the optimal edits to go from 'left' to 'right'. -// All edits cost the same, with replace having lower priority than -// add/remove. -// Simple implementation of the Wagner-Fischer algorithm. -// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm -enum EditType { kMatch, kAdd, kRemove, kReplace }; -GTEST_API_ std::vector CalculateOptimalEdits( - const std::vector& left, const std::vector& right); - -// Same as above, but the input is represented as strings. -GTEST_API_ std::vector CalculateOptimalEdits( - const std::vector& left, - const std::vector& right); - -// Create a diff of the input strings in Unified diff format. -GTEST_API_ std::string CreateUnifiedDiff(const std::vector& left, - const std::vector& right, - size_t context = 2); - -} // namespace edit_distance - -// Calculate the diff between 'left' and 'right' and return it in unified diff -// format. -// If not null, stores in 'total_line_count' the total number of lines found -// in left + right. -GTEST_API_ std::string DiffStrings(const std::string& left, - const std::string& right, - size_t* total_line_count); - -// Constructs and returns the message for an equality assertion -// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. -// -// The first four parameters are the expressions used in the assertion -// and their values, as strings. For example, for ASSERT_EQ(foo, bar) -// where foo is 5 and bar is 6, we have: -// -// expected_expression: "foo" -// actual_expression: "bar" -// expected_value: "5" -// actual_value: "6" -// -// The ignoring_case parameter is true if and only if the assertion is a -// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will -// be inserted into the message. -GTEST_API_ AssertionResult EqFailure(const char* expected_expression, - const char* actual_expression, - const std::string& expected_value, - const std::string& actual_value, - bool ignoring_case); - -// Constructs a failure message for Boolean assertions such as EXPECT_TRUE. -GTEST_API_ std::string GetBoolAssertionFailureMessage( - const AssertionResult& assertion_result, - const char* expression_text, - const char* actual_predicate_value, - const char* expected_predicate_value); - -// This template class represents an IEEE floating-point number -// (either single-precision or double-precision, depending on the -// template parameters). -// -// The purpose of this class is to do more sophisticated number -// comparison. (Due to round-off error, etc, it's very unlikely that -// two floating-points will be equal exactly. Hence a naive -// comparison by the == operation often doesn't work.) -// -// Format of IEEE floating-point: -// -// The most-significant bit being the leftmost, an IEEE -// floating-point looks like -// -// sign_bit exponent_bits fraction_bits -// -// Here, sign_bit is a single bit that designates the sign of the -// number. -// -// For float, there are 8 exponent bits and 23 fraction bits. -// -// For double, there are 11 exponent bits and 52 fraction bits. -// -// More details can be found at -// http://en.wikipedia.org/wiki/IEEE_floating-point_standard. -// -// Template parameter: -// -// RawType: the raw floating-point type (either float or double) -template -class FloatingPoint { - public: - // Defines the unsigned integer type that has the same size as the - // floating point number. - typedef typename TypeWithSize::UInt Bits; - - // Constants. - - // # of bits in a number. - static const size_t kBitCount = 8*sizeof(RawType); - - // # of fraction bits in a number. - static const size_t kFractionBitCount = - std::numeric_limits::digits - 1; - - // # of exponent bits in a number. - static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; - - // The mask for the sign bit. - static const Bits kSignBitMask = static_cast(1) << (kBitCount - 1); - - // The mask for the fraction bits. - static const Bits kFractionBitMask = - ~static_cast(0) >> (kExponentBitCount + 1); - - // The mask for the exponent bits. - static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); - - // How many ULP's (Units in the Last Place) we want to tolerate when - // comparing two numbers. The larger the value, the more error we - // allow. A 0 value means that two numbers must be exactly the same - // to be considered equal. - // - // The maximum error of a single floating-point operation is 0.5 - // units in the last place. On Intel CPU's, all floating-point - // calculations are done with 80-bit precision, while double has 64 - // bits. Therefore, 4 should be enough for ordinary use. - // - // See the following article for more details on ULP: - // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ - static const size_t kMaxUlps = 4; - - // Constructs a FloatingPoint from a raw floating-point number. - // - // On an Intel CPU, passing a non-normalized NAN (Not a Number) - // around may change its bits, although the new value is guaranteed - // to be also a NAN. Therefore, don't expect this constructor to - // preserve the bits in x when x is a NAN. - explicit FloatingPoint(const RawType& x) { u_.value_ = x; } - - // Static methods - - // Reinterprets a bit pattern as a floating-point number. - // - // This function is needed to test the AlmostEquals() method. - static RawType ReinterpretBits(const Bits bits) { - FloatingPoint fp(0); - fp.u_.bits_ = bits; - return fp.u_.value_; - } - - // Returns the floating-point number that represent positive infinity. - static RawType Infinity() { - return ReinterpretBits(kExponentBitMask); - } - - // Returns the maximum representable finite floating-point number. - static RawType Max(); - - // Non-static methods - - // Returns the bits that represents this number. - const Bits &bits() const { return u_.bits_; } - - // Returns the exponent bits of this number. - Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } - - // Returns the fraction bits of this number. - Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } - - // Returns the sign bit of this number. - Bits sign_bit() const { return kSignBitMask & u_.bits_; } - - // Returns true if and only if this is NAN (not a number). - bool is_nan() const { - // It's a NAN if the exponent bits are all ones and the fraction - // bits are not entirely zeros. - return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); - } - - // Returns true if and only if this number is at most kMaxUlps ULP's away - // from rhs. In particular, this function: - // - // - returns false if either number is (or both are) NAN. - // - treats really large numbers as almost equal to infinity. - // - thinks +0.0 and -0.0 are 0 DLP's apart. - bool AlmostEquals(const FloatingPoint& rhs) const { - // The IEEE standard says that any comparison operation involving - // a NAN must return false. - if (is_nan() || rhs.is_nan()) return false; - - return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) - <= kMaxUlps; - } - - private: - // The data type used to store the actual floating-point number. - union FloatingPointUnion { - RawType value_; // The raw floating-point number. - Bits bits_; // The bits that represent the number. - }; - - // Converts an integer from the sign-and-magnitude representation to - // the biased representation. More precisely, let N be 2 to the - // power of (kBitCount - 1), an integer x is represented by the - // unsigned number x + N. - // - // For instance, - // - // -N + 1 (the most negative number representable using - // sign-and-magnitude) is represented by 1; - // 0 is represented by N; and - // N - 1 (the biggest number representable using - // sign-and-magnitude) is represented by 2N - 1. - // - // Read http://en.wikipedia.org/wiki/Signed_number_representations - // for more details on signed number representations. - static Bits SignAndMagnitudeToBiased(const Bits &sam) { - if (kSignBitMask & sam) { - // sam represents a negative number. - return ~sam + 1; - } else { - // sam represents a positive number. - return kSignBitMask | sam; - } - } - - // Given two numbers in the sign-and-magnitude representation, - // returns the distance between them as an unsigned number. - static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, - const Bits &sam2) { - const Bits biased1 = SignAndMagnitudeToBiased(sam1); - const Bits biased2 = SignAndMagnitudeToBiased(sam2); - return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); - } - - FloatingPointUnion u_; -}; - -// We cannot use std::numeric_limits::max() as it clashes with the max() -// macro defined by . -template <> -inline float FloatingPoint::Max() { return FLT_MAX; } -template <> -inline double FloatingPoint::Max() { return DBL_MAX; } - -// Typedefs the instances of the FloatingPoint template class that we -// care to use. -typedef FloatingPoint Float; -typedef FloatingPoint Double; - -// In order to catch the mistake of putting tests that use different -// test fixture classes in the same test suite, we need to assign -// unique IDs to fixture classes and compare them. The TypeId type is -// used to hold such IDs. The user should treat TypeId as an opaque -// type: the only operation allowed on TypeId values is to compare -// them for equality using the == operator. -typedef const void* TypeId; - -template -class TypeIdHelper { - public: - // dummy_ must not have a const type. Otherwise an overly eager - // compiler (e.g. MSVC 7.1 & 8.0) may try to merge - // TypeIdHelper::dummy_ for different Ts as an "optimization". - static bool dummy_; -}; - -template -bool TypeIdHelper::dummy_ = false; - -// GetTypeId() returns the ID of type T. Different values will be -// returned for different types. Calling the function twice with the -// same type argument is guaranteed to return the same ID. -template -TypeId GetTypeId() { - // The compiler is required to allocate a different - // TypeIdHelper::dummy_ variable for each T used to instantiate - // the template. Therefore, the address of dummy_ is guaranteed to - // be unique. - return &(TypeIdHelper::dummy_); -} - -// Returns the type ID of ::testing::Test. Always call this instead -// of GetTypeId< ::testing::Test>() to get the type ID of -// ::testing::Test, as the latter may give the wrong result due to a -// suspected linker bug when compiling Google Test as a Mac OS X -// framework. -GTEST_API_ TypeId GetTestTypeId(); - -// Defines the abstract factory interface that creates instances -// of a Test object. -class TestFactoryBase { - public: - virtual ~TestFactoryBase() {} - - // Creates a test instance to run. The instance is both created and destroyed - // within TestInfoImpl::Run() - virtual Test* CreateTest() = 0; - - protected: - TestFactoryBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); -}; - -// This class provides implementation of TeastFactoryBase interface. -// It is used in TEST and TEST_F macros. -template -class TestFactoryImpl : public TestFactoryBase { - public: - Test* CreateTest() override { return new TestClass; } -}; - -#if GTEST_OS_WINDOWS - -// Predicate-formatters for implementing the HRESULT checking macros -// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} -// We pass a long instead of HRESULT to avoid causing an -// include dependency for the HRESULT type. -GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, - long hr); // NOLINT -GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, - long hr); // NOLINT - -#endif // GTEST_OS_WINDOWS - -// Types of SetUpTestSuite() and TearDownTestSuite() functions. -using SetUpTestSuiteFunc = void (*)(); -using TearDownTestSuiteFunc = void (*)(); - -struct CodeLocation { - CodeLocation(const std::string& a_file, int a_line) - : file(a_file), line(a_line) {} - - std::string file; - int line; -}; - -// Helper to identify which setup function for TestCase / TestSuite to call. -// Only one function is allowed, either TestCase or TestSute but not both. - -// Utility functions to help SuiteApiResolver -using SetUpTearDownSuiteFuncType = void (*)(); - -inline SetUpTearDownSuiteFuncType GetNotDefaultOrNull( - SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) { - return a == def ? nullptr : a; -} - -template -// Note that SuiteApiResolver inherits from T because -// SetUpTestSuite()/TearDownTestSuite() could be protected. Ths way -// SuiteApiResolver can access them. -struct SuiteApiResolver : T { - // testing::Test is only forward declared at this point. So we make it a - // dependend class for the compiler to be OK with it. - using Test = - typename std::conditional::type; - - static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename, - int line_num) { - SetUpTearDownSuiteFuncType test_case_fp = - GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase); - SetUpTearDownSuiteFuncType test_suite_fp = - GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite); - - GTEST_CHECK_(!test_case_fp || !test_suite_fp) - << "Test can not provide both SetUpTestSuite and SetUpTestCase, please " - "make sure there is only one present at " - << filename << ":" << line_num; - - return test_case_fp != nullptr ? test_case_fp : test_suite_fp; - } - - static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename, - int line_num) { - SetUpTearDownSuiteFuncType test_case_fp = - GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase); - SetUpTearDownSuiteFuncType test_suite_fp = - GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite); - - GTEST_CHECK_(!test_case_fp || !test_suite_fp) - << "Test can not provide both TearDownTestSuite and TearDownTestCase," - " please make sure there is only one present at" - << filename << ":" << line_num; - - return test_case_fp != nullptr ? test_case_fp : test_suite_fp; - } -}; - -// Creates a new TestInfo object and registers it with Google Test; -// returns the created object. -// -// Arguments: -// -// test_suite_name: name of the test suite -// name: name of the test -// type_param the name of the test's type parameter, or NULL if -// this is not a typed or a type-parameterized test. -// value_param text representation of the test's value parameter, -// or NULL if this is not a type-parameterized test. -// code_location: code location where the test is defined -// fixture_class_id: ID of the test fixture class -// set_up_tc: pointer to the function that sets up the test suite -// tear_down_tc: pointer to the function that tears down the test suite -// factory: pointer to the factory that creates a test object. -// The newly created TestInfo instance will assume -// ownership of the factory object. -GTEST_API_ TestInfo* MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, - const char* value_param, CodeLocation code_location, - TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc, - TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory); - -// If *pstr starts with the given prefix, modifies *pstr to be right -// past the prefix and returns true; otherwise leaves *pstr unchanged -// and returns false. None of pstr, *pstr, and prefix can be NULL. -GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); - -#if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -// State of the definition of a type-parameterized test suite. -class GTEST_API_ TypedTestSuitePState { - public: - TypedTestSuitePState() : registered_(false) {} - - // Adds the given test name to defined_test_names_ and return true - // if the test suite hasn't been registered; otherwise aborts the - // program. - bool AddTestName(const char* file, int line, const char* case_name, - const char* test_name) { - if (registered_) { - fprintf(stderr, - "%s Test %s must be defined before " - "REGISTER_TYPED_TEST_SUITE_P(%s, ...).\n", - FormatFileLocation(file, line).c_str(), test_name, case_name); - fflush(stderr); - posix::Abort(); - } - registered_tests_.insert( - ::std::make_pair(test_name, CodeLocation(file, line))); - return true; - } - - bool TestExists(const std::string& test_name) const { - return registered_tests_.count(test_name) > 0; - } - - const CodeLocation& GetCodeLocation(const std::string& test_name) const { - RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name); - GTEST_CHECK_(it != registered_tests_.end()); - return it->second; - } - - // Verifies that registered_tests match the test names in - // defined_test_names_; returns registered_tests if successful, or - // aborts the program otherwise. - const char* VerifyRegisteredTestNames( - const char* file, int line, const char* registered_tests); - - private: - typedef ::std::map RegisteredTestsMap; - - bool registered_; - RegisteredTestsMap registered_tests_; -}; - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -using TypedTestCasePState = TypedTestSuitePState; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -// Skips to the first non-space char after the first comma in 'str'; -// returns NULL if no comma is found in 'str'. -inline const char* SkipComma(const char* str) { - const char* comma = strchr(str, ','); - if (comma == nullptr) { - return nullptr; - } - while (IsSpace(*(++comma))) {} - return comma; -} - -// Returns the prefix of 'str' before the first comma in it; returns -// the entire string if it contains no comma. -inline std::string GetPrefixUntilComma(const char* str) { - const char* comma = strchr(str, ','); - return comma == nullptr ? str : std::string(str, comma); -} - -// Splits a given string on a given delimiter, populating a given -// vector with the fields. -void SplitString(const ::std::string& str, char delimiter, - ::std::vector< ::std::string>* dest); - -// The default argument to the template below for the case when the user does -// not provide a name generator. -struct DefaultNameGenerator { - template - static std::string GetName(int i) { - return StreamableToString(i); - } -}; - -template -struct NameGeneratorSelector { - typedef Provided type; -}; - -template -void GenerateNamesRecursively(Types0, std::vector*, int) {} - -template -void GenerateNamesRecursively(Types, std::vector* result, int i) { - result->push_back(NameGenerator::template GetName(i)); - GenerateNamesRecursively(typename Types::Tail(), result, - i + 1); -} - -template -std::vector GenerateNames() { - std::vector result; - GenerateNamesRecursively(Types(), &result, 0); - return result; -} - -// TypeParameterizedTest::Register() -// registers a list of type-parameterized tests with Google Test. The -// return value is insignificant - we just need to return something -// such that we can call this function in a namespace scope. -// -// Implementation note: The GTEST_TEMPLATE_ macro declares a template -// template parameter. It's defined in gtest-type-util.h. -template -class TypeParameterizedTest { - public: - // 'index' is the index of the test in the type list 'Types' - // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite, - // Types). Valid values for 'index' are [0, N - 1] where N is the - // length of Types. - static bool Register(const char* prefix, const CodeLocation& code_location, - const char* case_name, const char* test_names, int index, - const std::vector& type_names = - GenerateNames()) { - typedef typename Types::Head Type; - typedef Fixture FixtureClass; - typedef typename GTEST_BIND_(TestSel, Type) TestClass; - - // First, registers the first type-parameterized test in the type - // list. - MakeAndRegisterTestInfo( - (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + - "/" + type_names[static_cast(index)]) - .c_str(), - StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), - GetTypeName().c_str(), - nullptr, // No value parameter. - code_location, GetTypeId(), - SuiteApiResolver::GetSetUpCaseOrSuite( - code_location.file.c_str(), code_location.line), - SuiteApiResolver::GetTearDownCaseOrSuite( - code_location.file.c_str(), code_location.line), - new TestFactoryImpl); - - // Next, recurses (at compile time) with the tail of the type list. - return TypeParameterizedTest::Register(prefix, - code_location, - case_name, - test_names, - index + 1, - type_names); - } -}; - -// The base case for the compile time recursion. -template -class TypeParameterizedTest { - public: - static bool Register(const char* /*prefix*/, const CodeLocation&, - const char* /*case_name*/, const char* /*test_names*/, - int /*index*/, - const std::vector& = - std::vector() /*type_names*/) { - return true; - } -}; - -// TypeParameterizedTestSuite::Register() -// registers *all combinations* of 'Tests' and 'Types' with Google -// Test. The return value is insignificant - we just need to return -// something such that we can call this function in a namespace scope. -template -class TypeParameterizedTestSuite { - public: - static bool Register(const char* prefix, CodeLocation code_location, - const TypedTestSuitePState* state, const char* case_name, - const char* test_names, - const std::vector& type_names = - GenerateNames()) { - std::string test_name = StripTrailingSpaces( - GetPrefixUntilComma(test_names)); - if (!state->TestExists(test_name)) { - fprintf(stderr, "Failed to get code location for test %s.%s at %s.", - case_name, test_name.c_str(), - FormatFileLocation(code_location.file.c_str(), - code_location.line).c_str()); - fflush(stderr); - posix::Abort(); - } - const CodeLocation& test_location = state->GetCodeLocation(test_name); - - typedef typename Tests::Head Head; - - // First, register the first test in 'Test' for each type in 'Types'. - TypeParameterizedTest::Register( - prefix, test_location, case_name, test_names, 0, type_names); - - // Next, recurses (at compile time) with the tail of the test list. - return TypeParameterizedTestSuite::Register(prefix, code_location, - state, case_name, - SkipComma(test_names), - type_names); - } -}; - -// The base case for the compile time recursion. -template -class TypeParameterizedTestSuite { - public: - static bool Register(const char* /*prefix*/, const CodeLocation&, - const TypedTestSuitePState* /*state*/, - const char* /*case_name*/, const char* /*test_names*/, - const std::vector& = - std::vector() /*type_names*/) { - return true; - } -}; - -#endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P - -// Returns the current OS stack trace as an std::string. -// -// The maximum number of stack frames to be included is specified by -// the gtest_stack_trace_depth flag. The skip_count parameter -// specifies the number of top frames to be skipped, which doesn't -// count against the number of frames to be included. -// -// For example, if Foo() calls Bar(), which in turn calls -// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in -// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. -GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( - UnitTest* unit_test, int skip_count); - -// Helpers for suppressing warnings on unreachable code or constant -// condition. - -// Always returns true. -GTEST_API_ bool AlwaysTrue(); - -// Always returns false. -inline bool AlwaysFalse() { return !AlwaysTrue(); } - -// Helper for suppressing false warning from Clang on a const char* -// variable declared in a conditional expression always being NULL in -// the else branch. -struct GTEST_API_ ConstCharPtr { - ConstCharPtr(const char* str) : value(str) {} - operator bool() const { return true; } - const char* value; -}; - -// A simple Linear Congruential Generator for generating random -// numbers with a uniform distribution. Unlike rand() and srand(), it -// doesn't use global state (and therefore can't interfere with user -// code). Unlike rand_r(), it's portable. An LCG isn't very random, -// but it's good enough for our purposes. -class GTEST_API_ Random { - public: - static const UInt32 kMaxRange = 1u << 31; - - explicit Random(UInt32 seed) : state_(seed) {} - - void Reseed(UInt32 seed) { state_ = seed; } - - // Generates a random number from [0, range). Crashes if 'range' is - // 0 or greater than kMaxRange. - UInt32 Generate(UInt32 range); - - private: - UInt32 state_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); -}; - -// Turns const U&, U&, const U, and U all into U. -#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ - typename std::remove_const::type>::type - -// IsAProtocolMessage::value is a compile-time bool constant that's -// true if and only if T is type proto2::Message or a subclass of it. -template -struct IsAProtocolMessage - : public bool_constant< - std::is_convertible::value> {}; - -// When the compiler sees expression IsContainerTest(0), if C is an -// STL-style container class, the first overload of IsContainerTest -// will be viable (since both C::iterator* and C::const_iterator* are -// valid types and NULL can be implicitly converted to them). It will -// be picked over the second overload as 'int' is a perfect match for -// the type of argument 0. If C::iterator or C::const_iterator is not -// a valid type, the first overload is not viable, and the second -// overload will be picked. Therefore, we can determine whether C is -// a container class by checking the type of IsContainerTest(0). -// The value of the expression is insignificant. -// -// In C++11 mode we check the existence of a const_iterator and that an -// iterator is properly implemented for the container. -// -// For pre-C++11 that we look for both C::iterator and C::const_iterator. -// The reason is that C++ injects the name of a class as a member of the -// class itself (e.g. you can refer to class iterator as either -// 'iterator' or 'iterator::iterator'). If we look for C::iterator -// only, for example, we would mistakenly think that a class named -// iterator is an STL container. -// -// Also note that the simpler approach of overloading -// IsContainerTest(typename C::const_iterator*) and -// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. -typedef int IsContainer; -template ().begin()), - class = decltype(::std::declval().end()), - class = decltype(++::std::declval()), - class = decltype(*::std::declval()), - class = typename C::const_iterator> -IsContainer IsContainerTest(int /* dummy */) { - return 0; -} - -typedef char IsNotContainer; -template -IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } - -// Trait to detect whether a type T is a hash table. -// The heuristic used is that the type contains an inner type `hasher` and does -// not contain an inner type `reverse_iterator`. -// If the container is iterable in reverse, then order might actually matter. -template -struct IsHashTable { - private: - template - static char test(typename U::hasher*, typename U::reverse_iterator*); - template - static int test(typename U::hasher*, ...); - template - static char test(...); - - public: - static const bool value = sizeof(test(nullptr, nullptr)) == sizeof(int); -}; - -template -const bool IsHashTable::value; - -template (0)) == sizeof(IsContainer)> -struct IsRecursiveContainerImpl; - -template -struct IsRecursiveContainerImpl : public std::false_type {}; - -// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to -// obey the same inconsistencies as the IsContainerTest, namely check if -// something is a container is relying on only const_iterator in C++11 and -// is relying on both const_iterator and iterator otherwise -template -struct IsRecursiveContainerImpl { - using value_type = decltype(*std::declval()); - using type = - std::is_same::type>::type, - C>; -}; - -// IsRecursiveContainer is a unary compile-time predicate that -// evaluates whether C is a recursive container type. A recursive container -// type is a container type whose value_type is equal to the container type -// itself. An example for a recursive container type is -// boost::filesystem::path, whose iterator has a value_type that is equal to -// boost::filesystem::path. -template -struct IsRecursiveContainer : public IsRecursiveContainerImpl::type {}; - -// Utilities for native arrays. - -// ArrayEq() compares two k-dimensional native arrays using the -// elements' operator==, where k can be any integer >= 0. When k is -// 0, ArrayEq() degenerates into comparing a single pair of values. - -template -bool ArrayEq(const T* lhs, size_t size, const U* rhs); - -// This generic version is used when k is 0. -template -inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } - -// This overload is used when k >= 1. -template -inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { - return internal::ArrayEq(lhs, N, rhs); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous ArrayEq() function, arrays with different sizes would -// lead to different copies of the template code. -template -bool ArrayEq(const T* lhs, size_t size, const U* rhs) { - for (size_t i = 0; i != size; i++) { - if (!internal::ArrayEq(lhs[i], rhs[i])) - return false; - } - return true; -} - -// Finds the first element in the iterator range [begin, end) that -// equals elem. Element may be a native array type itself. -template -Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { - for (Iter it = begin; it != end; ++it) { - if (internal::ArrayEq(*it, elem)) - return it; - } - return end; -} - -// CopyArray() copies a k-dimensional native array using the elements' -// operator=, where k can be any integer >= 0. When k is 0, -// CopyArray() degenerates into copying a single value. - -template -void CopyArray(const T* from, size_t size, U* to); - -// This generic version is used when k is 0. -template -inline void CopyArray(const T& from, U* to) { *to = from; } - -// This overload is used when k >= 1. -template -inline void CopyArray(const T(&from)[N], U(*to)[N]) { - internal::CopyArray(from, N, *to); -} - -// This helper reduces code bloat. If we instead put its logic inside -// the previous CopyArray() function, arrays with different sizes -// would lead to different copies of the template code. -template -void CopyArray(const T* from, size_t size, U* to) { - for (size_t i = 0; i != size; i++) { - internal::CopyArray(from[i], to + i); - } -} - -// The relation between an NativeArray object (see below) and the -// native array it represents. -// We use 2 different structs to allow non-copyable types to be used, as long -// as RelationToSourceReference() is passed. -struct RelationToSourceReference {}; -struct RelationToSourceCopy {}; - -// Adapts a native array to a read-only STL-style container. Instead -// of the complete STL container concept, this adaptor only implements -// members useful for Google Mock's container matchers. New members -// should be added as needed. To simplify the implementation, we only -// support Element being a raw type (i.e. having no top-level const or -// reference modifier). It's the client's responsibility to satisfy -// this requirement. Element can be an array type itself (hence -// multi-dimensional arrays are supported). -template -class NativeArray { - public: - // STL-style container typedefs. - typedef Element value_type; - typedef Element* iterator; - typedef const Element* const_iterator; - - // Constructs from a native array. References the source. - NativeArray(const Element* array, size_t count, RelationToSourceReference) { - InitRef(array, count); - } - - // Constructs from a native array. Copies the source. - NativeArray(const Element* array, size_t count, RelationToSourceCopy) { - InitCopy(array, count); - } - - // Copy constructor. - NativeArray(const NativeArray& rhs) { - (this->*rhs.clone_)(rhs.array_, rhs.size_); - } - - ~NativeArray() { - if (clone_ != &NativeArray::InitRef) - delete[] array_; - } - - // STL-style container methods. - size_t size() const { return size_; } - const_iterator begin() const { return array_; } - const_iterator end() const { return array_ + size_; } - bool operator==(const NativeArray& rhs) const { - return size() == rhs.size() && - ArrayEq(begin(), size(), rhs.begin()); - } - - private: - static_assert(!std::is_const::value, "Type must not be const"); - static_assert(!std::is_reference::value, - "Type must not be a reference"); - - // Initializes this object with a copy of the input. - void InitCopy(const Element* array, size_t a_size) { - Element* const copy = new Element[a_size]; - CopyArray(array, a_size, copy); - array_ = copy; - size_ = a_size; - clone_ = &NativeArray::InitCopy; - } - - // Initializes this object with a reference of the input. - void InitRef(const Element* array, size_t a_size) { - array_ = array; - size_ = a_size; - clone_ = &NativeArray::InitRef; - } - - const Element* array_; - size_t size_; - void (NativeArray::*clone_)(const Element*, size_t); - - GTEST_DISALLOW_ASSIGN_(NativeArray); -}; - -// Backport of std::index_sequence. -template -struct IndexSequence { - using type = IndexSequence; -}; - -// Double the IndexSequence, and one if plus_one is true. -template -struct DoubleSequence; -template -struct DoubleSequence, sizeofT> { - using type = IndexSequence; -}; -template -struct DoubleSequence, sizeofT> { - using type = IndexSequence; -}; - -// Backport of std::make_index_sequence. -// It uses O(ln(N)) instantiation depth. -template -struct MakeIndexSequence - : DoubleSequence::type, - N / 2>::type {}; - -template <> -struct MakeIndexSequence<0> : IndexSequence<> {}; - -// FIXME: This implementation of ElemFromList is O(1) in instantiation depth, -// but it is O(N^2) in total instantiations. Not sure if this is the best -// tradeoff, as it will make it somewhat slow to compile. -template -struct ElemFromListImpl {}; - -template -struct ElemFromListImpl { - using type = T; -}; - -// Get the Nth element from T... -// It uses O(1) instantiation depth. -template -struct ElemFromList; - -template -struct ElemFromList, T...> - : ElemFromListImpl... {}; - -template -class FlatTuple; - -template -struct FlatTupleElemBase; - -template -struct FlatTupleElemBase, I> { - using value_type = - typename ElemFromList::type, - T...>::type; - FlatTupleElemBase() = default; - explicit FlatTupleElemBase(value_type t) : value(std::move(t)) {} - value_type value; -}; - -template -struct FlatTupleBase; - -template -struct FlatTupleBase, IndexSequence> - : FlatTupleElemBase, Idx>... { - using Indices = IndexSequence; - FlatTupleBase() = default; - explicit FlatTupleBase(T... t) - : FlatTupleElemBase, Idx>(std::move(t))... {} -}; - -// Analog to std::tuple but with different tradeoffs. -// This class minimizes the template instantiation depth, thus allowing more -// elements that std::tuple would. std::tuple has been seen to require an -// instantiation depth of more than 10x the number of elements in some -// implementations. -// FlatTuple and ElemFromList are not recursive and have a fixed depth -// regardless of T... -// MakeIndexSequence, on the other hand, it is recursive but with an -// instantiation depth of O(ln(N)). -template -class FlatTuple - : private FlatTupleBase, - typename MakeIndexSequence::type> { - using Indices = typename FlatTuple::FlatTupleBase::Indices; - - public: - FlatTuple() = default; - explicit FlatTuple(T... t) : FlatTuple::FlatTupleBase(std::move(t)...) {} - - template - const typename ElemFromList::type& Get() const { - return static_cast*>(this)->value; - } - - template - typename ElemFromList::type& Get() { - return static_cast*>(this)->value; - } -}; - -// Utility functions to be called with static_assert to induce deprecation -// warnings. -GTEST_INTERNAL_DEPRECATED( - "INSTANTIATE_TEST_CASE_P is deprecated, please use " - "INSTANTIATE_TEST_SUITE_P") -constexpr bool InstantiateTestCase_P_IsDeprecated() { return true; } - -GTEST_INTERNAL_DEPRECATED( - "TYPED_TEST_CASE_P is deprecated, please use " - "TYPED_TEST_SUITE_P") -constexpr bool TypedTestCase_P_IsDeprecated() { return true; } - -GTEST_INTERNAL_DEPRECATED( - "TYPED_TEST_CASE is deprecated, please use " - "TYPED_TEST_SUITE") -constexpr bool TypedTestCaseIsDeprecated() { return true; } - -GTEST_INTERNAL_DEPRECATED( - "REGISTER_TYPED_TEST_CASE_P is deprecated, please use " - "REGISTER_TYPED_TEST_SUITE_P") -constexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; } - -GTEST_INTERNAL_DEPRECATED( - "INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use " - "INSTANTIATE_TYPED_TEST_SUITE_P") -constexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; } - -} // namespace internal -} // namespace testing - -#define GTEST_MESSAGE_AT_(file, line, message, result_type) \ - ::testing::internal::AssertHelper(result_type, file, line, message) \ - = ::testing::Message() - -#define GTEST_MESSAGE_(message, result_type) \ - GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) - -#define GTEST_FATAL_FAILURE_(message) \ - return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) - -#define GTEST_NONFATAL_FAILURE_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) - -#define GTEST_SUCCESS_(message) \ - GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) - -#define GTEST_SKIP_(message) \ - return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip) - -// Suppress MSVC warning 4072 (unreachable code) for the code following -// statement if it returns or throws (or doesn't return or throw in some -// situations). -#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ - if (::testing::internal::AlwaysTrue()) { statement; } - -#define GTEST_TEST_THROW_(statement, expected_exception, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::ConstCharPtr gtest_msg = "") { \ - bool gtest_caught_expected = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (expected_exception const&) { \ - gtest_caught_expected = true; \ - } \ - catch (...) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws a different type."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - if (!gtest_caught_expected) { \ - gtest_msg.value = \ - "Expected: " #statement " throws an exception of type " \ - #expected_exception ".\n Actual: it throws nothing."; \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ - fail(gtest_msg.value) - -#define GTEST_TEST_NO_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ - fail("Expected: " #statement " doesn't throw an exception.\n" \ - " Actual: it throws.") - -#define GTEST_TEST_ANY_THROW_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - bool gtest_caught_any = false; \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } \ - catch (...) { \ - gtest_caught_any = true; \ - } \ - if (!gtest_caught_any) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ - fail("Expected: " #statement " throws an exception.\n" \ - " Actual: it doesn't.") - - -// Implements Boolean test assertions such as EXPECT_TRUE. expression can be -// either a boolean expression or an AssertionResult. text is a textual -// represenation of expression as it was passed into the EXPECT_TRUE. -#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar_ = \ - ::testing::AssertionResult(expression)) \ - ; \ - else \ - fail(::testing::internal::GetBoolAssertionFailureMessage(\ - gtest_ar_, text, #actual, #expected).c_str()) - -#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ - fail("Expected: " #statement " doesn't generate new fatal " \ - "failures in the current thread.\n" \ - " Actual: it does.") - -// Expands to the name of the class that implements the given test. -#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ - test_suite_name##_##test_name##_Test - -// Helper macro for defining tests. -#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id) \ - static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1, \ - "test_suite_name must not be empty"); \ - static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1, \ - "test_name must not be empty"); \ - class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ - : public parent_class { \ - public: \ - GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ - \ - private: \ - virtual void TestBody(); \ - static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)); \ - }; \ - \ - ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)::test_info_ = \ - ::testing::internal::MakeAndRegisterTestInfo( \ - #test_suite_name, #test_name, nullptr, nullptr, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \ - ::testing::internal::SuiteApiResolver< \ - parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__), \ - ::testing::internal::SuiteApiResolver< \ - parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__), \ - new ::testing::internal::TestFactoryImpl); \ - void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file defines the public API for death tests. It is -// #included by gtest.h so a user doesn't need to include this -// directly. -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ - -// Copyright 2005, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This header file defines internal utilities needed for implementing -// death tests. They are subject to change without notice. -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// The Google C++ Testing and Mocking Framework (Google Test) -// -// This file implements just enough of the matcher interface to allow -// EXPECT_DEATH and friends to accept a matcher argument. - -// IWYU pragma: private, include "testing/base/public/gunit.h" -// IWYU pragma: friend third_party/googletest/googlemock/.* -// IWYU pragma: friend third_party/googletest/googletest/.* - -#ifndef GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_ -#define GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_ - -#include -#include -#include -#include - -// Copyright 2007, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Google Test - The Google C++ Testing and Mocking Framework -// -// This file implements a universal value printer that can print a -// value of any type T: -// -// void ::testing::internal::UniversalPrinter::Print(value, ostream_ptr); -// -// A user can teach this function how to print a class type T by -// defining either operator<<() or PrintTo() in the namespace that -// defines T. More specifically, the FIRST defined function in the -// following list will be used (assuming T is defined in namespace -// foo): -// -// 1. foo::PrintTo(const T&, ostream*) -// 2. operator<<(ostream&, const T&) defined in either foo or the -// global namespace. -// -// However if T is an STL-style container then it is printed element-wise -// unless foo::PrintTo(const T&, ostream*) is defined. Note that -// operator<<() is ignored for container types. -// -// If none of the above is defined, it will print the debug string of -// the value if it is a protocol buffer, or print the raw bytes in the -// value otherwise. -// -// To aid debugging: when T is a reference type, the address of the -// value is also printed; when T is a (const) char pointer, both the -// pointer value and the NUL-terminated string it points to are -// printed. -// -// We also provide some convenient wrappers: -// -// // Prints a value to a string. For a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// std::string ::testing::PrintToString(const T& value); -// -// // Prints a value tersely: for a reference type, the referenced -// // value (but not the address) is printed; for a (const or not) char -// // pointer, the NUL-terminated string (but not the pointer) is -// // printed. -// void ::testing::internal::UniversalTersePrint(const T& value, ostream*); -// -// // Prints value using the type inferred by the compiler. The difference -// // from UniversalTersePrint() is that this function prints both the -// // pointer and the NUL-terminated string for a (const or not) char pointer. -// void ::testing::internal::UniversalPrint(const T& value, ostream*); -// -// // Prints the fields of a tuple tersely to a string vector, one -// // element for each field. Tuple support must be enabled in -// // gtest-port.h. -// std::vector UniversalTersePrintTupleFieldsToStrings( -// const Tuple& value); -// -// Known limitation: -// -// The print primitives print the elements of an STL-style container -// using the compiler-inferred type of *iter where iter is a -// const_iterator of the container. When const_iterator is an input -// iterator but not a forward iterator, this inferred type may not -// match value_type, and the print output may be incorrect. In -// practice, this is rarely a problem as for most containers -// const_iterator is a forward iterator. We'll fix this if there's an -// actual need for it. Note that this fix cannot rely on value_type -// being defined as many user-defined container types don't have -// value_type. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ - -#include -#include // NOLINT -#include -#include -#include -#include -#include -#include - -#if GTEST_HAS_ABSL -#include "absl/strings/string_view.h" -#include "absl/types/optional.h" -#include "absl/types/variant.h" -#endif // GTEST_HAS_ABSL - -namespace testing { - -// Definitions in the 'internal' and 'internal2' name spaces are -// subject to change without notice. DO NOT USE THEM IN USER CODE! -namespace internal2 { - -// Prints the given number of bytes in the given object to the given -// ostream. -GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, - size_t count, - ::std::ostream* os); - -// For selecting which printer to use when a given type has neither << -// nor PrintTo(). -enum TypeKind { - kProtobuf, // a protobuf type - kConvertibleToInteger, // a type implicitly convertible to BiggestInt - // (e.g. a named or unnamed enum type) -#if GTEST_HAS_ABSL - kConvertibleToStringView, // a type implicitly convertible to - // absl::string_view -#endif - kOtherType // anything else -}; - -// TypeWithoutFormatter::PrintValue(value, os) is called -// by the universal printer to print a value of type T when neither -// operator<< nor PrintTo() is defined for T, where kTypeKind is the -// "kind" of T as defined by enum TypeKind. -template -class TypeWithoutFormatter { - public: - // This default version is called when kTypeKind is kOtherType. - static void PrintValue(const T& value, ::std::ostream* os) { - PrintBytesInObjectTo( - static_cast( - reinterpret_cast(std::addressof(value))), - sizeof(value), os); - } -}; - -// We print a protobuf using its ShortDebugString() when the string -// doesn't exceed this many characters; otherwise we print it using -// DebugString() for better readability. -const size_t kProtobufOneLinerMaxLength = 50; - -template -class TypeWithoutFormatter { - public: - static void PrintValue(const T& value, ::std::ostream* os) { - std::string pretty_str = value.ShortDebugString(); - if (pretty_str.length() > kProtobufOneLinerMaxLength) { - pretty_str = "\n" + value.DebugString(); - } - *os << ("<" + pretty_str + ">"); - } -}; - -template -class TypeWithoutFormatter { - public: - // Since T has no << operator or PrintTo() but can be implicitly - // converted to BiggestInt, we print it as a BiggestInt. - // - // Most likely T is an enum type (either named or unnamed), in which - // case printing it as an integer is the desired behavior. In case - // T is not an enum, printing it as an integer is the best we can do - // given that it has no user-defined printer. - static void PrintValue(const T& value, ::std::ostream* os) { - const internal::BiggestInt kBigInt = value; - *os << kBigInt; - } -}; - -#if GTEST_HAS_ABSL -template -class TypeWithoutFormatter { - public: - // Since T has neither operator<< nor PrintTo() but can be implicitly - // converted to absl::string_view, we print it as a absl::string_view. - // - // Note: the implementation is further below, as it depends on - // internal::PrintTo symbol which is defined later in the file. - static void PrintValue(const T& value, ::std::ostream* os); -}; -#endif - -// Prints the given value to the given ostream. If the value is a -// protocol message, its debug string is printed; if it's an enum or -// of a type implicitly convertible to BiggestInt, it's printed as an -// integer; otherwise the bytes in the value are printed. This is -// what UniversalPrinter::Print() does when it knows nothing about -// type T and T has neither << operator nor PrintTo(). -// -// A user can override this behavior for a class type Foo by defining -// a << operator in the namespace where Foo is defined. -// -// We put this operator in namespace 'internal2' instead of 'internal' -// to simplify the implementation, as much code in 'internal' needs to -// use << in STL, which would conflict with our own << were it defined -// in 'internal'. -// -// Note that this operator<< takes a generic std::basic_ostream type instead of the more restricted std::ostream. If -// we define it to take an std::ostream instead, we'll get an -// "ambiguous overloads" compiler error when trying to print a type -// Foo that supports streaming to std::basic_ostream, as the compiler cannot tell whether -// operator<<(std::ostream&, const T&) or -// operator<<(std::basic_stream, const Foo&) is more -// specific. -template -::std::basic_ostream& operator<<( - ::std::basic_ostream& os, const T& x) { - TypeWithoutFormatter::value - ? kProtobuf - : std::is_convertible< - const T&, internal::BiggestInt>::value - ? kConvertibleToInteger - : -#if GTEST_HAS_ABSL - std::is_convertible< - const T&, absl::string_view>::value - ? kConvertibleToStringView - : -#endif - kOtherType)>::PrintValue(x, &os); - return os; -} - -} // namespace internal2 -} // namespace testing - -// This namespace MUST NOT BE NESTED IN ::testing, or the name look-up -// magic needed for implementing UniversalPrinter won't work. -namespace testing_internal { - -// Used to print a value that is not an STL-style container when the -// user doesn't define PrintTo() for it. -template -void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { - // With the following statement, during unqualified name lookup, - // testing::internal2::operator<< appears as if it was declared in - // the nearest enclosing namespace that contains both - // ::testing_internal and ::testing::internal2, i.e. the global - // namespace. For more details, refer to the C++ Standard section - // 7.3.4-1 [namespace.udir]. This allows us to fall back onto - // testing::internal2::operator<< in case T doesn't come with a << - // operator. - // - // We cannot write 'using ::testing::internal2::operator<<;', which - // gcc 3.3 fails to compile due to a compiler bug. - using namespace ::testing::internal2; // NOLINT - - // Assuming T is defined in namespace foo, in the next statement, - // the compiler will consider all of: - // - // 1. foo::operator<< (thanks to Koenig look-up), - // 2. ::operator<< (as the current namespace is enclosed in ::), - // 3. testing::internal2::operator<< (thanks to the using statement above). - // - // The operator<< whose type matches T best will be picked. - // - // We deliberately allow #2 to be a candidate, as sometimes it's - // impossible to define #1 (e.g. when foo is ::std, defining - // anything in it is undefined behavior unless you are a compiler - // vendor.). - *os << value; -} - -} // namespace testing_internal - -namespace testing { -namespace internal { - -// FormatForComparison::Format(value) formats a -// value of type ToPrint that is an operand of a comparison assertion -// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in -// the comparison, and is used to help determine the best way to -// format the value. In particular, when the value is a C string -// (char pointer) and the other operand is an STL string object, we -// want to format the C string as a string, since we know it is -// compared by value with the string object. If the value is a char -// pointer but the other operand is not an STL string object, we don't -// know whether the pointer is supposed to point to a NUL-terminated -// string, and thus want to print it as a pointer to be safe. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - -// The default case. -template -class FormatForComparison { - public: - static ::std::string Format(const ToPrint& value) { - return ::testing::PrintToString(value); - } -}; - -// Array. -template -class FormatForComparison { - public: - static ::std::string Format(const ToPrint* value) { - return FormatForComparison::Format(value); - } -}; - -// By default, print C string as pointers to be safe, as we don't know -// whether they actually point to a NUL-terminated string. - -#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ - template \ - class FormatForComparison { \ - public: \ - static ::std::string Format(CharType* value) { \ - return ::testing::PrintToString(static_cast(value)); \ - } \ - } - -GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); -GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); -GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); -GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); - -#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ - -// If a C string is compared with an STL string object, we know it's meant -// to point to a NUL-terminated string, and thus can print it as a string. - -#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ - template <> \ - class FormatForComparison { \ - public: \ - static ::std::string Format(CharType* value) { \ - return ::testing::PrintToString(value); \ - } \ - } - -GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); -GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); - -#if GTEST_HAS_STD_WSTRING -GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); -GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); -#endif - -#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_ - -// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) -// operand to be used in a failure message. The type (but not value) -// of the other operand may affect the format. This allows us to -// print a char* as a raw pointer when it is compared against another -// char* or void*, and print it as a C string when it is compared -// against an std::string object, for example. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -template -std::string FormatForComparisonFailureMessage( - const T1& value, const T2& /* other_operand */) { - return FormatForComparison::Format(value); -} - -// UniversalPrinter::Print(value, ostream_ptr) prints the given -// value to the given ostream. The caller must ensure that -// 'ostream_ptr' is not NULL, or the behavior is undefined. -// -// We define UniversalPrinter as a class template (as opposed to a -// function template), as we need to partially specialize it for -// reference types, which cannot be done with function templates. -template -class UniversalPrinter; - -template -void UniversalPrint(const T& value, ::std::ostream* os); - -enum DefaultPrinterType { - kPrintContainer, - kPrintPointer, - kPrintFunctionPointer, - kPrintOther, -}; -template struct WrapPrinterType {}; - -// Used to print an STL-style container when the user doesn't define -// a PrintTo() for it. -template -void DefaultPrintTo(WrapPrinterType /* dummy */, - const C& container, ::std::ostream* os) { - const size_t kMaxCount = 32; // The maximum number of elements to print. - *os << '{'; - size_t count = 0; - for (typename C::const_iterator it = container.begin(); - it != container.end(); ++it, ++count) { - if (count > 0) { - *os << ','; - if (count == kMaxCount) { // Enough has been printed. - *os << " ..."; - break; - } - } - *os << ' '; - // We cannot call PrintTo(*it, os) here as PrintTo() doesn't - // handle *it being a native array. - internal::UniversalPrint(*it, os); - } - - if (count > 0) { - *os << ' '; - } - *os << '}'; -} - -// Used to print a pointer that is neither a char pointer nor a member -// pointer, when the user doesn't define PrintTo() for it. (A member -// variable pointer or member function pointer doesn't really point to -// a location in the address space. Their representation is -// implementation-defined. Therefore they will be printed as raw -// bytes.) -template -void DefaultPrintTo(WrapPrinterType /* dummy */, - T* p, ::std::ostream* os) { - if (p == nullptr) { - *os << "NULL"; - } else { - // T is not a function type. We just call << to print p, - // relying on ADL to pick up user-defined << for their pointer - // types, if any. - *os << p; - } -} -template -void DefaultPrintTo(WrapPrinterType /* dummy */, - T* p, ::std::ostream* os) { - if (p == nullptr) { - *os << "NULL"; - } else { - // T is a function type, so '*os << p' doesn't do what we want - // (it just prints p as bool). We want to print p as a const - // void*. - *os << reinterpret_cast(p); - } -} - -// Used to print a non-container, non-pointer value when the user -// doesn't define PrintTo() for it. -template -void DefaultPrintTo(WrapPrinterType /* dummy */, - const T& value, ::std::ostream* os) { - ::testing_internal::DefaultPrintNonContainerTo(value, os); -} - -// Prints the given value using the << operator if it has one; -// otherwise prints the bytes in it. This is what -// UniversalPrinter::Print() does when PrintTo() is not specialized -// or overloaded for type T. -// -// A user can override this behavior for a class type Foo by defining -// an overload of PrintTo() in the namespace where Foo is defined. We -// give the user this option as sometimes defining a << operator for -// Foo is not desirable (e.g. the coding style may prevent doing it, -// or there is already a << operator but it doesn't do what the user -// wants). -template -void PrintTo(const T& value, ::std::ostream* os) { - // DefaultPrintTo() is overloaded. The type of its first argument - // determines which version will be picked. - // - // Note that we check for container types here, prior to we check - // for protocol message types in our operator<<. The rationale is: - // - // For protocol messages, we want to give people a chance to - // override Google Mock's format by defining a PrintTo() or - // operator<<. For STL containers, other formats can be - // incompatible with Google Mock's format for the container - // elements; therefore we check for container types here to ensure - // that our format is used. - // - // Note that MSVC and clang-cl do allow an implicit conversion from - // pointer-to-function to pointer-to-object, but clang-cl warns on it. - // So don't use ImplicitlyConvertible if it can be helped since it will - // cause this warning, and use a separate overload of DefaultPrintTo for - // function pointers so that the `*os << p` in the object pointer overload - // doesn't cause that warning either. - DefaultPrintTo( - WrapPrinterType < - (sizeof(IsContainerTest(0)) == sizeof(IsContainer)) && - !IsRecursiveContainer::value - ? kPrintContainer - : !std::is_pointer::value - ? kPrintOther - : std::is_function::type>::value - ? kPrintFunctionPointer - : kPrintPointer > (), - value, os); -} - -// The following list of PrintTo() overloads tells -// UniversalPrinter::Print() how to print standard types (built-in -// types, strings, plain arrays, and pointers). - -// Overloads for various char types. -GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); -GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); -inline void PrintTo(char c, ::std::ostream* os) { - // When printing a plain char, we always treat it as unsigned. This - // way, the output won't be affected by whether the compiler thinks - // char is signed or not. - PrintTo(static_cast(c), os); -} - -// Overloads for other simple built-in types. -inline void PrintTo(bool x, ::std::ostream* os) { - *os << (x ? "true" : "false"); -} - -// Overload for wchar_t type. -// Prints a wchar_t as a symbol if it is printable or as its internal -// code otherwise and also as its decimal code (except for L'\0'). -// The L'\0' char is printed as "L'\\0'". The decimal code is printed -// as signed integer when wchar_t is implemented by the compiler -// as a signed type and is printed as an unsigned integer when wchar_t -// is implemented as an unsigned type. -GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); - -// Overloads for C strings. -GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); -inline void PrintTo(char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} - -// signed/unsigned char is often used for representing binary data, so -// we print pointers to it as void* to be safe. -inline void PrintTo(const signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(signed char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(const unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -inline void PrintTo(unsigned char* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} - -// MSVC can be configured to define wchar_t as a typedef of unsigned -// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native -// type. When wchar_t is a typedef, defining an overload for const -// wchar_t* would cause unsigned short* be printed as a wide string, -// possibly causing invalid memory accesses. -#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) -// Overloads for wide C strings -GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); -inline void PrintTo(wchar_t* s, ::std::ostream* os) { - PrintTo(ImplicitCast_(s), os); -} -#endif - -// Overload for C arrays. Multi-dimensional arrays are printed -// properly. - -// Prints the given number of elements in an array, without printing -// the curly braces. -template -void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { - UniversalPrint(a[0], os); - for (size_t i = 1; i != count; i++) { - *os << ", "; - UniversalPrint(a[i], os); - } -} - -// Overloads for ::std::string. -GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); -inline void PrintTo(const ::std::string& s, ::std::ostream* os) { - PrintStringTo(s, os); -} - -// Overloads for ::std::wstring. -#if GTEST_HAS_STD_WSTRING -GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); -inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { - PrintWideStringTo(s, os); -} -#endif // GTEST_HAS_STD_WSTRING - -#if GTEST_HAS_ABSL -// Overload for absl::string_view. -inline void PrintTo(absl::string_view sp, ::std::ostream* os) { - PrintTo(::std::string(sp), os); -} -#endif // GTEST_HAS_ABSL - -inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; } - -template -void PrintTo(std::reference_wrapper ref, ::std::ostream* os) { - UniversalPrinter::Print(ref.get(), os); -} - -// Helper function for printing a tuple. T must be instantiated with -// a tuple type. -template -void PrintTupleTo(const T&, std::integral_constant, - ::std::ostream*) {} - -template -void PrintTupleTo(const T& t, std::integral_constant, - ::std::ostream* os) { - PrintTupleTo(t, std::integral_constant(), os); - GTEST_INTENTIONAL_CONST_COND_PUSH_() - if (I > 1) { - GTEST_INTENTIONAL_CONST_COND_POP_() - *os << ", "; - } - UniversalPrinter::type>::Print( - std::get(t), os); -} - -template -void PrintTo(const ::std::tuple& t, ::std::ostream* os) { - *os << "("; - PrintTupleTo(t, std::integral_constant(), os); - *os << ")"; -} - -// Overload for std::pair. -template -void PrintTo(const ::std::pair& value, ::std::ostream* os) { - *os << '('; - // We cannot use UniversalPrint(value.first, os) here, as T1 may be - // a reference type. The same for printing value.second. - UniversalPrinter::Print(value.first, os); - *os << ", "; - UniversalPrinter::Print(value.second, os); - *os << ')'; -} - -// Implements printing a non-reference type T by letting the compiler -// pick the right overload of PrintTo() for T. -template -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) - - // Note: we deliberately don't call this PrintTo(), as that name - // conflicts with ::testing::internal::PrintTo in the body of the - // function. - static void Print(const T& value, ::std::ostream* os) { - // By default, ::testing::internal::PrintTo() is used for printing - // the value. - // - // Thanks to Koenig look-up, if T is a class and has its own - // PrintTo() function defined in its namespace, that function will - // be visible here. Since it is more specific than the generic ones - // in ::testing::internal, it will be picked by the compiler in the - // following statement - exactly what we want. - PrintTo(value, os); - } - - GTEST_DISABLE_MSC_WARNINGS_POP_() -}; - -#if GTEST_HAS_ABSL - -// Printer for absl::optional - -template -class UniversalPrinter<::absl::optional> { - public: - static void Print(const ::absl::optional& value, ::std::ostream* os) { - *os << '('; - if (!value) { - *os << "nullopt"; - } else { - UniversalPrint(*value, os); - } - *os << ')'; - } -}; - -// Printer for absl::variant - -template -class UniversalPrinter<::absl::variant> { - public: - static void Print(const ::absl::variant& value, ::std::ostream* os) { - *os << '('; - absl::visit(Visitor{os}, value); - *os << ')'; - } - - private: - struct Visitor { - template - void operator()(const U& u) const { - *os << "'" << GetTypeName() << "' with value "; - UniversalPrint(u, os); - } - ::std::ostream* os; - }; -}; - -#endif // GTEST_HAS_ABSL - -// UniversalPrintArray(begin, len, os) prints an array of 'len' -// elements, starting at address 'begin'. -template -void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { - if (len == 0) { - *os << "{}"; - } else { - *os << "{ "; - const size_t kThreshold = 18; - const size_t kChunkSize = 8; - // If the array has more than kThreshold elements, we'll have to - // omit some details by printing only the first and the last - // kChunkSize elements. - if (len <= kThreshold) { - PrintRawArrayTo(begin, len, os); - } else { - PrintRawArrayTo(begin, kChunkSize, os); - *os << ", ..., "; - PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); - } - *os << " }"; - } -} -// This overload prints a (const) char array compactly. -GTEST_API_ void UniversalPrintArray( - const char* begin, size_t len, ::std::ostream* os); - -// This overload prints a (const) wchar_t array compactly. -GTEST_API_ void UniversalPrintArray( - const wchar_t* begin, size_t len, ::std::ostream* os); - -// Implements printing an array type T[N]. -template -class UniversalPrinter { - public: - // Prints the given array, omitting some elements when there are too - // many. - static void Print(const T (&a)[N], ::std::ostream* os) { - UniversalPrintArray(a, N, os); - } -}; - -// Implements printing a reference type T&. -template -class UniversalPrinter { - public: - // MSVC warns about adding const to a function type, so we want to - // disable the warning. - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) - - static void Print(const T& value, ::std::ostream* os) { - // Prints the address of the value. We use reinterpret_cast here - // as static_cast doesn't compile when T is a function type. - *os << "@" << reinterpret_cast(&value) << " "; - - // Then prints the value itself. - UniversalPrint(value, os); - } - - GTEST_DISABLE_MSC_WARNINGS_POP_() -}; - -// Prints a value tersely: for a reference type, the referenced value -// (but not the address) is printed; for a (const) char pointer, the -// NUL-terminated string (but not the pointer) is printed. - -template -class UniversalTersePrinter { - public: - static void Print(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); - } -}; -template -class UniversalTersePrinter { - public: - static void Print(const T& value, ::std::ostream* os) { - UniversalPrint(value, os); - } -}; -template -class UniversalTersePrinter { - public: - static void Print(const T (&value)[N], ::std::ostream* os) { - UniversalPrinter::Print(value, os); - } -}; -template <> -class UniversalTersePrinter { - public: - static void Print(const char* str, ::std::ostream* os) { - if (str == nullptr) { - *os << "NULL"; - } else { - UniversalPrint(std::string(str), os); - } - } -}; -template <> -class UniversalTersePrinter { - public: - static void Print(char* str, ::std::ostream* os) { - UniversalTersePrinter::Print(str, os); - } -}; - -#if GTEST_HAS_STD_WSTRING -template <> -class UniversalTersePrinter { - public: - static void Print(const wchar_t* str, ::std::ostream* os) { - if (str == nullptr) { - *os << "NULL"; - } else { - UniversalPrint(::std::wstring(str), os); - } - } -}; -#endif - -template <> -class UniversalTersePrinter { - public: - static void Print(wchar_t* str, ::std::ostream* os) { - UniversalTersePrinter::Print(str, os); - } -}; - -template -void UniversalTersePrint(const T& value, ::std::ostream* os) { - UniversalTersePrinter::Print(value, os); -} - -// Prints a value using the type inferred by the compiler. The -// difference between this and UniversalTersePrint() is that for a -// (const) char pointer, this prints both the pointer and the -// NUL-terminated string. -template -void UniversalPrint(const T& value, ::std::ostream* os) { - // A workarond for the bug in VC++ 7.1 that prevents us from instantiating - // UniversalPrinter with T directly. - typedef T T1; - UniversalPrinter::Print(value, os); -} - -typedef ::std::vector< ::std::string> Strings; - - // Tersely prints the first N fields of a tuple to a string vector, - // one element for each field. -template -void TersePrintPrefixToStrings(const Tuple&, std::integral_constant, - Strings*) {} -template -void TersePrintPrefixToStrings(const Tuple& t, - std::integral_constant, - Strings* strings) { - TersePrintPrefixToStrings(t, std::integral_constant(), - strings); - ::std::stringstream ss; - UniversalTersePrint(std::get(t), &ss); - strings->push_back(ss.str()); -} - -// Prints the fields of a tuple tersely to a string vector, one -// element for each field. See the comment before -// UniversalTersePrint() for how we define "tersely". -template -Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { - Strings result; - TersePrintPrefixToStrings( - value, std::integral_constant::value>(), - &result); - return result; -} - -} // namespace internal - -#if GTEST_HAS_ABSL -namespace internal2 { -template -void TypeWithoutFormatter::PrintValue( - const T& value, ::std::ostream* os) { - internal::PrintTo(absl::string_view(value), os); -} -} // namespace internal2 -#endif - -template -::std::string PrintToString(const T& value) { - ::std::stringstream ss; - internal::UniversalTersePrinter::Print(value, &ss); - return ss.str(); -} - -} // namespace testing - -// Include any custom printer added by the local installation. -// We must include this header at the end to make sure it can use the -// declarations from this file. -// Copyright 2015, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// This file provides an injection point for custom printers in a local -// installation of gTest. -// It will be included from gtest-printers.h and the overrides in this file -// will be visible to everyone. -// -// Injection point for custom user configurations. See README for details -// -// ** Custom implementation starts here ** - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ - -// MSVC warning C5046 is new as of VS2017 version 15.8. -#if defined(_MSC_VER) && _MSC_VER >= 1915 -#define GTEST_MAYBE_5046_ 5046 -#else -#define GTEST_MAYBE_5046_ -#endif - -GTEST_DISABLE_MSC_WARNINGS_PUSH_( - 4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by - clients of class B */ - /* Symbol involving type with internal linkage not defined */) - -namespace testing { - -// To implement a matcher Foo for type T, define: -// 1. a class FooMatcherImpl that implements the -// MatcherInterface interface, and -// 2. a factory function that creates a Matcher object from a -// FooMatcherImpl*. -// -// The two-level delegation design makes it possible to allow a user -// to write "v" instead of "Eq(v)" where a Matcher is expected, which -// is impossible if we pass matchers by pointers. It also eases -// ownership management as Matcher objects can now be copied like -// plain values. - -// MatchResultListener is an abstract class. Its << operator can be -// used by a matcher to explain why a value matches or doesn't match. -// -class MatchResultListener { - public: - // Creates a listener object with the given underlying ostream. The - // listener does not own the ostream, and does not dereference it - // in the constructor or destructor. - explicit MatchResultListener(::std::ostream* os) : stream_(os) {} - virtual ~MatchResultListener() = 0; // Makes this class abstract. - - // Streams x to the underlying ostream; does nothing if the ostream - // is NULL. - template - MatchResultListener& operator<<(const T& x) { - if (stream_ != nullptr) *stream_ << x; - return *this; - } - - // Returns the underlying ostream. - ::std::ostream* stream() { return stream_; } - - // Returns true if and only if the listener is interested in an explanation - // of the match result. A matcher's MatchAndExplain() method can use - // this information to avoid generating the explanation when no one - // intends to hear it. - bool IsInterested() const { return stream_ != nullptr; } - - private: - ::std::ostream* const stream_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); -}; - -inline MatchResultListener::~MatchResultListener() { -} - -// An instance of a subclass of this knows how to describe itself as a -// matcher. -class MatcherDescriberInterface { - public: - virtual ~MatcherDescriberInterface() {} - - // Describes this matcher to an ostream. The function should print - // a verb phrase that describes the property a value matching this - // matcher should have. The subject of the verb phrase is the value - // being matched. For example, the DescribeTo() method of the Gt(7) - // matcher prints "is greater than 7". - virtual void DescribeTo(::std::ostream* os) const = 0; - - // Describes the negation of this matcher to an ostream. For - // example, if the description of this matcher is "is greater than - // 7", the negated description could be "is not greater than 7". - // You are not required to override this when implementing - // MatcherInterface, but it is highly advised so that your matcher - // can produce good error messages. - virtual void DescribeNegationTo(::std::ostream* os) const { - *os << "not ("; - DescribeTo(os); - *os << ")"; - } -}; - -// The implementation of a matcher. -template -class MatcherInterface : public MatcherDescriberInterface { - public: - // Returns true if and only if the matcher matches x; also explains the - // match result to 'listener' if necessary (see the next paragraph), in - // the form of a non-restrictive relative clause ("which ...", - // "whose ...", etc) that describes x. For example, the - // MatchAndExplain() method of the Pointee(...) matcher should - // generate an explanation like "which points to ...". - // - // Implementations of MatchAndExplain() should add an explanation of - // the match result *if and only if* they can provide additional - // information that's not already present (or not obvious) in the - // print-out of x and the matcher's description. Whether the match - // succeeds is not a factor in deciding whether an explanation is - // needed, as sometimes the caller needs to print a failure message - // when the match succeeds (e.g. when the matcher is used inside - // Not()). - // - // For example, a "has at least 10 elements" matcher should explain - // what the actual element count is, regardless of the match result, - // as it is useful information to the reader; on the other hand, an - // "is empty" matcher probably only needs to explain what the actual - // size is when the match fails, as it's redundant to say that the - // size is 0 when the value is already known to be empty. - // - // You should override this method when defining a new matcher. - // - // It's the responsibility of the caller (Google Test) to guarantee - // that 'listener' is not NULL. This helps to simplify a matcher's - // implementation when it doesn't care about the performance, as it - // can talk to 'listener' without checking its validity first. - // However, in order to implement dummy listeners efficiently, - // listener->stream() may be NULL. - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; - - // Inherits these methods from MatcherDescriberInterface: - // virtual void DescribeTo(::std::ostream* os) const = 0; - // virtual void DescribeNegationTo(::std::ostream* os) const; -}; - -namespace internal { - -// Converts a MatcherInterface to a MatcherInterface. -template -class MatcherInterfaceAdapter : public MatcherInterface { - public: - explicit MatcherInterfaceAdapter(const MatcherInterface* impl) - : impl_(impl) {} - ~MatcherInterfaceAdapter() override { delete impl_; } - - void DescribeTo(::std::ostream* os) const override { impl_->DescribeTo(os); } - - void DescribeNegationTo(::std::ostream* os) const override { - impl_->DescribeNegationTo(os); - } - - bool MatchAndExplain(const T& x, - MatchResultListener* listener) const override { - return impl_->MatchAndExplain(x, listener); - } - - private: - const MatcherInterface* const impl_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(MatcherInterfaceAdapter); -}; - -struct AnyEq { - template - bool operator()(const A& a, const B& b) const { return a == b; } -}; -struct AnyNe { - template - bool operator()(const A& a, const B& b) const { return a != b; } -}; -struct AnyLt { - template - bool operator()(const A& a, const B& b) const { return a < b; } -}; -struct AnyGt { - template - bool operator()(const A& a, const B& b) const { return a > b; } -}; -struct AnyLe { - template - bool operator()(const A& a, const B& b) const { return a <= b; } -}; -struct AnyGe { - template - bool operator()(const A& a, const B& b) const { return a >= b; } -}; - -// A match result listener that ignores the explanation. -class DummyMatchResultListener : public MatchResultListener { - public: - DummyMatchResultListener() : MatchResultListener(nullptr) {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); -}; - -// A match result listener that forwards the explanation to a given -// ostream. The difference between this and MatchResultListener is -// that the former is concrete. -class StreamMatchResultListener : public MatchResultListener { - public: - explicit StreamMatchResultListener(::std::ostream* os) - : MatchResultListener(os) {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); -}; - -// An internal class for implementing Matcher, which will derive -// from it. We put functionalities common to all Matcher -// specializations here to avoid code duplication. -template -class MatcherBase { - public: - // Returns true if and only if the matcher matches x; also explains the - // match result to 'listener'. - bool MatchAndExplain(const T& x, MatchResultListener* listener) const { - return impl_->MatchAndExplain(x, listener); - } - - // Returns true if and only if this matcher matches x. - bool Matches(const T& x) const { - DummyMatchResultListener dummy; - return MatchAndExplain(x, &dummy); - } - - // Describes this matcher to an ostream. - void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } - - // Describes the negation of this matcher to an ostream. - void DescribeNegationTo(::std::ostream* os) const { - impl_->DescribeNegationTo(os); - } - - // Explains why x matches, or doesn't match, the matcher. - void ExplainMatchResultTo(const T& x, ::std::ostream* os) const { - StreamMatchResultListener listener(os); - MatchAndExplain(x, &listener); - } - - // Returns the describer for this matcher object; retains ownership - // of the describer, which is only guaranteed to be alive when - // this matcher object is alive. - const MatcherDescriberInterface* GetDescriber() const { - return impl_.get(); - } - - protected: - MatcherBase() {} - - // Constructs a matcher from its implementation. - explicit MatcherBase(const MatcherInterface* impl) : impl_(impl) {} - - template - explicit MatcherBase( - const MatcherInterface* impl, - typename std::enable_if::value>::type* = - nullptr) - : impl_(new internal::MatcherInterfaceAdapter(impl)) {} - - MatcherBase(const MatcherBase&) = default; - MatcherBase& operator=(const MatcherBase&) = default; - MatcherBase(MatcherBase&&) = default; - MatcherBase& operator=(MatcherBase&&) = default; - - virtual ~MatcherBase() {} - - private: - std::shared_ptr> impl_; -}; - -} // namespace internal - -// A Matcher is a copyable and IMMUTABLE (except by assignment) -// object that can check whether a value of type T matches. The -// implementation of Matcher is just a std::shared_ptr to const -// MatcherInterface. Don't inherit from Matcher! -template -class Matcher : public internal::MatcherBase { - public: - // Constructs a null matcher. Needed for storing Matcher objects in STL - // containers. A default-constructed matcher is not yet initialized. You - // cannot use it until a valid value has been assigned to it. - explicit Matcher() {} // NOLINT - - // Constructs a matcher from its implementation. - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - - template - explicit Matcher( - const MatcherInterface* impl, - typename std::enable_if::value>::type* = - nullptr) - : internal::MatcherBase(impl) {} - - // Implicit constructor here allows people to write - // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes - Matcher(T value); // NOLINT -}; - -// The following two specializations allow the user to write str -// instead of Eq(str) and "foo" instead of Eq("foo") when a std::string -// matcher is expected. -template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { - public: - Matcher() {} - - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - - // Allows the user to write str instead of Eq(str) sometimes, where - // str is a std::string object. - Matcher(const std::string& s); // NOLINT - - // Allows the user to write "foo" instead of Eq("foo") sometimes. - Matcher(const char* s); // NOLINT -}; - -template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { - public: - Matcher() {} - - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - - // Allows the user to write str instead of Eq(str) sometimes, where - // str is a string object. - Matcher(const std::string& s); // NOLINT - - // Allows the user to write "foo" instead of Eq("foo") sometimes. - Matcher(const char* s); // NOLINT -}; - -#if GTEST_HAS_ABSL -// The following two specializations allow the user to write str -// instead of Eq(str) and "foo" instead of Eq("foo") when a absl::string_view -// matcher is expected. -template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { - public: - Matcher() {} - - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - - // Allows the user to write str instead of Eq(str) sometimes, where - // str is a std::string object. - Matcher(const std::string& s); // NOLINT - - // Allows the user to write "foo" instead of Eq("foo") sometimes. - Matcher(const char* s); // NOLINT - - // Allows the user to pass absl::string_views directly. - Matcher(absl::string_view s); // NOLINT -}; - -template <> -class GTEST_API_ Matcher - : public internal::MatcherBase { - public: - Matcher() {} - - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - explicit Matcher(const MatcherInterface* impl) - : internal::MatcherBase(impl) {} - - // Allows the user to write str instead of Eq(str) sometimes, where - // str is a std::string object. - Matcher(const std::string& s); // NOLINT - - // Allows the user to write "foo" instead of Eq("foo") sometimes. - Matcher(const char* s); // NOLINT - - // Allows the user to pass absl::string_views directly. - Matcher(absl::string_view s); // NOLINT -}; -#endif // GTEST_HAS_ABSL - -// Prints a matcher in a human-readable format. -template -std::ostream& operator<<(std::ostream& os, const Matcher& matcher) { - matcher.DescribeTo(&os); - return os; -} - -// The PolymorphicMatcher class template makes it easy to implement a -// polymorphic matcher (i.e. a matcher that can match values of more -// than one type, e.g. Eq(n) and NotNull()). -// -// To define a polymorphic matcher, a user should provide an Impl -// class that has a DescribeTo() method and a DescribeNegationTo() -// method, and define a member function (or member function template) -// -// bool MatchAndExplain(const Value& value, -// MatchResultListener* listener) const; -// -// See the definition of NotNull() for a complete example. -template -class PolymorphicMatcher { - public: - explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {} - - // Returns a mutable reference to the underlying matcher - // implementation object. - Impl& mutable_impl() { return impl_; } - - // Returns an immutable reference to the underlying matcher - // implementation object. - const Impl& impl() const { return impl_; } - - template - operator Matcher() const { - return Matcher(new MonomorphicImpl(impl_)); - } - - private: - template - class MonomorphicImpl : public MatcherInterface { - public: - explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} - - virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } - - virtual void DescribeNegationTo(::std::ostream* os) const { - impl_.DescribeNegationTo(os); - } - - virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { - return impl_.MatchAndExplain(x, listener); - } - - private: - const Impl impl_; - }; - - Impl impl_; -}; - -// Creates a matcher from its implementation. -// DEPRECATED: Especially in the generic code, prefer: -// Matcher(new MyMatcherImpl(...)); -// -// MakeMatcher may create a Matcher that accepts its argument by value, which -// leads to unnecessary copies & lack of support for non-copyable types. -template -inline Matcher MakeMatcher(const MatcherInterface* impl) { - return Matcher(impl); -} - -// Creates a polymorphic matcher from its implementation. This is -// easier to use than the PolymorphicMatcher constructor as it -// doesn't require you to explicitly write the template argument, e.g. -// -// MakePolymorphicMatcher(foo); -// vs -// PolymorphicMatcher(foo); -template -inline PolymorphicMatcher MakePolymorphicMatcher(const Impl& impl) { - return PolymorphicMatcher(impl); -} - -namespace internal { -// Implements a matcher that compares a given value with a -// pre-supplied value using one of the ==, <=, <, etc, operators. The -// two values being compared don't have to have the same type. -// -// The matcher defined here is polymorphic (for example, Eq(5) can be -// used to match an int, a short, a double, etc). Therefore we use -// a template type conversion operator in the implementation. -// -// The following template definition assumes that the Rhs parameter is -// a "bare" type (i.e. neither 'const T' nor 'T&'). -template -class ComparisonBase { - public: - explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {} - template - operator Matcher() const { - return Matcher(new Impl(rhs_)); - } - - private: - template - static const T& Unwrap(const T& v) { return v; } - template - static const T& Unwrap(std::reference_wrapper v) { return v; } - - template - class Impl : public MatcherInterface { - public: - explicit Impl(const Rhs& rhs) : rhs_(rhs) {} - bool MatchAndExplain(Lhs lhs, - MatchResultListener* /* listener */) const override { - return Op()(lhs, Unwrap(rhs_)); - } - void DescribeTo(::std::ostream* os) const override { - *os << D::Desc() << " "; - UniversalPrint(Unwrap(rhs_), os); - } - void DescribeNegationTo(::std::ostream* os) const override { - *os << D::NegatedDesc() << " "; - UniversalPrint(Unwrap(rhs_), os); - } - - private: - Rhs rhs_; - }; - Rhs rhs_; -}; - -template -class EqMatcher : public ComparisonBase, Rhs, AnyEq> { - public: - explicit EqMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyEq>(rhs) { } - static const char* Desc() { return "is equal to"; } - static const char* NegatedDesc() { return "isn't equal to"; } -}; -template -class NeMatcher : public ComparisonBase, Rhs, AnyNe> { - public: - explicit NeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyNe>(rhs) { } - static const char* Desc() { return "isn't equal to"; } - static const char* NegatedDesc() { return "is equal to"; } -}; -template -class LtMatcher : public ComparisonBase, Rhs, AnyLt> { - public: - explicit LtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLt>(rhs) { } - static const char* Desc() { return "is <"; } - static const char* NegatedDesc() { return "isn't <"; } -}; -template -class GtMatcher : public ComparisonBase, Rhs, AnyGt> { - public: - explicit GtMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGt>(rhs) { } - static const char* Desc() { return "is >"; } - static const char* NegatedDesc() { return "isn't >"; } -}; -template -class LeMatcher : public ComparisonBase, Rhs, AnyLe> { - public: - explicit LeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyLe>(rhs) { } - static const char* Desc() { return "is <="; } - static const char* NegatedDesc() { return "isn't <="; } -}; -template -class GeMatcher : public ComparisonBase, Rhs, AnyGe> { - public: - explicit GeMatcher(const Rhs& rhs) - : ComparisonBase, Rhs, AnyGe>(rhs) { } - static const char* Desc() { return "is >="; } - static const char* NegatedDesc() { return "isn't >="; } -}; - -// Implements polymorphic matchers MatchesRegex(regex) and -// ContainsRegex(regex), which can be used as a Matcher as long as -// T can be converted to a string. -class MatchesRegexMatcher { - public: - MatchesRegexMatcher(const RE* regex, bool full_match) - : regex_(regex), full_match_(full_match) {} - -#if GTEST_HAS_ABSL - bool MatchAndExplain(const absl::string_view& s, - MatchResultListener* listener) const { - return MatchAndExplain(std::string(s), listener); - } -#endif // GTEST_HAS_ABSL - - // Accepts pointer types, particularly: - // const char* - // char* - // const wchar_t* - // wchar_t* - template - bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { - return s != nullptr && MatchAndExplain(std::string(s), listener); - } - - // Matches anything that can convert to std::string. - // - // This is a template, not just a plain function with const std::string&, - // because absl::string_view has some interfering non-explicit constructors. - template - bool MatchAndExplain(const MatcheeStringType& s, - MatchResultListener* /* listener */) const { - const std::string& s2(s); - return full_match_ ? RE::FullMatch(s2, *regex_) - : RE::PartialMatch(s2, *regex_); - } - - void DescribeTo(::std::ostream* os) const { - *os << (full_match_ ? "matches" : "contains") << " regular expression "; - UniversalPrinter::Print(regex_->pattern(), os); - } - - void DescribeNegationTo(::std::ostream* os) const { - *os << "doesn't " << (full_match_ ? "match" : "contain") - << " regular expression "; - UniversalPrinter::Print(regex_->pattern(), os); - } - - private: - const std::shared_ptr regex_; - const bool full_match_; -}; -} // namespace internal - -// Matches a string that fully matches regular expression 'regex'. -// The matcher takes ownership of 'regex'. -inline PolymorphicMatcher MatchesRegex( - const internal::RE* regex) { - return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); -} -inline PolymorphicMatcher MatchesRegex( - const std::string& regex) { - return MatchesRegex(new internal::RE(regex)); -} - -// Matches a string that contains regular expression 'regex'. -// The matcher takes ownership of 'regex'. -inline PolymorphicMatcher ContainsRegex( - const internal::RE* regex) { - return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); -} -inline PolymorphicMatcher ContainsRegex( - const std::string& regex) { - return ContainsRegex(new internal::RE(regex)); -} - -// Creates a polymorphic matcher that matches anything equal to x. -// Note: if the parameter of Eq() were declared as const T&, Eq("foo") -// wouldn't compile. -template -inline internal::EqMatcher Eq(T x) { return internal::EqMatcher(x); } - -// Constructs a Matcher from a 'value' of type T. The constructed -// matcher matches any value that's equal to 'value'. -template -Matcher::Matcher(T value) { *this = Eq(value); } - -// Creates a monomorphic matcher that matches anything with type Lhs -// and equal to rhs. A user may need to use this instead of Eq(...) -// in order to resolve an overloading ambiguity. -// -// TypedEq(x) is just a convenient short-hand for Matcher(Eq(x)) -// or Matcher(x), but more readable than the latter. -// -// We could define similar monomorphic matchers for other comparison -// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do -// it yet as those are used much less than Eq() in practice. A user -// can always write Matcher(Lt(5)) to be explicit about the type, -// for example. -template -inline Matcher TypedEq(const Rhs& rhs) { return Eq(rhs); } - -// Creates a polymorphic matcher that matches anything >= x. -template -inline internal::GeMatcher Ge(Rhs x) { - return internal::GeMatcher(x); -} - -// Creates a polymorphic matcher that matches anything > x. -template -inline internal::GtMatcher Gt(Rhs x) { - return internal::GtMatcher(x); -} - -// Creates a polymorphic matcher that matches anything <= x. -template -inline internal::LeMatcher Le(Rhs x) { - return internal::LeMatcher(x); -} - -// Creates a polymorphic matcher that matches anything < x. -template -inline internal::LtMatcher Lt(Rhs x) { - return internal::LtMatcher(x); -} - -// Creates a polymorphic matcher that matches anything != x. -template -inline internal::NeMatcher Ne(Rhs x) { - return internal::NeMatcher(x); -} -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 5046 - -#endif // GTEST_INCLUDE_GTEST_GTEST_MATCHERS_H_ - -#include -#include - -namespace testing { -namespace internal { - -GTEST_DECLARE_string_(internal_run_death_test); - -// Names of the flags (needed for parsing Google Test flags). -const char kDeathTestStyleFlag[] = "death_test_style"; -const char kDeathTestUseFork[] = "death_test_use_fork"; -const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; - -#if GTEST_HAS_DEATH_TEST - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -// DeathTest is a class that hides much of the complexity of the -// GTEST_DEATH_TEST_ macro. It is abstract; its static Create method -// returns a concrete class that depends on the prevailing death test -// style, as defined by the --gtest_death_test_style and/or -// --gtest_internal_run_death_test flags. - -// In describing the results of death tests, these terms are used with -// the corresponding definitions: -// -// exit status: The integer exit information in the format specified -// by wait(2) -// exit code: The integer code passed to exit(3), _exit(2), or -// returned from main() -class GTEST_API_ DeathTest { - public: - // Create returns false if there was an error determining the - // appropriate action to take for the current death test; for example, - // if the gtest_death_test_style flag is set to an invalid value. - // The LastMessage method will return a more detailed message in that - // case. Otherwise, the DeathTest pointer pointed to by the "test" - // argument is set. If the death test should be skipped, the pointer - // is set to NULL; otherwise, it is set to the address of a new concrete - // DeathTest object that controls the execution of the current test. - static bool Create(const char* statement, Matcher matcher, - const char* file, int line, DeathTest** test); - DeathTest(); - virtual ~DeathTest() { } - - // A helper class that aborts a death test when it's deleted. - class ReturnSentinel { - public: - explicit ReturnSentinel(DeathTest* test) : test_(test) { } - ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } - private: - DeathTest* const test_; - GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); - } GTEST_ATTRIBUTE_UNUSED_; - - // An enumeration of possible roles that may be taken when a death - // test is encountered. EXECUTE means that the death test logic should - // be executed immediately. OVERSEE means that the program should prepare - // the appropriate environment for a child process to execute the death - // test, then wait for it to complete. - enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; - - // An enumeration of the three reasons that a test might be aborted. - enum AbortReason { - TEST_ENCOUNTERED_RETURN_STATEMENT, - TEST_THREW_EXCEPTION, - TEST_DID_NOT_DIE - }; - - // Assumes one of the above roles. - virtual TestRole AssumeRole() = 0; - - // Waits for the death test to finish and returns its status. - virtual int Wait() = 0; - - // Returns true if the death test passed; that is, the test process - // exited during the test, its exit status matches a user-supplied - // predicate, and its stderr output matches a user-supplied regular - // expression. - // The user-supplied predicate may be a macro expression rather - // than a function pointer or functor, or else Wait and Passed could - // be combined. - virtual bool Passed(bool exit_status_ok) = 0; - - // Signals that the death test did not die as expected. - virtual void Abort(AbortReason reason) = 0; - - // Returns a human-readable outcome message regarding the outcome of - // the last death test. - static const char* LastMessage(); - - static void set_last_death_test_message(const std::string& message); - - private: - // A string containing a description of the outcome of the last death test. - static std::string last_death_test_message_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); -}; - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -// Factory interface for death tests. May be mocked out for testing. -class DeathTestFactory { - public: - virtual ~DeathTestFactory() { } - virtual bool Create(const char* statement, - Matcher matcher, const char* file, - int line, DeathTest** test) = 0; -}; - -// A concrete DeathTestFactory implementation for normal use. -class DefaultDeathTestFactory : public DeathTestFactory { - public: - bool Create(const char* statement, Matcher matcher, - const char* file, int line, DeathTest** test) override; -}; - -// Returns true if exit_status describes a process that was terminated -// by a signal, or exited normally with a nonzero exit code. -GTEST_API_ bool ExitedUnsuccessfully(int exit_status); - -// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads -// and interpreted as a regex (rather than an Eq matcher) for legacy -// compatibility. -inline Matcher MakeDeathTestMatcher( - ::testing::internal::RE regex) { - return ContainsRegex(regex.pattern()); -} -inline Matcher MakeDeathTestMatcher(const char* regex) { - return ContainsRegex(regex); -} -inline Matcher MakeDeathTestMatcher( - const ::std::string& regex) { - return ContainsRegex(regex); -} - -// If a Matcher is passed to EXPECT_DEATH (etc.), it's -// used directly. -inline Matcher MakeDeathTestMatcher( - Matcher matcher) { - return matcher; -} - -// Traps C++ exceptions escaping statement and reports them as test -// failures. Note that trapping SEH exceptions is not implemented here. -# if GTEST_HAS_EXCEPTIONS -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - try { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } catch (const ::std::exception& gtest_exception) { \ - fprintf(\ - stderr, \ - "\n%s: Caught std::exception-derived exception escaping the " \ - "death test statement. Exception message: %s\n", \ - ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ - gtest_exception.what()); \ - fflush(stderr); \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } catch (...) { \ - death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ - } - -# else -# define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) - -# endif - -// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, -// ASSERT_EXIT*, and EXPECT_EXIT*. -#define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - ::testing::internal::DeathTest* gtest_dt; \ - if (!::testing::internal::DeathTest::Create( \ - #statement, \ - ::testing::internal::MakeDeathTestMatcher(regex_or_matcher), \ - __FILE__, __LINE__, >est_dt)) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - if (gtest_dt != nullptr) { \ - std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \ - switch (gtest_dt->AssumeRole()) { \ - case ::testing::internal::DeathTest::OVERSEE_TEST: \ - if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ - goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ - } \ - break; \ - case ::testing::internal::DeathTest::EXECUTE_TEST: { \ - ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \ - gtest_dt); \ - GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ - gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ - break; \ - } \ - default: \ - break; \ - } \ - } \ - } else \ - GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \ - : fail(::testing::internal::DeathTest::LastMessage()) -// The symbol "fail" here expands to something into which a message -// can be streamed. - -// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in -// NDEBUG mode. In this case we need the statements to be executed and the macro -// must accept a streamed message even though the message is never printed. -// The regex object is not evaluated, but it is used to prevent "unused" -// warnings and to avoid an expression that doesn't compile in debug mode. -#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - } else if (!::testing::internal::AlwaysTrue()) { \ - ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \ - } else \ - ::testing::Message() - -// A class representing the parsed contents of the -// --gtest_internal_run_death_test flag, as it existed when -// RUN_ALL_TESTS was called. -class InternalRunDeathTestFlag { - public: - InternalRunDeathTestFlag(const std::string& a_file, - int a_line, - int an_index, - int a_write_fd) - : file_(a_file), line_(a_line), index_(an_index), - write_fd_(a_write_fd) {} - - ~InternalRunDeathTestFlag() { - if (write_fd_ >= 0) - posix::Close(write_fd_); - } - - const std::string& file() const { return file_; } - int line() const { return line_; } - int index() const { return index_; } - int write_fd() const { return write_fd_; } - - private: - std::string file_; - int line_; - int index_; - int write_fd_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); -}; - -// Returns a newly created InternalRunDeathTestFlag object with fields -// initialized from the GTEST_FLAG(internal_run_death_test) flag if -// the flag is specified; otherwise returns NULL. -InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); - -#endif // GTEST_HAS_DEATH_TEST - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ - -namespace testing { - -// This flag controls the style of death tests. Valid values are "threadsafe", -// meaning that the death test child process will re-execute the test binary -// from the start, running only a single death test, or "fast", -// meaning that the child process will execute the test logic immediately -// after forking. -GTEST_DECLARE_string_(death_test_style); - -#if GTEST_HAS_DEATH_TEST - -namespace internal { - -// Returns a Boolean value indicating whether the caller is currently -// executing in the context of the death test child process. Tools such as -// Valgrind heap checkers may need this to modify their behavior in death -// tests. IMPORTANT: This is an internal utility. Using it may break the -// implementation of death tests. User code MUST NOT use it. -GTEST_API_ bool InDeathTestChild(); - -} // namespace internal - -// The following macros are useful for writing death tests. - -// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is -// executed: -// -// 1. It generates a warning if there is more than one active -// thread. This is because it's safe to fork() or clone() only -// when there is a single thread. -// -// 2. The parent process clone()s a sub-process and runs the death -// test in it; the sub-process exits with code 0 at the end of the -// death test, if it hasn't exited already. -// -// 3. The parent process waits for the sub-process to terminate. -// -// 4. The parent process checks the exit code and error message of -// the sub-process. -// -// Examples: -// -// ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); -// for (int i = 0; i < 5; i++) { -// EXPECT_DEATH(server.ProcessRequest(i), -// "Invalid request .* in ProcessRequest()") -// << "Failed to die on request " << i; -// } -// -// ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); -// -// bool KilledBySIGHUP(int exit_code) { -// return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; -// } -// -// ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); -// -// On the regular expressions used in death tests: -// -// GOOGLETEST_CM0005 DO NOT DELETE -// On POSIX-compliant systems (*nix), we use the library, -// which uses the POSIX extended regex syntax. -// -// On other platforms (e.g. Windows or Mac), we only support a simple regex -// syntax implemented as part of Google Test. This limited -// implementation should be enough most of the time when writing -// death tests; though it lacks many features you can find in PCRE -// or POSIX extended regex syntax. For example, we don't support -// union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and -// repetition count ("x{5,7}"), among others. -// -// Below is the syntax that we do support. We chose it to be a -// subset of both PCRE and POSIX extended regex, so it's easy to -// learn wherever you come from. In the following: 'A' denotes a -// literal character, period (.), or a single \\ escape sequence; -// 'x' and 'y' denote regular expressions; 'm' and 'n' are for -// natural numbers. -// -// c matches any literal character c -// \\d matches any decimal digit -// \\D matches any character that's not a decimal digit -// \\f matches \f -// \\n matches \n -// \\r matches \r -// \\s matches any ASCII whitespace, including \n -// \\S matches any character that's not a whitespace -// \\t matches \t -// \\v matches \v -// \\w matches any letter, _, or decimal digit -// \\W matches any character that \\w doesn't match -// \\c matches any literal character c, which must be a punctuation -// . matches any single character except \n -// A? matches 0 or 1 occurrences of A -// A* matches 0 or many occurrences of A -// A+ matches 1 or many occurrences of A -// ^ matches the beginning of a string (not that of each line) -// $ matches the end of a string (not that of each line) -// xy matches x followed by y -// -// If you accidentally use PCRE or POSIX extended regex features -// not implemented by us, you will get a run-time failure. In that -// case, please try to rewrite your regular expression within the -// above syntax. -// -// This implementation is *not* meant to be as highly tuned or robust -// as a compiled regex library, but should perform well enough for a -// death test, which already incurs significant overhead by launching -// a child process. -// -// Known caveats: -// -// A "threadsafe" style death test obtains the path to the test -// program from argv[0] and re-executes it in the sub-process. For -// simplicity, the current implementation doesn't search the PATH -// when launching the sub-process. This means that the user must -// invoke the test program via a path that contains at least one -// path separator (e.g. path/to/foo_test and -// /absolute/path/to/bar_test are fine, but foo_test is not). This -// is rarely a problem as people usually don't put the test binary -// directory in PATH. -// - -// Asserts that a given statement causes the program to exit, with an -// integer exit status that satisfies predicate, and emitting error output -// that matches regex. -# define ASSERT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) - -// Like ASSERT_EXIT, but continues on to successive tests in the -// test suite, if any: -# define EXPECT_EXIT(statement, predicate, regex) \ - GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) - -// Asserts that a given statement causes the program to exit, either by -// explicitly exiting with a nonzero exit code or being killed by a -// signal, and emitting error output that matches regex. -# define ASSERT_DEATH(statement, regex) \ - ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) - -// Like ASSERT_DEATH, but continues on to successive tests in the -// test suite, if any: -# define EXPECT_DEATH(statement, regex) \ - EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) - -// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: - -// Tests that an exit code describes a normal exit with a given exit code. -class GTEST_API_ ExitedWithCode { - public: - explicit ExitedWithCode(int exit_code); - bool operator()(int exit_status) const; - private: - // No implementation - assignment is unsupported. - void operator=(const ExitedWithCode& other); - - const int exit_code_; -}; - -# if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA -// Tests that an exit code describes an exit due to termination by a -// given signal. -// GOOGLETEST_CM0006 DO NOT DELETE -class GTEST_API_ KilledBySignal { - public: - explicit KilledBySignal(int signum); - bool operator()(int exit_status) const; - private: - const int signum_; -}; -# endif // !GTEST_OS_WINDOWS - -// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. -// The death testing framework causes this to have interesting semantics, -// since the sideeffects of the call are only visible in opt mode, and not -// in debug mode. -// -// In practice, this can be used to test functions that utilize the -// LOG(DFATAL) macro using the following style: -// -// int DieInDebugOr12(int* sideeffect) { -// if (sideeffect) { -// *sideeffect = 12; -// } -// LOG(DFATAL) << "death"; -// return 12; -// } -// -// TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) { -// int sideeffect = 0; -// // Only asserts in dbg. -// EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); -// -// #ifdef NDEBUG -// // opt-mode has sideeffect visible. -// EXPECT_EQ(12, sideeffect); -// #else -// // dbg-mode no visible sideeffect. -// EXPECT_EQ(0, sideeffect); -// #endif -// } -// -// This will assert that DieInDebugReturn12InOpt() crashes in debug -// mode, usually due to a DCHECK or LOG(DFATAL), but returns the -// appropriate fallback value (12 in this case) in opt mode. If you -// need to test that a function has appropriate side-effects in opt -// mode, include assertions against the side-effects. A general -// pattern for this is: -// -// EXPECT_DEBUG_DEATH({ -// // Side-effects here will have an effect after this statement in -// // opt mode, but none in debug mode. -// EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); -// }, "death"); -// -# ifdef NDEBUG - -# define EXPECT_DEBUG_DEATH(statement, regex) \ - GTEST_EXECUTE_STATEMENT_(statement, regex) - -# define ASSERT_DEBUG_DEATH(statement, regex) \ - GTEST_EXECUTE_STATEMENT_(statement, regex) - -# else - -# define EXPECT_DEBUG_DEATH(statement, regex) \ - EXPECT_DEATH(statement, regex) - -# define ASSERT_DEBUG_DEATH(statement, regex) \ - ASSERT_DEATH(statement, regex) - -# endif // NDEBUG for EXPECT_DEBUG_DEATH -#endif // GTEST_HAS_DEATH_TEST - -// This macro is used for implementing macros such as -// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where -// death tests are not supported. Those macros must compile on such systems -// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters -// on systems that support death tests. This allows one to write such a macro on -// a system that does not support death tests and be sure that it will compile -// on a death-test supporting system. It is exposed publicly so that systems -// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST -// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and -// ASSERT_DEATH_IF_SUPPORTED. -// -// Parameters: -// statement - A statement that a macro such as EXPECT_DEATH would test -// for program termination. This macro has to make sure this -// statement is compiled but not executed, to ensure that -// EXPECT_DEATH_IF_SUPPORTED compiles with a certain -// parameter if and only if EXPECT_DEATH compiles with it. -// regex - A regex that a macro such as EXPECT_DEATH would use to test -// the output of statement. This parameter has to be -// compiled but not evaluated by this macro, to ensure that -// this macro only accepts expressions that a macro such as -// EXPECT_DEATH would accept. -// terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED -// and a return statement for ASSERT_DEATH_IF_SUPPORTED. -// This ensures that ASSERT_DEATH_IF_SUPPORTED will not -// compile inside functions where ASSERT_DEATH doesn't -// compile. -// -// The branch that has an always false condition is used to ensure that -// statement and regex are compiled (and thus syntactically correct) but -// never executed. The unreachable code macro protects the terminator -// statement from generating an 'unreachable code' warning in case -// statement unconditionally returns or throws. The Message constructor at -// the end allows the syntax of streaming additional messages into the -// macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. -# define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (::testing::internal::AlwaysTrue()) { \ - GTEST_LOG_(WARNING) \ - << "Death tests are not supported on this platform.\n" \ - << "Statement '" #statement "' cannot be verified."; \ - } else if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::RE::PartialMatch(".*", (regex)); \ - GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ - terminator; \ - } else \ - ::testing::Message() - -// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and -// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if -// death tests are supported; otherwise they just issue a warning. This is -// useful when you are combining death test assertions with normal test -// assertions in one test. -#if GTEST_HAS_DEATH_TEST -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - EXPECT_DEATH(statement, regex) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - ASSERT_DEATH(statement, regex) -#else -# define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, ) -# define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ - GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return) -#endif - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Macros and functions for implementing parameterized tests -// in Google C++ Testing and Mocking Framework (Google Test) -// -// This file is generated by a SCRIPT. DO NOT EDIT BY HAND! -// -// GOOGLETEST_CM0001 DO NOT DELETE -#ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ - - -// Value-parameterized tests allow you to test your code with different -// parameters without writing multiple copies of the same test. -// -// Here is how you use value-parameterized tests: - -#if 0 - -// To write value-parameterized tests, first you should define a fixture -// class. It is usually derived from testing::TestWithParam (see below for -// another inheritance scheme that's sometimes useful in more complicated -// class hierarchies), where the type of your parameter values. -// TestWithParam is itself derived from testing::Test. T can be any -// copyable type. If it's a raw pointer, you are responsible for managing the -// lifespan of the pointed values. - -class FooTest : public ::testing::TestWithParam { - // You can implement all the usual class fixture members here. -}; - -// Then, use the TEST_P macro to define as many parameterized tests -// for this fixture as you want. The _P suffix is for "parameterized" -// or "pattern", whichever you prefer to think. - -TEST_P(FooTest, DoesBlah) { - // Inside a test, access the test parameter with the GetParam() method - // of the TestWithParam class: - EXPECT_TRUE(foo.Blah(GetParam())); - ... -} - -TEST_P(FooTest, HasBlahBlah) { - ... -} - -// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test -// case with any set of parameters you want. Google Test defines a number -// of functions for generating test parameters. They return what we call -// (surprise!) parameter generators. Here is a summary of them, which -// are all in the testing namespace: -// -// -// Range(begin, end [, step]) - Yields values {begin, begin+step, -// begin+step+step, ...}. The values do not -// include end. step defaults to 1. -// Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. -// ValuesIn(container) - Yields values from a C-style array, an STL -// ValuesIn(begin,end) container, or an iterator range [begin, end). -// Bool() - Yields sequence {false, true}. -// Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product -// for the math savvy) of the values generated -// by the N generators. -// -// For more details, see comments at the definitions of these functions below -// in this file. -// -// The following statement will instantiate tests from the FooTest test suite -// each with parameter values "meeny", "miny", and "moe". - -INSTANTIATE_TEST_SUITE_P(InstantiationName, - FooTest, - Values("meeny", "miny", "moe")); - -// To distinguish different instances of the pattern, (yes, you -// can instantiate it more than once) the first argument to the -// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the -// actual test suite name. Remember to pick unique prefixes for different -// instantiations. The tests from the instantiation above will have -// these names: -// -// * InstantiationName/FooTest.DoesBlah/0 for "meeny" -// * InstantiationName/FooTest.DoesBlah/1 for "miny" -// * InstantiationName/FooTest.DoesBlah/2 for "moe" -// * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" -// * InstantiationName/FooTest.HasBlahBlah/1 for "miny" -// * InstantiationName/FooTest.HasBlahBlah/2 for "moe" -// -// You can use these names in --gtest_filter. -// -// This statement will instantiate all tests from FooTest again, each -// with parameter values "cat" and "dog": - -const char* pets[] = {"cat", "dog"}; -INSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); - -// The tests from the instantiation above will have these names: -// -// * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" -// * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" -// * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" -// * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" -// -// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests -// in the given test suite, whether their definitions come before or -// AFTER the INSTANTIATE_TEST_SUITE_P statement. -// -// Please also note that generator expressions (including parameters to the -// generators) are evaluated in InitGoogleTest(), after main() has started. -// This allows the user on one hand, to adjust generator parameters in order -// to dynamically determine a set of tests to run and on the other hand, -// give the user a chance to inspect the generated tests with Google Test -// reflection API before RUN_ALL_TESTS() is executed. -// -// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc -// for more examples. -// -// In the future, we plan to publish the API for defining new parameter -// generators. But for now this interface remains part of the internal -// implementation and is subject to change. -// -// -// A parameterized test fixture must be derived from testing::Test and from -// testing::WithParamInterface, where T is the type of the parameter -// values. Inheriting from TestWithParam satisfies that requirement because -// TestWithParam inherits from both Test and WithParamInterface. In more -// complicated hierarchies, however, it is occasionally useful to inherit -// separately from Test and WithParamInterface. For example: - -class BaseTest : public ::testing::Test { - // You can inherit all the usual members for a non-parameterized test - // fixture here. -}; - -class DerivedTest : public BaseTest, public ::testing::WithParamInterface { - // The usual test fixture members go here too. -}; - -TEST_F(BaseTest, HasFoo) { - // This is an ordinary non-parameterized test. -} - -TEST_P(DerivedTest, DoesBlah) { - // GetParam works just the same here as if you inherit from TestWithParam. - EXPECT_TRUE(foo.Blah(GetParam())); -} - -#endif // 0 - -#include -#include - -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// Type and function utilities for implementing parameterized tests. - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ -#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include - - -namespace testing { -// Input to a parameterized test name generator, describing a test parameter. -// Consists of the parameter value and the integer parameter index. -template -struct TestParamInfo { - TestParamInfo(const ParamType& a_param, size_t an_index) : - param(a_param), - index(an_index) {} - ParamType param; - size_t index; -}; - -// A builtin parameterized test name generator which returns the result of -// testing::PrintToString. -struct PrintToStringParamName { - template - std::string operator()(const TestParamInfo& info) const { - return PrintToString(info.param); - } -}; - -namespace internal { - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// Utility Functions - -// Outputs a message explaining invalid registration of different -// fixture class for the same test suite. This may happen when -// TEST_P macro is used to define two tests with the same name -// but in different namespaces. -GTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name, - CodeLocation code_location); - -template class ParamGeneratorInterface; -template class ParamGenerator; - -// Interface for iterating over elements provided by an implementation -// of ParamGeneratorInterface. -template -class ParamIteratorInterface { - public: - virtual ~ParamIteratorInterface() {} - // A pointer to the base generator instance. - // Used only for the purposes of iterator comparison - // to make sure that two iterators belong to the same generator. - virtual const ParamGeneratorInterface* BaseGenerator() const = 0; - // Advances iterator to point to the next element - // provided by the generator. The caller is responsible - // for not calling Advance() on an iterator equal to - // BaseGenerator()->End(). - virtual void Advance() = 0; - // Clones the iterator object. Used for implementing copy semantics - // of ParamIterator. - virtual ParamIteratorInterface* Clone() const = 0; - // Dereferences the current iterator and provides (read-only) access - // to the pointed value. It is the caller's responsibility not to call - // Current() on an iterator equal to BaseGenerator()->End(). - // Used for implementing ParamGenerator::operator*(). - virtual const T* Current() const = 0; - // Determines whether the given iterator and other point to the same - // element in the sequence generated by the generator. - // Used for implementing ParamGenerator::operator==(). - virtual bool Equals(const ParamIteratorInterface& other) const = 0; -}; - -// Class iterating over elements provided by an implementation of -// ParamGeneratorInterface. It wraps ParamIteratorInterface -// and implements the const forward iterator concept. -template -class ParamIterator { - public: - typedef T value_type; - typedef const T& reference; - typedef ptrdiff_t difference_type; - - // ParamIterator assumes ownership of the impl_ pointer. - ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} - ParamIterator& operator=(const ParamIterator& other) { - if (this != &other) - impl_.reset(other.impl_->Clone()); - return *this; - } - - const T& operator*() const { return *impl_->Current(); } - const T* operator->() const { return impl_->Current(); } - // Prefix version of operator++. - ParamIterator& operator++() { - impl_->Advance(); - return *this; - } - // Postfix version of operator++. - ParamIterator operator++(int /*unused*/) { - ParamIteratorInterface* clone = impl_->Clone(); - impl_->Advance(); - return ParamIterator(clone); - } - bool operator==(const ParamIterator& other) const { - return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); - } - bool operator!=(const ParamIterator& other) const { - return !(*this == other); - } - - private: - friend class ParamGenerator; - explicit ParamIterator(ParamIteratorInterface* impl) : impl_(impl) {} - std::unique_ptr > impl_; -}; - -// ParamGeneratorInterface is the binary interface to access generators -// defined in other translation units. -template -class ParamGeneratorInterface { - public: - typedef T ParamType; - - virtual ~ParamGeneratorInterface() {} - - // Generator interface definition - virtual ParamIteratorInterface* Begin() const = 0; - virtual ParamIteratorInterface* End() const = 0; -}; - -// Wraps ParamGeneratorInterface and provides general generator syntax -// compatible with the STL Container concept. -// This class implements copy initialization semantics and the contained -// ParamGeneratorInterface instance is shared among all copies -// of the original object. This is possible because that instance is immutable. -template -class ParamGenerator { - public: - typedef ParamIterator iterator; - - explicit ParamGenerator(ParamGeneratorInterface* impl) : impl_(impl) {} - ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} - - ParamGenerator& operator=(const ParamGenerator& other) { - impl_ = other.impl_; - return *this; - } - - iterator begin() const { return iterator(impl_->Begin()); } - iterator end() const { return iterator(impl_->End()); } - - private: - std::shared_ptr > impl_; -}; - -// Generates values from a range of two comparable values. Can be used to -// generate sequences of user-defined types that implement operator+() and -// operator<(). -// This class is used in the Range() function. -template -class RangeGenerator : public ParamGeneratorInterface { - public: - RangeGenerator(T begin, T end, IncrementT step) - : begin_(begin), end_(end), - step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} - ~RangeGenerator() override {} - - ParamIteratorInterface* Begin() const override { - return new Iterator(this, begin_, 0, step_); - } - ParamIteratorInterface* End() const override { - return new Iterator(this, end_, end_index_, step_); - } - - private: - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, T value, int index, - IncrementT step) - : base_(base), value_(value), index_(index), step_(step) {} - ~Iterator() override {} - - const ParamGeneratorInterface* BaseGenerator() const override { - return base_; - } - void Advance() override { - value_ = static_cast(value_ + step_); - index_++; - } - ParamIteratorInterface* Clone() const override { - return new Iterator(*this); - } - const T* Current() const override { return &value_; } - bool Equals(const ParamIteratorInterface& other) const override { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const int other_index = - CheckedDowncastToActualType(&other)->index_; - return index_ == other_index; - } - - private: - Iterator(const Iterator& other) - : ParamIteratorInterface(), - base_(other.base_), value_(other.value_), index_(other.index_), - step_(other.step_) {} - - // No implementation - assignment is unsupported. - void operator=(const Iterator& other); - - const ParamGeneratorInterface* const base_; - T value_; - int index_; - const IncrementT step_; - }; // class RangeGenerator::Iterator - - static int CalculateEndIndex(const T& begin, - const T& end, - const IncrementT& step) { - int end_index = 0; - for (T i = begin; i < end; i = static_cast(i + step)) - end_index++; - return end_index; - } - - // No implementation - assignment is unsupported. - void operator=(const RangeGenerator& other); - - const T begin_; - const T end_; - const IncrementT step_; - // The index for the end() iterator. All the elements in the generated - // sequence are indexed (0-based) to aid iterator comparison. - const int end_index_; -}; // class RangeGenerator - - -// Generates values from a pair of STL-style iterators. Used in the -// ValuesIn() function. The elements are copied from the source range -// since the source can be located on the stack, and the generator -// is likely to persist beyond that stack frame. -template -class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface { - public: - template - ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) - : container_(begin, end) {} - ~ValuesInIteratorRangeGenerator() override {} - - ParamIteratorInterface* Begin() const override { - return new Iterator(this, container_.begin()); - } - ParamIteratorInterface* End() const override { - return new Iterator(this, container_.end()); - } - - private: - typedef typename ::std::vector ContainerType; - - class Iterator : public ParamIteratorInterface { - public: - Iterator(const ParamGeneratorInterface* base, - typename ContainerType::const_iterator iterator) - : base_(base), iterator_(iterator) {} - ~Iterator() override {} - - const ParamGeneratorInterface* BaseGenerator() const override { - return base_; - } - void Advance() override { - ++iterator_; - value_.reset(); - } - ParamIteratorInterface* Clone() const override { - return new Iterator(*this); - } - // We need to use cached value referenced by iterator_ because *iterator_ - // can return a temporary object (and of type other then T), so just - // having "return &*iterator_;" doesn't work. - // value_ is updated here and not in Advance() because Advance() - // can advance iterator_ beyond the end of the range, and we cannot - // detect that fact. The client code, on the other hand, is - // responsible for not calling Current() on an out-of-range iterator. - const T* Current() const override { - if (value_.get() == nullptr) value_.reset(new T(*iterator_)); - return value_.get(); - } - bool Equals(const ParamIteratorInterface& other) const override { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - return iterator_ == - CheckedDowncastToActualType(&other)->iterator_; - } - - private: - Iterator(const Iterator& other) - // The explicit constructor call suppresses a false warning - // emitted by gcc when supplied with the -Wextra option. - : ParamIteratorInterface(), - base_(other.base_), - iterator_(other.iterator_) {} - - const ParamGeneratorInterface* const base_; - typename ContainerType::const_iterator iterator_; - // A cached value of *iterator_. We keep it here to allow access by - // pointer in the wrapping iterator's operator->(). - // value_ needs to be mutable to be accessed in Current(). - // Use of std::unique_ptr helps manage cached value's lifetime, - // which is bound by the lifespan of the iterator itself. - mutable std::unique_ptr value_; - }; // class ValuesInIteratorRangeGenerator::Iterator - - // No implementation - assignment is unsupported. - void operator=(const ValuesInIteratorRangeGenerator& other); - - const ContainerType container_; -}; // class ValuesInIteratorRangeGenerator - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Default parameterized test name generator, returns a string containing the -// integer test parameter index. -template -std::string DefaultParamName(const TestParamInfo& info) { - Message name_stream; - name_stream << info.index; - return name_stream.GetString(); -} - -template -void TestNotEmpty() { - static_assert(sizeof(T) == 0, "Empty arguments are not allowed."); -} -template -void TestNotEmpty(const T&) {} - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Stores a parameter value and later creates tests parameterized with that -// value. -template -class ParameterizedTestFactory : public TestFactoryBase { - public: - typedef typename TestClass::ParamType ParamType; - explicit ParameterizedTestFactory(ParamType parameter) : - parameter_(parameter) {} - Test* CreateTest() override { - TestClass::SetParam(¶meter_); - return new TestClass(); - } - - private: - const ParamType parameter_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// TestMetaFactoryBase is a base class for meta-factories that create -// test factories for passing into MakeAndRegisterTestInfo function. -template -class TestMetaFactoryBase { - public: - virtual ~TestMetaFactoryBase() {} - - virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// TestMetaFactory creates test factories for passing into -// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives -// ownership of test factory pointer, same factory object cannot be passed -// into that method twice. But ParameterizedTestSuiteInfo is going to call -// it for each Test/Parameter value combination. Thus it needs meta factory -// creator class. -template -class TestMetaFactory - : public TestMetaFactoryBase { - public: - using ParamType = typename TestSuite::ParamType; - - TestMetaFactory() {} - - TestFactoryBase* CreateTestFactory(ParamType parameter) override { - return new ParameterizedTestFactory(parameter); - } - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestSuiteInfoBase is a generic interface -// to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase -// accumulates test information provided by TEST_P macro invocations -// and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations -// and uses that information to register all resulting test instances -// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds -// a collection of pointers to the ParameterizedTestSuiteInfo objects -// and calls RegisterTests() on each of them when asked. -class ParameterizedTestSuiteInfoBase { - public: - virtual ~ParameterizedTestSuiteInfoBase() {} - - // Base part of test suite name for display purposes. - virtual const std::string& GetTestSuiteName() const = 0; - // Test case id to verify identity. - virtual TypeId GetTestSuiteTypeId() const = 0; - // UnitTest class invokes this method to register tests in this - // test suite right before running them in RUN_ALL_TESTS macro. - // This method should not be called more than once on any single - // instance of a ParameterizedTestSuiteInfoBase derived class. - virtual void RegisterTests() = 0; - - protected: - ParameterizedTestSuiteInfoBase() {} - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfoBase); -}; - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P -// macro invocations for a particular test suite and generators -// obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that -// test suite. It registers tests with all values generated by all -// generators when asked. -template -class ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase { - public: - // ParamType and GeneratorCreationFunc are private types but are required - // for declarations of public methods AddTestPattern() and - // AddTestSuiteInstantiation(). - using ParamType = typename TestSuite::ParamType; - // A function that returns an instance of appropriate generator type. - typedef ParamGenerator(GeneratorCreationFunc)(); - using ParamNameGeneratorFunc = std::string(const TestParamInfo&); - - explicit ParameterizedTestSuiteInfo(const char* name, - CodeLocation code_location) - : test_suite_name_(name), code_location_(code_location) {} - - // Test case base name for display purposes. - const std::string& GetTestSuiteName() const override { - return test_suite_name_; - } - // Test case id to verify identity. - TypeId GetTestSuiteTypeId() const override { return GetTypeId(); } - // TEST_P macro uses AddTestPattern() to record information - // about a single test in a LocalTestInfo structure. - // test_suite_name is the base name of the test suite (without invocation - // prefix). test_base_name is the name of an individual test without - // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is - // test suite base name and DoBar is test base name. - void AddTestPattern(const char* test_suite_name, const char* test_base_name, - TestMetaFactoryBase* meta_factory) { - tests_.push_back(std::shared_ptr( - new TestInfo(test_suite_name, test_base_name, meta_factory))); - } - // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information - // about a generator. - int AddTestSuiteInstantiation(const std::string& instantiation_name, - GeneratorCreationFunc* func, - ParamNameGeneratorFunc* name_func, - const char* file, int line) { - instantiations_.push_back( - InstantiationInfo(instantiation_name, func, name_func, file, line)); - return 0; // Return value used only to run this method in namespace scope. - } - // UnitTest class invokes this method to register tests in this test suite - // test suites right before running tests in RUN_ALL_TESTS macro. - // This method should not be called more than once on any single - // instance of a ParameterizedTestSuiteInfoBase derived class. - // UnitTest has a guard to prevent from calling this method more than once. - void RegisterTests() override { - for (typename TestInfoContainer::iterator test_it = tests_.begin(); - test_it != tests_.end(); ++test_it) { - std::shared_ptr test_info = *test_it; - for (typename InstantiationContainer::iterator gen_it = - instantiations_.begin(); gen_it != instantiations_.end(); - ++gen_it) { - const std::string& instantiation_name = gen_it->name; - ParamGenerator generator((*gen_it->generator)()); - ParamNameGeneratorFunc* name_func = gen_it->name_func; - const char* file = gen_it->file; - int line = gen_it->line; - - std::string test_suite_name; - if ( !instantiation_name.empty() ) - test_suite_name = instantiation_name + "/"; - test_suite_name += test_info->test_suite_base_name; - - size_t i = 0; - std::set test_param_names; - for (typename ParamGenerator::iterator param_it = - generator.begin(); - param_it != generator.end(); ++param_it, ++i) { - Message test_name_stream; - - std::string param_name = name_func( - TestParamInfo(*param_it, i)); - - GTEST_CHECK_(IsValidParamName(param_name)) - << "Parameterized test name '" << param_name - << "' is invalid, in " << file - << " line " << line << std::endl; - - GTEST_CHECK_(test_param_names.count(param_name) == 0) - << "Duplicate parameterized test name '" << param_name - << "', in " << file << " line " << line << std::endl; - - test_param_names.insert(param_name); - - if (!test_info->test_base_name.empty()) { - test_name_stream << test_info->test_base_name << "/"; - } - test_name_stream << param_name; - MakeAndRegisterTestInfo( - test_suite_name.c_str(), test_name_stream.GetString().c_str(), - nullptr, // No type parameter. - PrintToString(*param_it).c_str(), code_location_, - GetTestSuiteTypeId(), - SuiteApiResolver::GetSetUpCaseOrSuite(file, line), - SuiteApiResolver::GetTearDownCaseOrSuite(file, line), - test_info->test_meta_factory->CreateTestFactory(*param_it)); - } // for param_it - } // for gen_it - } // for test_it - } // RegisterTests - - private: - // LocalTestInfo structure keeps information about a single test registered - // with TEST_P macro. - struct TestInfo { - TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name, - TestMetaFactoryBase* a_test_meta_factory) - : test_suite_base_name(a_test_suite_base_name), - test_base_name(a_test_base_name), - test_meta_factory(a_test_meta_factory) {} - - const std::string test_suite_base_name; - const std::string test_base_name; - const std::unique_ptr > test_meta_factory; - }; - using TestInfoContainer = ::std::vector >; - // Records data received from INSTANTIATE_TEST_SUITE_P macros: - // - struct InstantiationInfo { - InstantiationInfo(const std::string &name_in, - GeneratorCreationFunc* generator_in, - ParamNameGeneratorFunc* name_func_in, - const char* file_in, - int line_in) - : name(name_in), - generator(generator_in), - name_func(name_func_in), - file(file_in), - line(line_in) {} - - std::string name; - GeneratorCreationFunc* generator; - ParamNameGeneratorFunc* name_func; - const char* file; - int line; - }; - typedef ::std::vector InstantiationContainer; - - static bool IsValidParamName(const std::string& name) { - // Check for empty string - if (name.empty()) - return false; - - // Check for invalid characters - for (std::string::size_type index = 0; index < name.size(); ++index) { - if (!isalnum(name[index]) && name[index] != '_') - return false; - } - - return true; - } - - const std::string test_suite_name_; - CodeLocation code_location_; - TestInfoContainer tests_; - InstantiationContainer instantiations_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteInfo); -}; // class ParameterizedTestSuiteInfo - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -template -using ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// ParameterizedTestSuiteRegistry contains a map of -// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P -// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding -// ParameterizedTestSuiteInfo descriptors. -class ParameterizedTestSuiteRegistry { - public: - ParameterizedTestSuiteRegistry() {} - ~ParameterizedTestSuiteRegistry() { - for (auto& test_suite_info : test_suite_infos_) { - delete test_suite_info; - } - } - - // Looks up or creates and returns a structure containing information about - // tests and instantiations of a particular test suite. - template - ParameterizedTestSuiteInfo* GetTestSuitePatternHolder( - const char* test_suite_name, CodeLocation code_location) { - ParameterizedTestSuiteInfo* typed_test_info = nullptr; - for (auto& test_suite_info : test_suite_infos_) { - if (test_suite_info->GetTestSuiteName() == test_suite_name) { - if (test_suite_info->GetTestSuiteTypeId() != GetTypeId()) { - // Complain about incorrect usage of Google Test facilities - // and terminate the program since we cannot guaranty correct - // test suite setup and tear-down in this case. - ReportInvalidTestSuiteType(test_suite_name, code_location); - posix::Abort(); - } else { - // At this point we are sure that the object we found is of the same - // type we are looking for, so we downcast it to that type - // without further checks. - typed_test_info = CheckedDowncastToActualType< - ParameterizedTestSuiteInfo >(test_suite_info); - } - break; - } - } - if (typed_test_info == nullptr) { - typed_test_info = new ParameterizedTestSuiteInfo( - test_suite_name, code_location); - test_suite_infos_.push_back(typed_test_info); - } - return typed_test_info; - } - void RegisterTests() { - for (auto& test_suite_info : test_suite_infos_) { - test_suite_info->RegisterTests(); - } - } -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - template - ParameterizedTestCaseInfo* GetTestCasePatternHolder( - const char* test_case_name, CodeLocation code_location) { - return GetTestSuitePatternHolder(test_case_name, code_location); - } - -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - private: - using TestSuiteInfoContainer = ::std::vector; - - TestSuiteInfoContainer test_suite_infos_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestSuiteRegistry); -}; - -} // namespace internal - -// Forward declarations of ValuesIn(), which is implemented in -// include/gtest/gtest-param-test.h. -template -internal::ParamGenerator ValuesIn( - const Container& container); - -namespace internal { -// Used in the Values() function to provide polymorphic capabilities. - -template -class ValueArray { - public: - ValueArray(Ts... v) : v_{std::move(v)...} {} - - template - operator ParamGenerator() const { // NOLINT - return ValuesIn(MakeVector(MakeIndexSequence())); - } - - private: - template - std::vector MakeVector(IndexSequence) const { - return std::vector{static_cast(v_.template Get())...}; - } - - FlatTuple v_; -}; - -template -class CartesianProductGenerator - : public ParamGeneratorInterface<::std::tuple> { - public: - typedef ::std::tuple ParamType; - - CartesianProductGenerator(const std::tuple...>& g) - : generators_(g) {} - ~CartesianProductGenerator() override {} - - ParamIteratorInterface* Begin() const override { - return new Iterator(this, generators_, false); - } - ParamIteratorInterface* End() const override { - return new Iterator(this, generators_, true); - } - - private: - template - class IteratorImpl; - template - class IteratorImpl> - : public ParamIteratorInterface { - public: - IteratorImpl(const ParamGeneratorInterface* base, - const std::tuple...>& generators, bool is_end) - : base_(base), - begin_(std::get(generators).begin()...), - end_(std::get(generators).end()...), - current_(is_end ? end_ : begin_) { - ComputeCurrentValue(); - } - ~IteratorImpl() override {} - - const ParamGeneratorInterface* BaseGenerator() const override { - return base_; - } - // Advance should not be called on beyond-of-range iterators - // so no component iterators must be beyond end of range, either. - void Advance() override { - assert(!AtEnd()); - // Advance the last iterator. - ++std::get(current_); - // if that reaches end, propagate that up. - AdvanceIfEnd(); - ComputeCurrentValue(); - } - ParamIteratorInterface* Clone() const override { - return new IteratorImpl(*this); - } - - const ParamType* Current() const override { return current_value_.get(); } - - bool Equals(const ParamIteratorInterface& other) const override { - // Having the same base generator guarantees that the other - // iterator is of the same type and we can downcast. - GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) - << "The program attempted to compare iterators " - << "from different generators." << std::endl; - const IteratorImpl* typed_other = - CheckedDowncastToActualType(&other); - - // We must report iterators equal if they both point beyond their - // respective ranges. That can happen in a variety of fashions, - // so we have to consult AtEnd(). - if (AtEnd() && typed_other->AtEnd()) return true; - - bool same = true; - bool dummy[] = { - (same = same && std::get(current_) == - std::get(typed_other->current_))...}; - (void)dummy; - return same; - } - - private: - template - void AdvanceIfEnd() { - if (std::get(current_) != std::get(end_)) return; - - bool last = ThisI == 0; - if (last) { - // We are done. Nothing else to propagate. - return; - } - - constexpr size_t NextI = ThisI - (ThisI != 0); - std::get(current_) = std::get(begin_); - ++std::get(current_); - AdvanceIfEnd(); - } - - void ComputeCurrentValue() { - if (!AtEnd()) - current_value_ = std::make_shared(*std::get(current_)...); - } - bool AtEnd() const { - bool at_end = false; - bool dummy[] = { - (at_end = at_end || std::get(current_) == std::get(end_))...}; - (void)dummy; - return at_end; - } - - const ParamGeneratorInterface* const base_; - std::tuple::iterator...> begin_; - std::tuple::iterator...> end_; - std::tuple::iterator...> current_; - std::shared_ptr current_value_; - }; - - using Iterator = IteratorImpl::type>; - - std::tuple...> generators_; -}; - -template -class CartesianProductHolder { - public: - CartesianProductHolder(const Gen&... g) : generators_(g...) {} - template - operator ParamGenerator<::std::tuple>() const { - return ParamGenerator<::std::tuple>( - new CartesianProductGenerator(generators_)); - } - - private: - std::tuple generators_; -}; - -} // namespace internal -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ - -namespace testing { - -// Functions producing parameter generators. -// -// Google Test uses these generators to produce parameters for value- -// parameterized tests. When a parameterized test suite is instantiated -// with a particular generator, Google Test creates and runs tests -// for each element in the sequence produced by the generator. -// -// In the following sample, tests from test suite FooTest are instantiated -// each three times with parameter values 3, 5, and 8: -// -// class FooTest : public TestWithParam { ... }; -// -// TEST_P(FooTest, TestThis) { -// } -// TEST_P(FooTest, TestThat) { -// } -// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8)); -// - -// Range() returns generators providing sequences of values in a range. -// -// Synopsis: -// Range(start, end) -// - returns a generator producing a sequence of values {start, start+1, -// start+2, ..., }. -// Range(start, end, step) -// - returns a generator producing a sequence of values {start, start+step, -// start+step+step, ..., }. -// Notes: -// * The generated sequences never include end. For example, Range(1, 5) -// returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) -// returns a generator producing {1, 3, 5, 7}. -// * start and end must have the same type. That type may be any integral or -// floating-point type or a user defined type satisfying these conditions: -// * It must be assignable (have operator=() defined). -// * It must have operator+() (operator+(int-compatible type) for -// two-operand version). -// * It must have operator<() defined. -// Elements in the resulting sequences will also have that type. -// * Condition start < end must be satisfied in order for resulting sequences -// to contain any elements. -// -template -internal::ParamGenerator Range(T start, T end, IncrementT step) { - return internal::ParamGenerator( - new internal::RangeGenerator(start, end, step)); -} - -template -internal::ParamGenerator Range(T start, T end) { - return Range(start, end, 1); -} - -// ValuesIn() function allows generation of tests with parameters coming from -// a container. -// -// Synopsis: -// ValuesIn(const T (&array)[N]) -// - returns a generator producing sequences with elements from -// a C-style array. -// ValuesIn(const Container& container) -// - returns a generator producing sequences with elements from -// an STL-style container. -// ValuesIn(Iterator begin, Iterator end) -// - returns a generator producing sequences with elements from -// a range [begin, end) defined by a pair of STL-style iterators. These -// iterators can also be plain C pointers. -// -// Please note that ValuesIn copies the values from the containers -// passed in and keeps them to generate tests in RUN_ALL_TESTS(). -// -// Examples: -// -// This instantiates tests from test suite StringTest -// each with C-string values of "foo", "bar", and "baz": -// -// const char* strings[] = {"foo", "bar", "baz"}; -// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings)); -// -// This instantiates tests from test suite StlStringTest -// each with STL strings with values "a" and "b": -// -// ::std::vector< ::std::string> GetParameterStrings() { -// ::std::vector< ::std::string> v; -// v.push_back("a"); -// v.push_back("b"); -// return v; -// } -// -// INSTANTIATE_TEST_SUITE_P(CharSequence, -// StlStringTest, -// ValuesIn(GetParameterStrings())); -// -// -// This will also instantiate tests from CharTest -// each with parameter values 'a' and 'b': -// -// ::std::list GetParameterChars() { -// ::std::list list; -// list.push_back('a'); -// list.push_back('b'); -// return list; -// } -// ::std::list l = GetParameterChars(); -// INSTANTIATE_TEST_SUITE_P(CharSequence2, -// CharTest, -// ValuesIn(l.begin(), l.end())); -// -template -internal::ParamGenerator< - typename std::iterator_traits::value_type> -ValuesIn(ForwardIterator begin, ForwardIterator end) { - typedef typename std::iterator_traits::value_type ParamType; - return internal::ParamGenerator( - new internal::ValuesInIteratorRangeGenerator(begin, end)); -} - -template -internal::ParamGenerator ValuesIn(const T (&array)[N]) { - return ValuesIn(array, array + N); -} - -template -internal::ParamGenerator ValuesIn( - const Container& container) { - return ValuesIn(container.begin(), container.end()); -} - -// Values() allows generating tests from explicitly specified list of -// parameters. -// -// Synopsis: -// Values(T v1, T v2, ..., T vN) -// - returns a generator producing sequences with elements v1, v2, ..., vN. -// -// For example, this instantiates tests from test suite BarTest each -// with values "one", "two", and "three": -// -// INSTANTIATE_TEST_SUITE_P(NumSequence, -// BarTest, -// Values("one", "two", "three")); -// -// This instantiates tests from test suite BazTest each with values 1, 2, 3.5. -// The exact type of values will depend on the type of parameter in BazTest. -// -// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); -// -// -template -internal::ValueArray Values(T... v) { - return internal::ValueArray(std::move(v)...); -} - -// Bool() allows generating tests with parameters in a set of (false, true). -// -// Synopsis: -// Bool() -// - returns a generator producing sequences with elements {false, true}. -// -// It is useful when testing code that depends on Boolean flags. Combinations -// of multiple flags can be tested when several Bool()'s are combined using -// Combine() function. -// -// In the following example all tests in the test suite FlagDependentTest -// will be instantiated twice with parameters false and true. -// -// class FlagDependentTest : public testing::TestWithParam { -// virtual void SetUp() { -// external_flag = GetParam(); -// } -// } -// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool()); -// -inline internal::ParamGenerator Bool() { - return Values(false, true); -} - -// Combine() allows the user to combine two or more sequences to produce -// values of a Cartesian product of those sequences' elements. -// -// Synopsis: -// Combine(gen1, gen2, ..., genN) -// - returns a generator producing sequences with elements coming from -// the Cartesian product of elements from the sequences generated by -// gen1, gen2, ..., genN. The sequence elements will have a type of -// std::tuple where T1, T2, ..., TN are the types -// of elements from sequences produces by gen1, gen2, ..., genN. -// -// Combine can have up to 10 arguments. -// -// Example: -// -// This will instantiate tests in test suite AnimalTest each one with -// the parameter values tuple("cat", BLACK), tuple("cat", WHITE), -// tuple("dog", BLACK), and tuple("dog", WHITE): -// -// enum Color { BLACK, GRAY, WHITE }; -// class AnimalTest -// : public testing::TestWithParam > {...}; -// -// TEST_P(AnimalTest, AnimalLooksNice) {...} -// -// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest, -// Combine(Values("cat", "dog"), -// Values(BLACK, WHITE))); -// -// This will instantiate tests in FlagDependentTest with all variations of two -// Boolean flags: -// -// class FlagDependentTest -// : public testing::TestWithParam > { -// virtual void SetUp() { -// // Assigns external_flag_1 and external_flag_2 values from the tuple. -// std::tie(external_flag_1, external_flag_2) = GetParam(); -// } -// }; -// -// TEST_P(FlagDependentTest, TestFeature1) { -// // Test your code using external_flag_1 and external_flag_2 here. -// } -// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest, -// Combine(Bool(), Bool())); -// -template -internal::CartesianProductHolder Combine(const Generator&... g) { - return internal::CartesianProductHolder(g...); -} - -#define TEST_P(test_suite_name, test_name) \ - class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \ - : public test_suite_name { \ - public: \ - GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {} \ - virtual void TestBody(); \ - \ - private: \ - static int AddToRegistry() { \ - ::testing::UnitTest::GetInstance() \ - ->parameterized_test_registry() \ - .GetTestSuitePatternHolder( \ - #test_suite_name, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ - ->AddTestPattern( \ - GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name), \ - new ::testing::internal::TestMetaFactory()); \ - return 0; \ - } \ - static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ - GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)); \ - }; \ - int GTEST_TEST_CLASS_NAME_(test_suite_name, \ - test_name)::gtest_registering_dummy_ = \ - GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry(); \ - void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody() - -// The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify -// generator and an optional function or functor that generates custom test name -// suffixes based on the test parameters. Such a function or functor should -// accept one argument of type testing::TestParamInfo, and -// return std::string. -// -// testing::PrintToStringParamName is a builtin test suffix generator that -// returns the value of testing::PrintToString(GetParam()). -// -// Note: test names must be non-empty, unique, and may only contain ASCII -// alphanumeric characters or underscore. Because PrintToString adds quotes -// to std::string and C strings, it won't work for these types. - -#define GTEST_EXPAND_(arg) arg -#define GTEST_GET_FIRST_(first, ...) first -#define GTEST_GET_SECOND_(first, second, ...) second - -#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...) \ - static ::testing::internal::ParamGenerator \ - gtest_##prefix##test_suite_name##_EvalGenerator_() { \ - return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_)); \ - } \ - static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_( \ - const ::testing::TestParamInfo& info) { \ - if (::testing::internal::AlwaysFalse()) { \ - ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_( \ - __VA_ARGS__, \ - ::testing::internal::DefaultParamName, \ - DUMMY_PARAM_))); \ - auto t = std::make_tuple(__VA_ARGS__); \ - static_assert(std::tuple_size::value <= 2, \ - "Too Many Args!"); \ - } \ - return ((GTEST_EXPAND_(GTEST_GET_SECOND_( \ - __VA_ARGS__, \ - ::testing::internal::DefaultParamName, \ - DUMMY_PARAM_))))(info); \ - } \ - static int gtest_##prefix##test_suite_name##_dummy_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::UnitTest::GetInstance() \ - ->parameterized_test_registry() \ - .GetTestSuitePatternHolder( \ - #test_suite_name, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__)) \ - ->AddTestSuiteInstantiation( \ - #prefix, >est_##prefix##test_suite_name##_EvalGenerator_, \ - >est_##prefix##test_suite_name##_EvalGenerateName_, \ - __FILE__, __LINE__) - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define INSTANTIATE_TEST_CASE_P \ - static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \ - ""); \ - INSTANTIATE_TEST_SUITE_P -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ -// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// -// Google C++ Testing and Mocking Framework definitions useful in production code. -// GOOGLETEST_CM0003 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ - -// When you need to test the private or protected members of a class, -// use the FRIEND_TEST macro to declare your tests as friends of the -// class. For example: -// -// class MyClass { -// private: -// void PrivateMethod(); -// FRIEND_TEST(MyClassTest, PrivateMethodWorks); -// }; -// -// class MyClassTest : public testing::Test { -// // ... -// }; -// -// TEST_F(MyClassTest, PrivateMethodWorks) { -// // Can call MyClass::PrivateMethod() here. -// } -// -// Note: The test class must be in the same namespace as the class being tested. -// For example, putting MyClassTest in an anonymous namespace will not work. - -#define FRIEND_TEST(test_case_name, test_name)\ -friend class test_case_name##_##test_name##_Test - -#endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_ -// Copyright 2008, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ -#define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ - -#include -#include - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -namespace testing { - -// A copyable object representing the result of a test part (i.e. an -// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). -// -// Don't inherit from TestPartResult as its destructor is not virtual. -class GTEST_API_ TestPartResult { - public: - // The possible outcomes of a test part (i.e. an assertion or an - // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). - enum Type { - kSuccess, // Succeeded. - kNonFatalFailure, // Failed but the test can continue. - kFatalFailure, // Failed and the test should be terminated. - kSkip // Skipped. - }; - - // C'tor. TestPartResult does NOT have a default constructor. - // Always use this constructor (with parameters) to create a - // TestPartResult object. - TestPartResult(Type a_type, const char* a_file_name, int a_line_number, - const char* a_message) - : type_(a_type), - file_name_(a_file_name == nullptr ? "" : a_file_name), - line_number_(a_line_number), - summary_(ExtractSummary(a_message)), - message_(a_message) {} - - // Gets the outcome of the test part. - Type type() const { return type_; } - - // Gets the name of the source file where the test part took place, or - // NULL if it's unknown. - const char* file_name() const { - return file_name_.empty() ? nullptr : file_name_.c_str(); - } - - // Gets the line in the source file where the test part took place, - // or -1 if it's unknown. - int line_number() const { return line_number_; } - - // Gets the summary of the failure message. - const char* summary() const { return summary_.c_str(); } - - // Gets the message associated with the test part. - const char* message() const { return message_.c_str(); } - - // Returns true if and only if the test part was skipped. - bool skipped() const { return type_ == kSkip; } - - // Returns true if and only if the test part passed. - bool passed() const { return type_ == kSuccess; } - - // Returns true if and only if the test part non-fatally failed. - bool nonfatally_failed() const { return type_ == kNonFatalFailure; } - - // Returns true if and only if the test part fatally failed. - bool fatally_failed() const { return type_ == kFatalFailure; } - - // Returns true if and only if the test part failed. - bool failed() const { return fatally_failed() || nonfatally_failed(); } - - private: - Type type_; - - // Gets the summary of the failure message by omitting the stack - // trace in it. - static std::string ExtractSummary(const char* message); - - // The name of the source file where the test part took place, or - // "" if the source file is unknown. - std::string file_name_; - // The line in the source file where the test part took place, or -1 - // if the line number is unknown. - int line_number_; - std::string summary_; // The test failure summary. - std::string message_; // The test failure message. -}; - -// Prints a TestPartResult object. -std::ostream& operator<<(std::ostream& os, const TestPartResult& result); - -// An array of TestPartResult objects. -// -// Don't inherit from TestPartResultArray as its destructor is not -// virtual. -class GTEST_API_ TestPartResultArray { - public: - TestPartResultArray() {} - - // Appends the given TestPartResult to the array. - void Append(const TestPartResult& result); - - // Returns the TestPartResult at the given index (0-based). - const TestPartResult& GetTestPartResult(int index) const; - - // Returns the number of TestPartResult objects in the array. - int size() const; - - private: - std::vector array_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); -}; - -// This interface knows how to report a test part result. -class GTEST_API_ TestPartResultReporterInterface { - public: - virtual ~TestPartResultReporterInterface() {} - - virtual void ReportTestPartResult(const TestPartResult& result) = 0; -}; - -namespace internal { - -// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a -// statement generates new fatal failures. To do so it registers itself as the -// current test part result reporter. Besides checking if fatal failures were -// reported, it only delegates the reporting to the former result reporter. -// The original result reporter is restored in the destructor. -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -class GTEST_API_ HasNewFatalFailureHelper - : public TestPartResultReporterInterface { - public: - HasNewFatalFailureHelper(); - ~HasNewFatalFailureHelper() override; - void ReportTestPartResult(const TestPartResult& result) override; - bool has_new_fatal_failure() const { return has_new_fatal_failure_; } - private: - bool has_new_fatal_failure_; - TestPartResultReporterInterface* original_reporter_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); -}; - -} // namespace internal - -} // namespace testing - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -#endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ -// Copyright 2008 Google Inc. -// All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ -#define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ - -// This header implements typed tests and type-parameterized tests. - -// Typed (aka type-driven) tests repeat the same test for types in a -// list. You must know which types you want to test with when writing -// typed tests. Here's how you do it: - -#if 0 - -// First, define a fixture class template. It should be parameterized -// by a type. Remember to derive it from testing::Test. -template -class FooTest : public testing::Test { - public: - ... - typedef std::list List; - static T shared_; - T value_; -}; - -// Next, associate a list of types with the test suite, which will be -// repeated for each type in the list. The typedef is necessary for -// the macro to parse correctly. -typedef testing::Types MyTypes; -TYPED_TEST_SUITE(FooTest, MyTypes); - -// If the type list contains only one type, you can write that type -// directly without Types<...>: -// TYPED_TEST_SUITE(FooTest, int); - -// Then, use TYPED_TEST() instead of TEST_F() to define as many typed -// tests for this test suite as you want. -TYPED_TEST(FooTest, DoesBlah) { - // Inside a test, refer to the special name TypeParam to get the type - // parameter. Since we are inside a derived class template, C++ requires - // us to visit the members of FooTest via 'this'. - TypeParam n = this->value_; - - // To visit static members of the fixture, add the TestFixture:: - // prefix. - n += TestFixture::shared_; - - // To refer to typedefs in the fixture, add the "typename - // TestFixture::" prefix. - typename TestFixture::List values; - values.push_back(n); - ... -} - -TYPED_TEST(FooTest, HasPropertyA) { ... } - -// TYPED_TEST_SUITE takes an optional third argument which allows to specify a -// class that generates custom test name suffixes based on the type. This should -// be a class which has a static template function GetName(int index) returning -// a string for each type. The provided integer index equals the index of the -// type in the provided type list. In many cases the index can be ignored. -// -// For example: -// class MyTypeNames { -// public: -// template -// static std::string GetName(int) { -// if (std::is_same()) return "char"; -// if (std::is_same()) return "int"; -// if (std::is_same()) return "unsignedInt"; -// } -// }; -// TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames); - -#endif // 0 - -// Type-parameterized tests are abstract test patterns parameterized -// by a type. Compared with typed tests, type-parameterized tests -// allow you to define the test pattern without knowing what the type -// parameters are. The defined pattern can be instantiated with -// different types any number of times, in any number of translation -// units. -// -// If you are designing an interface or concept, you can define a -// suite of type-parameterized tests to verify properties that any -// valid implementation of the interface/concept should have. Then, -// each implementation can easily instantiate the test suite to verify -// that it conforms to the requirements, without having to write -// similar tests repeatedly. Here's an example: - -#if 0 - -// First, define a fixture class template. It should be parameterized -// by a type. Remember to derive it from testing::Test. -template -class FooTest : public testing::Test { - ... -}; - -// Next, declare that you will define a type-parameterized test suite -// (the _P suffix is for "parameterized" or "pattern", whichever you -// prefer): -TYPED_TEST_SUITE_P(FooTest); - -// Then, use TYPED_TEST_P() to define as many type-parameterized tests -// for this type-parameterized test suite as you want. -TYPED_TEST_P(FooTest, DoesBlah) { - // Inside a test, refer to TypeParam to get the type parameter. - TypeParam n = 0; - ... -} - -TYPED_TEST_P(FooTest, HasPropertyA) { ... } - -// Now the tricky part: you need to register all test patterns before -// you can instantiate them. The first argument of the macro is the -// test suite name; the rest are the names of the tests in this test -// case. -REGISTER_TYPED_TEST_SUITE_P(FooTest, - DoesBlah, HasPropertyA); - -// Finally, you are free to instantiate the pattern with the types you -// want. If you put the above code in a header file, you can #include -// it in multiple C++ source files and instantiate it multiple times. -// -// To distinguish different instances of the pattern, the first -// argument to the INSTANTIATE_* macro is a prefix that will be added -// to the actual test suite name. Remember to pick unique prefixes for -// different instances. -typedef testing::Types MyTypes; -INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); - -// If the type list contains only one type, you can write that type -// directly without Types<...>: -// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); -// -// Similar to the optional argument of TYPED_TEST_SUITE above, -// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to -// generate custom names. -// INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames); - -#endif // 0 - - -// Implements typed tests. - -#if GTEST_HAS_TYPED_TEST - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the name of the typedef for the type parameters of the -// given test suite. -#define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_ - -// Expands to the name of the typedef for the NameGenerator, responsible for -// creating the suffixes of the name. -#define GTEST_NAME_GENERATOR_(TestSuiteName) \ - gtest_type_params_##TestSuiteName##_NameGenerator - -#define TYPED_TEST_SUITE(CaseName, Types, ...) \ - typedef ::testing::internal::TypeList::type GTEST_TYPE_PARAMS_( \ - CaseName); \ - typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ - GTEST_NAME_GENERATOR_(CaseName) - -# define TYPED_TEST(CaseName, TestName) \ - template \ - class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ - : public CaseName { \ - private: \ - typedef CaseName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - static bool gtest_##CaseName##_##TestName##_registered_ \ - GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTest< \ - CaseName, \ - ::testing::internal::TemplateSel, \ - GTEST_TYPE_PARAMS_( \ - CaseName)>::Register("", \ - ::testing::internal::CodeLocation( \ - __FILE__, __LINE__), \ - #CaseName, #TestName, 0, \ - ::testing::internal::GenerateNames< \ - GTEST_NAME_GENERATOR_(CaseName), \ - GTEST_TYPE_PARAMS_(CaseName)>()); \ - template \ - void GTEST_TEST_CLASS_NAME_(CaseName, \ - TestName)::TestBody() - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define TYPED_TEST_CASE \ - static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \ - TYPED_TEST_SUITE -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -#endif // GTEST_HAS_TYPED_TEST - -// Implements type-parameterized tests. - -#if GTEST_HAS_TYPED_TEST_P - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the namespace name that the type-parameterized tests for -// the given type-parameterized test suite are defined in. The exact -// name of the namespace is subject to change without notice. -#define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// -// Expands to the name of the variable used to remember the names of -// the defined tests in the given test suite. -#define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \ - gtest_typed_test_suite_p_state_##TestSuiteName##_ - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. -// -// Expands to the name of the variable used to remember the names of -// the registered tests in the given test suite. -#define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \ - gtest_registered_test_names_##TestSuiteName##_ - -// The variables defined in the type-parameterized test macros are -// static as typically these macros are used in a .h file that can be -// #included in multiple translation units linked together. -#define TYPED_TEST_SUITE_P(SuiteName) \ - static ::testing::internal::TypedTestSuitePState \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define TYPED_TEST_CASE_P \ - static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \ - TYPED_TEST_SUITE_P -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -#define TYPED_TEST_P(SuiteName, TestName) \ - namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ - template \ - class TestName : public SuiteName { \ - private: \ - typedef SuiteName TestFixture; \ - typedef gtest_TypeParam_ TypeParam; \ - virtual void TestBody(); \ - }; \ - static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ - __FILE__, __LINE__, #SuiteName, #TestName); \ - } \ - template \ - void GTEST_SUITE_NAMESPACE_( \ - SuiteName)::TestName::TestBody() - -#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ - namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ - typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ - } \ - static const char* const GTEST_REGISTERED_TEST_NAMES_( \ - SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ - GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ - __FILE__, __LINE__, #__VA_ARGS__) - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define REGISTER_TYPED_TEST_CASE_P \ - static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \ - ""); \ - REGISTER_TYPED_TEST_SUITE_P -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ - static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ - ::testing::internal::TypeParameterizedTestSuite< \ - SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ - ::testing::internal::TypeList::type>:: \ - Register(#Prefix, \ - ::testing::internal::CodeLocation(__FILE__, __LINE__), \ - >EST_TYPED_TEST_SUITE_P_STATE_(SuiteName), #SuiteName, \ - GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ - ::testing::internal::GenerateNames< \ - ::testing::internal::NameGeneratorSelector< \ - __VA_ARGS__>::type, \ - ::testing::internal::TypeList::type>()) - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -#define INSTANTIATE_TYPED_TEST_CASE_P \ - static_assert( \ - ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \ - INSTANTIATE_TYPED_TEST_SUITE_P -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - -#endif // GTEST_HAS_TYPED_TEST_P - -#endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ - -GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \ -/* class A needs to have dll-interface to be used by clients of class B */) - -namespace testing { - -// Silence C4100 (unreferenced formal parameter) and 4805 -// unsafe mix of type 'const int' and type 'const bool' -#ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable:4805) -# pragma warning(disable:4100) -#endif - - -// Declares the flags. - -// This flag temporary enables the disabled tests. -GTEST_DECLARE_bool_(also_run_disabled_tests); - -// This flag brings the debugger on an assertion failure. -GTEST_DECLARE_bool_(break_on_failure); - -// This flag controls whether Google Test catches all test-thrown exceptions -// and logs them as failures. -GTEST_DECLARE_bool_(catch_exceptions); - -// This flag enables using colors in terminal output. Available values are -// "yes" to enable colors, "no" (disable colors), or "auto" (the default) -// to let Google Test decide. -GTEST_DECLARE_string_(color); - -// This flag sets up the filter to select by name using a glob pattern -// the tests to run. If the filter is not given all tests are executed. -GTEST_DECLARE_string_(filter); - -// This flag controls whether Google Test installs a signal handler that dumps -// debugging information when fatal signals are raised. -GTEST_DECLARE_bool_(install_failure_signal_handler); - -// This flag causes the Google Test to list tests. None of the tests listed -// are actually run if the flag is provided. -GTEST_DECLARE_bool_(list_tests); - -// This flag controls whether Google Test emits a detailed XML report to a file -// in addition to its normal textual output. -GTEST_DECLARE_string_(output); - -// This flags control whether Google Test prints the elapsed time for each -// test. -GTEST_DECLARE_bool_(print_time); - -// This flags control whether Google Test prints UTF8 characters as text. -GTEST_DECLARE_bool_(print_utf8); - -// This flag specifies the random number seed. -GTEST_DECLARE_int32_(random_seed); - -// This flag sets how many times the tests are repeated. The default value -// is 1. If the value is -1 the tests are repeating forever. -GTEST_DECLARE_int32_(repeat); - -// This flag controls whether Google Test includes Google Test internal -// stack frames in failure stack traces. -GTEST_DECLARE_bool_(show_internal_stack_frames); - -// When this flag is specified, tests' order is randomized on every iteration. -GTEST_DECLARE_bool_(shuffle); - -// This flag specifies the maximum number of stack frames to be -// printed in a failure message. -GTEST_DECLARE_int32_(stack_trace_depth); - -// When this flag is specified, a failed assertion will throw an -// exception if exceptions are enabled, or exit the program with a -// non-zero code otherwise. For use with an external test framework. -GTEST_DECLARE_bool_(throw_on_failure); - -// When this flag is set with a "host:port" string, on supported -// platforms test results are streamed to the specified port on -// the specified host machine. -GTEST_DECLARE_string_(stream_result_to); - -#if GTEST_USE_OWN_FLAGFILE_FLAG_ -GTEST_DECLARE_string_(flagfile); -#endif // GTEST_USE_OWN_FLAGFILE_FLAG_ - -// The upper limit for valid stack trace depths. -const int kMaxStackTraceDepth = 100; - -namespace internal { - -class AssertHelper; -class DefaultGlobalTestPartResultReporter; -class ExecDeathTest; -class NoExecDeathTest; -class FinalSuccessChecker; -class GTestFlagSaver; -class StreamingListenerTest; -class TestResultAccessor; -class TestEventListenersAccessor; -class TestEventRepeater; -class UnitTestRecordPropertyTestHelper; -class WindowsDeathTest; -class FuchsiaDeathTest; -class UnitTestImpl* GetUnitTestImpl(); -void ReportFailureInUnknownLocation(TestPartResult::Type result_type, - const std::string& message); - -} // namespace internal - -// The friend relationship of some of these classes is cyclic. -// If we don't forward declare them the compiler might confuse the classes -// in friendship clauses with same named classes on the scope. -class Test; -class TestSuite; - -// Old API is still available but deprecated -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ -using TestCase = TestSuite; -#endif -class TestInfo; -class UnitTest; - -// A class for indicating whether an assertion was successful. When -// the assertion wasn't successful, the AssertionResult object -// remembers a non-empty message that describes how it failed. -// -// To create an instance of this class, use one of the factory functions -// (AssertionSuccess() and AssertionFailure()). -// -// This class is useful for two purposes: -// 1. Defining predicate functions to be used with Boolean test assertions -// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts -// 2. Defining predicate-format functions to be -// used with predicate assertions (ASSERT_PRED_FORMAT*, etc). -// -// For example, if you define IsEven predicate: -// -// testing::AssertionResult IsEven(int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess(); -// else -// return testing::AssertionFailure() << n << " is odd"; -// } -// -// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) -// will print the message -// -// Value of: IsEven(Fib(5)) -// Actual: false (5 is odd) -// Expected: true -// -// instead of a more opaque -// -// Value of: IsEven(Fib(5)) -// Actual: false -// Expected: true -// -// in case IsEven is a simple Boolean predicate. -// -// If you expect your predicate to be reused and want to support informative -// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up -// about half as often as positive ones in our tests), supply messages for -// both success and failure cases: -// -// testing::AssertionResult IsEven(int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess() << n << " is even"; -// else -// return testing::AssertionFailure() << n << " is odd"; -// } -// -// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print -// -// Value of: IsEven(Fib(6)) -// Actual: true (8 is even) -// Expected: false -// -// NB: Predicates that support negative Boolean assertions have reduced -// performance in positive ones so be careful not to use them in tests -// that have lots (tens of thousands) of positive Boolean assertions. -// -// To use this class with EXPECT_PRED_FORMAT assertions such as: -// -// // Verifies that Foo() returns an even number. -// EXPECT_PRED_FORMAT1(IsEven, Foo()); -// -// you need to define: -// -// testing::AssertionResult IsEven(const char* expr, int n) { -// if ((n % 2) == 0) -// return testing::AssertionSuccess(); -// else -// return testing::AssertionFailure() -// << "Expected: " << expr << " is even\n Actual: it's " << n; -// } -// -// If Foo() returns 5, you will see the following message: -// -// Expected: Foo() is even -// Actual: it's 5 -// -class GTEST_API_ AssertionResult { - public: - // Copy constructor. - // Used in EXPECT_TRUE/FALSE(assertion_result). - AssertionResult(const AssertionResult& other); - -#if defined(_MSC_VER) && _MSC_VER < 1910 - GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) -#endif - - // Used in the EXPECT_TRUE/FALSE(bool_expression). - // - // T must be contextually convertible to bool. - // - // The second parameter prevents this overload from being considered if - // the argument is implicitly convertible to AssertionResult. In that case - // we want AssertionResult's copy constructor to be used. - template - explicit AssertionResult( - const T& success, - typename std::enable_if< - !std::is_convertible::value>::type* - /*enabler*/ - = nullptr) - : success_(success) {} - -#if defined(_MSC_VER) && _MSC_VER < 1910 - GTEST_DISABLE_MSC_WARNINGS_POP_() -#endif - - // Assignment operator. - AssertionResult& operator=(AssertionResult other) { - swap(other); - return *this; - } - - // Returns true if and only if the assertion succeeded. - operator bool() const { return success_; } // NOLINT - - // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. - AssertionResult operator!() const; - - // Returns the text streamed into this AssertionResult. Test assertions - // use it when they fail (i.e., the predicate's outcome doesn't match the - // assertion's expectation). When nothing has been streamed into the - // object, returns an empty string. - const char* message() const { - return message_.get() != nullptr ? message_->c_str() : ""; - } - // Deprecated; please use message() instead. - const char* failure_message() const { return message(); } - - // Streams a custom failure message into this object. - template AssertionResult& operator<<(const T& value) { - AppendMessage(Message() << value); - return *this; - } - - // Allows streaming basic output manipulators such as endl or flush into - // this object. - AssertionResult& operator<<( - ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { - AppendMessage(Message() << basic_manipulator); - return *this; - } - - private: - // Appends the contents of message to message_. - void AppendMessage(const Message& a_message) { - if (message_.get() == nullptr) message_.reset(new ::std::string); - message_->append(a_message.GetString().c_str()); - } - - // Swap the contents of this AssertionResult with other. - void swap(AssertionResult& other); - - // Stores result of the assertion predicate. - bool success_; - // Stores the message describing the condition in case the expectation - // construct is not satisfied with the predicate's outcome. - // Referenced via a pointer to avoid taking too much stack frame space - // with test assertions. - std::unique_ptr< ::std::string> message_; -}; - -// Makes a successful assertion result. -GTEST_API_ AssertionResult AssertionSuccess(); - -// Makes a failed assertion result. -GTEST_API_ AssertionResult AssertionFailure(); - -// Makes a failed assertion result with the given failure message. -// Deprecated; use AssertionFailure() << msg. -GTEST_API_ AssertionResult AssertionFailure(const Message& msg); - -} // namespace testing - -// Includes the auto-generated header that implements a family of generic -// predicate assertion macros. This include comes late because it relies on -// APIs declared above. -// Copyright 2006, Google Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// This file is AUTOMATICALLY GENERATED on 01/02/2019 by command -// 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! -// -// Implements a family of generic predicate assertion macros. -// GOOGLETEST_CM0001 DO NOT DELETE - -#ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ -#define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - - -namespace testing { - -// This header implements a family of generic predicate assertion -// macros: -// -// ASSERT_PRED_FORMAT1(pred_format, v1) -// ASSERT_PRED_FORMAT2(pred_format, v1, v2) -// ... -// -// where pred_format is a function or functor that takes n (in the -// case of ASSERT_PRED_FORMATn) values and their source expression -// text, and returns a testing::AssertionResult. See the definition -// of ASSERT_EQ in gtest.h for an example. -// -// If you don't care about formatting, you can use the more -// restrictive version: -// -// ASSERT_PRED1(pred, v1) -// ASSERT_PRED2(pred, v1, v2) -// ... -// -// where pred is an n-ary function or functor that returns bool, -// and the values v1, v2, ..., must support the << operator for -// streaming to std::ostream. -// -// We also define the EXPECT_* variations. -// -// For now we only support predicates whose arity is at most 5. -// Please email googletestframework@googlegroups.com if you need -// support for higher arities. - -// GTEST_ASSERT_ is the basic statement to which all of the assertions -// in this file reduce. Don't use this in your code. - -#define GTEST_ASSERT_(expression, on_failure) \ - GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ - if (const ::testing::AssertionResult gtest_ar = (expression)) \ - ; \ - else \ - on_failure(gtest_ar.failure_message()) - - -// Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use -// this in your code. -template -AssertionResult AssertPred1Helper(const char* pred_text, - const char* e1, - Pred pred, - const T1& v1) { - if (pred(v1)) return AssertionSuccess(); - - return AssertionFailure() - << pred_text << "(" << e1 << ") evaluates to false, where" - << "\n" - << e1 << " evaluates to " << ::testing::PrintToString(v1); -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. -// Don't use this in your code. -#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, v1), \ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use -// this in your code. -#define GTEST_PRED1_(pred, v1, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ - #v1, \ - pred, \ - v1), on_failure) - -// Unary predicate assertion macros. -#define EXPECT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT1(pred_format, v1) \ - GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED1(pred, v1) \ - GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use -// this in your code. -template -AssertionResult AssertPred2Helper(const char* pred_text, - const char* e1, - const char* e2, - Pred pred, - const T1& v1, - const T2& v2) { - if (pred(v1, v2)) return AssertionSuccess(); - - return AssertionFailure() - << pred_text << "(" << e1 << ", " << e2 - << ") evaluates to false, where" - << "\n" - << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" - << e2 << " evaluates to " << ::testing::PrintToString(v2); -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. -// Don't use this in your code. -#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use -// this in your code. -#define GTEST_PRED2_(pred, v1, v2, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ - #v1, \ - #v2, \ - pred, \ - v1, \ - v2), on_failure) - -// Binary predicate assertion macros. -#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ - GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED2(pred, v1, v2) \ - GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use -// this in your code. -template -AssertionResult AssertPred3Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3) { - if (pred(v1, v2, v3)) return AssertionSuccess(); - - return AssertionFailure() - << pred_text << "(" << e1 << ", " << e2 << ", " << e3 - << ") evaluates to false, where" - << "\n" - << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" - << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" - << e3 << " evaluates to " << ::testing::PrintToString(v3); -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. -// Don't use this in your code. -#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use -// this in your code. -#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - pred, \ - v1, \ - v2, \ - v3), on_failure) - -// Ternary predicate assertion macros. -#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ - GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED3(pred, v1, v2, v3) \ - GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use -// this in your code. -template -AssertionResult AssertPred4Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4) { - if (pred(v1, v2, v3, v4)) return AssertionSuccess(); - - return AssertionFailure() - << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 - << ") evaluates to false, where" - << "\n" - << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" - << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" - << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" - << e4 << " evaluates to " << ::testing::PrintToString(v4); -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. -// Don't use this in your code. -#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use -// this in your code. -#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4), on_failure) - -// 4-ary predicate assertion macros. -#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ - GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ - GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED4(pred, v1, v2, v3, v4) \ - GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) - - - -// Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use -// this in your code. -template -AssertionResult AssertPred5Helper(const char* pred_text, - const char* e1, - const char* e2, - const char* e3, - const char* e4, - const char* e5, - Pred pred, - const T1& v1, - const T2& v2, - const T3& v3, - const T4& v4, - const T5& v5) { - if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); - - return AssertionFailure() - << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 - << ", " << e5 << ") evaluates to false, where" - << "\n" - << e1 << " evaluates to " << ::testing::PrintToString(v1) << "\n" - << e2 << " evaluates to " << ::testing::PrintToString(v2) << "\n" - << e3 << " evaluates to " << ::testing::PrintToString(v3) << "\n" - << e4 << " evaluates to " << ::testing::PrintToString(v4) << "\n" - << e5 << " evaluates to " << ::testing::PrintToString(v5); -} - -// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. -// Don't use this in your code. -#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ - on_failure) - -// Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use -// this in your code. -#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ - GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ - #v1, \ - #v2, \ - #v3, \ - #v4, \ - #v5, \ - pred, \ - v1, \ - v2, \ - v3, \ - v4, \ - v5), on_failure) - -// 5-ary predicate assertion macros. -#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ - GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) -#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ - GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) -#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ - GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) - - - -} // namespace testing - -#endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ - -namespace testing { - -// The abstract class that all tests inherit from. -// -// In Google Test, a unit test program contains one or many TestSuites, and -// each TestSuite contains one or many Tests. -// -// When you define a test using the TEST macro, you don't need to -// explicitly derive from Test - the TEST macro automatically does -// this for you. -// -// The only time you derive from Test is when defining a test fixture -// to be used in a TEST_F. For example: -// -// class FooTest : public testing::Test { -// protected: -// void SetUp() override { ... } -// void TearDown() override { ... } -// ... -// }; -// -// TEST_F(FooTest, Bar) { ... } -// TEST_F(FooTest, Baz) { ... } -// -// Test is not copyable. -class GTEST_API_ Test { - public: - friend class TestInfo; - - // The d'tor is virtual as we intend to inherit from Test. - virtual ~Test(); - - // Sets up the stuff shared by all tests in this test case. - // - // Google Test will call Foo::SetUpTestSuite() before running the first - // test in test case Foo. Hence a sub-class can define its own - // SetUpTestSuite() method to shadow the one defined in the super - // class. - // Failures that happen during SetUpTestSuite are logged but otherwise - // ignored. - static void SetUpTestSuite() {} - - // Tears down the stuff shared by all tests in this test suite. - // - // Google Test will call Foo::TearDownTestSuite() after running the last - // test in test case Foo. Hence a sub-class can define its own - // TearDownTestSuite() method to shadow the one defined in the super - // class. - // Failures that happen during TearDownTestSuite are logged but otherwise - // ignored. - static void TearDownTestSuite() {} - - // Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - static void TearDownTestCase() {} - static void SetUpTestCase() {} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Returns true if and only if the current test has a fatal failure. - static bool HasFatalFailure(); - - // Returns true if and only if the current test has a non-fatal failure. - static bool HasNonfatalFailure(); - - // Returns true if and only if the current test was skipped. - static bool IsSkipped(); - - // Returns true if and only if the current test has a (either fatal or - // non-fatal) failure. - static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } - - // Logs a property for the current test, test suite, or for the entire - // invocation of the test program when used outside of the context of a - // test suite. Only the last value for a given key is remembered. These - // are public static so they can be called from utility functions that are - // not members of the test fixture. Calls to RecordProperty made during - // lifespan of the test (from the moment its constructor starts to the - // moment its destructor finishes) will be output in XML as attributes of - // the element. Properties recorded from fixture's - // SetUpTestSuite or TearDownTestSuite are logged as attributes of the - // corresponding element. Calls to RecordProperty made in the - // global context (before or after invocation of RUN_ALL_TESTS and from - // SetUp/TearDown method of Environment objects registered with Google - // Test) will be output as attributes of the element. - static void RecordProperty(const std::string& key, const std::string& value); - static void RecordProperty(const std::string& key, int value); - - protected: - // Creates a Test object. - Test(); - - // Sets up the test fixture. - virtual void SetUp(); - - // Tears down the test fixture. - virtual void TearDown(); - - private: - // Returns true if and only if the current test has the same fixture class - // as the first test in the current test suite. - static bool HasSameFixtureClass(); - - // Runs the test after the test fixture has been set up. - // - // A sub-class must implement this to define the test logic. - // - // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. - // Instead, use the TEST or TEST_F macro. - virtual void TestBody() = 0; - - // Sets up, executes, and tears down the test. - void Run(); - - // Deletes self. We deliberately pick an unusual name for this - // internal method to avoid clashing with names used in user TESTs. - void DeleteSelf_() { delete this; } - - const std::unique_ptr gtest_flag_saver_; - - // Often a user misspells SetUp() as Setup() and spends a long time - // wondering why it is never called by Google Test. The declaration of - // the following method is solely for catching such an error at - // compile time: - // - // - The return type is deliberately chosen to be not void, so it - // will be a conflict if void Setup() is declared in the user's - // test fixture. - // - // - This method is private, so it will be another compiler error - // if the method is called from the user's test fixture. - // - // DO NOT OVERRIDE THIS FUNCTION. - // - // If you see an error about overriding the following function or - // about it being private, you have mis-spelled SetUp() as Setup(). - struct Setup_should_be_spelled_SetUp {}; - virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; } - - // We disallow copying Tests. - GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); -}; - -typedef internal::TimeInMillis TimeInMillis; - -// A copyable object representing a user specified test property which can be -// output as a key/value string pair. -// -// Don't inherit from TestProperty as its destructor is not virtual. -class TestProperty { - public: - // C'tor. TestProperty does NOT have a default constructor. - // Always use this constructor (with parameters) to create a - // TestProperty object. - TestProperty(const std::string& a_key, const std::string& a_value) : - key_(a_key), value_(a_value) { - } - - // Gets the user supplied key. - const char* key() const { - return key_.c_str(); - } - - // Gets the user supplied value. - const char* value() const { - return value_.c_str(); - } - - // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const std::string& new_value) { - value_ = new_value; - } - - private: - // The key supplied by the user. - std::string key_; - // The value supplied by the user. - std::string value_; -}; - -// The result of a single Test. This includes a list of -// TestPartResults, a list of TestProperties, a count of how many -// death tests there are in the Test, and how much time it took to run -// the Test. -// -// TestResult is not copyable. -class GTEST_API_ TestResult { - public: - // Creates an empty TestResult. - TestResult(); - - // D'tor. Do not inherit from TestResult. - ~TestResult(); - - // Gets the number of all test parts. This is the sum of the number - // of successful test parts and the number of failed test parts. - int total_part_count() const; - - // Returns the number of the test properties. - int test_property_count() const; - - // Returns true if and only if the test passed (i.e. no test part failed). - bool Passed() const { return !Skipped() && !Failed(); } - - // Returns true if and only if the test was skipped. - bool Skipped() const; - - // Returns true if and only if the test failed. - bool Failed() const; - - // Returns true if and only if the test fatally failed. - bool HasFatalFailure() const; - - // Returns true if and only if the test has a non-fatal failure. - bool HasNonfatalFailure() const; - - // Returns the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Gets the time of the test case start, in ms from the start of the - // UNIX epoch. - TimeInMillis start_timestamp() const { return start_timestamp_; } - - // Returns the i-th test part result among all the results. i can range from 0 - // to total_part_count() - 1. If i is not in that range, aborts the program. - const TestPartResult& GetTestPartResult(int i) const; - - // Returns the i-th test property. i can range from 0 to - // test_property_count() - 1. If i is not in that range, aborts the - // program. - const TestProperty& GetTestProperty(int i) const; - - private: - friend class TestInfo; - friend class TestSuite; - friend class UnitTest; - friend class internal::DefaultGlobalTestPartResultReporter; - friend class internal::ExecDeathTest; - friend class internal::TestResultAccessor; - friend class internal::UnitTestImpl; - friend class internal::WindowsDeathTest; - friend class internal::FuchsiaDeathTest; - - // Gets the vector of TestPartResults. - const std::vector& test_part_results() const { - return test_part_results_; - } - - // Gets the vector of TestProperties. - const std::vector& test_properties() const { - return test_properties_; - } - - // Sets the start time. - void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; } - - // Sets the elapsed time. - void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } - - // Adds a test property to the list. The property is validated and may add - // a non-fatal failure if invalid (e.g., if it conflicts with reserved - // key names). If a property is already recorded for the same key, the - // value will be updated, rather than storing multiple values for the same - // key. xml_element specifies the element for which the property is being - // recorded and is used for validation. - void RecordProperty(const std::string& xml_element, - const TestProperty& test_property); - - // Adds a failure if the key is a reserved attribute of Google Test - // testsuite tags. Returns true if the property is valid. - // FIXME: Validate attribute names are legal and human readable. - static bool ValidateTestProperty(const std::string& xml_element, - const TestProperty& test_property); - - // Adds a test part result to the list. - void AddTestPartResult(const TestPartResult& test_part_result); - - // Returns the death test count. - int death_test_count() const { return death_test_count_; } - - // Increments the death test count, returning the new count. - int increment_death_test_count() { return ++death_test_count_; } - - // Clears the test part results. - void ClearTestPartResults(); - - // Clears the object. - void Clear(); - - // Protects mutable state of the property vector and of owned - // properties, whose values may be updated. - internal::Mutex test_properites_mutex_; - - // The vector of TestPartResults - std::vector test_part_results_; - // The vector of TestProperties - std::vector test_properties_; - // Running count of death tests. - int death_test_count_; - // The start time, in milliseconds since UNIX Epoch. - TimeInMillis start_timestamp_; - // The elapsed time, in milliseconds. - TimeInMillis elapsed_time_; - - // We disallow copying TestResult. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); -}; // class TestResult - -// A TestInfo object stores the following information about a test: -// -// Test suite name -// Test name -// Whether the test should be run -// A function pointer that creates the test object when invoked -// Test result -// -// The constructor of TestInfo registers itself with the UnitTest -// singleton such that the RUN_ALL_TESTS() macro knows which tests to -// run. -class GTEST_API_ TestInfo { - public: - // Destructs a TestInfo object. This function is not virtual, so - // don't inherit from TestInfo. - ~TestInfo(); - - // Returns the test suite name. - const char* test_suite_name() const { return test_suite_name_.c_str(); } - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - const char* test_case_name() const { return test_suite_name(); } -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Returns the test name. - const char* name() const { return name_.c_str(); } - - // Returns the name of the parameter type, or NULL if this is not a typed - // or a type-parameterized test. - const char* type_param() const { - if (type_param_.get() != nullptr) return type_param_->c_str(); - return nullptr; - } - - // Returns the text representation of the value parameter, or NULL if this - // is not a value-parameterized test. - const char* value_param() const { - if (value_param_.get() != nullptr) return value_param_->c_str(); - return nullptr; - } - - // Returns the file name where this test is defined. - const char* file() const { return location_.file.c_str(); } - - // Returns the line where this test is defined. - int line() const { return location_.line; } - - // Return true if this test should not be run because it's in another shard. - bool is_in_another_shard() const { return is_in_another_shard_; } - - // Returns true if this test should run, that is if the test is not - // disabled (or it is disabled but the also_run_disabled_tests flag has - // been specified) and its full name matches the user-specified filter. - // - // Google Test allows the user to filter the tests by their full names. - // The full name of a test Bar in test suite Foo is defined as - // "Foo.Bar". Only the tests that match the filter will run. - // - // A filter is a colon-separated list of glob (not regex) patterns, - // optionally followed by a '-' and a colon-separated list of - // negative patterns (tests to exclude). A test is run if it - // matches one of the positive patterns and does not match any of - // the negative patterns. - // - // For example, *A*:Foo.* is a filter that matches any string that - // contains the character 'A' or starts with "Foo.". - bool should_run() const { return should_run_; } - - // Returns true if and only if this test will appear in the XML report. - bool is_reportable() const { - // The XML report includes tests matching the filter, excluding those - // run in other shards. - return matches_filter_ && !is_in_another_shard_; - } - - // Returns the result of the test. - const TestResult* result() const { return &result_; } - - private: -#if GTEST_HAS_DEATH_TEST - friend class internal::DefaultDeathTestFactory; -#endif // GTEST_HAS_DEATH_TEST - friend class Test; - friend class TestSuite; - friend class internal::UnitTestImpl; - friend class internal::StreamingListenerTest; - friend TestInfo* internal::MakeAndRegisterTestInfo( - const char* test_suite_name, const char* name, const char* type_param, - const char* value_param, internal::CodeLocation code_location, - internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc, - internal::TestFactoryBase* factory); - - // Constructs a TestInfo object. The newly constructed instance assumes - // ownership of the factory object. - TestInfo(const std::string& test_suite_name, const std::string& name, - const char* a_type_param, // NULL if not a type-parameterized test - const char* a_value_param, // NULL if not a value-parameterized test - internal::CodeLocation a_code_location, - internal::TypeId fixture_class_id, - internal::TestFactoryBase* factory); - - // Increments the number of death tests encountered in this test so - // far. - int increment_death_test_count() { - return result_.increment_death_test_count(); - } - - // Creates the test object, runs it, records its result, and then - // deletes it. - void Run(); - - static void ClearTestResult(TestInfo* test_info) { - test_info->result_.Clear(); - } - - // These fields are immutable properties of the test. - const std::string test_suite_name_; // test suite name - const std::string name_; // Test name - // Name of the parameter type, or NULL if this is not a typed or a - // type-parameterized test. - const std::unique_ptr type_param_; - // Text representation of the value parameter, or NULL if this is not a - // value-parameterized test. - const std::unique_ptr value_param_; - internal::CodeLocation location_; - const internal::TypeId fixture_class_id_; // ID of the test fixture class - bool should_run_; // True if and only if this test should run - bool is_disabled_; // True if and only if this test is disabled - bool matches_filter_; // True if this test matches the - // user-specified filter. - bool is_in_another_shard_; // Will be run in another shard. - internal::TestFactoryBase* const factory_; // The factory that creates - // the test object - - // This field is mutable and needs to be reset before running the - // test for the second time. - TestResult result_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); -}; - -// A test suite, which consists of a vector of TestInfos. -// -// TestSuite is not copyable. -class GTEST_API_ TestSuite { - public: - // Creates a TestSuite with the given name. - // - // TestSuite does NOT have a default constructor. Always use this - // constructor to create a TestSuite object. - // - // Arguments: - // - // name: name of the test suite - // a_type_param: the name of the test's type parameter, or NULL if - // this is not a type-parameterized test. - // set_up_tc: pointer to the function that sets up the test suite - // tear_down_tc: pointer to the function that tears down the test suite - TestSuite(const char* name, const char* a_type_param, - internal::SetUpTestSuiteFunc set_up_tc, - internal::TearDownTestSuiteFunc tear_down_tc); - - // Destructor of TestSuite. - virtual ~TestSuite(); - - // Gets the name of the TestSuite. - const char* name() const { return name_.c_str(); } - - // Returns the name of the parameter type, or NULL if this is not a - // type-parameterized test suite. - const char* type_param() const { - if (type_param_.get() != nullptr) return type_param_->c_str(); - return nullptr; - } - - // Returns true if any test in this test suite should run. - bool should_run() const { return should_run_; } - - // Gets the number of successful tests in this test suite. - int successful_test_count() const; - - // Gets the number of skipped tests in this test suite. - int skipped_test_count() const; - - // Gets the number of failed tests in this test suite. - int failed_test_count() const; - - // Gets the number of disabled tests that will be reported in the XML report. - int reportable_disabled_test_count() const; - - // Gets the number of disabled tests in this test suite. - int disabled_test_count() const; - - // Gets the number of tests to be printed in the XML report. - int reportable_test_count() const; - - // Get the number of tests in this test suite that should run. - int test_to_run_count() const; - - // Gets the number of all tests in this test suite. - int total_test_count() const; - - // Returns true if and only if the test suite passed. - bool Passed() const { return !Failed(); } - - // Returns true if and only if the test suite failed. - bool Failed() const { return failed_test_count() > 0; } - - // Returns the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const { return elapsed_time_; } - - // Gets the time of the test suite start, in ms from the start of the - // UNIX epoch. - TimeInMillis start_timestamp() const { return start_timestamp_; } - - // Returns the i-th test among all the tests. i can range from 0 to - // total_test_count() - 1. If i is not in that range, returns NULL. - const TestInfo* GetTestInfo(int i) const; - - // Returns the TestResult that holds test properties recorded during - // execution of SetUpTestSuite and TearDownTestSuite. - const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } - - private: - friend class Test; - friend class internal::UnitTestImpl; - - // Gets the (mutable) vector of TestInfos in this TestSuite. - std::vector& test_info_list() { return test_info_list_; } - - // Gets the (immutable) vector of TestInfos in this TestSuite. - const std::vector& test_info_list() const { - return test_info_list_; - } - - // Returns the i-th test among all the tests. i can range from 0 to - // total_test_count() - 1. If i is not in that range, returns NULL. - TestInfo* GetMutableTestInfo(int i); - - // Sets the should_run member. - void set_should_run(bool should) { should_run_ = should; } - - // Adds a TestInfo to this test suite. Will delete the TestInfo upon - // destruction of the TestSuite object. - void AddTestInfo(TestInfo * test_info); - - // Clears the results of all tests in this test suite. - void ClearResult(); - - // Clears the results of all tests in the given test suite. - static void ClearTestSuiteResult(TestSuite* test_suite) { - test_suite->ClearResult(); - } - - // Runs every test in this TestSuite. - void Run(); - - // Runs SetUpTestSuite() for this TestSuite. This wrapper is needed - // for catching exceptions thrown from SetUpTestSuite(). - void RunSetUpTestSuite() { - if (set_up_tc_ != nullptr) { - (*set_up_tc_)(); - } - } - - // Runs TearDownTestSuite() for this TestSuite. This wrapper is - // needed for catching exceptions thrown from TearDownTestSuite(). - void RunTearDownTestSuite() { - if (tear_down_tc_ != nullptr) { - (*tear_down_tc_)(); - } - } - - // Returns true if and only if test passed. - static bool TestPassed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Passed(); - } - - // Returns true if and only if test skipped. - static bool TestSkipped(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Skipped(); - } - - // Returns true if and only if test failed. - static bool TestFailed(const TestInfo* test_info) { - return test_info->should_run() && test_info->result()->Failed(); - } - - // Returns true if and only if the test is disabled and will be reported in - // the XML report. - static bool TestReportableDisabled(const TestInfo* test_info) { - return test_info->is_reportable() && test_info->is_disabled_; - } - - // Returns true if and only if test is disabled. - static bool TestDisabled(const TestInfo* test_info) { - return test_info->is_disabled_; - } - - // Returns true if and only if this test will appear in the XML report. - static bool TestReportable(const TestInfo* test_info) { - return test_info->is_reportable(); - } - - // Returns true if the given test should run. - static bool ShouldRunTest(const TestInfo* test_info) { - return test_info->should_run(); - } - - // Shuffles the tests in this test suite. - void ShuffleTests(internal::Random* random); - - // Restores the test order to before the first shuffle. - void UnshuffleTests(); - - // Name of the test suite. - std::string name_; - // Name of the parameter type, or NULL if this is not a typed or a - // type-parameterized test. - const std::unique_ptr type_param_; - // The vector of TestInfos in their original order. It owns the - // elements in the vector. - std::vector test_info_list_; - // Provides a level of indirection for the test list to allow easy - // shuffling and restoring the test order. The i-th element in this - // vector is the index of the i-th test in the shuffled test list. - std::vector test_indices_; - // Pointer to the function that sets up the test suite. - internal::SetUpTestSuiteFunc set_up_tc_; - // Pointer to the function that tears down the test suite. - internal::TearDownTestSuiteFunc tear_down_tc_; - // True if and only if any test in this test suite should run. - bool should_run_; - // The start time, in milliseconds since UNIX Epoch. - TimeInMillis start_timestamp_; - // Elapsed time, in milliseconds. - TimeInMillis elapsed_time_; - // Holds test properties recorded during execution of SetUpTestSuite and - // TearDownTestSuite. - TestResult ad_hoc_test_result_; - - // We disallow copying TestSuites. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestSuite); -}; - -// An Environment object is capable of setting up and tearing down an -// environment. You should subclass this to define your own -// environment(s). -// -// An Environment object does the set-up and tear-down in virtual -// methods SetUp() and TearDown() instead of the constructor and the -// destructor, as: -// -// 1. You cannot safely throw from a destructor. This is a problem -// as in some cases Google Test is used where exceptions are enabled, and -// we may want to implement ASSERT_* using exceptions where they are -// available. -// 2. You cannot use ASSERT_* directly in a constructor or -// destructor. -class Environment { - public: - // The d'tor is virtual as we need to subclass Environment. - virtual ~Environment() {} - - // Override this to define how to set up the environment. - virtual void SetUp() {} - - // Override this to define how to tear down the environment. - virtual void TearDown() {} - private: - // If you see an error about overriding the following function or - // about it being private, you have mis-spelled SetUp() as Setup(). - struct Setup_should_be_spelled_SetUp {}; - virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; } -}; - -#if GTEST_HAS_EXCEPTIONS - -// Exception which can be thrown from TestEventListener::OnTestPartResult. -class GTEST_API_ AssertionException - : public internal::GoogleTestFailureException { - public: - explicit AssertionException(const TestPartResult& result) - : GoogleTestFailureException(result) {} -}; - -#endif // GTEST_HAS_EXCEPTIONS - -// The interface for tracing execution of tests. The methods are organized in -// the order the corresponding events are fired. -class TestEventListener { - public: - virtual ~TestEventListener() {} - - // Fired before any test activity starts. - virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; - - // Fired before each iteration of tests starts. There may be more than - // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration - // index, starting from 0. - virtual void OnTestIterationStart(const UnitTest& unit_test, - int iteration) = 0; - - // Fired before environment set-up for each iteration of tests starts. - virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; - - // Fired after environment set-up for each iteration of tests ends. - virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; - - // Fired before the test suite starts. - virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {} - - // Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Fired before the test starts. - virtual void OnTestStart(const TestInfo& test_info) = 0; - - // Fired after a failed assertion or a SUCCEED() invocation. - // If you want to throw an exception from this function to skip to the next - // TEST, it must be AssertionException defined above, or inherited from it. - virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; - - // Fired after the test ends. - virtual void OnTestEnd(const TestInfo& test_info) = 0; - - // Fired after the test suite ends. - virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {} - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Fired before environment tear-down for each iteration of tests starts. - virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; - - // Fired after environment tear-down for each iteration of tests ends. - virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; - - // Fired after each iteration of tests finishes. - virtual void OnTestIterationEnd(const UnitTest& unit_test, - int iteration) = 0; - - // Fired after all test activities have ended. - virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; -}; - -// The convenience class for users who need to override just one or two -// methods and are not concerned that a possible change to a signature of -// the methods they override will not be caught during the build. For -// comments about each method please see the definition of TestEventListener -// above. -class EmptyTestEventListener : public TestEventListener { - public: - void OnTestProgramStart(const UnitTest& /*unit_test*/) override {} - void OnTestIterationStart(const UnitTest& /*unit_test*/, - int /*iteration*/) override {} - void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {} - void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {} - void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {} -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestCaseStart(const TestCase& /*test_case*/) override {} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - void OnTestStart(const TestInfo& /*test_info*/) override {} - void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {} - void OnTestEnd(const TestInfo& /*test_info*/) override {} - void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {} -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - void OnTestCaseEnd(const TestCase& /*test_case*/) override {} -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {} - void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {} - void OnTestIterationEnd(const UnitTest& /*unit_test*/, - int /*iteration*/) override {} - void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {} -}; - -// TestEventListeners lets users add listeners to track events in Google Test. -class GTEST_API_ TestEventListeners { - public: - TestEventListeners(); - ~TestEventListeners(); - - // Appends an event listener to the end of the list. Google Test assumes - // the ownership of the listener (i.e. it will delete the listener when - // the test program finishes). - void Append(TestEventListener* listener); - - // Removes the given event listener from the list and returns it. It then - // becomes the caller's responsibility to delete the listener. Returns - // NULL if the listener is not found in the list. - TestEventListener* Release(TestEventListener* listener); - - // Returns the standard listener responsible for the default console - // output. Can be removed from the listeners list to shut down default - // console output. Note that removing this object from the listener list - // with Release transfers its ownership to the caller and makes this - // function return NULL the next time. - TestEventListener* default_result_printer() const { - return default_result_printer_; - } - - // Returns the standard listener responsible for the default XML output - // controlled by the --gtest_output=xml flag. Can be removed from the - // listeners list by users who want to shut down the default XML output - // controlled by this flag and substitute it with custom one. Note that - // removing this object from the listener list with Release transfers its - // ownership to the caller and makes this function return NULL the next - // time. - TestEventListener* default_xml_generator() const { - return default_xml_generator_; - } - - private: - friend class TestSuite; - friend class TestInfo; - friend class internal::DefaultGlobalTestPartResultReporter; - friend class internal::NoExecDeathTest; - friend class internal::TestEventListenersAccessor; - friend class internal::UnitTestImpl; - - // Returns repeater that broadcasts the TestEventListener events to all - // subscribers. - TestEventListener* repeater(); - - // Sets the default_result_printer attribute to the provided listener. - // The listener is also added to the listener list and previous - // default_result_printer is removed from it and deleted. The listener can - // also be NULL in which case it will not be added to the list. Does - // nothing if the previous and the current listener objects are the same. - void SetDefaultResultPrinter(TestEventListener* listener); - - // Sets the default_xml_generator attribute to the provided listener. The - // listener is also added to the listener list and previous - // default_xml_generator is removed from it and deleted. The listener can - // also be NULL in which case it will not be added to the list. Does - // nothing if the previous and the current listener objects are the same. - void SetDefaultXmlGenerator(TestEventListener* listener); - - // Controls whether events will be forwarded by the repeater to the - // listeners in the list. - bool EventForwardingEnabled() const; - void SuppressEventForwarding(); - - // The actual list of listeners. - internal::TestEventRepeater* repeater_; - // Listener responsible for the standard result output. - TestEventListener* default_result_printer_; - // Listener responsible for the creation of the XML output file. - TestEventListener* default_xml_generator_; - - // We disallow copying TestEventListeners. - GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); -}; - -// A UnitTest consists of a vector of TestSuites. -// -// This is a singleton class. The only instance of UnitTest is -// created when UnitTest::GetInstance() is first called. This -// instance is never deleted. -// -// UnitTest is not copyable. -// -// This class is thread-safe as long as the methods are called -// according to their specification. -class GTEST_API_ UnitTest { - public: - // Gets the singleton UnitTest object. The first time this method - // is called, a UnitTest object is constructed and returned. - // Consecutive calls will return the same object. - static UnitTest* GetInstance(); - - // Runs all tests in this UnitTest object and prints the result. - // Returns 0 if successful, or 1 otherwise. - // - // This method can only be called from the main thread. - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - int Run() GTEST_MUST_USE_RESULT_; - - // Returns the working directory when the first TEST() or TEST_F() - // was executed. The UnitTest object owns the string. - const char* original_working_dir() const; - - // Returns the TestSuite object for the test that's currently running, - // or NULL if no test is running. - const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_); - -// Legacy API is still available but deprecated -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_); -#endif - - // Returns the TestInfo object for the test that's currently running, - // or NULL if no test is running. - const TestInfo* current_test_info() const - GTEST_LOCK_EXCLUDED_(mutex_); - - // Returns the random seed used at the start of the current test run. - int random_seed() const; - - // Returns the ParameterizedTestSuiteRegistry object used to keep track of - // value-parameterized tests and instantiate and register them. - // - // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() - GTEST_LOCK_EXCLUDED_(mutex_); - - // Gets the number of successful test suites. - int successful_test_suite_count() const; - - // Gets the number of failed test suites. - int failed_test_suite_count() const; - - // Gets the number of all test suites. - int total_test_suite_count() const; - - // Gets the number of all test suites that contain at least one test - // that should run. - int test_suite_to_run_count() const; - - // Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - int successful_test_case_count() const; - int failed_test_case_count() const; - int total_test_case_count() const; - int test_case_to_run_count() const; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Gets the number of successful tests. - int successful_test_count() const; - - // Gets the number of skipped tests. - int skipped_test_count() const; - - // Gets the number of failed tests. - int failed_test_count() const; - - // Gets the number of disabled tests that will be reported in the XML report. - int reportable_disabled_test_count() const; - - // Gets the number of disabled tests. - int disabled_test_count() const; - - // Gets the number of tests to be printed in the XML report. - int reportable_test_count() const; - - // Gets the number of all tests. - int total_test_count() const; - - // Gets the number of tests that should run. - int test_to_run_count() const; - - // Gets the time of the test program start, in ms from the start of the - // UNIX epoch. - TimeInMillis start_timestamp() const; - - // Gets the elapsed time, in milliseconds. - TimeInMillis elapsed_time() const; - - // Returns true if and only if the unit test passed (i.e. all test suites - // passed). - bool Passed() const; - - // Returns true if and only if the unit test failed (i.e. some test suite - // failed or something outside of all tests failed). - bool Failed() const; - - // Gets the i-th test suite among all the test suites. i can range from 0 to - // total_test_suite_count() - 1. If i is not in that range, returns NULL. - const TestSuite* GetTestSuite(int i) const; - -// Legacy API is deprecated but still available -#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - const TestCase* GetTestCase(int i) const; -#endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ - - // Returns the TestResult containing information on test failures and - // properties logged outside of individual test suites. - const TestResult& ad_hoc_test_result() const; - - // Returns the list of event listeners that can be used to track events - // inside Google Test. - TestEventListeners& listeners(); - - private: - // Registers and returns a global test environment. When a test - // program is run, all global test environments will be set-up in - // the order they were registered. After all tests in the program - // have finished, all global test environments will be torn-down in - // the *reverse* order they were registered. - // - // The UnitTest object takes ownership of the given environment. - // - // This method can only be called from the main thread. - Environment* AddEnvironment(Environment* env); - - // Adds a TestPartResult to the current TestResult object. All - // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) - // eventually call this to report their results. The user code - // should use the assertion macros instead of calling this directly. - void AddTestPartResult(TestPartResult::Type result_type, - const char* file_name, - int line_number, - const std::string& message, - const std::string& os_stack_trace) - GTEST_LOCK_EXCLUDED_(mutex_); - - // Adds a TestProperty to the current TestResult object when invoked from - // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked - // from SetUpTestSuite or TearDownTestSuite, or to the global property set - // when invoked elsewhere. If the result already contains a property with - // the same key, the value will be updated. - void RecordProperty(const std::string& key, const std::string& value); - - // Gets the i-th test suite among all the test suites. i can range from 0 to - // total_test_suite_count() - 1. If i is not in that range, returns NULL. - TestSuite* GetMutableTestSuite(int i); - - // Accessors for the implementation object. - internal::UnitTestImpl* impl() { return impl_; } - const internal::UnitTestImpl* impl() const { return impl_; } - - // These classes and functions are friends as they need to access private - // members of UnitTest. - friend class ScopedTrace; - friend class Test; - friend class internal::AssertHelper; - friend class internal::StreamingListenerTest; - friend class internal::UnitTestRecordPropertyTestHelper; - friend Environment* AddGlobalTestEnvironment(Environment* env); - friend internal::UnitTestImpl* internal::GetUnitTestImpl(); - friend void internal::ReportFailureInUnknownLocation( - TestPartResult::Type result_type, - const std::string& message); - - // Creates an empty UnitTest. - UnitTest(); - - // D'tor - virtual ~UnitTest(); - - // Pushes a trace defined by SCOPED_TRACE() on to the per-thread - // Google Test trace stack. - void PushGTestTrace(const internal::TraceInfo& trace) - GTEST_LOCK_EXCLUDED_(mutex_); - - // Pops a trace from the per-thread Google Test trace stack. - void PopGTestTrace() - GTEST_LOCK_EXCLUDED_(mutex_); - - // Protects mutable state in *impl_. This is mutable as some const - // methods need to lock it too. - mutable internal::Mutex mutex_; - - // Opaque implementation object. This field is never changed once - // the object is constructed. We don't mark it as const here, as - // doing so will cause a warning in the constructor of UnitTest. - // Mutable state in *impl_ is protected by mutex_. - internal::UnitTestImpl* impl_; - - // We disallow copying UnitTest. - GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); -}; - -// A convenient wrapper for adding an environment for the test -// program. -// -// You should call this before RUN_ALL_TESTS() is called, probably in -// main(). If you use gtest_main, you need to call this before main() -// starts for it to take effect. For example, you can define a global -// variable like this: -// -// testing::Environment* const foo_env = -// testing::AddGlobalTestEnvironment(new FooEnvironment); -// -// However, we strongly recommend you to write your own main() and -// call AddGlobalTestEnvironment() there, as relying on initialization -// of global variables makes the code harder to read and may cause -// problems when you register multiple environments from different -// translation units and the environments have dependencies among them -// (remember that the compiler doesn't guarantee the order in which -// global variables from different translation units are initialized). -inline Environment* AddGlobalTestEnvironment(Environment* env) { - return UnitTest::GetInstance()->AddEnvironment(env); -} - -// Initializes Google Test. This must be called before calling -// RUN_ALL_TESTS(). In particular, it parses a command line for the -// flags that Google Test recognizes. Whenever a Google Test flag is -// seen, it is removed from argv, and *argc is decremented. -// -// No value is returned. Instead, the Google Test flag variables are -// updated. -// -// Calling the function for the second time has no user-visible effect. -GTEST_API_ void InitGoogleTest(int* argc, char** argv); - -// This overloaded version can be used in Windows programs compiled in -// UNICODE mode. -GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); - -// This overloaded version can be used on Arduino/embedded platforms where -// there is no argc/argv. -GTEST_API_ void InitGoogleTest(); - -namespace internal { - -// Separate the error generating code from the code path to reduce the stack -// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers -// when calling EXPECT_* in a tight loop. -template -AssertionResult CmpHelperEQFailure(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, const T2& rhs) { - return EqFailure(lhs_expression, - rhs_expression, - FormatForComparisonFailureMessage(lhs, rhs), - FormatForComparisonFailureMessage(rhs, lhs), - false); -} - -// This block of code defines operator==/!= -// to block lexical scope lookup. -// It prevents using invalid operator==/!= defined at namespace scope. -struct faketype {}; -inline bool operator==(faketype, faketype) { return true; } -inline bool operator!=(faketype, faketype) { return false; } - -// The helper function for {ASSERT|EXPECT}_EQ. -template -AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - const T1& lhs, - const T2& rhs) { - if (lhs == rhs) { - return AssertionSuccess(); - } - - return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); -} - -// With this overloaded version, we allow anonymous enums to be used -// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums -// can be implicitly cast to BiggestInt. -GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs); - -class EqHelper { - public: - // This templatized version is for the general case. - template < - typename T1, typename T2, - // Disable this overload for cases where one argument is a pointer - // and the other is the null pointer constant. - typename std::enable_if::value || - !std::is_pointer::value>::type* = nullptr> - static AssertionResult Compare(const char* lhs_expression, - const char* rhs_expression, const T1& lhs, - const T2& rhs) { - return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); - } - - // With this overloaded version, we allow anonymous enums to be used - // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous - // enums can be implicitly cast to BiggestInt. - // - // Even though its body looks the same as the above version, we - // cannot merge the two, as it will make anonymous enums unhappy. - static AssertionResult Compare(const char* lhs_expression, - const char* rhs_expression, - BiggestInt lhs, - BiggestInt rhs) { - return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); - } - - template - static AssertionResult Compare( - const char* lhs_expression, const char* rhs_expression, - // Handle cases where '0' is used as a null pointer literal. - std::nullptr_t /* lhs */, T* rhs) { - // We already know that 'lhs' is a null pointer. - return CmpHelperEQ(lhs_expression, rhs_expression, static_cast(nullptr), - rhs); - } -}; - -// Separate the error generating code from the code path to reduce the stack -// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers -// when calling EXPECT_OP in a tight loop. -template -AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, - const T1& val1, const T2& val2, - const char* op) { - return AssertionFailure() - << "Expected: (" << expr1 << ") " << op << " (" << expr2 - << "), actual: " << FormatForComparisonFailureMessage(val1, val2) - << " vs " << FormatForComparisonFailureMessage(val2, val1); -} - -// A macro for implementing the helper functions needed to implement -// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste -// of similar code. -// -// For each templatized helper function, we also define an overloaded -// version for BiggestInt in order to reduce code bloat and allow -// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled -// with gcc 4. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - -#define GTEST_IMPL_CMP_HELPER_(op_name, op)\ -template \ -AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ - const T1& val1, const T2& val2) {\ - if (val1 op val2) {\ - return AssertionSuccess();\ - } else {\ - return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ - }\ -}\ -GTEST_API_ AssertionResult CmpHelper##op_name(\ - const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) - -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. - -// Implements the helper function for {ASSERT|EXPECT}_NE -GTEST_IMPL_CMP_HELPER_(NE, !=); -// Implements the helper function for {ASSERT|EXPECT}_LE -GTEST_IMPL_CMP_HELPER_(LE, <=); -// Implements the helper function for {ASSERT|EXPECT}_LT -GTEST_IMPL_CMP_HELPER_(LT, <); -// Implements the helper function for {ASSERT|EXPECT}_GE -GTEST_IMPL_CMP_HELPER_(GE, >=); -// Implements the helper function for {ASSERT|EXPECT}_GT -GTEST_IMPL_CMP_HELPER_(GT, >); - -#undef GTEST_IMPL_CMP_HELPER_ - -// The helper function for {ASSERT|EXPECT}_STREQ. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - -// The helper function for {ASSERT|EXPECT}_STRCASEEQ. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - -// The helper function for {ASSERT|EXPECT}_STRNE. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - -// The helper function for {ASSERT|EXPECT}_STRCASENE. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, - const char* s2_expression, - const char* s1, - const char* s2); - - -// Helper function for *_STREQ on wide strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); - -// Helper function for *_STRNE on wide strings. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, - const char* s2_expression, - const wchar_t* s1, - const wchar_t* s2); - -} // namespace internal - -// IsSubstring() and IsNotSubstring() are intended to be used as the -// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by -// themselves. They check whether needle is a substring of haystack -// (NULL is considered a substring of itself only), and return an -// appropriate error message when they fail. -// -// The {needle,haystack}_expr arguments are the stringified -// expressions that generated the two real arguments. -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const char* needle, const char* haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const wchar_t* needle, const wchar_t* haystack); -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::string& needle, const ::std::string& haystack); - -#if GTEST_HAS_STD_WSTRING -GTEST_API_ AssertionResult IsSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -GTEST_API_ AssertionResult IsNotSubstring( - const char* needle_expr, const char* haystack_expr, - const ::std::wstring& needle, const ::std::wstring& haystack); -#endif // GTEST_HAS_STD_WSTRING - -namespace internal { - -// Helper template function for comparing floating-points. -// -// Template parameter: -// -// RawType: the raw floating-point type (either float or double) -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -template -AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, - const char* rhs_expression, - RawType lhs_value, - RawType rhs_value) { - const FloatingPoint lhs(lhs_value), rhs(rhs_value); - - if (lhs.AlmostEquals(rhs)) { - return AssertionSuccess(); - } - - ::std::stringstream lhs_ss; - lhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << lhs_value; - - ::std::stringstream rhs_ss; - rhs_ss << std::setprecision(std::numeric_limits::digits10 + 2) - << rhs_value; - - return EqFailure(lhs_expression, - rhs_expression, - StringStreamToString(&lhs_ss), - StringStreamToString(&rhs_ss), - false); -} - -// Helper function for implementing ASSERT_NEAR. -// -// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. -GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, - const char* expr2, - const char* abs_error_expr, - double val1, - double val2, - double abs_error); - -// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. -// A class that enables one to stream messages to assertion macros -class GTEST_API_ AssertHelper { - public: - // Constructor. - AssertHelper(TestPartResult::Type type, - const char* file, - int line, - const char* message); - ~AssertHelper(); - - // Message assignment is a semantic trick to enable assertion - // streaming; see the GTEST_MESSAGE_ macro below. - void operator=(const Message& message) const; - - private: - // We put our data in a struct so that the size of the AssertHelper class can - // be as small as possible. This is important because gcc is incapable of - // re-using stack space even for temporary variables, so every EXPECT_EQ - // reserves stack space for another AssertHelper. - struct AssertHelperData { - AssertHelperData(TestPartResult::Type t, - const char* srcfile, - int line_num, - const char* msg) - : type(t), file(srcfile), line(line_num), message(msg) { } - - TestPartResult::Type const type; - const char* const file; - int const line; - std::string const message; - - private: - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); - }; - - AssertHelperData* const data_; - - GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); -}; - -enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; - -GTEST_API_ GTEST_ATTRIBUTE_PRINTF_(2, 3) void ColoredPrintf(GTestColor color, - const char* fmt, - ...); - -} // namespace internal - -// The pure interface class that all value-parameterized tests inherit from. -// A value-parameterized class must inherit from both ::testing::Test and -// ::testing::WithParamInterface. In most cases that just means inheriting -// from ::testing::TestWithParam, but more complicated test hierarchies -// may need to inherit from Test and WithParamInterface at different levels. -// -// This interface has support for accessing the test parameter value via -// the GetParam() method. -// -// Use it with one of the parameter generator defining functions, like Range(), -// Values(), ValuesIn(), Bool(), and Combine(). -// -// class FooTest : public ::testing::TestWithParam { -// protected: -// FooTest() { -// // Can use GetParam() here. -// } -// ~FooTest() override { -// // Can use GetParam() here. -// } -// void SetUp() override { -// // Can use GetParam() here. -// } -// void TearDown override { -// // Can use GetParam() here. -// } -// }; -// TEST_P(FooTest, DoesBar) { -// // Can use GetParam() method here. -// Foo foo; -// ASSERT_TRUE(foo.DoesBar(GetParam())); -// } -// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); - -template -class WithParamInterface { - public: - typedef T ParamType; - virtual ~WithParamInterface() {} - - // The current parameter value. Is also available in the test fixture's - // constructor. - static const ParamType& GetParam() { - GTEST_CHECK_(parameter_ != nullptr) - << "GetParam() can only be called inside a value-parameterized test " - << "-- did you intend to write TEST_P instead of TEST_F?"; - return *parameter_; - } - - private: - // Sets parameter value. The caller is responsible for making sure the value - // remains alive and unchanged throughout the current test. - static void SetParam(const ParamType* parameter) { - parameter_ = parameter; - } - - // Static value used for accessing parameter during a test lifetime. - static const ParamType* parameter_; - - // TestClass must be a subclass of WithParamInterface and Test. - template friend class internal::ParameterizedTestFactory; -}; - -template -const T* WithParamInterface::parameter_ = nullptr; - -// Most value-parameterized classes can ignore the existence of -// WithParamInterface, and can just inherit from ::testing::TestWithParam. - -template -class TestWithParam : public Test, public WithParamInterface { -}; - -// Macros for indicating success/failure in test code. - -// Skips test in runtime. -// Skipping test aborts current function. -// Skipped tests are neither successful nor failed. -#define GTEST_SKIP() GTEST_SKIP_("Skipped") - -// ADD_FAILURE unconditionally adds a failure to the current test. -// SUCCEED generates a success - it doesn't automatically make the -// current test successful, as a test is only successful when it has -// no failure. -// -// EXPECT_* verifies that a certain condition is satisfied. If not, -// it behaves like ADD_FAILURE. In particular: -// -// EXPECT_TRUE verifies that a Boolean condition is true. -// EXPECT_FALSE verifies that a Boolean condition is false. -// -// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except -// that they will also abort the current function on failure. People -// usually want the fail-fast behavior of FAIL and ASSERT_*, but those -// writing data-driven tests often find themselves using ADD_FAILURE -// and EXPECT_* more. - -// Generates a nonfatal failure with a generic message. -#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") - -// Generates a nonfatal failure at the given source file location with -// a generic message. -#define ADD_FAILURE_AT(file, line) \ - GTEST_MESSAGE_AT_(file, line, "Failed", \ - ::testing::TestPartResult::kNonFatalFailure) - -// Generates a fatal failure with a generic message. -#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") - -// Like GTEST_FAIL(), but at the given source file location. -#define GTEST_FAIL_AT(file, line) \ - GTEST_MESSAGE_AT_(file, line, "Failed", \ - ::testing::TestPartResult::kFatalFailure) - -// Define this macro to 1 to omit the definition of FAIL(), which is a -// generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_FAIL -# define FAIL() GTEST_FAIL() -#endif - -// Generates a success with a generic message. -#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") - -// Define this macro to 1 to omit the definition of SUCCEED(), which -// is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_SUCCEED -# define SUCCEED() GTEST_SUCCEED() -#endif - -// Macros for testing exceptions. -// -// * {ASSERT|EXPECT}_THROW(statement, expected_exception): -// Tests that the statement throws the expected exception. -// * {ASSERT|EXPECT}_NO_THROW(statement): -// Tests that the statement doesn't throw any exception. -// * {ASSERT|EXPECT}_ANY_THROW(statement): -// Tests that the statement throws an exception. - -#define EXPECT_THROW(statement, expected_exception) \ - GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) -#define EXPECT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define EXPECT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) -#define ASSERT_THROW(statement, expected_exception) \ - GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) -#define ASSERT_NO_THROW(statement) \ - GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) -#define ASSERT_ANY_THROW(statement) \ - GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) - -// Boolean assertions. Condition can be either a Boolean expression or an -// AssertionResult. For more information on how to use AssertionResult with -// these macros see comments on that class. -#define EXPECT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_NONFATAL_FAILURE_) -#define EXPECT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_NONFATAL_FAILURE_) -#define ASSERT_TRUE(condition) \ - GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \ - GTEST_FATAL_FAILURE_) -#define ASSERT_FALSE(condition) \ - GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ - GTEST_FATAL_FAILURE_) - -// Macros for testing equalities and inequalities. -// -// * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2 -// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 -// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 -// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 -// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 -// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 -// -// When they are not, Google Test prints both the tested expressions and -// their actual values. The values must be compatible built-in types, -// or you will get a compiler error. By "compatible" we mean that the -// values can be compared by the respective operator. -// -// Note: -// -// 1. It is possible to make a user-defined type work with -// {ASSERT|EXPECT}_??(), but that requires overloading the -// comparison operators and is thus discouraged by the Google C++ -// Usage Guide. Therefore, you are advised to use the -// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are -// equal. -// -// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on -// pointers (in particular, C strings). Therefore, if you use it -// with two C strings, you are testing how their locations in memory -// are related, not how their content is related. To compare two C -// strings by content, use {ASSERT|EXPECT}_STR*(). -// -// 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to -// {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you -// what the actual value is when it fails, and similarly for the -// other comparisons. -// -// 4. Do not depend on the order in which {ASSERT|EXPECT}_??() -// evaluate their arguments, which is undefined. -// -// 5. These macros evaluate their arguments exactly once. -// -// Examples: -// -// EXPECT_NE(Foo(), 5); -// EXPECT_EQ(a_pointer, NULL); -// ASSERT_LT(i, array_size); -// ASSERT_GT(records.size(), 0) << "There is no record left."; - -#define EXPECT_EQ(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2) -#define EXPECT_NE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define EXPECT_LE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define EXPECT_LT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define EXPECT_GE(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define EXPECT_GT(val1, val2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) - -#define GTEST_ASSERT_EQ(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2) -#define GTEST_ASSERT_NE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) -#define GTEST_ASSERT_LE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) -#define GTEST_ASSERT_LT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) -#define GTEST_ASSERT_GE(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) -#define GTEST_ASSERT_GT(val1, val2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) - -// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of -// ASSERT_XY(), which clashes with some users' own code. - -#if !GTEST_DONT_DEFINE_ASSERT_EQ -# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_NE -# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_LE -# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_LT -# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_GE -# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) -#endif - -#if !GTEST_DONT_DEFINE_ASSERT_GT -# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) -#endif - -// C-string Comparisons. All tests treat NULL and any non-NULL string -// as different. Two NULLs are equal. -// -// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 -// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 -// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case -// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case -// -// For wide or narrow string objects, you can use the -// {ASSERT|EXPECT}_??() macros. -// -// Don't depend on the order in which the arguments are evaluated, -// which is undefined. -// -// These macros evaluate their arguments exactly once. - -#define EXPECT_STREQ(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) -#define EXPECT_STRNE(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define EXPECT_STRCASEEQ(s1, s2) \ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) -#define EXPECT_STRCASENE(s1, s2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -#define ASSERT_STREQ(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) -#define ASSERT_STRNE(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) -#define ASSERT_STRCASEEQ(s1, s2) \ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) -#define ASSERT_STRCASENE(s1, s2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) - -// Macros for comparing floating-point numbers. -// -// * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2): -// Tests that two float values are almost equal. -// * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2): -// Tests that two double values are almost equal. -// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): -// Tests that v1 and v2 are within the given distance to each other. -// -// Google Test uses ULP-based comparison to automatically pick a default -// error bound that is appropriate for the operands. See the -// FloatingPoint template class in gtest-internal.h if you are -// interested in the implementation details. - -#define EXPECT_FLOAT_EQ(val1, val2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) - -#define EXPECT_DOUBLE_EQ(val1, val2)\ - EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) - -#define ASSERT_FLOAT_EQ(val1, val2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) - -#define ASSERT_DOUBLE_EQ(val1, val2)\ - ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ, \ - val1, val2) - -#define EXPECT_NEAR(val1, val2, abs_error)\ - EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) - -#define ASSERT_NEAR(val1, val2, abs_error)\ - ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ - val1, val2, abs_error) - -// These predicate format functions work on floating-point values, and -// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. -// -// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); - -// Asserts that val1 is less than, or almost equal to, val2. Fails -// otherwise. In particular, it fails if either val1 or val2 is NaN. -GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, - float val1, float val2); -GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, - double val1, double val2); - - -#if GTEST_OS_WINDOWS - -// Macros that test for HRESULT failure and success, these are only useful -// on Windows, and rely on Windows SDK macros and APIs to compile. -// -// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) -// -// When expr unexpectedly fails or succeeds, Google Test prints the -// expected result and the actual result with both a human-readable -// string representation of the error, if available, as well as the -// hex result code. -# define EXPECT_HRESULT_SUCCEEDED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) - -# define ASSERT_HRESULT_SUCCEEDED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) - -# define EXPECT_HRESULT_FAILED(expr) \ - EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) - -# define ASSERT_HRESULT_FAILED(expr) \ - ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) - -#endif // GTEST_OS_WINDOWS - -// Macros that execute statement and check that it doesn't generate new fatal -// failures in the current thread. -// -// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); -// -// Examples: -// -// EXPECT_NO_FATAL_FAILURE(Process()); -// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; -// -#define ASSERT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) -#define EXPECT_NO_FATAL_FAILURE(statement) \ - GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) - -// Causes a trace (including the given source file path and line number, -// and the given message) to be included in every test failure message generated -// by code in the scope of the lifetime of an instance of this class. The effect -// is undone with the destruction of the instance. -// -// The message argument can be anything streamable to std::ostream. -// -// Example: -// testing::ScopedTrace trace("file.cc", 123, "message"); -// -class GTEST_API_ ScopedTrace { - public: - // The c'tor pushes the given source file location and message onto - // a trace stack maintained by Google Test. - - // Template version. Uses Message() to convert the values into strings. - // Slow, but flexible. - template - ScopedTrace(const char* file, int line, const T& message) { - PushTrace(file, line, (Message() << message).GetString()); - } - - // Optimize for some known types. - ScopedTrace(const char* file, int line, const char* message) { - PushTrace(file, line, message ? message : "(null)"); - } - - ScopedTrace(const char* file, int line, const std::string& message) { - PushTrace(file, line, message); - } - - // The d'tor pops the info pushed by the c'tor. - // - // Note that the d'tor is not virtual in order to be efficient. - // Don't inherit from ScopedTrace! - ~ScopedTrace(); - - private: - void PushTrace(const char* file, int line, std::string message); - - GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); -} GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its - // c'tor and d'tor. Therefore it doesn't - // need to be used otherwise. - -// Causes a trace (including the source file path, the current line -// number, and the given message) to be included in every test failure -// message generated by code in the current scope. The effect is -// undone when the control leaves the current scope. -// -// The message argument can be anything streamable to std::ostream. -// -// In the implementation, we include the current line number as part -// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s -// to appear in the same block - as long as they are on different -// lines. -// -// Assuming that each thread maintains its own stack of traces. -// Therefore, a SCOPED_TRACE() would (correctly) only affect the -// assertions in its own thread. -#define SCOPED_TRACE(message) \ - ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ - __FILE__, __LINE__, (message)) - -// Compile-time assertion for type equality. -// StaticAssertTypeEq() compiles if and only if type1 and type2 -// are the same type. The value it returns is not interesting. -// -// Instead of making StaticAssertTypeEq a class template, we make it a -// function template that invokes a helper class template. This -// prevents a user from misusing StaticAssertTypeEq by -// defining objects of that type. -// -// CAVEAT: -// -// When used inside a method of a class template, -// StaticAssertTypeEq() is effective ONLY IF the method is -// instantiated. For example, given: -// -// template class Foo { -// public: -// void Bar() { testing::StaticAssertTypeEq(); } -// }; -// -// the code: -// -// void Test1() { Foo foo; } -// -// will NOT generate a compiler error, as Foo::Bar() is never -// actually instantiated. Instead, you need: -// -// void Test2() { Foo foo; foo.Bar(); } -// -// to cause a compiler error. -template -constexpr bool StaticAssertTypeEq() noexcept { - static_assert(std::is_same::value, - "type1 and type2 are not the same type"); - return true; -} - -// Defines a test. -// -// The first parameter is the name of the test suite, and the second -// parameter is the name of the test within the test suite. -// -// The convention is to end the test suite name with "Test". For -// example, a test suite for the Foo class can be named FooTest. -// -// Test code should appear between braces after an invocation of -// this macro. Example: -// -// TEST(FooTest, InitializesCorrectly) { -// Foo foo; -// EXPECT_TRUE(foo.StatusIsOK()); -// } - -// Note that we call GetTestTypeId() instead of GetTypeId< -// ::testing::Test>() here to get the type ID of testing::Test. This -// is to work around a suspected linker bug when using Google Test as -// a framework on Mac OS X. The bug causes GetTypeId< -// ::testing::Test>() to return different values depending on whether -// the call is from the Google Test framework itself or from user test -// code. GetTestTypeId() is guaranteed to always return the same -// value, as it always calls GetTypeId<>() from the Google Test -// framework. -#define GTEST_TEST(test_suite_name, test_name) \ - GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \ - ::testing::internal::GetTestTypeId()) - -// Define this macro to 1 to omit the definition of TEST(), which -// is a generic name and clashes with some other libraries. -#if !GTEST_DONT_DEFINE_TEST -#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name) -#endif - -// Defines a test that uses a test fixture. -// -// The first parameter is the name of the test fixture class, which -// also doubles as the test suite name. The second parameter is the -// name of the test within the test suite. -// -// A test fixture class must be declared earlier. The user should put -// the test code between braces after using this macro. Example: -// -// class FooTest : public testing::Test { -// protected: -// void SetUp() override { b_.AddElement(3); } -// -// Foo a_; -// Foo b_; -// }; -// -// TEST_F(FooTest, InitializesCorrectly) { -// EXPECT_TRUE(a_.StatusIsOK()); -// } -// -// TEST_F(FooTest, ReturnsElementCountCorrectly) { -// EXPECT_EQ(a_.size(), 0); -// EXPECT_EQ(b_.size(), 1); -// } -// -// GOOGLETEST_CM0011 DO NOT DELETE -#define TEST_F(test_fixture, test_name)\ - GTEST_TEST_(test_fixture, test_name, test_fixture, \ - ::testing::internal::GetTypeId()) - -// Returns a path to temporary directory. -// Tries to determine an appropriate directory for the platform. -GTEST_API_ std::string TempDir(); - -#ifdef _MSC_VER -# pragma warning(pop) -#endif - -// Dynamically registers a test with the framework. -// -// This is an advanced API only to be used when the `TEST` macros are -// insufficient. The macros should be preferred when possible, as they avoid -// most of the complexity of calling this function. -// -// The `factory` argument is a factory callable (move-constructible) object or -// function pointer that creates a new instance of the Test object. It -// handles ownership to the caller. The signature of the callable is -// `Fixture*()`, where `Fixture` is the test fixture class for the test. All -// tests registered with the same `test_suite_name` must return the same -// fixture type. This is checked at runtime. -// -// The framework will infer the fixture class from the factory and will call -// the `SetUpTestSuite` and `TearDownTestSuite` for it. -// -// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is -// undefined. -// -// Use case example: -// -// class MyFixture : public ::testing::Test { -// public: -// // All of these optional, just like in regular macro usage. -// static void SetUpTestSuite() { ... } -// static void TearDownTestSuite() { ... } -// void SetUp() override { ... } -// void TearDown() override { ... } -// }; -// -// class MyTest : public MyFixture { -// public: -// explicit MyTest(int data) : data_(data) {} -// void TestBody() override { ... } -// -// private: -// int data_; -// }; -// -// void RegisterMyTests(const std::vector& values) { -// for (int v : values) { -// ::testing::RegisterTest( -// "MyFixture", ("Test" + std::to_string(v)).c_str(), nullptr, -// std::to_string(v).c_str(), -// __FILE__, __LINE__, -// // Important to use the fixture type as the return type here. -// [=]() -> MyFixture* { return new MyTest(v); }); -// } -// } -// ... -// int main(int argc, char** argv) { -// std::vector values_to_test = LoadValuesFromConfig(); -// RegisterMyTests(values_to_test); -// ... -// return RUN_ALL_TESTS(); -// } -// -template -TestInfo* RegisterTest(const char* test_suite_name, const char* test_name, - const char* type_param, const char* value_param, - const char* file, int line, Factory factory) { - using TestT = typename std::remove_pointer::type; - - class FactoryImpl : public internal::TestFactoryBase { - public: - explicit FactoryImpl(Factory f) : factory_(std::move(f)) {} - Test* CreateTest() override { return factory_(); } - - private: - Factory factory_; - }; - - return internal::MakeAndRegisterTestInfo( - test_suite_name, test_name, type_param, value_param, - internal::CodeLocation(file, line), internal::GetTypeId(), - internal::SuiteApiResolver::GetSetUpCaseOrSuite(file, line), - internal::SuiteApiResolver::GetTearDownCaseOrSuite(file, line), - new FactoryImpl{std::move(factory)}); -} - -} // namespace testing - -// Use this function in main() to run all tests. It returns 0 if all -// tests are successful, or 1 otherwise. -// -// RUN_ALL_TESTS() should be invoked after the command line has been -// parsed by InitGoogleTest(). -// -// This function was formerly a macro; thus, it is in the global -// namespace and has an all-caps name. -int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; - -inline int RUN_ALL_TESTS() { - return ::testing::UnitTest::GetInstance()->Run(); -} - -GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251 - -#endif // GTEST_INCLUDE_GTEST_GTEST_H_ diff --git a/ThirdParty/openzgy b/ThirdParty/openzgy index 2463662b48..194068f4dc 160000 --- a/ThirdParty/openzgy +++ b/ThirdParty/openzgy @@ -1 +1 @@ -Subproject commit 2463662b48c220db468df2ba6c8ba7ed314613ae +Subproject commit 194068f4dca443a782b81d35533a89877e25a7e4 diff --git a/ThirdParty/qtadvanceddocking b/ThirdParty/qtadvanceddocking index 3afbfe6ed5..fc54cc5e5a 160000 --- a/ThirdParty/qtadvanceddocking +++ b/ThirdParty/qtadvanceddocking @@ -1 +1 @@ -Subproject commit 3afbfe6ed5f6596ea92ebeeb3ca8d0ba4e478004 +Subproject commit fc54cc5e5af0bdf49670e10bd6366015eb3ab3f2 diff --git a/ThirdParty/spdlog b/ThirdParty/spdlog new file mode 160000 index 0000000000..8979f7fb2a --- /dev/null +++ b/ThirdParty/spdlog @@ -0,0 +1 @@ +Subproject commit 8979f7fb2a119754e5fe7fe6d8155f67d934316a