Compare commits

..

11 Commits

Author SHA1 Message Date
Arne Morten Kvarving
65dd2b1eb9 bump version to 2021.10-rc2 2021-11-03 08:47:25 +01:00
Atgeirr Flø Rasmussen
d27d01a8a8 Merge pull request #2793 from atgeirr/backport-of-pr-2761
Backport of pr 2761
2021-10-28 10:06:14 +02:00
Bård Skaflestad
98388a7a7e Initialize RPTONLY/SUMTHIN Settings From SUMMARY Section 2021-10-28 10:05:31 +02:00
Bård Skaflestad
173a404725 Sort Includes in Schedule.hpp 2021-10-28 10:05:31 +02:00
Atgeirr Flø Rasmussen
f16fd2f662 Merge pull request #2792 from atgeirr/backport-of-pr-2774
Backport of pr 2774
2021-10-28 09:50:43 +02:00
Markus Blatt
bed2250cb5 Search for GMP if dune-common is used.
We do suggest dune-fem for opm-models and that one links to it
if available.
2021-10-28 09:47:44 +02:00
Markus Blatt
832a30a4d5 dune-fem uses QuadMath if available, search for it.
One still has to set USE_QUADMATH to true otherwise no
search will happen.
2021-10-28 09:47:44 +02:00
Markus Blatt
4ba3d16cfe Introduced DUNE-2.8 compatible imported targets where needed.
I.e. in the find_package files for PTScotch ParMETIS, Quadmath,
SuiteSparse, and SuperLU.
2021-10-28 09:47:44 +02:00
Markus Blatt
ef659cbfd3 Adds a rudimentary FindTBB.cmake to make DUNE 2.8 with TBB work
Fixes errors like

Target "test_communication_utils" links to target
"PkgConfig::PkgConfigTBB" but the target
was not found.  Perhaps a find_package() call is missing for an IMPORTED
target, or an ALIAS target is missing?
2021-10-28 09:47:44 +02:00
Markus Blatt
9cb632d4be Search for TBB in Finddune-common.cmake
When configured with TBB dune-common-targets.cmake lists the
imported TBB::tbb or PkgConfig::PkgConfigTBB target
in INTERFACE_LINK_LIBRARIES. Hence we need to be able to resolve
this target in opm. We do this by searching for TBB id dune-common
is a prerequisite.

This commit fixes the problem only for newer versions of TBB shipping a
TBBConfig.cmake file.

The error fixed is along these lines:

Target "test_communication_utils" links to target "TBB::tbb" but the target
was not found.  Perhaps a find_package() call is missing for an IMPORTED
target, or an ALIAS target is missing?
2021-10-28 09:47:44 +02:00
Arne Morten Kvarving
4e413a3aa7 bump version to 2021.10-rc1 2021-10-18 08:22:23 +02:00
2454 changed files with 22885 additions and 259485 deletions

View File

@@ -9,7 +9,7 @@ option(ENABLE_ECL_INPUT "Enable eclipse input support?" ON)
option(ENABLE_ECL_OUTPUT "Enable eclipse output support?" ON)
option(ENABLE_MOCKSIM "Build the mock simulator for io testing" ON)
option(OPM_ENABLE_PYTHON "Enable python bindings?" OFF)
option(OPM_INSTALL_PYTHON "Install python bindings?" ON)
option(OPM_INSTALL_PYTHON "Enable python bindings?" OFF)
option(OPM_ENABLE_EMBEDDED_PYTHON "Enable embedded python?" OFF)
# Output implies input
@@ -32,13 +32,13 @@ set(OPM_PROJECT_EXTRA_CODE_INSTALLED "#ENABLE_ECL_INPUT is needed by opm-common
set(ENABLE_ECL_INPUT ${ENABLE_ECL_INPUT})
set(OPM_MACROS_ROOT ${CMAKE_INSTALL_PREFIX}/share/opm)
list(APPEND CMAKE_MODULE_PATH \${OPM_MACROS_ROOT}/cmake/Modules)
include(OpmPackage) #Make macros available after find_package(opm-common)")
include(OpmPackage) #Make macros availabe after find_package(opm-common)")
set(OPM_PROJECT_EXTRA_CODE_INTREE "#ENABLE_ECL_INPUT is needed by opm-common-prereq.cmake
set(ENABLE_ECL_INPUT ${ENABLE_ECL_INPUT})
set(OPM_MACROS_ROOT ${OPM_MACROS_ROOT})
list(APPEND CMAKE_MODULE_PATH \${OPM_MACROS_ROOT}/cmake/Modules)
include(OpmPackage) #Make macros available after find_package(opm-common)")
include(OpmPackage) #Make macros availabe after find_package(opm-common)")
if(ENABLE_ECL_OUTPUT)
set(OPM_PROJECT_EXTRA_CODE_INSTALLED "${OPM_PROJECT_EXTRA_CODE_INSTALLED}
set(COMPARE_ECL_COMMAND ${CMAKE_INSTALL_PREFIX}/bin${${name}_VER_DIR}/compareECL)
@@ -66,25 +66,20 @@ include(Findopm-tests)
# with the find module
include (${project}-prereqs)
# source_hook runs before config_hook and the former needs fmt, hence this
# needs to be here.
if(fmt_FOUND)
# OpmSatellites will not add the library, do it here.
list(APPEND opm-common_LIBRARIES fmt::fmt)
else()
add_definitions(-DFMT_HEADER_ONLY)
include_directories(SYSTEM ${PROJECT_SOURCE_DIR}/external/fmtlib/include)
# Not sure why this is needed.
list(APPEND EXTRA_INCLUDES ${PROJECT_SOURCE_DIR}/external/fmtlib/include)
if(ENABLE_ECL_INPUT)
# source_hook runs before config_hook and the former needs fmt, hence this
# needs to be here.
if(fmt_FOUND)
# OpmSatellites will not add the library, do it here.
list(APPEND opm-common_LIBRARIES fmt::fmt)
else()
add_definitions(-DFMT_HEADER_ONLY)
include_directories(SYSTEM ${PROJECT_SOURCE_DIR}/external/fmtlib/include)
# Not sure why this is needed.
list(APPEND EXTRA_INCLUDES ${PROJECT_SOURCE_DIR}/external/fmtlib/include)
endif()
endif()
if(OPM_ENABLE_EMBEDDED_PYTHON AND NOT OPM_ENABLE_PYTHON)
# This needs to be here to run before source_hook
message(WARNING "Inconsistent settings: OPM_ENABLE_PYTHON=OFF and "
"OPM_ENABLE_EMBEDDED_PYTHON=ON. Please use OPM_ENABLE_PYTHON=ON to "
"activate. Will disable embedded python in this run.")
set(OPM_ENABLE_EMBEDDED_PYTHON OFF CACHE BOOL "Enable embedded python?" FORCE)
endif()
# read the list of components from this file (in the project directory);
# it should set various lists with the names of the files to include
include (CMakeLists_files.cmake)
@@ -106,7 +101,6 @@ macro (config_hook)
set(HAVE_ECL_INPUT 1)")
set(OPM_PROJECT_EXTRA_CODE_INSTALLED "${OPM_PROJECT_EXTRA_CODE_INSTALLED}
set(HAVE_ECL_INPUT 1)")
set(HAVE_ECL_INPUT 1)
endif()
if(ENABLE_ECL_OUTPUT)
set(OPM_PROJECT_EXTRA_CODE_INTREE "${OPM_PROJECT_EXTRA_CODE_INTREE}
@@ -114,19 +108,13 @@ macro (config_hook)
set(OPM_PROJECT_EXTRA_CODE_INSTALLED "${OPM_PROJECT_EXTRA_CODE_INSTALLED}
set(HAVE_ECL_OUTPUT 1)")
endif()
# We need to use the correct search mode. Otherwise not finding one
# boost component beloq will mark the previously found ones as not
# found again. (Code stolen from UseDynamicBoost.cmake
if(Boost_DIR)
set(_Boost_CONFIG_MODE CONFIG)
endif()
find_package(Boost COMPONENTS filesystem regex system unit_test_framework ${_Boost_CONFIG_MODE})
find_package(Boost COMPONENTS filesystem regex system unit_test_framework)
if (HAVE_DYNAMIC_BOOST_TEST)
set_target_properties(Boost::unit_test_framework PROPERTIES INTERFACE_COMPILE_DEFINITIONS BOOST_TEST_DYN_LINK=1)
endif()
endif()
endmacro (config_hook)
macro (prereqs_hook)
@@ -141,25 +129,13 @@ macro (sources_hook)
list(INSERT opm-common_SOURCES 0 ${PROJECT_BINARY_DIR}/ParserInit.cpp)
foreach (name A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
list(INSERT opm-common_SOURCES 0 ${PROJECT_BINARY_DIR}/ParserKeywords/${name}.cpp)
list(INSERT opm-common_SOURCES 0 ${PROJECT_BINARY_DIR}/ParserKeywords/ParserInit${name}.cpp)
list(INSERT opm-common_SOURCES 0 ${PROJECT_BINARY_DIR}/ParserKeywords/Builtin${name}.cpp)
list(INSERT opm-common_HEADERS 0 ${PROJECT_BINARY_DIR}/include/opm/input/eclipse/Parser/ParserKeywords/${name}.hpp)
endforeach()
if (OPM_ENABLE_EMBEDDED_PYTHON)
if (OPM_ENABLE_PYTHON)
list(INSERT opm-common_SOURCES 0 ${PROJECT_BINARY_DIR}/python/cxx/builtin_pybind11.cpp)
endif()
endif()
set_source_files_properties(src/opm/input/eclipse/Python/Python.cpp
set_source_files_properties(src/opm/parser/eclipse/Python/Python.cpp
PROPERTIES COMPILE_FLAGS -Wno-shadow)
if(QuadMath_FOUND)
get_target_property(qm_defs QuadMath::QuadMath INTERFACE_COMPILE_DEFINITIONS)
get_target_property(qm_options QuadMath::QuadMath INTERFACE_COMPILE_OPTIONS)
set_source_files_properties(src/opm/material/components/CO2.cpp
src/opm/material/densead/Evaluation.cpp
PROPERTIES COMPILE_DEFINITIONS "${qm_defs}"
COMPILE_OPTIONS "${qm_options}")
endif()
endmacro (sources_hook)
macro (fortran_hook)
@@ -180,19 +156,11 @@ macro (install_hook)
PATTERN *.hpp)
endmacro (install_hook)
# Used to append entries from one list to another.
# The output list is suitable for use in setup.py subtitution
macro(append_quoted OUT IN)
foreach(ENTRY ${${IN}})
list(APPEND ${OUT} "'${ARGN}${ENTRY}'")
endforeach()
endmacro()
# If opm-common is configured to embed the python interpreter we must make sure
# that all downstream modules link libpython transitively. Due to the required
# integration with Python+cmake machinery provided by pybind11 this is done by
# manually adding to the opm-common_LIBRARIES variable here, and not in the
# OpmLibMain function. Here only the library dependency is implemented, the
# OpmnLibMain function. Here only the library dependency is implemented, the
# bulk of the python configuration is further down in the file.
if (OPM_ENABLE_PYTHON)
# We need to be compatible with older CMake versions
@@ -209,48 +177,24 @@ if (OPM_ENABLE_PYTHON)
endif()
set(Python3_EXECUTABLE ${PYTHON_EXECUTABLE})
set(Python3_LIBRARIES ${PYTHON_LIBRARIES})
set(Python3_VERSION "${PYTHON_VERSION_STRING}")
set(Python3_VERSION_MINOR ${PYTHON_VERSION_MINOR})
else()
# Be backwards compatible.
if(PYTHON_EXECUTABLE AND NOT Python3_EXECUTABLE)
set(Python3_EXECUTABLE ${PYTHON_EXECUTABLE})
endif()
# We always need to search for Development as we use
# pybind11_add_module even if don't embed Python
if (NOT OPM_ENABLE_EMBEDDED_PYTHON)
if(${CMAKE_VERSION} VERSION_LESS "3.18.0")
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
else()
find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module)
endif()
else()
if(${CMAKE_VERSION} VERSION_LESS "3.18.0")
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
else()
find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Embed Development.Module)
endif()
if (OPM_ENABLE_EMBEDDED_PYTHON)
find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
get_target_property(_lib_path Python3::Python IMPORTED_LOCATION)
set(PYTHON_LIBRARY ${_lib_path})
set(PYTHON_LIBRARIES {PYTHON_LIBRARY})
list(APPEND opm-common_LIBRARIES ${PYTHON_LIBRARY})
set(PYTHON_INCLUDE_DIRS ${Python3_INCLUDE_DIRS})
else()
find_package(Python3 REQUIRED COMPONENTS Interpreter)
endif()
if(Python3_VERSION_MINOR LESS 3)
# Python native namespace packages requires python >= 3.3
message(SEND_ERROR "OPM requires python >= 3.3 but only version ${Python3_VERSION} was found")
endif()
# Compatibility settings for PythonInterp and PythonLibs
# used e.g. in FindCwrap, pybind11
set(PYTHON_EXECUTABLE ${Python3_EXECUTABLE})
# Directory to install common (for opm modules) python scripts
include (GNUInstallDirs)
set(OPM_PYTHON_COMMON_DIR "${CMAKE_INSTALL_DATAROOTDIR}/opm/python")
set(OPM_PROJECT_EXTRA_CODE_INTREE "${OPM_PROJECT_EXTRA_CODE_INTREE}
set(opm-common_PYTHON_COMMON_DIR ${PROJECT_SOURCE_DIR}/python)")
set(OPM_PROJECT_EXTRA_CODE_INSTALLED "${OPM_PROJECT_EXTRA_CODE_INSTALLED}
set(opm-common_PYTHON_COMMON_DIR ${CMAKE_INSTALL_PREFIX}/${OPM_PYTHON_COMMON_DIR})")
endif()
# We always need the PYTHON_INCLUDE_DIR. Unfortunately
# When we build pypi packages CMake will fail to determine
@@ -269,10 +213,8 @@ if (OPM_ENABLE_PYTHON)
endif()
find_package(pybind11 2.2 CONFIG)
if (NOT pybind11_FOUND)
add_subdirectory(python/pybind11)
if (NOT pybind11_INCLUDE_DIRS)
set(pybind11_INCLUDE_DIRS ${PYBIND11_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS})
endif()
# Use full path for reuse with pypi
set(pybind11_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/python/pybind11/include ${PYTHON_INCLUDE_DIRS})
endif()
endif()
@@ -280,7 +222,7 @@ endif()
# all setup common to the OPM library modules is done here
include (OpmLibMain)
if (ENABLE_MOCKSIM AND ENABLE_ECL_INPUT)
if (ENABLE_MOCKSIM)
add_library(mocksim
msim/src/msim.cpp)
target_link_libraries(mocksim opmcommon)
@@ -301,6 +243,10 @@ if (ENABLE_MOCKSIM AND ENABLE_ECL_INPUT)
endif()
endif()
if (ENABLE_SCHEDULE_DEBUG)
add_compile_definitions( SCHEDULE_DEBUG )
endif()
# Build the compare utilities
if(ENABLE_ECL_INPUT)
add_executable(compareECL
@@ -317,15 +263,11 @@ if(ENABLE_ECL_INPUT)
test_util/summary.cpp
)
add_executable(arraylist
test_util/arraylist.cpp
)
add_executable(rewriteEclFile
test_util/rewriteEclFile.cpp
)
foreach(target compareECL convertECL summary rewriteEclFile arraylist)
foreach(target compareECL convertECL summary rewriteEclFile)
target_link_libraries(${target} opmcommon)
install(TARGETS ${target} DESTINATION bin)
endforeach()
@@ -359,27 +301,12 @@ if(ENABLE_ECL_INPUT)
${PROJECT_BINARY_DIR}/tests
)
endif()
# Explicitly link tests needing dune-common.
# To avoid pulling dune-common into the opm-common interface
find_package(dune-common REQUIRED)
opm_need_version_of ("dune-common")
target_include_directories(dunecommon INTERFACE ${dune-common_INCLUDE_DIRS})
string(REPLACE " " ";" dflags ${dune-common_CXX_FLAGS})
target_compile_options(dunecommon INTERFACE ${dflags})
target_compile_definitions(dunecommon INTERFACE DUNE_COMMON_VERSION_MAJOR=${DUNE_COMMON_VERSION_MAJOR})
target_compile_definitions(dunecommon INTERFACE DUNE_COMMON_VERSION_MINOR=${DUNE_COMMON_VERSION_MINOR})
target_compile_definitions(dunecommon INTERFACE DUNE_COMMON_VERSION_REVISION=${DUNE_COMMON_VERSION_REVISION})
if(Boost_UNIT_TEST_FRAMEWORK_FOUND)
foreach(src ${DUNE_TEST_SOURCE_FILES})
get_filename_component(tgt ${src} NAME_WE)
target_link_libraries(${tgt} dunecommon)
foreach(test test_EclIO test_EGrid test_ERft test_ERst test_ESmry test_EInit test_ExtESmry)
opm_add_test(${test} CONDITION ENABLE_ECL_INPUT AND Boost_UNIT_TEST_FRAMEWORK_FOUND
LIBRARIES ${_libs}
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/tests)
endforeach()
endif()
if(BUILD_EXAMPLES)
target_link_libraries(co2brinepvt dunecommon)
endif()
# Install build system files and documentation
install(DIRECTORY cmake
@@ -393,53 +320,116 @@ install(FILES cmake/OPM-CMake.md
install(FILES etc/opm_bash_completion.sh.in DESTINATION share/opm/etc)
if (OPM_ENABLE_PYTHON)
# -------------------------------------------------------------------------
# 1: Wrap C++ functionality in Python
if (EXISTS "/etc/debian_version")
set(PYTHON_PACKAGE_PATH "dist-packages")
else()
set(PYTHON_PACKAGE_PATH "site-packages")
endif()
if(PYTHON_VERSION_MAJOR)
set(PY_MAJOR ${PYTHON_VERSION_MAJOR})
else()
set(PY_MAJOR ${Python3_VERSION_MAJOR})
endif()
if(PYTHON_VERSION_MINOR)
set(PY_MINOR ${PYTHON_VERSION_MINOR})
else()
set(PY_MINOR ${Python3_VERSION_MINOR})
endif()
set(PYTHON_INSTALL_PREFIX "lib/python${PY_MAJOR}.${PY_MINOR}/${PYTHON_PACKAGE_PATH}" CACHE STRING "Subdirectory to install Python modules in")
make_directory(${PROJECT_BINARY_DIR}/python)
get_target_property(_opmcommon_include_dirs opmcommon INCLUDE_DIRECTORIES)
list(APPEND _opmcommon_include_dirs ${_ecl_include_dirs})
string(REPLACE ";" ":" _setup_include_dirs "${_opmcommon_include_dirs}")
get_target_property(_opmcommon_lib_dirs opmcommon LINK_DIRECTORIES)
if (CMAKE_PREFIX_PATH)
list(APPEND _opmcommon_lib_dirs ${PROJECT_BINARY_DIR}/lib ${CMAKE_PREFIX_PATH}/${CMAKE_INSTALL_LIBDIR})
else()
list(APPEND _opmcommon_lib_dirs ${PROJECT_BINARY_DIR}/lib)
endif()
string(REPLACE ";" ":" _setup_lib_dirs "${_opmcommon_lib_dirs}")
if (USE_RUNPATH)
set (_python_rpath_list)
if (CMAKE_PREFIX_PATH)
foreach(path ${CMAKE_PREFIX_PATH})
list(APPEND _python_rpath_list "${path}/${CMAKE_INSTALL_LIBDIR}")
endforeach()
endif()
if (BUILD_SHARED_LIBS)
list(APPEND _python_rpath_list "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}")
endif()
if (_python_rpath_list)
string(REPLACE ";" ":" _rpath "${_python_rpath_list}")
set( _rpath_arg "--rpath=${_rpath}")
else()
set(_rpath_arg "")
endif()
else()
set( _rpath_arg "")
endif()
set(opm-common_PYTHON_PACKAGE_VERSION ${OPM_PYTHON_PACKAGE_VERSION_TAG})
# Generate versioned setup.py
if (pybind11_INCLUDE_DIRS)
string(REGEX REPLACE ";" "', '" _tmp "${pybind11_INCLUDE_DIRS}")
set(SETUP_PY_PYBIND_INCLUDE_DIR "'${_tmp}'")
endif()
if (TARGET fmt::fmt)
get_target_property(SETUP_PY_FMT_LIBS fmt::fmt LOCATION)
get_target_property(FMT_FLAGS fmt::fmt INTERFACE_COMPILE_DEFINITIONS)
foreach(flag ${FMT_FLAGS})
set(SETUP_PY_FMT_FLAGS "${SETUP_PY_FMT_FLAGS} '-D${flag}',")
endforeach()
list(APPEND opm-common_PYTHON_LINKAGE "'${SETUP_PY_FMT_LIBS}'")
else()
set(SETUP_PY_FMT_FLAGS "'-DFMT_HEADER_ONLY'")
endif()
configure_file (${PROJECT_SOURCE_DIR}/python/setup.py.in ${PROJECT_BINARY_DIR}/python/setup.py)
file(COPY ${PROJECT_SOURCE_DIR}/python/README.md DESTINATION ${PROJECT_BINARY_DIR}/python)
execute_process(COMMAND ${Python3_EXECUTABLE} target_name.py
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/python
OUTPUT_VARIABLE python_lib_target)
add_custom_target(copy_python ALL
COMMAND ${Python3_EXECUTABLE} ${PROJECT_SOURCE_DIR}/python/install.py ${PROJECT_SOURCE_DIR}/python ${PROJECT_BINARY_DIR} 0)
file(COPY ${PROJECT_SOURCE_DIR}/python/README.md DESTINATION ${PROJECT_BINARY_DIR}/python)
pybind11_add_module(opmcommon_python
${PYTHON_CXX_SOURCE_FILES}
${PROJECT_BINARY_DIR}/python/cxx/builtin_pybind11.cpp)
target_link_libraries(opmcommon_python PRIVATE
opmcommon)
if(TARGET pybind11::pybind11)
target_link_libraries(opmcommon_python PRIVATE
pybind11::pybind11)
else()
target_include_directories(opmcommon_python SYSTEM PRIVATE ${pybind11_INCLUDE_DIRS})
endif()
set_target_properties(opmcommon_python PROPERTIES
LIBRARY_OUTPUT_DIRECTORY python/opm)
add_dependencies(opmcommon_python copy_python)
# Generate versioned setup.py
configure_file(${PROJECT_SOURCE_DIR}/python/setup.py.in
${PROJECT_BINARY_DIR}/python/setup.py.tmp)
file(GENERATE OUTPUT ${PROJECT_BINARY_DIR}/python/setup.py
INPUT ${PROJECT_BINARY_DIR}/python/setup.py.tmp)
add_custom_command(OUTPUT python/opm/${python_lib_target}
DEPENDS ${PYTHON_CXX_DEPENDS}
DEPENDS copy_python
COMMAND ${Python3_EXECUTABLE} ${PROJECT_BINARY_DIR}/python/setup.py
build
build_ext
--build-lib=${PROJECT_BINARY_DIR}/python
--library-dirs=${_setup_lib_dirs}
${_rpath_arg}
--include-dirs=${_setup_include_dirs}
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/python
COMMENT "Building python bindings at python/opm/${python_lib_target}")
add_custom_target(opmcommon_python ALL DEPENDS python/opm/${python_lib_target})
add_dependencies(opmcommon_python opmcommon)
# The install target is based on manually copying the python file tree to the
# installation area with a small installation script 'install.py'. Would have
# preferred to use standard setup.py install, but the setup.py based solution
# refuses to install to a location which the current python executable can not
# load from, and the use of eggs in the setup.py based installation makes
# debugging quite difficult.
#
# Since the installation of Python code is nonstandard it is protected by an
# extra cmake switch, OPM_INSTALL_PYTHON. If you prefer you can still invoke
# setup.py install manually - optionally with the generated script
# setup-install.sh - and completely bypass cmake in the installation phase.
if (OPM_INSTALL_PYTHON)
include(PyInstallPrefix)
install(TARGETS opmcommon_python DESTINATION ${DEST_PREFIX}${CMAKE_INSTALL_PREFIX}/${PYTHON_INSTALL_PREFIX}/opm)
install(
CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE}
python/install.py
${PROJECT_BINARY_DIR}/python/opm
${DEST_PREFIX}${CMAKE_INSTALL_PREFIX}/${PYTHON_INSTALL_PREFIX} 1)")
## Need to install this Python script such that it can be used by opm-simulators when building against an installed
## opm-common
install( PROGRAMS "python/install.py" DESTINATION "${OPM_PYTHON_COMMON_DIR}" )
install( CODE "execute_process(COMMAND ${Python3_EXECUTABLE} ${PROJECT_BINARY_DIR}/python/install.py ${PROJECT_BINARY_DIR}/python/opm ${DEST_PREFIX}${CMAKE_INSTALL_PREFIX}/${PYTHON_INSTALL_PREFIX} 1)")
endif()
# Observe that if the opmcommon library has been built as a shared library the
@@ -447,7 +437,7 @@ if (OPM_ENABLE_PYTHON)
# testing.
add_test(NAME python_tests
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/python
COMMAND ${CMAKE_COMMAND} -E env LD_LIBRARY_PATH=${PROJECT_BINARY_DIR}/lib ${Python3_EXECUTABLE} -m unittest discover
COMMAND ${CMAKE_COMMAND} -E env LD_LIBRARY_PATH=${PROJECT_BINARY_DIR}/lib ${Python3_EXECUTABLE} setup.py build_ext --dry-run --build-lib ${PROJECT_BINARY_DIR}/python test
)
set_target_properties(opmcommon PROPERTIES POSITION_INDEPENDENT_CODE ON)
@@ -461,6 +451,11 @@ if (OPM_ENABLE_PYTHON)
DESTINATION ${PROJECT_BINARY_DIR}
FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE )
configure_file(python/setup-package.sh.in tmp/setup-package.sh)
file( COPY ${PROJECT_BINARY_DIR}/tmp/setup-package.sh
DESTINATION ${PROJECT_BINARY_DIR}
FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE )
configure_file(python/setup-test.sh.in tmp/setup-test.sh)
file( COPY ${PROJECT_BINARY_DIR}/tmp/setup-test.sh
DESTINATION ${PROJECT_BINARY_DIR}
@@ -480,6 +475,11 @@ if (OPM_ENABLE_PYTHON)
target_link_libraries(opmcommon PUBLIC ${PYTHON_LIBRARY})
add_definitions(-DEMBEDDED_PYTHON)
endif()
else()
if (OPM_ENABLE_EMBEDDED_PYTHON)
message(WARNING "Inconsistent settings OPM_ENABLE_PYTHON / OPM_ENABLE_EMBEDDED_PYTHON")
set(OPM_ENABLE_EMBEDDED_PYTHON OFF CACHE BOOL "Enable embedded python?" FORCE)
endif()
endif()
install(DIRECTORY docs/man1 DESTINATION ${CMAKE_INSTALL_MANDIR}

File diff suppressed because it is too large Load Diff

View File

@@ -13,17 +13,17 @@ if (EXISTS ${BASE_DIR}/python/cxx)
endif()
execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
${BASE_DIR}/tmp_gen/include/opm/input/eclipse/Parser/ParserKeywords/Builtin.hpp
${BASE_DIR}/include/opm/input/eclipse/Parser/ParserKeywords/Builtin.hpp)
${BASE_DIR}/tmp_gen/include/opm/parser/eclipse/Parser/ParserKeywords/Builtin.hpp
${BASE_DIR}/include/opm/parser/eclipse/Parser/ParserKeywords/Builtin.hpp)
file(GLOB HDRS ${BASE_DIR}/tmp_gen/include/opm/input/eclipse/Parser/ParserKeywords/*.hpp)
file(GLOB HDRS ${BASE_DIR}/tmp_gen/include/opm/parser/eclipse/Parser/ParserKeywords/*.hpp)
foreach(HDR ${HDRS})
file(RELATIVE_PATH hdr ${BASE_DIR}/tmp_gen/include/opm/input/eclipse/Parser/ParserKeywords ${HDR})
file(RELATIVE_PATH hdr ${BASE_DIR}/tmp_gen/include/opm/parser/eclipse/Parser/ParserKeywords ${HDR})
execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
${HDR}
${BASE_DIR}/include/opm/input/eclipse/Parser/ParserKeywords/${hdr})
${BASE_DIR}/include/opm/parser/eclipse/Parser/ParserKeywords/${hdr})
endforeach()
@@ -31,10 +31,4 @@ foreach (name A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
${BASE_DIR}/tmp_gen/ParserKeywords/${name}.cpp
${BASE_DIR}/ParserKeywords/${name}.cpp)
execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
${BASE_DIR}/tmp_gen/ParserKeywords/ParserInit${name}.cpp
${BASE_DIR}/ParserKeywords/ParserInit${name}.cpp)
execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
${BASE_DIR}/tmp_gen/ParserKeywords/Builtin${name}.cpp
${BASE_DIR}/ParserKeywords/Builtin${name}.cpp)
endforeach()

View File

@@ -42,7 +42,6 @@ opm_add_test(EclipseStateTests
list(APPEND EXTRA_TESTS EclipseStateTests)
foreach (test BoxTest
CarfinTest
CheckDeckValidity
EclipseGridCreateFromDeck
IncludeTest
@@ -60,20 +59,21 @@ foreach (test BoxTest
list(APPEND EXTRA_TESTS ${test})
endforeach ()
opm_add_test( rst_spe1
SOURCES tests/rst_test.cpp
LIBRARIES ${TEST_LIBS}
TEST_ARGS tests/SPE1CASE2.DATA tests/SPE1CASE2_RESTART.DATA )
opm_add_test( rst_msw
SOURCES tests/rst_test.cpp
LIBRARIES ${TEST_LIBS}
TEST_ARGS tests/MSW.DATA tests/MSW_RESTART.DATA )
add_test( NAME rst_deck_test
COMMAND ${PROJECT_SOURCE_DIR}/tests/rst_test_driver.sh ${PROJECT_BINARY_DIR}/bin/rst_deck ${PROJECT_BINARY_DIR}/bin/opmhash
${PROJECT_SOURCE_DIR}/tests/SPE1CASE2_INCLUDE.DATA)
add_test( NAME rst_deck_test2
COMMAND ${PROJECT_SOURCE_DIR}/tests/rst_test_driver2.sh
${PROJECT_BINARY_DIR}/bin/rst_deck
${PROJECT_BINARY_DIR}/bin/opmi
${PROJECT_SOURCE_DIR}/tests/ACTIONX_M1.DATA
${PROJECT_SOURCE_DIR}/tests/ACTIONX_M1_MULTIPLE.DATA
${PROJECT_SOURCE_DIR}/tests/ACTIONX_M1.UNRST
${PROJECT_SOURCE_DIR}/tests/ACTIONX_M1.X0010 )
# opm-tests dependent tests
if(HAVE_OPM_TESTS)
opm_add_test(parse_write ONLY_COMPILE
@@ -94,7 +94,10 @@ if(HAVE_OPM_TESTS)
${OPM_TESTS_ROOT}/spe9/SPE9_CP.DATA
${OPM_TESTS_ROOT}/spe9/SPE9_CP_GROUP.DATA
${OPM_TESTS_ROOT}/spe9/SPE9_CP_SHORT.DATA
${OPM_TESTS_ROOT}/spe9/SPE9_CP_SHORT_RESTART.DATA
${OPM_TESTS_ROOT}/spe9/SPE9.DATA
${OPM_TESTS_ROOT}/spe10model1/SPE10_MODEL1.DATA
${OPM_TESTS_ROOT}/spe10model2/SPE10_MODEL2.DATA
${OPM_TESTS_ROOT}/msw_2d_h/2D_H__.DATA
${OPM_TESTS_ROOT}/model2/0_BASE_MODEL2.DATA
${OPM_TESTS_ROOT}/model2/1_MULTREGT_MODEL2.DATA
@@ -117,7 +120,7 @@ if(HAVE_OPM_TESTS)
PROPERTY ENVIRONMENT "OPM_ERRORS_IGNORE=PARSE_RANDOM_SLASH")
add_test( NAME rst_deck_test_norne
COMMAND ${PROJECT_SOURCE_DIR}/tests/rst_test_driver.sh ${PROJECT_BINARY_DIR}/bin/rst_deck ${PROJECT_BINARY_DIR}/bin/opmhash
COMMAND ${PROJECT_SOURCE_DIR}/tests/rst_test_driver.sh ${CMAKE_BINARY_DIR}/bin/rst_deck ${CMAKE_BINARY_DIR}/bin/opmhash
${OPM_TESTS_ROOT}/norne/NORNE_ATW2013.DATA)
set_property(TEST rst_deck_test_norne

View File

@@ -1,31 +1,27 @@
set(genkw_SOURCES src/opm/json/JsonObject.cpp
src/opm/input/eclipse/Parser/createDefaultKeywordList.cpp
src/opm/input/eclipse/Deck/UDAValue.cpp
src/opm/input/eclipse/Deck/DeckTree.cpp
src/opm/input/eclipse/Deck/DeckValue.cpp
src/opm/input/eclipse/Deck/Deck.cpp
src/opm/input/eclipse/Deck/DeckView.cpp
src/opm/input/eclipse/Deck/DeckItem.cpp
src/opm/input/eclipse/Deck/DeckKeyword.cpp
src/opm/input/eclipse/Deck/DeckRecord.cpp
src/opm/input/eclipse/Deck/DeckOutput.cpp
src/opm/input/eclipse/Generator/KeywordGenerator.cpp
src/opm/input/eclipse/Generator/KeywordLoader.cpp
src/opm/input/eclipse/Schedule/UDQ/UDQEnums.cpp
src/opm/input/eclipse/Parser/ErrorGuard.cpp
src/opm/input/eclipse/Parser/ParseContext.cpp
src/opm/input/eclipse/Parser/ParserEnums.cpp
src/opm/input/eclipse/Parser/ParserItem.cpp
src/opm/input/eclipse/Parser/ParserKeyword.cpp
src/opm/input/eclipse/Parser/ParserRecord.cpp
src/opm/input/eclipse/Parser/raw/RawKeyword.cpp
src/opm/input/eclipse/Parser/raw/RawRecord.cpp
src/opm/input/eclipse/Parser/raw/StarToken.cpp
src/opm/input/eclipse/Units/Dimension.cpp
src/opm/input/eclipse/Units/UnitSystem.cpp
src/opm/parser/eclipse/Parser/createDefaultKeywordList.cpp
src/opm/parser/eclipse/Deck/UDAValue.cpp
src/opm/parser/eclipse/Deck/DeckTree.cpp
src/opm/parser/eclipse/Deck/DeckValue.cpp
src/opm/parser/eclipse/Deck/Deck.cpp
src/opm/parser/eclipse/Deck/DeckItem.cpp
src/opm/parser/eclipse/Deck/DeckKeyword.cpp
src/opm/parser/eclipse/Deck/DeckRecord.cpp
src/opm/parser/eclipse/Deck/DeckOutput.cpp
src/opm/parser/eclipse/Generator/KeywordGenerator.cpp
src/opm/parser/eclipse/Generator/KeywordLoader.cpp
src/opm/parser/eclipse/Parser/ErrorGuard.cpp
src/opm/parser/eclipse/Parser/ParseContext.cpp
src/opm/parser/eclipse/Parser/ParserEnums.cpp
src/opm/parser/eclipse/Parser/ParserItem.cpp
src/opm/parser/eclipse/Parser/ParserKeyword.cpp
src/opm/parser/eclipse/Parser/ParserRecord.cpp
src/opm/parser/eclipse/Parser/raw/RawKeyword.cpp
src/opm/parser/eclipse/Parser/raw/RawRecord.cpp
src/opm/parser/eclipse/Parser/raw/StarToken.cpp
src/opm/parser/eclipse/Units/Dimension.cpp
src/opm/parser/eclipse/Units/UnitSystem.cpp
src/opm/common/utility/OpmInputError.cpp
src/opm/common/utility/shmatch.cpp
src/opm/common/utility/String.cpp
src/opm/common/OpmLog/OpmLog.cpp
src/opm/common/OpmLog/Logger.cpp
src/opm/common/OpmLog/StreamLog.cpp
@@ -40,9 +36,9 @@ add_executable(genkw ${genkw_SOURCES})
target_link_libraries(genkw ${opm-common_LIBRARIES})
# Generate keyword list
include(src/opm/input/eclipse/share/keywords/keyword_list.cmake)
string(REGEX REPLACE "([^;]+)" "${PROJECT_SOURCE_DIR}/src/opm/input/eclipse/share/keywords/\\1" keyword_files "${keywords}")
configure_file(src/opm/input/eclipse/keyword_list.argv.in keyword_list.argv)
include(src/opm/parser/eclipse/share/keywords/keyword_list.cmake)
string(REGEX REPLACE "([^;]+)" "${PROJECT_SOURCE_DIR}/src/opm/parser/eclipse/share/keywords/\\1" keyword_files "${keywords}")
configure_file(src/opm/parser/eclipse/keyword_list.argv.in keyword_list.argv)
# Generate keyword source
@@ -50,45 +46,86 @@ set( genkw_argv keyword_list.argv
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords
${PROJECT_BINARY_DIR}/tmp_gen/ParserInit.cpp
${PROJECT_BINARY_DIR}/tmp_gen/include/
opm/input/eclipse/Parser/ParserKeywords
opm/parser/eclipse/Parser/ParserKeywords
${PROJECT_BINARY_DIR}/tmp_gen/TestKeywords.cpp)
foreach (name A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
list(APPEND _tmp_output ${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/${name}.cpp
${PROJECT_BINARY_DIR}/tmp_gen/include/opm/input/eclipse/Parser/ParserKeywords/${name}.hpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/ParserInit${name}.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/Builtin${name}.cpp
${PROJECT_BINARY_DIR}/tmp_gen/include/opm/input/eclipse/Parser/ParserKeywords/ParserInit${name}.hpp)
list(APPEND _target_output ${PROJECT_BINARY_DIR}/ParserKeywords/${name}.cpp
${PROJECT_BINARY_DIR}/include/opm/input/eclipse/Parser/ParserKeywords/${name}.hpp
${PROJECT_BINARY_DIR}/ParserKeywords/ParserInit${name}.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/Builtin${name}.cpp
${PROJECT_BINARY_DIR}/include/opm/input/eclipse/Parser/ParserKeywords/ParserInit${name}.hpp)
endforeach()
set( _tmp_output
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/A.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/B.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/C.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/D.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/E.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/F.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/G.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/H.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/I.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/J.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/K.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/L.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/M.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/N.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/O.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/P.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/Q.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/R.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/S.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/T.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/U.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/V.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/W.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/X.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/Y.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/Z.cpp
${PROJECT_BINARY_DIR}/tmp_gen/ParserInit.cpp
${PROJECT_BINARY_DIR}/tmp_gen/TestKeywords.cpp)
foreach(name TestKeywords.cpp ParserInit.cpp)
list(APPEND _target_output ${PROJECT_BINARY_DIR}/${name})
list(APPEND _tmp_output ${PROJECT_BINARY_DIR}/tmp_gen/${name})
endforeach()
list(APPEND _target_output ${PROJECT_BINARY_DIR}/include/opm/input/eclipse/Parser/ParserKeywords/Builtin.hpp)
list(APPEND _tmp_output ${PROJECT_BINARY_DIR}/tmp_gen/include/opm/input/eclipse/Parser/ParserKeywords/Builtin.hpp)
set( _target_output
${PROJECT_BINARY_DIR}/ParserKeywords/A.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/B.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/C.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/D.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/E.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/F.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/G.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/H.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/I.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/J.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/K.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/L.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/M.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/N.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/O.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/P.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/Q.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/R.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/S.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/T.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/U.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/V.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/W.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/X.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/Y.cpp
${PROJECT_BINARY_DIR}/ParserKeywords/Z.cpp
${PROJECT_BINARY_DIR}/TestKeywords.cpp
${PROJECT_BINARY_DIR}/ParserInit.cpp)
set(GEN_DEPS ${_tmp_output})
if (OPM_ENABLE_PYTHON)
list(APPEND genkw_argv ${PROJECT_BINARY_DIR}/tmp_gen/builtin_pybind11.cpp)
list(APPEND _tmp_output ${PROJECT_BINARY_DIR}/tmp_gen/builtin_pybind11.cpp)
list(APPEND _target_output ${PROJECT_BINARY_DIR}/python/cxx/builtin_pybind11.cpp)
list(APPEND GEN_DEPS copy_python)
endif()
add_custom_command( OUTPUT
${_tmp_output}
COMMAND genkw ${genkw_argv}
DEPENDS genkw ${keyword_files} src/opm/input/eclipse/share/keywords/keyword_list.cmake)
DEPENDS genkw ${keyword_files} src/opm/parser/eclipse/share/keywords/keyword_list.cmake)
# To avoid some rebuilds
add_custom_command(OUTPUT
${_target_output}
DEPENDS ${GEN_DEPS}
DEPENDS ${PROJECT_BINARY_DIR}/tmp_gen/ParserKeywords/A.cpp
COMMAND ${CMAKE_COMMAND} -DBASE_DIR=${PROJECT_BINARY_DIR} -P ${PROJECT_SOURCE_DIR}/CopyHeaders.cmake)

View File

@@ -1,23 +1,3 @@
# opm-common: Tools for Eclipse reservoir simulation files
The Open Porous Media (OPM) software suite provides libraries and
tools for modeling and simulation of porous media processes,
especially for simulating CO2 sequestration and improved and enhanced
oil recovery. The Eclipse file format is widely used in the reservoir
simulation community. This package provides a library containing code
for processing files in Eclipse format, Python binding for accessing
Eclipse files and utility code used by other OPM modules (e.g. CMake
modules used).
License
-------
The library is distributed under the GNU General Public License,
version 3 or later (GPLv3+).
Requirements
-----------
- C++17 compatible compiler
- CMake >= 3.10
- Posix compatibility
# opm-common
Contains common components used throughout all of OPM,
in particular CMake modules for the build system.

File diff suppressed because it is too large Load Diff

View File

@@ -46,8 +46,8 @@ if (METIS_INCLUDE_DIRS OR METIS_LIBRARIES)
file(READ "${METIS_INCLUDE_DIRS}/metis.h" metisheader)
string(REGEX MATCH "#define METIS_VER_MAJOR[ ]+([0-9]+)" METIS_MAJOR_VERSION ${metisheader})
if(NOT METIS_API_VERSION AND METIS_MAJOR_VERSION)
string(REGEX REPLACE ".*#define METIS_VER_MAJOR[ ]+([0-9]+).*" "\\1"
METIS_MAJOR_VERSION "${metisheader}")
# string(REGEX REPLACE ".*#define METIS_VER_MAJOR[ ]+([0-9]+).*" "\\1"
# METIS_MAJOR_VERSION "${metisheader}")
if(METIS_MAJOR_VERSION GREATER_EQUAL 3 AND METIS_MAJOR_VERSION LESS 5)
set(METIS_API_VERSION "3")
else()
@@ -55,13 +55,11 @@ if (METIS_INCLUDE_DIRS OR METIS_LIBRARIES)
endif()
endif()
if (NOT TARGET METIS::METIS)
add_library(METIS::METIS UNKNOWN IMPORTED)
set_target_properties(METIS::METIS PROPERTIES
IMPORTED_LOCATION ${METIS_LIBRARIES}
INTERFACE_INCLUDE_DIRECTORIES ${METIS_INCLUDE_DIRS}
INTERFACE_COMPILE_DEFINITIONS METIS_API_VERSION=${METIS_API_VERSION})
endif()
add_library(METIS::METIS UNKNOWN IMPORTED)
set_target_properties(METIS::METIS PROPERTIES
IMPORTED_LOCATION ${METIS_LIBRARIES}
INTERFACE_INCLUDE_DIRECTORIES ${METIS_INCLUDE_DIRS}
INTERFACE_COMPILE_DEFINITIONS METIS_API_VERSION=${METIS_API_VERSION})
endif()
# print a message to indicate status of this package

View File

@@ -1,49 +0,0 @@
# Module that checks whether the compiler supports the
# quadruple precision floating point math
#
# Adds target QuadMath::QuadMath if found
#
# perform tests
include(CheckCXXSourceCompiles)
include(CMakePushCheckState)
cmake_push_check_state()
set(CMAKE_REQUIRED_LIBRARIES quadmath)
if(${CMAKE_CXX_COMPILER_ID} STREQUAL GNU)
set(CMAKE_REQUIRED_FLAGS "-fext-numeric-literals")
endif()
check_cxx_source_compiles("
#include <quadmath.h>
int main ()
{
__float128 r = 1.0q;
r = strtoflt128(\"1.2345678\", NULL);
return 0;
}" QuadMath_COMPILES)
cmake_pop_check_state() # Reset CMAKE_REQUIRED_XXX variables
if(QuadMath_COMPILES)
# Use additional variable for better report message
set(QuadMath_VAR "(Supported by compiler)")
endif()
# Report that package was found
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(QuadMath
DEFAULT_MSG
QuadMath_VAR QuadMath_COMPILES
)
# add imported target for quadmath
if(QuadMath_FOUND AND NOT TARGET QuadMath::QuadMath)
# Compiler supports QuadMath: Add appropriate linker flag
add_library(QuadMath::QuadMath INTERFACE IMPORTED)
target_link_libraries(QuadMath::QuadMath INTERFACE quadmath)
target_compile_definitions(QuadMath::QuadMath INTERFACE
_GLIBCXX_USE_FLOAT128 HAVE_QUAD=1
)
target_compile_options(QuadMath::QuadMath INTERFACE
$<$<CXX_COMPILER_ID:GNU>:-fext-numeric-literals>
)
endif()

View File

@@ -0,0 +1,54 @@
# Module that checks whether the compiler supports the
# quadruple precision floating point math
#
# Sets the following variables:
# HAVE_QUAD
# QUADMATH_LIBRARIES
#
# perform tests
include(CheckCSourceCompiles)
include(CheckCXXSourceCompiles)
include(CMakePushCheckState)
include(CheckCXXCompilerFlag)
if(NOT DEFINED USE_QUADMATH OR USE_QUADMATH)
if(NOT DEFINED HAVE_EXTENDED_NUMERIC_LITERALS)
check_cxx_compiler_flag("-Werror -fext-numeric-literals" HAVE_EXTENDED_NUMERIC_LITERALS)
endif()
if (HAVE_EXTENDED_NUMERIC_LITERALS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fext-numeric-literals")
endif()
cmake_push_check_state(RESET)
list(APPEND CMAKE_REQUIRED_LIBRARIES "quadmath")
CHECK_CXX_SOURCE_COMPILES("
#include <quadmath.h>
int main(void){
__float128 foo = sqrtq(123.456);
foo = FLT128_MIN;
}" QUADMATH_FOUND)
cmake_pop_check_state()
if (QUADMATH_FOUND)
set(QUADMATH_LIBRARIES "quadmath")
set(HAVE_QUAD "${QUADMATH_FOUND}")
add_library(QuadMath::QuadMath INTERFACE IMPORTED)
set_target_properties(QuadMath::QuadMath PROPERTIES
INTERFACE_LINK_LIBRARIES quadmath
INTERFACE_COMPILE_DEFINITIONS _GLIBCXX_USE_FLOAT128
INTERFACE_COMPILE_OPTIONS $<$<CXX_COMPILER_ID:GNU>:-fext-numeric-literals>)
endif()
endif()
if (USE_QUADMATH AND NOT QUADMATH_FOUND)
message(FATAL_ERROR "Quadruple precision math support was explicitly requested but is unavailable!")
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Quadmath
DEFAULT_MSG
QUADMATH_LIBRARIES
HAVE_QUAD
)

View File

@@ -259,9 +259,9 @@ foreach (module IN LISTS SuiteSparse_FIND_COMPONENTS)
set (SuiteSparse_FOUND FALSE)
# use empty string instead of zero, so it can be tested with #ifdef
# as well as #if in the source code
set (HAVE_SUITESPARSE_${MODULE}_H "" CACHE STRING "Is ${module} header present?")
set (HAVE_SUITESPARSE_${MODULE}_H "" CACHE INT "Is ${module} header present?")
else (NOT SuiteSparse_${MODULE}_FOUND)
set (HAVE_SUITESPARSE_${MODULE}_H 1 CACHE STRING "Is ${module} header present?")
set (HAVE_SUITESPARSE_${MODULE}_H 1 CACHE INT "Is ${module} header present?")
list (APPEND SuiteSparse_LIBRARIES "${${MODULE}_LIBRARIES}")
list (APPEND SuiteSparse_LINKER_FLAGS "${${MODULE}_LINKER_FLAGS}")
list (APPEND SuiteSparse_INCLUDE_DIRS "${${MODULE}_INCLUDE_DIRS}")

View File

@@ -3,10 +3,13 @@
# This module defines:
# VALGRIND_INCLUDE_DIR, where to find valgrind/memcheck.h, etc.
# VALGRIND_PROGRAM, the valgrind executable.
# Valgrind_FOUND, If false, do not try to use valgrind.
# VALGRIND_FOUND, If false, do not try to use valgrind.
#
# If you have valgrind installed in a non-standard place, you can define
# VALGRIND_ROOT to tell cmake where it is.
if (VALGRIND_FOUND)
return()
endif()
find_path(VALGRIND_INCLUDE_DIR valgrind/memcheck.h
/usr/include /usr/local/include ${VALGRIND_ROOT}/include)
@@ -15,7 +18,7 @@ find_path(VALGRIND_INCLUDE_DIR valgrind/memcheck.h
# path, but this does not hurt...
find_program(VALGRIND_PROGRAM NAMES valgrind PATH ${VALGRIND_ROOT}/bin)
find_package_handle_standard_args(Valgrind DEFAULT_MSG
find_package_handle_standard_args(VALGRIND DEFAULT_MSG
VALGRIND_INCLUDE_DIR
VALGRIND_PROGRAM)

View File

@@ -24,7 +24,7 @@ find_package(PTScotch)
#find_package(ParMETIS)
# search for files which implements this module
find_path (ZOLTAN_INCLUDE_DIR
find_path (ZOLTAN_INCLUDE_DIRS
NAMES "zoltan.h"
PATHS ${ZOLTAN_SEARCH_PATH}
PATH_SUFFIXES include trilinos
@@ -35,7 +35,7 @@ if (CMAKE_SIZEOF_VOID_P)
math (EXPR _BITS "8 * ${CMAKE_SIZEOF_VOID_P}")
endif (CMAKE_SIZEOF_VOID_P)
find_library(ZOLTAN_LIBRARY
find_library(ZOLTAN_LIBRARIES
NAMES zoltan trilinos_zoltan
PATHS ${ZOLTAN_SEARCH_PATH}
PATH_SUFFIXES "lib/.libs" "lib" "lib${_BITS}" "lib/${CMAKE_LIBRARY_ARCHITECTURE}"
@@ -50,20 +50,15 @@ include (FindPackageHandleStandardArgs)
find_package_handle_standard_args(ZOLTAN
DEFAULT_MSG
ZOLTAN_LIBRARY
ZOLTAN_INCLUDE_DIR
ZOLTAN_LIBRARIES
ZOLTAN_INCLUDE_DIRS
MPI_FOUND
)
if (ZOLTAN_FOUND)
set(HAVE_ZOLTAN 1)
set(ZOLTAN_LIBRARIES ${ZOLTAN_LIBRARY} ${PARMETIS_LIBRARIES} ${PTSCOTCH_LIBRARIES})
set(ZOLTAN_INCLUDE_DIRS ${ZOLTAN_INCLUDE_DIR} ${PARMETIS_INCLUDE_DIRS}
set(ZOLTAN_LIBRARIES ${ZOLTAN_LIBRARIES} ${PARMETIS_LIBRARIES} ${PTSCOTCH_LIBRARIES})
set(ZOLTAN_INCLUDE_DIRS ${ZOLTAN_INCLUDE_DIRS} ${PARMETIS_INCLUDE_DIRS}
${PTSCOTCH_INCLUDE_DIRS})
# log result
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Determing location of ZOLTAN succeeded:\n"
" Include directory: ${ZOLTAN_INCLUDE_DIRS}\n"
" Library directory: ${ZOLTAN_LIBRARIES}\n\n")
endif()

View File

@@ -36,8 +36,8 @@ find_library (CJSON_LIBRARY
${_no_default_path} )
# setup list of all required libraries to link with cjson
set (cjson_INCLUDE_DIRS ${CJSON_INCLUDE_DIR})
set (cjson_LIBRARIES ${CJSON_LIBRARY})
set (CJSON_INCLUDE_DIRS ${CJSON_INCLUDE_DIR})
set (CJSON_LIBRARIES ${CJSON_LIBRARY})
# math library (should exist on all unices; automatically linked on Windows)
if (UNIX)
@@ -72,7 +72,10 @@ endif ()
# if the test program didn't compile, but was required to do so, bail
# out now and display an error; otherwise limp on
find_package_handle_standard_args (cjson
set (CJSON_FIND_REQUIRED ${cjson_FIND_REQUIRED})
set (CJSON_FIND_QUIETLY ${cjson_FIND_QUIETLY})
find_package_handle_standard_args (CJSON
DEFAULT_MSG
cjson_INCLUDE_DIRS cjson_LIBRARIES HAVE_CJSON
CJSON_INCLUDE_DIRS CJSON_LIBRARIES HAVE_CJSON
)
set (cjson_FOUND ${CJSON_FOUND})

View File

@@ -22,11 +22,10 @@ find_opm_package (
"dune-common REQUIRED;
dune-grid REQUIRED;
dune-alugrid;
dune-polygongrid;
ZLIB;
ZOLTAN;
METIS;
QuadMath
Quadmath
"
# header to search for
"dune/fem/space/shapefunctionset/legendre.hh"

View File

@@ -19,7 +19,7 @@ find_opm_package (
"dune-common REQUIRED;
ParMETIS;
SuperLU;
SuiteSparse COMPONENTS umfpack REQUIRED
SuiteSparse COMPONENTS umfpack
"
# header to search for
"dune/istl/bcrsmatrix.hh"

View File

@@ -1,47 +0,0 @@
# - Find DUNE Fem library
#
# Defines the following variables:
# dune-polygongrid_INCLUDE_DIRS Directory of header files
# dune-polygongrid_LIBRARIES Directory of shared object files
# dune-polygongrid_DEFINITIONS Defines that must be set to compile
# dune-alugrid_CONFIG_VARS List of defines that should be in config.h
# HAVE_DUNE_POLYGONGRID Binary value to use in config.h
# Copyright (C) 2015 IRIS AS
# This code is licensed under The GNU General Public License v3.0
include (OpmPackage)
find_opm_package (
# module name
"dune-polygongrid"
# dependencies
# TODO: we should probe for all the HAVE_* values listed below;
# however, we don't actually use them in our implementation, so
# we just include them to forward here in case anyone else does
"dune-common REQUIRED;
"
# header to search for
"dune/polygongrid/mesh.hh"
# library to search for
"dunepolygongrid"
# defines to be added to compilations
""
# test program
"#include <dune/polygongrid/mesh.hh>
int main (void) {
return 0;
}
"
# config variables
"HAVE_DUNE_POLYGONGRID
")
#debug_find_vars ("dune-polygongrid")
# make version number available in config.h
include (UseDuneVer)
find_dune_version ("dune" "polygongrid")

View File

@@ -38,7 +38,7 @@ macro (opm_compile opm)
endif()
set (${opm}_VERSION "${${opm}_VERSION_MAJOR}.${${opm}_VERSION_MINOR}")
if (${opm}_SOURCES)
add_library (${${opm}_TARGET} ${${opm}_LIBRARY_TYPE} ${${opm}_SOURCES} ${${opm}_HEADERS})
add_library (${${opm}_TARGET} ${${opm}_LIBRARY_TYPE} ${${opm}_SOURCES})
set_target_properties (${${opm}_TARGET} PROPERTIES
SOVERSION ${${opm}_VERSION}
VERSION ${${opm}_VERSION}

View File

@@ -128,41 +128,35 @@ macro (find_and_append_package_to prefix name)
# We even need to repeat the search for opm-common once as this is done
# in the top most CMakeLists.txt without querying defines, setting dependencies
# and the likes which is only done via opm_find_package
string(REGEX MATCH "(opm)-.*" _is_opm ${name})
if(NOT _is_opm)
# When using Boost >= 1.70 and e.g. CMake 3.18 we need to make sure that
# subsequent searches are using config mode too. Otherwise the library
# list will be completely messed up. We use a set Boost_Dir to detect that
# previous searches were done using config mode.
if("${name}" STREQUAL "Boost" AND Boost_DIR)
set(_CONFIG_MODE CONFIG)
if ( (NOT DEFINED ${name}_FOUND AND NOT DEFINED ${NAME}_FOUND )
OR _search_components GREATER -1)
string(REGEX MATCH "(opm)-.*" _is_opm ${name})
if(NOT _is_opm)
# When using Boost >= 1.70 and e.g. CMake 3.18 we need to make sure that
# subsequent searches are using config mode too. Otherwise the library
# list will be completely messed up. We use a set Boost_Dir to detect that
# previous searches were done using config mode.
if("${name}" STREQUAL "Boost" AND Boost_DIR)
set(_CONFIG_MODE CONFIG)
else()
set(_CONFIG_MODE "")
endif()
find_package (${name} ${ARGN} ${_CONFIG_MODE})
else()
set(_CONFIG_MODE "")
endif()
find_package (${name} ${ARGN} ${_CONFIG_MODE})
else()
if(${name}_DIR)
find_package (${name} ${${prefix}_VERSION_MAJOR}.${${prefix}_VERSION_MINOR} ${ARGN} NO_MODULE PATHS ${${name}_DIR} NO_DEFAULT_PATH)
else()
find_package (${name} ${${prefix}_VERSION_MAJOR}.${${prefix}_VERSION_MINOR} ${ARGN} NO_MODULE)
endif()
include(FindPackageHandleStandardArgs)
if( CMAKE_VERSION VERSION_GREATER_EQUAL "3.17")
# For some reason we will e.g. call
# find_package_handle_standard_args(opm-common)
# in a find_package(opm-material) call and this will
# usuallly print an annoying warnig. Prevent this at least
# for cmake >=3.17
# \todo Check why/whether these calls are even needed.
set(_NAME_MISMATCHED "NAME_MISMATCHED")
endif()
if(${name}_FOUND AND ${name}_LIBRARY STREQUAL "")
find_package_handle_standard_args(${name}
REQUIRED_VARS ${name}_INCLUDE_DIRS ${_NAME_MISMATCHED})
else()
find_package_handle_standard_args(${name}
REQUIRED_VARS ${name}_LIBRARY ${_NAME_MISMATCHED})
endif()
if(${name}_DIR)
find_package (${name} ${${prefix}_VERSION_MAJOR}.${${prefix}_VERSION_MINOR} ${ARGN} NO_MODULE PATHS ${${name}_DIR} NO_DEFAULT_PATH)
else()
find_package (${name} ${${prefix}_VERSION_MAJOR}.${${prefix}_VERSION_MINOR} ${ARGN} NO_MODULE)
endif()
include(FindPackageHandleStandardArgs)
if(${name}_FOUND AND ${name}_LIBRARY STREQUAL "")
find_package_handle_standard_args(${name}
REQUIRED_VARS ${name}_INCLUDE_DIRS)
else()
find_package_handle_standard_args(${name}
REQUIRED_VARS ${name}_LIBRARY)
endif()
endif ()
endif ()
if (NOT DEFINED ${name}_FOUND)
set (${name}_FOUND "${${NAME}_FOUND}")

View File

@@ -130,7 +130,7 @@ endif ()
# parallel computing must be explicitly enabled
# This needs to be in OpmInit as prereqs is called before OpmLibMain is included.
option (USE_MPI "Use Message Passing Interface for parallel computing" ON)
option (USE_MPI "Use Message Passing Interface for parallel computing" OFF)
if (NOT USE_MPI)
set (CMAKE_DISABLE_FIND_PACKAGE_MPI TRUE)
endif ()
@@ -142,7 +142,9 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option (USE_SUPERLU "Use SuperLU direct solvers for AMG (if umfpack is not found)" ON)
if (NOT USE_SUPERLU)
set (CMAKE_DISABLE_FIND_PACKAGE_SuperLU TRUE)
# quadmath must be explicitly enabled
# This needs to be in OpmInit as prereqs is called before OpmLibMain is included.
option (USE_QUADMATH "Use high precision floating point library (slow)" OFF)
if (NOT USE_QUADMATH)
set (CMAKE_DISABLE_FIND_PACKAGE_QuadMath TRUE)
endif ()

View File

@@ -63,6 +63,9 @@ find_openmp (${project})
include (UseThreads)
find_threads (${project})
# SuperLU is optional
option (USE_SUPERLU "Use SuperLU direct solvers" OFF)
# PETSc is optional
option (USE_PETSC "Use PETSc iterative solvers" OFF)

View File

@@ -124,7 +124,7 @@ macro (find_opm_package module deps header lib defs prog conf)
# without config.h
config_cmd_line (${module}_CMD_CONFIG ${module}_CONFIG_VARS)
if(prog) # always evaluates to false, but makes tests with DUNE 2.6-2.7 work
if(prog)
# check that we can compile a small test-program
include (CMakePushCheckState)
cmake_push_check_state ()
@@ -138,16 +138,13 @@ macro (find_opm_package module deps header lib defs prog conf)
list (APPEND CMAKE_REQUIRED_DEFINITIONS ${${module}_CMD_CONFIG})
check_cxx_source_compiles ("${prog}" HAVE_${MODULE})
cmake_pop_check_state ()
else()
else(prog)
if(${module}_FOUND)
# No test code provided, mark compilation as successful
# if module was found
# Has to be cached because of scope. Otherwise it is not accessible
# where it is used.
set(HAVE_${MODULE} 1 CACHE BOOL "${module} found")
mark_as_advanced(HAVE_${MODULE})
# if module was founf
set(HAVE_${MODULE} 1)
endif(${module}_FOUND)
endif()
endif(prog)
# write status message in the same manner as everyone else
include (FindPackageHandleStandardArgs)

View File

@@ -54,12 +54,6 @@ function (configure_cmake_file name variant version)
foreach (suffix IN LISTS variable_suffices)
set (opm-project_${suffix} "${${name}_${suffix}}")
endforeach (suffix)
if (BUILD_SHARED_LIBS)
# No need to list shared libraries as the linker information is alread
# in the shared lib
string(REGEX REPLACE ";?[^;]*.so" "" opm-project_LIBRARIES "${opm-project_LIBRARIES}")
endif()
set (opm-project_NAME "${${name}_NAME}")
set (opm-project_NAME_UC "${${name}_NAME}")
string(TOUPPER "${opm-project_NAME}" opm-project_NAME_UC)

View File

@@ -338,7 +338,7 @@ macro(opm_add_test TestName)
# has been specified to supervise the test binary, use it else
# run the test binary "naked".
if (CURTEST_DRIVER)
set(CURTEST_COMMAND ${CURTEST_DRIVER} ${CURTEST_DRIVER_ARGS} -e ${CURTEST_EXE_NAME} -- ${CURTEST_TEST_ARGS})
set(CURTEST_COMMAND ${CURTEST_DRIVER} ${CURTEST_DRIVER_ARGS} ${CURTEST_EXE_NAME} ${CURTEST_TEST_ARGS})
else()
set(CURTEST_COMMAND ${PROJECT_BINARY_DIR}/bin/${CURTEST_EXE_NAME})
if (CURTEST_TEST_ARGS)

View File

@@ -1,28 +0,0 @@
# We make this a cmake module so it can be used from opm-simulators' CMakeLists.txt also
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "
import site, sys
try:
sys.stdout.write(site.getsitepackages()[-1])
except e:
sys.stdout.write('')" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES_PATH)
# -------------------------------------------------------------------------
# 1: Wrap C++ functionality in Python
if (PYTHON_SITE_PACKAGES_PATH MATCHES ".*/dist-packages/?" AND
CMAKE_INSTALL_PREFIX MATCHES "^/usr.*")
# dist-packages is only used if we install below /usr and python's site packages
# path matches dist-packages
set(PYTHON_PACKAGE_PATH "dist-packages")
else()
set(PYTHON_PACKAGE_PATH "site-packages")
endif()
if(PYTHON_VERSION_MAJOR)
set(PY_MAJOR ${PYTHON_VERSION_MAJOR})
else()
set(PY_MAJOR ${Python3_VERSION_MAJOR})
endif()
if(PYTHON_VERSION_MINOR)
set(PY_MINOR ${PYTHON_VERSION_MINOR})
else()
set(PY_MINOR ${Python3_VERSION_MINOR})
endif()
set(PYTHON_INSTALL_PREFIX "lib/python${PY_MAJOR}.${PY_MINOR}/${PYTHON_PACKAGE_PATH}" CACHE STRING "Subdirectory to install Python modules in")

View File

@@ -1,27 +0,0 @@
if(USE_DAMARIS_LIB AND MPI_FOUND)
if (Damaris_FOUND)
set(HAVE_DAMARIS 1)
message(STATUS "The Damaris library was found: ${Damaris_VERSION} ${Damaris_DIR}")
if (Damaris_HAS_HDF5)
message(STATUS "The Damaris library has HDF5 support: ${HDF5_VERSION}")
else()
message(STATUS "The Damaris library does NOT have HDF5 support")
endif()
if (Damaris_HAS_VISIT)
message(STATUS "The Damaris library has VisIt support: ${VisIt_VERSION}")
else()
message(STATUS "The Damaris library does NOT have VisIt support")
endif()
if (Damaris_HAS_CATALYST)
message(STATUS "The Damaris library has Catalyst support: ${Catalyst_VERSION} ${Paraview_VERSION}")
else()
message(STATUS "The Damaris library does NOT have Catalyst support")
endif()
else()
message(STATUS "The Damaris library was requested but NOT found")
endif()
else() # User did not request Damaris support
unset(HAVE_DAMARIS)
endif()
mark_as_advanced(HAVE_DAMARIS)

View File

@@ -64,14 +64,7 @@ if (CXX_COMPAT_GCC)
# use these options for release builds - full optimization
add_options (ALL_LANGUAGES "${_prof_RELEASE}" ${_opt_rel} ${_opt_flags})
option(WITH_NDEBUG "Disable asserts in release mode" OFF)
if(WITH_NDEBUG)
foreach(type ${_prof_RELEASE})
string(TOUPPER ${type} type)
string(REPLACE -UNDEBUG "" CMAKE_CXX_FLAGS_${type} "${CMAKE_CXX_FLAGS_${type}}")
string(REPLACE -UNDEBUG "" CMAKE_C_FLAGS_${type} "${CMAKE_C_FLAGS_${type}}")
string(REPLACE -UNDEBUG "" CMAKE_Fortran_FLAGS_${type} "${CMAKE_Fortran_FLAGS_${type}}")
endforeach()
else()
if(NOT WITH_NDEBUG)
add_options (ALL_LANGUAGES "${_prof_RELEASE}" -UNDEBUG)
endif()

View File

@@ -17,9 +17,6 @@ message("-- Writing version information to local header project-version.h")
string (TIMESTAMP build_timestamp "%Y-%m-%d at %H:%M:%S hrs")
string (TOUPPER "${CMAKE_BUILD_TYPE}" cmake_build_type_upper_)
set(OPM_BINARY_PACKAGE_VERSION "" CACHE STRING
"Version of the binary Linux package built (will be printed in PRT file of flow if not empty)")
string(LENGTH "${OPM_BINARY_PACKAGE_VERSION}" _BINARY_PACKAGE_VERSION_LENGTH)
if (cmake_build_type_upper_ MATCHES DEBUG)
file (WRITE "${PROJECT_BINARY_DIR}/project-version.h"
"#ifndef OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
@@ -46,30 +43,22 @@ else ()
# system, so there is "no" way we can update the SHA. notice
# that this is a slightly different version of the label than
# above.
if (NOT GIT_FOUND OR NOT EXISTS ${PROJECT_SOURCE_DIR}/.git)
if(_BINARY_PACKAGE_VERSION_LENGTH GREATER 0)
set(_PROJECT_VERSION_HASH "${OPM_BINARY_PACKAGE_VERSION}")
else()
set(_PROJECT_VERSION_HASH "unknown git version")
endif()
file (WRITE "${PROJECT_BINARY_DIR}/project-version.h"
"#ifndef OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
"#define OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
"#define PROJECT_VERSION_NAME \"${${project}_LABEL}\"\n"
"#define PROJECT_VERSION_HASH \"${_PROJECT_VERSION_HASH}\"\n"
"#define PROJECT_VERSION \"${${project}_LABEL} (${_PROJECT_VERSION_HASH})\"\n"
"#endif // OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
)
# Write header file with build timestamp
file (WRITE "${PROJECT_BINARY_DIR}/project-timestamp.h"
if (NOT GIT_FOUND)
file (WRITE "${PROJECT_BINARY_DIR}/project-version.h"
"#ifndef OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
"#define OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
"#define PROJECT_VERSION_NAME \"${${project}_LABEL}\"\n"
"#define PROJECT_VERSION_HASH \"unknown git version\"\n"
"#define PROJECT_VERSION \"${${project}_LABEL} (unknown git version)\"\n"
"#endif // OPM_GENERATED_OPM_VERSION_HEADER_INCLUDED\n"
)
# Write header file with build timestamp
file (WRITE "${PROJECT_BINARY_DIR}/project-timestamp.h"
"#ifndef OPM_GENERATED_OPM_TIMESTAMP_HEADER_INCLUDED\n"
"#define OPM_GENERATED_OPM_TIMESTAMP_HEADER_INCLUDED\n")
if (_BINARY_PACKAGE_VERSION_LENGTH EQUAL 0)
file(APPEND "${PROJECT_BINARY_DIR}/project-timestamp.h"
"#define BUILD_TIMESTAMP \"${build_timestamp}\"\n")
endif()
file(APPEND "${PROJECT_BINARY_DIR}/project-timestamp.h"
"#endif // OPM_GENERATED_OPM_TIMESTAMP_HEADER_INCLUDED\n")
"#define OPM_GENERATED_OPM_TIMESTAMP_HEADER_INCLUDED\n"
"#define BUILD_TIMESTAMP \"${build_timestamp}\"\n"
"#endif // OPM_GENERATED_OPM_TIMESTAMP_HEADER_INCLUDED\n"
)
else ()
add_custom_target (update-version ALL
COMMAND ${CMAKE_COMMAND}

View File

@@ -58,7 +58,6 @@ if(NOT @opm-project_NAME@_FOUND)
string(REPLACE ${@opm-project_NAME@_PREFIX} ${DEST_PREFIX} @opm-project_NAME@_INCLUDE_DIRS "${@opm-project_NAME@_INCLUDE_DIRS}")
string(REPLACE ${@opm-project_NAME@_PREFIX} ${DEST_PREFIX} @opm-project_NAME@_LIBRARY_DIRS "${@opm-project_NAME@_LIBRARY_DIRS}")
string(REPLACE ${@opm-project_NAME@_PREFIX} ${DEST_PREFIX} @opm-project_NAME@_LIBRARY "${@opm-project_NAME@_LIBRARY}")
string(REPLACE ${@opm-project_NAME@_PREFIX} ${DEST_PREFIX} @opm-project_NAME@_PYTHON_COMMON_DIR "${@opm-project_NAME@_PYTHON_COMMON_DIR}")
endif()
@@ -108,18 +107,7 @@ if(NOT @opm-project_NAME@_FOUND)
# The settings in this block do not mix well with the DEST_PREFIX
# setting.
if (NOT DEST_PREFIX)
# if this file is not processed using the OPM CMake system but
# simply by a call to find_package(module) then the CMAKE_MODULE_PATH
# might not include the location of the OPM cmake module yet.
# Hence we search for opm-common using config mode to set it up.
# The check for opm-common_PREFIX is there to not do this in
# opm-common-config.cmake
if(NOT opm-common_PREFIX
AND NOT opm-common_FOUND)
# This needed to find the path to the CMake modules
find_package(opm-common CONFIG)
endif()
# This is required to include OpmPackage /opm-common-prereq.cmake
# This is required to include OpmPackage
set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" @PREREQ_LOCATION@)
# extra code from variable OPM_PROJECT_EXTRA_CODE

View File

@@ -9,6 +9,5 @@ Name: @name@
Description: @description@ @major@.@minor@
Version: @major@.@minor@
URL: http://opm-project.org
Libs.private: @libs@
Libs: @target@
Libs: @target@ @libs@
Cflags: @includes@ @defs@

View File

@@ -1,4 +1,4 @@
/* Userspecific CSS for doxygen */
/* Userspesific CSS for doxygen */
body, table, div, p, dl {
font-family: Lucida Grande, Verdana, Geneva, Arial, sans-serif;
font-size: 16px;

5
debian/changelog vendored Normal file
View File

@@ -0,0 +1,5 @@
opm-common (2021.10-rc2-1~focal) focal; urgency=medium
* New release
-- Arne Morten Kvarving <arne.morten.kvarving@sintef.no> Mon, 19 Oct 2015 10:49:00 +0200

1
debian/compat vendored Normal file
View File

@@ -0,0 +1 @@
9

64
debian/control vendored Normal file
View File

@@ -0,0 +1,64 @@
Source: opm-common
Priority: extra
Maintainer: Arne Morten Kvarving <arne.morten.kvarving@sintef.no>
Build-Depends: build-essential, debhelper (>= 9),
pkg-config, cmake, git, libtool, doxygen, graphviz,
texlive-latex-extra, texlive-latex-recommended,
ghostscript, libboost-system-dev, libboost-test-dev,
zlib1g-dev, libpython3-dev, python3-numpy, python3-distutils,
python3-setuptools, python3-setuptools-scm, python3-pytest-runner,
python3-decorator
Standards-Version: 3.9.2
Section: libs
Homepage: http://opm-project.org
Vcs-Git: git://github.com/OPM/opm-common.git
Vcs-Browser: https://github.com/OPM/opm-common
Package: libopm-common1
Section: libs
Pre-Depends: ${misc:Pre-Depends}
Architecture: any
Multi-Arch: same
Depends: ${shlibs:Depends}, ${misc:Depends}
Provides: libopm-common
Description: OPM common library
The OPM common library contains generic code shared across all OPM modules.
Package: libopm-common1-bin
Section: libs
Pre-Depends: ${misc:Pre-Depends}
Architecture: any
Multi-Arch: same
Depends: ${shlibs:Depends}, ${misc:Depends}
Provides: libopm-common-bin
Description: OPM common binaries
The OPM common binaries.
Package: libopm-common1-dev
Section: libdevel
Architecture: any
Multi-Arch: foreign
Provides: libopm-common-dev
Suggests: libopm-common1-doc
Depends: libopm-common1 (= ${binary:Version})
Description: OPM common library -- development files
The OPM common library contains the shared buildsystem
and helpers shared across all OPM modules.
Package: libopm-common1-doc
Section: doc
Architecture: all
Multi-Arch: foreign
Provides: libopm-common-doc
Description: OPM common library -- documentation
The OPM common library contains the shared buildsystem
and helpers shared across all OPM modules.
Package: python3-opm-common
Section: libs
Pre-Depends: ${misc:Pre-Depends}
Architecture: any
Multi-Arch: same
Depends: ${shlibs:Depends}, ${misc:Depends}, libopm-common1, python3-numpy, python3-decorator
Description: OPM common python bindings
Python package for opm-common

13
debian/copyright vendored Normal file
View File

@@ -0,0 +1,13 @@
License: GPL-3+
This package 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 package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>

2
debian/docs vendored Normal file
View File

@@ -0,0 +1,2 @@
LICENSE
README.md

1
debian/libopm-common1-bin.install vendored Normal file
View File

@@ -0,0 +1 @@
usr/bin/*

6
debian/libopm-common1-dev.install vendored Normal file
View File

@@ -0,0 +1,6 @@
usr/include/*
usr/lib/dunecontrol/*
usr/lib/*/pkgconfig/*
usr/share/cmake/*
usr/share/opm/*
usr/lib/*/lib*.so

1
debian/libopm-common1-doc.install vendored Normal file
View File

@@ -0,0 +1 @@
usr/share/doc/*

1
debian/libopm-common1.install vendored Normal file
View File

@@ -0,0 +1 @@
usr/lib/*/lib*.so.*

1
debian/python3-opm-common.install vendored Normal file
View File

@@ -0,0 +1 @@
usr/lib/python*/*

29
debian/rules vendored Executable file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/make -f
# -*- makefile -*-
# Sample debian/rules that uses debhelper.
# This file was originally written by Joey Hess and Craig Small.
# As a special exception, when this file is copied by dh-make into a
# dh-make output file, you may use that output file without restriction.
# This special exception was added by Craig Small in version 0.37 of dh-make.
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
%:
dh $@ --parallel
override_dh_auto_clean:
dh_auto_clean --buildsystem=cmake
override_dh_auto_build:
dh_auto_build --buildsystem=cmake
# consider using -DUSE_VERSIONED_DIR=ON if backporting
override_dh_auto_configure:
dh_auto_configure --buildsystem=cmake -- -DCMAKE_BUILD_TYPE=RelWithDebInfo -DSTRIP_DEBUGGING_SYMBOLS=ON -DBUILD_SHARED_LIBS=1 -DCMAKE_INSTALL_DOCDIR=share/doc/libopm-common1 -DWHOLE_PROG_OPTIM=ON -DUSE_RUNPATH=OFF -DWITH_NATIVE=OFF -DOPM_ENABLE_PYTHON=1 -DOPM_INSTALL_PYTHON=1 -DPYTHON_EXECUTABLE=/usr/bin/python3 -DOPM_ENABLE_EMBEDDED_PYTHON=1
override_dh_auto_install:
dh_auto_install -- install-html
override_dh_installdocs:
dh_installdocs --link-doc=libopm-common1

1
debian/source/format vendored Normal file
View File

@@ -0,0 +1 @@
1.0

View File

@@ -297,7 +297,7 @@ composite units based on the dimension of the composite quantity. As a
consequence the list of dimensions supported by the parser is long,
and growing. The current list can be found in the source file:
opm/input/eclipse/Units/UnitSystem.cpp
opm/parser/eclipse/Units/UnitSystem.cpp

View File

@@ -1,11 +0,0 @@
.TH SUMMARY "1" "October 2022" "arraylist 2022.10" "User Commands"
.SH NAME
summary \- Printer for list of arrays in Eclipse summary files
.SH DESCRIPTION
List all arrays found in an EclFile specified on the command line.
.PP
.SH OPTIONS
\fB\-h\fR Print help and exit.
.TP
\fB\-r\fR List array for a specific report time step number. Option only valid for a unified restart file.
.PP

View File

@@ -1,29 +0,0 @@
.TH CO2BRINEPVT "1" "April 2022" "co2brinepvt" "User Commands"
.SH NAME
co2brinepvt \- compute and print pvt properties for co2 with brine
.SH DESCRIPTION
co2brinepvt computes PVT properties of a brine/co2 system
for a given phase (oil or brine), pressure, temperature, salinity and rs.
The properties support are: density, the inverse phase formation volume factor (invB), viscosity,
saturated dissolution factor (rsSat)
See CO2STORE in the OPM manual for more details.
.PP
.SH Synopsis
co2brinepvt <prop> <phase> <p> <T> <salinity> <rs>
.br
where
.br
prop = {density, invB, B, viscosity, rsSat, diffusionCoefficient}
.br
phase = {CO2, brine}
.br
p: pressure in pascal
.br
T: temperature in kelvin
.br
salinity(optional): salt molality in mol/kg
.nr
rs(optional): amount of dissolved CO2 in Brine in SM3/SM3
.PP
.SH OPTIONS
\fB\-\-h\fR/\-\-help Print help and exit.

View File

@@ -1,4 +1,5 @@
.TH COMPAREECL "1" "October 2022" "compareECL 2022.10" "User Commands"
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.8.
.TH COMPAREECL "1" "April 2021" "compareECL 2020.04" "User Commands"
.SH NAME
compareECL \- Comparator for Eclipse files
.SH DESCRIPTION
@@ -10,57 +11,55 @@ The program takes four arguments:
3. Absolute tolerance
4. Relative tolerance (between 0 and 1)
.PP
.SH OPTIONS
.HP
In addition, the program takes these options (which must be given before the arguments):
.PP
\fB\-a\fR Run a full analysis of errors.
.TP
\fB\-h\fR Print help and exit.
.TP
\fB\-d\fR Use report steps only when comparing results from summary files.
.TP
\fB\-i\fR Execute integration test (regression test is default).
.IP
The integration test compares SGAS, SWAT and PRESSURE in unified restart files, and WOPR, WGPR, WWPR and WBHP (all wells) in summary file.
.PP
\fB\-k\fR Specify specific keyword to compare (capitalized), for examples \fB\-k\fR PRESSURE or \fB\-k\fR WOPR:A\-1H
.TP
\fB\-l\fR Only do comparison for the last Report Step. This option is only valid for restart files.
.TP
\fB\-n\fR Do not throw on errors.
.TP
\fB\-p\fR Print keywords in both cases and exit.
.TP
\fB\-r\fR compare a specific report time step number in a restart file.
.TP
\fB\-r\fR compare a spesific report time step number in a restart file.
\fB\-t\fR Specify ECLIPSE filetype to compare, (default behaviour is that all files are compared if found). Different possible arguments are:
.IP
.TP
\fB\-t\fR UNRST
Compare two unified restart files (.UNRST). This the default value, so it is the same as not passing option \fB\-t\fR.
.IP
.TP
\fB\-t\fR EGRID
Compare two EGrid files (.EGRID).
.IP
.TP
\fB\-t\fR INIT
Compare two initial files (.INIT).
.IP
.TP
\fB\-t\fR RFT
Compare two RFT files (.RFT).
.IP
.TP
\fB\-t\fR SMRY
Compare two cases consistent of (unified) summary files.
.IP
\fB\-t\fR RSM
Compare RSM file against a summary file.
.PP
\fB\-x\fR Allow extra keywords in case number 2. These additional keywords (not found in case number1) will be ignored in the comparison.
.PP
.SH Example usage of the program:
Example usage of the program:
.PP
compareECL \fB\-k\fR PRESSURE <path to first casefile> <path to second casefile> 1e\-3 1e\-5
compareECL \fB\-t\fR INIT \fB\-k\fR PORO <path to first casefile> <path to second casefile> 1e\-3 1e\-5
compareECL \fB\-i\fR <path to first casefile> <path to second casefile> 0.01 1e\-6
.PP
Exceptions are thrown (and hence program exits) when deviations are larger than the specified tolerances, or when the number of cells does not match \fB\-\-\fR either in the grid file or for a specific keyword. Information about the keyword, keyword occurrence (zero based) and cell coordinate is printed when an exception is thrown. For more information about how the cases are compared, see the documentation of the EclFilesComparator class.
.SH "SEE ALSO"
The full documentation for
.B compareECL
is maintained as a Texinfo manual. If the
.B info
and
.B compareECL
programs are properly installed at your site, the command
.IP
.B info compareECL
.PP
should give you access to the complete manual.

View File

@@ -1,4 +1,5 @@
.TH CONVERTECL "1" "October 2022" "convertECL 2022.10" "User Commands"
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.8.
.TH CONVERTECL "1" "April 2021" "convertECL 2020.04" "User Commands"
.SH NAME
convertECL \- Converter for Eclipse files (binary <-> formatted format)
.SH DESCRIPTION
@@ -6,13 +7,18 @@ convertECL needs one argument which is the input file to be converted. If this i
.PP
In addition, the program takes these options (which must be given before the arguments):
.PP
.SH OPTIONS
.HP
\fB\-h\fR Print help and exit.
.TP
\fB\-l\fR list report step numbers in the selected restart file.
.TP
\fB\-i\fR Enforce IX standard on output file.
.TP
\fB\-r\fR extract and convert a specific report time step number from a unified restart file.
\fB\-r\fR extract and convert a spesific report time step number from a unified restart file.
.SH "SEE ALSO"
The full documentation for
.B convertECL
is maintained as a Texinfo manual. If the
.B info
and
.B convertECL
programs are properly installed at your site, the command
.IP
.B info convertECL
.PP
should give you access to the complete manual.

View File

@@ -1,4 +1,5 @@
.TH OPMHASH "1" "October 2022" "opmhash 2022.10" "User Commands"
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.8.
.TH OPMHASH "1" "April 2021" "opmhash 2020.04" "User Commands"
.SH NAME
opmhash \- Hasher for summary keywords in Eclipse files
.SH DESCRIPTION
@@ -39,11 +40,15 @@ depends on the keyword order.
\fB\-l\fR : Add filename and linenumber information to each keyword.
.HP
\fB\-s\fR : Short form \- only print the hash of the complete deck.
.HP
\fB\-S\fR : Silent form \- will not print any deck output.
.SH "SEE ALSO"
The full documentation for
.B opmhash
is maintained as a Texinfo manual. If the
.B info
and
.B opmhash
programs are properly installed at your site, the command
.IP
.B info opmhash
.PP
It is possible to add multiple deck arguments, they are then scanned repeatedly,
and the decks are compared. In the case of multiple deck arguments the exit
status of the program will be zero if all are equal and nonzero in case of
differences.
should give you access to the complete manual.

View File

@@ -1,7 +1,10 @@
.TH OPMPACK "1" "October 2022" "opmpack 2022.10" "User Commands"
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.8.
.TH OPMPACK "1" "April 2021" "opmpack 2020.04" "User Commands"
.SH NAME
opmpack \- Validator and printer of deck in Eclipse files without comments
.SH DESCRIPTION
opmpack: invalid option \fB\-\-\fR 'h'
.PP
The opmpack program will load a deck, resolve all include
files and then print it out again on stdout. All comments
will be stripped and the value types will be validated.
@@ -25,4 +28,15 @@ opmpack \fB\-o\fR NEW_CASE.DATA path/to/MY_CASE.DATA
As an alternative to the \fB\-o\fR option you can use \fB\-c\fR; that is equivalent to \fB\-o\fR \-
but restart and import files referred to in the deck are also copied. The \fB\-o\fR and
\fB\-c\fR options are mutually exclusive.
.SH "SEE ALSO"
The full documentation for
.B opmpack
is maintained as a Texinfo manual. If the
.B info
and
.B opmpack
programs are properly installed at your site, the command
.IP
.B info opmpack
.PP
should give you access to the complete manual.

View File

@@ -1,88 +1,7 @@
.TH RST_DECK: "1" "October 2022" "rst_deck 2022.10" "User Commands"
.TH RST_DECK
.SH NAME
rst_deck \- Convert simulation deck to a deck ready for restart
.SH DESCRIPTION
The rst_deck program will load a simulation deck and parameters for a restart
and reformat the deck to become a restart deck. Before the updated deck is
output the program will update the SOLUTION and SCHEDULE sections. All keywords
from the SOLUTION section will be cleared out(1) and a RESTART keyword will be
inserted. In the SCHEDULE section the program can either remove all keywords up
until the restart date, or alternatively insert SKIPREST immediately following
the SCHEDULE keyword.
.PP
When creating the updated restart deck the program can either link to unmodified
include files with INCLUDE statements, create a copy of deck structure in an
alternative location or create one large file with all keywords in the same
file. Apart from the alterations to support restart the output deck will be
equivalent to the input deck, but formatting is not retained and comments have
been stripped away.
.PP
Arguments:
.PP
1. The data file we are starting with.
.PP
2. The restart source; this can either be a basename with an optional path
.IP
prefix and a :N to restart from step N; alternatively you can point to an
existing restart file. If you point to an existing restart file the input
will be validated in several ways:
.IP
a) Unified/multiple files will be checked against the UNIFIN setting of
.IP
the deck.
.IP
b) Formatted/unformatted will be checked against the FMTIn setting of the
.IP
deck.
.IP
c) If a single file like \fI\,/path/to/case/HISTORY.X0067\/\fP is given as argument the
.IP
:N notation to denote report step should not be used.
.IP
If the restart argument is given as the path to an existing file the content
of the RESTART keyword will be updated to contain the correct path from the
location of the restart deck to the location of the restart file. This path
awareness will be fooled if the restart deck is redirected from stdout to a
path different from cwd. If the restart argument is given as an absolute
filename the RESTART keyword will have an absolute path, if the restart
argument is a relative path the RESTART keyword will get a relative path \-
although an absolute path will be used if the restart file and the output
deck have different roots. If the restart argument is given as a string not
pointing to an existing file it will be inserted verbatim in the restart
deck.
.IP
A restart step value of 0 is interpreted as a dry run \- a deck which has not
been set up for restart will be written out.
.PP
3. Basename of the restart deck we create, can optionally contain a path prefix;
.IP
the path will be created if it does not already exist. This argument is
optional, if it is not provided the program will dump a restart deck on
stdout. If the argument corresponds to an existing directory the restart case
will get the same name as the base case.
.SH OPTIONS
\fB\-s\fR: Manipulate the SCHEDULE section by inserting a SKIPREST keyword immediately
.IP
following the SCHEDULE keyword. If the \fB\-s\fR option is not used the SCHEDULE
section will be modified by removing all keywords until we reach the restart
date.
.PP
\fB\-m\fR: [share|inline|copy] The restart deck can reuse the unmodified include files
.IP
from the base case, this is mode 'share' and is the default. With mode
\&'inline' the restart deck will be one long file and with mode 'copy' the
file structure of the base case will be retained. The default if no \fB\-m\fR
option is given is the 'share' mode.
.IP
In the case of 'share' and 'copy' the correct path to include files will be
negotiated based on the path given to the output case in the third argument.
If the restart deck is passed to stdout the include files will be resolved
based on output in cwd.
.PP
Example:
.IP
rst_deck \fI\,/path/to/history/HISTORY.DATA\/\fP rst/HISTORY:30 \fI\,/path/to/rst/RESTART\/\fP \fB\-s\fR
.PP
1: The program has a compiled list of keywords which will be retained in the
.IP
SOLUTION section. The current value of that list is: RPTRST
rst_deck \- Create a version of deck ready for restart

View File

@@ -1,4 +1,5 @@
.TH SUMMARY "1" "October 2022" "summary 2022.10" "User Commands"
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.8.
.TH SUMMARY "1" "April 2021" "summary 2020.04" "User Commands"
.SH NAME
summary \- Printer for summary keys in Eclipse summary files
.SH DESCRIPTION
@@ -6,10 +7,18 @@ summary needs a minimum of two arguments. First is smspec filename and then list
.PP
In addition, the program takes these options (which must be given before the arguments):
.PP
.SH OPTIONS
\fB\-h\fR Print help and exit.
.TP
\fB\-l\fR list all summary vectors.
.TP
\fB\-r\fR extract data only for report steps.
.SH "SEE ALSO"
The full documentation for
.B summary
is maintained as a Texinfo manual. If the
.B info
and
.B summary
programs are properly installed at your site, the command
.IP
.B info summary
.PP
should give you access to the complete manual.

View File

@@ -1,27 +0,0 @@
\documentclass[a4paper,11pt]{book}
\usepackage{verbatim}
\newcommand{\kw}[1]{\texttt{#1}}
\newcommand{\inlinecode}[1]{\texttt{#1}}
\newcommand{\flow}[0]{\texttt{flow}}
\newcommand{\eclipse}[0]{\texttt{Eclipse}}
\newcommand{\path}[1]{\texttt{#1}}
\newenvironment{deck}[0]{\verbatim}{\endverbatim}
\newenvironment{code}[0]{\verbatim}{\endverbatim}
\begin{document}
\begin{titlepage}
\begin{center}
\Huge
\textbf{Technical manual}
\end{center}
\end{titlepage}
\tableofcontents
\input{udq_actionx/udq}
\input{udq_actionx/actionx}
\input{udq_actionx/pyaction}
\end{document}

View File

@@ -1,437 +0,0 @@
\newcommand{\actionx}{\kw{ACTIONX}}
\chapter{Programming in the deck: \actionx}
\label{actionx}
The \actionx{} keyword is the most direct way to \emph{program} in the deck. The
\actionx{} functionality consist of the \actionx{} keyword itself, with some
metadata and a condition and then a list of keywords which are injected into the
in-memory representation of the \kw{SCHEDULE} section at the point in time where
the condition evaluates to true. The \actionx{} statement is evaluated at the
end of every timestep, and if it evaluates to true the new keywords should take
effect immediately. The \actionx{} conditions are less sophisticated than the
expressions used in \udq{}, this implies that a common pattern is to make
involved calculations as \udq{} expressions, and then use a simple test as
\actionx{} condition.
The \actionx{} keyword is also documented in section 12.3.6 in the \flow{}
reference manual.
\section{Structure of the \actionx{} keyword}
\label{actionx_structure}
The \actionx{} keyword itself consist of multiple records. The first record is
metadata with name of the action, the number of times the action can be
triggered and the minimum time elapsed before an action is eligible for a second
run. The subsequent records are \emph{conditions}, all the conditions are of the
same form
\begin{code}
lhs comparison rhs
\end{code}
and subsequent conditions are combined with \inlinecode{AND} or \inlinecode{OR}.
The \inlinecode{lhs} is a field, well or group quantity, in addition you can use
time variables \kw{DAY}, \kw{MNTH} and \kw{YEAR} as left hand
side\footnote{\eclipse{} supports a wider list of summary variables like region,
block and aquifer quantities on both left and right hand side.}. As with the
\udq{} variables the well and group variables are \emph{sets}, and the
evaluation status is maintained individually for each well and group.
The comparison is one of the ordinary mathematical comparison operators
\inlinecode{>,<,=,!=, <=} and \inlinecode{>=}. Numerical comparisons are done
with the corresponding plain C++ operators, this is in contrast to the \udq{}
implementation where an epsilon defined in \kw{UDQPARAMS} is used in floating
point comparisons.
The \inlinecode{rhs} is a numerical scalar, or a field, well or group quantity.
If your \inlinecode{rhs} is a well or group quantity the \inlinecode{lhs} and
\inlinecode{rhs} must be of the same type. If you use the symbol \kw{MNTH} as
\inlinecode{lhs} you can compare with named months, i.e. the following will
trigger on leap days
\begin{deck}
ACTIONX
LEAP 1000 /
MNTH=FEB AND /
DAY=29 /
/
...
...
ENDACTIO
\end{deck}
When there is a well/group quantity as \inlinecode{lhs} the evaluation status is
maintained individually for each well/group. The complete condition evaluates to
true if \emph{any} of the wells/groups satisfy the condition. In the case of
wells the wells matching the condition can subsequently be accessed with
wellname '?' in the \kw{ACTIONX} keywords, this is a quite common pattern to
e.g. close the well with highest watercut.
If there are more conditions they must be joined with a trailing \kw{AND} or
\kw{OR}, furthermore conditions can be grouped with paranthesis. The \actionx{}
expressions can only contain the four arithmetic operators $+,-,*,/$ and not
mathematical functions like $\log()$, for more advanced expressions the natural
approach is to first define a \udq{} and then use the \udq{} symbol in the
\actionx{}, this is illustrated in section \ref{uda}. When multiple conditions
involving the same well set are evaluated, the list of matching wells available
in '?' will contain all the wells from the final condition, i.e. for
\begin{code}
WWCT = {"OP1": 0.25, "OP2": 0.50, "OP3": 0.75}
\end{code}
and the action
\begin{deck}
ACTIONX
WWCT /
WWCT > 0.33 AND /
WWCT < 0.66 /
/
...
ENDACTIO
\end{deck}
the set of wells available for further use in '?' are \emph{all} the wells
matching the condition \inlinecode{WWCT < 0.66} i.e. OP1 and OP2 and \emph{not}
the wells matching the combined expression \inlinecode{0.33 < WWCT < 0.66}. In
order to select wells in a range as attempted here you will have to create an
indicator variable with \udq{} first and then select based on that indicator -
e.g. something like
\begin{deck}
UDQ
DEFINE WUCTR (WWCT < 0.66) * (WWCT > 0.33) /
/
ACTIONX
WUCTR /
WUCTR = 1 /
/
...
ENDACTIO
\end{deck}
The \actionx{} implementation is located in
\path{opm/input/eclipse/Schedule/Action} and all the classes are in namespace
\inlinecode{Action::}. As with the \udq{} the input parser needs some special
case to handle '/' and '*' as division operator and multiplier respectively, but
that is the only code shared between the \udq{} and the \actionx{}
implementation\footnote{It might be possible to share more code between the two,
in particular both have an internal recursive descent parser, but both \udq{}
and \actionx{} have so much ``personality'' that at least initially separate
implementations was the simplest.}.
The condition part of the \actionx{} keyword is internalized while the
\kw{SCHEDULE} section is parsed, the final product is maintained in a class
\inlinecode{Action::ActionX} which has a \inlinecode{eval()} method waiting to
be called. The keywords in the \actionx{} block are stored in the
\inlinecode{Action::ActionX} keyword for future use. All of the \actionx{}
keywords are stored in a container \inlinecode{Action::Actions} which will
eventually manage the book keeping of which actions are eligible for evaluation.
\section{The structure of the \inlinecode{Schedule} implementation}
\label{schedule_design}
\flow{} internalizes all keywords from the input deck and passes fully baked
datastructures to the simulator, whereas our impression is that \eclipse{} works
more like a reservoir model interepreter, executing one keywords at a time.
Mostly the \flow{} approach has worked out well, however for the \actionx{}
functionality the difference in execution model is quite acute, and the nature
of the \actionx{} keyword has had quite strong influence on the final Schedule
implementation. Although not required for use of \actionx{} it is valuable to
understand how the \actionx{} functionality has influenced the design of the
Schedule class, that way you will hopefully better understand problems or bugs
which might arise in the future.
At the very first pass the \kw{SCHEDULE} section is split in \emph{blocks}, with
one block for each report step. The blocks are implemented with the class
\inlinecode{ScheduleBlock}. Each block has a starting time and a list of
keywords, the keywords are maintained in the input format
\inlinecode{DeckKeyword}. Then the entire \kw{SCHEDULE} section is internalized
in the class \inlinecode{ScheduleDeck} which essentially contains a list of
\inlinecode{ScheduleBlock} instances. Consider the \kw{SCHEDULE} section
\begin{deck}
START
1 'JAN' 2020 /
...
...
SCHEDULE
WELSPECS
'PROD' 'G1' 10 10 8400 'OIL' /
'INJ' 'G1' 1 1 8335 'GAS' /
/
COMPDAT
'PROD' 10 10 3 3 'OPEN' 1* 1* 0.5 /
'INJ' 1 1 1 1 'OPEN' 1* 1* 0.5 /
/
-- End of block 0
DATES
1 'FEB' 2020 /
/
WCONPROD
'PROD' 'OPEN' 'ORAT' 20000 4* 1000 /
/
WCONINJE
'INJ' 'GAS' 'OPEN' 'RATE' 100000 1* 9014 /
/
-- End of block 1
DATES
1 'MAR' 2020 /
/
-- End of block 2
END
\end{deck}
When this is internalized we get a \inlinecode{ScheduleDeck} instance with three
\inlinecode{ScheduleBlock} values:
\begin{code}
ScheduleDeck sched_deck = [
ScheduleBlock {
start = "2020-01-01",
keywords = ["WELSPECS","COMPDAT"]
},
ScheduleBlock {
start = "2020-02-01",
keywords = ["WCONPROD","WCONINJE"]
},
ScheduleBlock {
start = "2020-03-01",
keywords = []
}
]
\end{code}
The \inlinecode{Schedule} class has a \inlinecode{ScheduleDeck} member. The
processed content of the \inlinecode{Schedule} class is managed in vector of
\inlinecode{ScheduleState} instances, where one \inlinecode{ScheduleState}
represents the complete dynamic input state at a particular report step. The
processed \kw{SCHEDULE} code is created with the method
\begin{code}
Schedule::iterateScheduleSection().
\end{code}
When \inlinecode{Schedule::iterateScheduleSection(report\_step)} is called it
starts by clearing the vector of \inlinecode{ScheduleState} instances from
\inlinecode{report\_step} to the end of the simulation, and then recreates those
by treating the \inlinecode{ScheduleBlock}. The advantage of this approach is
that the \inlinecode{Schedule::iterateScheduleSection(report\_step)} method is
idempotent - it can be called repeatedly, from an arbitrary point in the
timeseries.
The implementation of the \actionx{} functionality is just to append the
\actionx{} keywords in the \inlinecode{ScheduleBlock} instance corresponding to
the current report step and then rerun the
\inlinecode{Schedule::iterateScheduleSection()} from this report step.
\section{Forward references of wells and groups}
When a well or group is defined as an \actionx{} keyword and then
unconditionally referenced in the deck we get a challenge at the first pass
through the \kw{SCHEDULE} section. In the example below a new well \kw{W1} is
defined with the \kw{WELSPECS} keyword when the action \inlinecode{NEW\_WELL}
evaluates to true. At 1.st of January 2025 the well \kw{W1} is opened with the
\kw{WCONPROD} keyword. The engineer making this model assumes that the
\inlinecode{NEW\_WELL} action will evaluate to true sometime before 1.st of
January 2025, and thereby ensure that the well is fully defined when it is
eventually opened with \kw{WCONPROD}:
\begin{deck}
ACTIONX
'NEW_WELL/
WWCT OPX > 0.75 /
/
WELSPECS
'W1' 'OP' 1 1 3.33 'OIL' 7*/
/
ENDACTIO
TSTEP
10*30 /
DATES
1 'JAN' 2025 /
/
WCONPROD
'W1' 'OPEN' 'ORAT' 0.000 0.000 0.000 5* /
/
TSTEP
10*30 /
\end{deck}
For \flow{} this creates problems because the entire \kw{SCHEDULE} section is
parsed when the simulator starts, and at first pass the well \kw{W1} is unknown
in the \kw{WCONPROD} keyword. This is ``solved'' in the following way:
\begin{enumerate}
\item At first pass we inspect the keywords inside the \actionx{} block and if
we discover \kw{WELSPECS} we store the name of the well which will be defined
at a later stage through \actionx{}.
\item When we parse further on as part of the first pass and said well is
referenced e.g. in a \kw{WCONPROD} keyword, we verify that the well will
eventually appear via \actionx{} - we issue a warning and ignore the well in
the \kw{WCONPROD} keyword\footnote{If the well is not registered as ``will
appear through \actionx{}'' there will be a runtime error with unknown well
name when parsing \kw{WCONPROD}.}.
\item When the \actionx{} evaluates to true the well will be properly defined,
and when reiterating over the Schedule keywords the \kw{WCONPROD} keyword will
now be properly internalized. If the \actionx{} never evaluates to true the
\kw{WCONPROD} keyword will never be applied, and the warning from point 2 will
be the only trace of this well.
\end{enumerate}
It should be mentioned that the functionality with forward referencing of well
names is quite new\footnote{In January 2022}, there might be well keywords in
the \kw{SCHEDULE} section where the implementation is not yet prepared for this.
Furthermore the forward referencing is not at all implemented for groups. The
relevant data structure is the member \inlinecode{Action::WGNames
action\_wgnames} in the \inlinecode{Schedule} class.
\section{To enable a new keyword for \actionx}
The keywords must be explicitly enabled to be available in an \actionx{} block,
and enabling a new keyword requires recompiling \flow{}. The keywords available
as \actionx{} keywords are listed in the static method
\inlinecode{ActionX::valid\_keyword()} in
\path{opm/input/eclipse/Schedule/Action/ActionX.cpp}. In principle it should
just be to add the keyword to the \inlinecode{ActionX::valid\_keyword()} method
and rebuild \flow{}, but experience has unfortunately shown that problems of
various kinds have had a tendency to pop up when new keywords are tried out as
\actionx{} keywords. Most commonly the problems have been in the interaction
between the \inlinecode{Schedule} class in opm-common and the simulator - things
have a tendency to go out of sync.
\section{Running \actionx{} during simulation}
The first part of the \actionx{} treatment is parsing the keyword and conditions
and assemble a syntax tree which can be used to evaluate the conditions. This
parsing takes place when the \kw{SCHEDULE} section is parsed for the first time.
This takes place fully within the realms of the opm-common codebase, and is
quite mature.
When the simulation actually runs the \actionx{} behavior consists of three
distinct parts, taking place in the simulator, in opm-common and again in the
simulator. The simulator will manage an instance of \inlinecode{Action::State}
which will hold on to the time of last run and the latest results for the
various actions.
\subsection{Prepare and evaluate}
As with \udq{} the \inlinecode{SummaryState} instance is the most important
variable to provide context to the \actionx{} evaluation, i.e. the
\inlinecode{SummaryState} variable must be evaluated before \actionx{}. In
addition the \udq{} variables must be evaluated and available in the
\inlinecode{SummaryState} instance before we invoke the \actionx{}
functionality.
The evaluation of actions is called from the method \inlinecode{applyActions()}
in \path{eclproblem.hh}. The method will evaluate which actions are eligible for
running by inspecting the \inlinecode{Action::Actions} variable and call the
\inlinecode{ActionX::eval()} method.
\subsection{Recreate \inlinecode{Schedule}}
When an \actionx{} has evaluated to \inlinecode{true} the simulator will call
into the opm-common method \inlinecode{Schedule::applyAction(report\_step)}.
That function will add the keywords from the \actionx{} keyword to the
\inlinecode{ScheduleBlock} for the correct report step, and then reiterate
through the \kw{SCHEDULE} section to the end of the simulation.
This reiterate process will recreate all internal members in the
\inlinecode{Schedule} class, i.e. if the simulator was holding on to a reference
to an internal \inlinecode{Schedule} datastructure that will be invalidated.
While recreating the \inlinecode{Schedule} instance there is some book keeping
as to which datastructures need to be recalculated in the simulator as a
consequence of the \actionx{}. That information is maintained in the data
structure \inlinecode{Action::SimulatorUpdate} which is returned back to the
simulator.
\subsection{Updating simulator data structures}
The \actionx{} implementation is in the module opm-common, whereas when the
simulation is proceeding it is the simulator code which is clearly in control.
If an action has evaluated to true and new keywords are injected in the Schedule
object the complete simulator state is updated. This is complex, and many of the
bugs in \actionx{} functionality have been in the interaction between the
simulator and opm-common, in particular when an action has evaluated to true.
An assumption permeating the simulator code is that changes to the well and
group configuration only take place at report steps, and in between those the
simulator ``owns'' the well and group data. Unfortunately this is no longer the
case when \actionx{} is active, and depending on the keywords in the \actionx{}
block we need to update the simulator data structures after \actionx{} has been
evaluated to true. Some details of what is currently updated is decsribed below.
This update mechanism will probably need to be continously updated in the
future.
The simulator code makes \emph{copies} of many of the objects like wells and
connections from the \inlinecode{Schedule} class, and also assembles many
simulator specific data structures which to a large extent consist of extracts
of information from the internals of the \inlinecode{Schedule} object. Some of
the interaction between the simulator and the input layer could probably be
simplified if the simulator would call the \inlinecode{Schedule} object when
e.g. a well or connection is needed, instead of storing references or copies to
the \inlinecode{Schedule} objects internally.
There are currently three categories of changes that can take place due to
\actionx{}:
\subsubsection{General changes in well status}
\label{actionx_change_well}
When there is well related keyword in the \actionx{} block - e.g. \kw{WELOPEN}
to open or close a well or \kw{WCONPROD} to adjust rates, the simulator is
required update it's internal data structures with the updated input information.
This will be communicated by flagging all the wells which need an update in the
\inlinecode{Action::SimulatorUpdate} instance which is passed from the
simulator.
\subsubsection{Changes in geo properties}
The grid keywords are in general not permitted in the \kw{SCHEDULE} section,
however there are a few geo multipliers like \kw{MULTZ} and \kw{MULTFLT} which
are allowed in the \kw{SCHEDULE} section, and thereby also in \actionx{}. If one
of these keywords are encountered in the \actionx{} block we set the flag
\inlinecode{Action::SimulatorUpdate::tran\_update = true} to encourage the
simulator to recalculate the transmissibilities.
\subsubsection{WELPI}
\label{actionx_welpi}
The \kw{WELPI} keyword is quite complex from the outset, when it is included as
an \actionx{} keyword it gets even more complicated. In order to support
\kw{WELPI} in \actionx{} the simulator needs to inspect the \actionx{} keywords
before invoking them, and if \kw{WELPI} is included the PI values must be
assembled from the simulator and passed to the
\inlinecode{Schedule::applyAction()}. This is implemented and works, but it is
complex and the special treatment in order to support the combination \kw{WELPI}
+ \actionx{} is quite considerable.
\section{Problems in parallel}
\label{actionx_paralle}
The operation environment for \actionx{} is quite similar to \udq{} when it
comes to parallel behavior - see section \ref{udq_parallel}, in addition we
need to be aware of parallel challenges after the \actionx{} has completed. If
the \actionx{} keyword changes the well structure there will be problems with
with the parallel well distribution in the simulator. \emph{As of Januarry 2022
this will fail undetected.}
\section{\actionx{} restart output}
As with the \udq{} keyword some of the structure and complexity of the
\actionx{} datastructures are there primarily to enable \eclipse{} compatible
restart. Regarding restart of \actionx{} related data:
\begin{enumerate}
\item The restart output contains the result of parsing an \actionx{}
condition in an intermediate representation which has been reverse
engineered, this is complex and might not be 100\% correct.
\item When restarting \flow{} from an \eclipse{} formatted restart file the
\actionx{} conditions are reparsed based on string data in the restart file
and the intermediate representation mentioned in point 1 is not utilised.
\end{enumerate}

View File

@@ -1,405 +0,0 @@
\newcommand{\pyaction}{\kw{PYACTION}}
\chapter{Programming in the deck: \pyaction{}}
\label{pyaction}
The \pyaction{} keyword is a \flow{} specific keyword which allows for Python
programming in the \kw{SCHEDULE} section. The \pyaction{} keyword is inspired by
the \actionx{} keyword, but instead of a \inlinecode{.DATA} formatted condition
you are allowed to implement the condition with a general Python script. The
\actionx{} keywords are very clearly separated in a condition part and an action
part in the form of a list of keywords which are effectively injected in the
\kw{SCHEDULE} section when the condition evaluates to true. This is not so for
\pyaction{} where there is only one Python script which can both evaluate
conditions and apply changes. In principle the script can run arbitrary code,
but due to the complexity of the \kw{SCHEDULE} datamodel the ``current best''
way to actually change the course of the simulation is through the use of an
additional dummy \actionx{} keyword.
In order to enable the \pyaction{} keyword \flow{} must be compiled with the
\path{cmake} switches \inlinecode{-DOPM\_ENABLE\_EMBEDDED\_PYTHON=ON} and
\inlinecode{-DOPM\_ENABLE\_PYTHON=ON}, the default is to build with these switches
set to \inlinecode{OFF}. Before you enable \pyaction{} in your \flow{}
installation please read carefully through section \ref{pyaction_security} for
security implications of \pyaction{}.
\section{Python - wrapping and embedding}
Python is present in the \flow{} codebase in two different ways. For many of
the classes in the \flow{} codebase - in particular in opm-common, there are
\emph{Python wrappers} available. That means that you can invoke the C++
functionality in \flow{} classes from Python - e.g. this Python script can be used to
load a deck and print all the keywords:
\begin{code}
import sys
from opm.io.parser import Parser
input_file = sys.argv[1]
parser = Parser()
deck = parser.parse_file(input_file)
for kw in deck:
print(kw.name)
\end{code}
When used this way the Python interpreter is the main program running, and the
\flow{} classes like \inlinecode{Opm::Parser} are loaded to extend the Python
interpreter. This can also be flipped around, the Python interpreter can be
\emph{embedded} in the \flow{} executable. When Python is embedded, \flow{} is
the main program running, and with help of the embedded interpreter the \flow{}
program can be extended with Python plugins. The \pyaction{} keyword can be
perceived as a Python plugin. To really interact with the state of the \flow{}
simulation the plugin needs to utilize the functionality which wraps the C++
functionality, so for \pyaction{} both wrapping and embedding is at play.
Exporting more functionality from C++ to Python in the form of new and updated
wrappers is a quite simple and mechanical process. If you need a particular
functionality which is already available in C++ also in Python it will probably
be a quite limited effort for a developer who is already familiar with the code.
\section{The \pyaction{} keyword}
The \pyaction{} keyword is in the \kw{SCHEDULE} section like \actionx{}. The
first record is the name of the action and a string identifier for how many
times the action should run, then there is a path to a Python module:
\begin{deck}
PYACTION
PYTEST 'FIRST_TRUE' /
'pytest.py' /
\end{deck}
This keyword defines a \pyaction{} called \kw{PYTEST} which will run at the end
of every timestep until the first time a \inlinecode{true} value is returned. In
addition to \kw{FIRST\_TRUE} you can choose \kw{SINGLE} to run exactly once and
\kw{UNLIMITED} to continue running at the end of every timestep for the entire
simulation. The second record is the path to a file with Python code which will
run when this \pyaction{} is invoked. The path to the module will be interpreted
relative to the location of the \path{.DATA} file.
The python module can be quite arbitrary, but it must contain a function
\inlinecode{run} with the correct signature:
\begin{code}
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
print('Running python code in PYACTION')
return True
\end{code}
The \pyaction{} machinery is not as robust as the simulator proper: while
loading the \kw{PYACTION} keyword \flow{} will check that the Python module
contains syntactically valid Python code, and that it contains a
\inlinecode{run()} function, but it will \emph{not} check the signature of the
\inlinecode{run()} function. If the signature is wrong you will get a hard to
diagnose runtime error.
When the Python module is loaded it does so in an environment where the path to
the \path{.DATA} file has been appended to the Python load path by manipulating
the internal \inlinecode{sys.path} variable.
\subsection{The different arguments}
The \inlinecode{run()} function will be called with exactly five arguments which
your implementation can use. These arguments point to datastructures in the
simulator, and is the way to interact with the state of the simulation. The five
arguments are:
\begin{description}
\item[\inlinecode{ecl\_state}:] An instance of the \inlinecode{Opm::EclipseState}
class - this is a representation of \emph{all static properties} in the model,
ranging from porosity to relperm tables. The content of the
\inlinecode{ecl\_state} is immutable - you are not allowed to change the static
properties at runtime\footnote{This could certainly be interesting, but this
is beyond the scope of the \pyaction{} keyword.}.
\item[\inlinecode{schedule}:] An instance of the \inlinecode{Opm::Schedule}
class - this is a representation of all the content from the \kw{SCHEDULE}
section, notably all well and group information and the timestepping. Being
able to change the \kw{SCHEDULE} information runtime is certainly one of the
main motivations for this functionality, however due to the complexity of
the \inlinecode{Opm::Schedule} class (section \ref{schedule_design})
the recommended way to actually mutate the \inlinecode{Opm::Schedule} is
through the use of a dummy \actionx{} keyword (section
\ref{pyaction_actionx}).
\item[\inlinecode{report\_step}:] This is an integer for the report step we
are currently working on. Observe that the \pyaction{} is called for every
simulator timestep, i.e. it will typically be called multiple times with
the same value for the $\mathrm{report\_step}$ argument.
\item[\inlinecode{summary\_state}:] An instance of the
\inlinecode{Opm::SummaryState} class, this is where the current summary
results of the simulator are stored. The \inlinecode{SummaryState} class has
methods to get hold of well, group and general variables
\begin{code}
# Print all well names
for well in summary_state.wells:
print(well)
# Assign all group names to the variable group_names
group_names = summary_state.groups
# Sum the oil rate from all wells.
sum_wopr = 0
for well in summary_state.wells:
sum_wopr += summary_state.well_var(well, 'WOPR')
# Directly fetch the FOPR from the summary_state
fopr = summary_state['FOPR']
\end{code}
The \inlinecode{summary\_state} variable can also be updated with the
\inlinecode{update()}, \inlinecode{update\_well\_var()} and
\inlinecode{update\_group\_var()} methods.
\item[\inlinecode{actionx\_callback}:] The \inlinecode{actionx\_callback} is a
specialized function which is used to update the \inlinecode{Schedule} object
by applying the keywords from a normal \actionx{} keyword. This is described
in detail in section \ref{pyaction_actionx}.
\end{description}
\subsection{Holding state}
The \pyaction{} keywords will often be invoked multiple times, a Python
dictionary \inlinecode{state} has been injected in the module - that dictionary
can be used to maintain state between invocations. Let us assume we want to
detect when the field oil production starts curving down - i.e. when
$\partial^2_{t} \mathrm{FOPR} < 0$, in order to calculate that we need to keep
track of the timesteps and the $\mathrm{FOPR}$ as function of time - this is one
possible implementation:
\begin{code}
def diff(pair1, pair2):
return (pair1[0] - pair2[0], pair1[1] - pair2[1])
def fopr_diff2(summary_state):
fopr = summary_state.get('FOPR')
sim_time = summary_state.get('TIME')
if not 'fopr' in state:
state['fopr'] = []
fopr_series = state['fopr']
fopr_series.append( (sim_time, fopr) )
if len(fopr_series) < 2:
return None
pair0 = fopr_series[-1]
pair1 = fopr_series[-2]
pair2 = fopr_series[-3]
dt1, df1 = diff(pair0, pair1)
dt2, df2 = diff(pair1, pair2)
return 2*(df1/dt1 - df2/dt2)/(dt1 + dt2)
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
fopr_d2 = fopr_diff2(summary_state)
if not fopr_d2 is None:
if fopr_d2 < 0:
print('Hmmm - this is going the wrong way')
else:
print('All good - sky is the limit!')
\end{code}
\section{Changing the \inlinecode{Schedule} object - using a ``normal'' \actionx{}}
\label{pyaction_actionx}
Before reading this section you should make sure to understand the
\inlinecode{Schedule} design described in section \ref{schedule_design}. The
initial plan when implementing the \pyaction{} keyword was to be able to make
function calls like
\begin{code}
schedule.close_well(w1, report_step)
schedule.set_orat(w2, 1000, report_step)
\end{code}
to close a well and set the oil rate of another well. Unfortunately it proved
very complex to get good semantics for combining such runtime changes with the
keyword based model for \kw{SCHEDULE} section. The current recommendation is to
apply changes to the \kw{SCHEDULE} section using callbacks to \kw{ACTIONX}
keywords from Python code, this is illustrated in the example
below\footnote{From a programmers point of view the solution seems very
unsatisfactory, but it works and it plays nicely with the \kw{ACTIONX} behavior.
If/when the underlying \inlinecode{Schedule} implementation changes there is
nothing per se in the \pyaction{} design which inhibits use of a better
\inlinecode{Schedule} api in the future.}.
The recommended way to achieve this is to create a normal \actionx{} keyword
which is set up to run zero times, and then explicitly invoke that from the
Python \inlinecode{run()} function. In the example below we create an \actionx{}
\inlinecode{CLOSEWELLS} which will close all matching wells (the wellname '?')
\begin{deck}
ACTIONX
CLOSEWELLS 0 /
/
/
WELOPEN
'?' 'CLOSE' /
/
ENDACTIO
\end{deck}
The \inlinecode{CLOSEWELLS} action is set up to run zero times, so the normal
\actionx{} machinery will never run this action\footnote{The \kw{CLOSEWELL}
action has an \emph{empty condition}, the \actionx{} keywords with empty
condition will always evaluate as false.}. Then in the Python run function we go
through all the wells and call the \inlinecode{CLOSEWELL} action to close those
with \inlinecode{OPR < 1000}:
\begin{code}
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
close_wells = []
for well in summary_state.wells:
if summary_state.well_var(well, 'WOPR') < 1000:
close_wells.append(well)
if close_wells:
actionx_callback('CLOSEWELLS', close_wells)
\end{code}
The implementation of this is quite complex with thread of execution going from
C++ to Python, then invoking a callback to C++ which will call
\inlinecode{Schedule::iterateScheduleSection()}, going back to Python to
complete the \inlinecode{run()} method before the function pointers pops back to
C++ and continues the simulator execution\footnote{This is documented in some
detail as code comments of \inlinecode{Schedule::applyPyAction()} in the
\path{Schedule.cpp} file.}.
\section{Implementing \udq{} like behavior}
The \udq{} keyword has three different purposes - all based on defining
complex quantities from the current state of the simulation:
\begin{enumerate}
\item Define a complex quantity to be used in a \actionx{} condition.
\item Define a complex quantity for reporting in the summary file.
\item Define a quantity which can used as a control in \kw{UDA}.
\end{enumerate}
All of these can be achieved by using the \pyaction{} keyword, although for the
two latter alternatives you must specify the \udq{} keyword in the deck first,
but you can let the \pyaction{} implementation override the value:
\begin{deck}
-- Observe that this UDQ will be assigned from a PYACTION keyword,
-- the value used in the ASSIGN statement below is pure dummy.
UDQ
ASSIGN WUGOOD 1 /
ASSIGN FUGOOD 1 /
/
\end{deck}
\subsection{Using \pyaction{} instead of \udq{} + \actionx{}}
Towards the end of section \ref{actionx_structure} it is demonstrated how \udq{}
and \actionx{} can be combined to implement an action in case a complicated
condition applies. As described in section \ref{pyaction_actionx} the best way
to actually invoke changes on the \kw{SCHEDULE} section is through the use of a
dummy \actionx{} keyword, but \pyaction{} is very well suited to evaluate
complex conditions. In the example below we close all wells which have
consistently produced less than 1000 $\mathrm{m^3/day}$ for more than 60 days:
\begin{code}
wopr_limit = 1000
time_limit = 60 * 3600 * 24
def init_state(summary_state):
if 'closed_wells' in state:
return
state['closed_wells'] = set()
bad_wells = {}
for well in summary_state.wells:
bad_wells[well] = None
state['bad_wells'] = bad_wells
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
shut_wells = []
init_state(summary_state)
for well in summary_state.wells:
if well in state['closed_wells']:
continue
if summary_state.well_var(well, 'WOPR') < wopr_limit:
elapsed = summary_state.elapsed()
if state['bad_wells'][well] is None:
state['bad_wells'][well] = elapsed
else:
bad_time = elapsed - state['bad_wells'][well]
if bad_time > time_limit:
shut_wells.append(well)
state['closed_wells'].add( well )
else:
state['bad_wells'][well] = None
if shut_wells:
actionx_callback(shut_wells)
\end{code}
\subsection{Using \pyaction{} to report to the summary file}
The important point when using \pyaction{} to report complex results to the
summary file is just that the \inlinecode{summary\_state} argument to the
\inlinecode{run()} function is \emph{writable} with \inlinecode{updata\_xxx}
calls. Assuming dummy \udq{} variables \kw{WUGOOD} and \kw{FUGOOD} have been
defined as per the example above, we can use \pyaction{} to set variable
\kw{FUGOOD} to one for all wells with rate above a limit, and the \kw{FUGOOD}
variable can be the count of such wells:
\begin{code}
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
good_count = 0
opr_limit = 1000
for wname in schedule.well_names():
if summary_state.well_var(wname, 'FOPR') > opr_limit:
good_count += 1
summary_state.update_well_var(wname, 'WUGOOD', 1)
else:
summary_state.update_well_var(wname, 'WUGOOD', 0)
summary_state.update_var('FUGOOD', good_count)
\end{code}
\subsection{Using \pyaction{} to set a \kw{UDA} control}
Using \pyaction{} to set \kw{UDA} controls is quite simple. Again the \udq{}
keyword must have been defined with a dummy value in the \kw{SCHEDULE} section,
and the \kw{UDA} keyword used in e.g. a \kw{WCONDPROD} keyword. Then the
\inlinecode{run()} function can just be used to assign to the \udq{} variable.
In the example below we use a \kw{UDA} to control the oil production rate, and
the value is set to the average value of the producing wells:
\begin{deck}
-- Define dummy UDQ WUOPR to be used as control in the WCONPROD
-- keyword. The actual value for this UDQ is assigned in a PYACTION
-- keyword
UDQ
ASSIGN WUOPR 0 /
/
...
...
-- Need to define a well list with all the production wells.
-- This is to ensure that the WCONPROD keyword is only applied
-- to producers.
WLIST
'PROD' P1 P2 P3 .../
WCONPROD
'*PROD' 'OPEN' 'ORAT' 'WUOPR' /
/
\end{deck}
This can then be combined with the python code:
\begin{code}
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
num_prod_wells = 0
for wname in schedule.well_names():
if summary_state.well_var(wname, 'WOPR') > 0:
num_prod_wells += 1
fopr = summary_state['FOPR']
new_rate = fopr / num_prod_wells
for wname in schedule.well_names():
summary_state.update_well_var(wname, 'WUOPR', new_rate)
\end{code}
\section{Security implications of \pyaction{}}
\label{pyaction_security}
The \pyaction{} keyword allows for execution of arbitrary user supplied Python
code, with the priviliges of the user actually running \flow{}. If you have a
setup where \flow{} runs with a different user account than the person
submitting the simulation you should be \emph{very careful} about enabling the
embedded Python functionality and the \pyaction{} keyword. As a scary example
this script will wipe your disks:
\begin{code}
import shutil
def run(ecl_state, schedule, report_step, summary_state, actionx_callback):
shutil.rmtree('/')
\end{code}
If the user running \flow{} has different security credentials than the user
submits the job, this has significant security implications.

View File

@@ -1,599 +0,0 @@
\newcommand{\udq}{\kw{UDQ}}
\chapter{Programming in the deck: \udq{}}
\udq{} and \kw{ACTIONX} are two keywords which offer a sort of
\emph{programming} in the input deck. \udq{} is an acronym for \emph{User
Defined Quantity}, and the essence of the \udq{} keyword is the ability to
define arithmetic expressions based on the result vectors of the ongoing
simulation. The quantites evaluated with \udq{} can then be output as summary
variables, and they can be used as controls in keywords like \kw{WCONPROD} and
\kw{GCONINJE}. When used as controls the \udq{} variables are called \emph{User
Defined Arguments} (UDA).
For both the \udq{} and \kw{ACTIONX} keywords evaluating an arithmetic
expression based on the current results of the ongoing simulation is an
important part of the concept, and they are often referenced in pair as
\udq{}/\kw{ACTIONX}, this is slightly misleading as the two are fully
independent and share very little both as concepts in \flow{} and in the C++
implementation. The \kw{ACTIONX} keyword is described in chapter \ref{actionx}.
The \udq{} keyword is also documented in section 12.3.233 in the \flow{}
reference manual.
\section{Defining a new \udq{} keyword}
New \udq{} variables are defined with the \udq{} keyword in the \kw{SCHEDULE}
section. The \udq{} keyword is a sort of a super keyword with four additional
subcommands: \kw{DEFINE}, \kw{ASSIGN}, \kw{UNIT} and \kw{UPDATE}. The
\kw{DEFINE} subcommand is the most important command, that is used to
\emph{define} an arithmetic expression for a \udq{} variable, which is evaluated
at the end of every simulator time step. \kw{ASSIGN} is used to define a \udq{}
variable with a constant numerical value, in addition the \kw{ASSIGN} subcommand
is often used as a ``forward reference'' to enable using a \udq{} keyword in
another \kw{DEFINE} expression. The \kw{UNIT} command is used to assign a unit
string to a \udq{} variable, see section \ref{udq_units} for more details about
\udq{} variables and units. The \kw{UPDATE ON} and \kw{UPDATE OFF} commands can
be used to switch updating of \udq{} variables on and off. The \udq{} variables
are created in mode \kw{ON}.
All \udq{} keywords must have the letter \emph{U} as their second character, the
first character should be 'F', 'G' or 'W' to indicate whether this is a field,
group or well quantity\footnote{In \eclipse{} also the characters 'S', 'C', 'A'
and 'B' are used to denote \emph{segment}, \emph{connection} \emph{aquifer} and
\emph{block} variables respectively. None of these are supported in \flow{}.}.
The simplest way to define a \udq{} is just using the \kw{ASSIGN} subcommand of
the \udq{} keyword:
\begin{deck}
UDQ
ASSIGN FUVAR1 123 /
ASSIGN FUVAR2 456 /
/
\end{deck}
This way we will assign to variables \inlinecode{FUVAR1} and \inlinecode{FUVAR2}
with values 123 and 456 respectively. These values can output to the summary
file, be used as control values in a control keyword like \kw{WELTARG} and be
used to recursively define another \udq{} keyword.
The more interesting \udq{} subcommand is \kw{DEFINE} which is used to define an
arithmetic expression for a \udq{} variable, the arithmetic expression will be
evaluated at the end of every timestep. The expressions are built from the
normal arithmetic operators +,-,*,/, a predefined set of available functions
(see \ref{udq_functions}) and results from the ongoing simulation.
In the example below we create \udq{} variables \kw{FUWCT1} and \kw{FUWCT2} as
user defined field water cut, one based on the summary variables \kw{FWPR} and
\kw{FOPR} and one based on summing \kw{WOPR} and \kw{WWPR} over all wells
\begin{deck}
UDQ
DEFINE FUWCT1 FWPR/(FWPR + FOPR) /
DEFINE FUWCT2 SUM(WWPR)/(SUM(WWPR) + SUM(WOPR)) /
/
\end{deck}
A \udq{} variable can be redefined during the simulation, and also change from
constant \kw{ASSIGN} to variable \kw{DEFINE}. Observe that \udq{} values are
always evaluated in order of occurence in the input deck. For instance for this
input
\begin{deck}
UDQ
ASSIGN FU1 100 /
DEFINE FU2 FU1 + FOPR /
DEFINE FU1 FWPR /
/
\end{deck}
the evaluation order will be \{\kw{FU1}, \kw{FU2}\}\footnote{Maintaining the
input order and whether a certain \udq{} symbol is now a \kw{ASSIGN} or
\kw{DEFINE} keyword is also very important for the restart code.}. \kw{ASSIGN}
statements take effect at input time, making the newly defined symbol
immediately available for reuse in a subsequent defintion. This is utilized in
the \udq{} keyword above where the symbol \kw{FU1} is referenced in the
defintion of \kw{FU2}. As used in this example the \kw{ASSIGN FU1 100} can be
seen as a \emph{forward reference}. When we have completed the first timestep
and it is time to evalute the \udq{} expressions they will be evaluated in order
of \emph{first appearance}, i.e. \{\kw{FU1}, \kw{FU2}\}. At this stage the
active definition of \kw{FU1} is \inlinecode{FU1 = FWPR}, i.e. the value
\inlinecode{100} from the initial definition \inlinecode{FU1 = 100} is never
actually used.
\section{Different types of \udq{} - field, group and well}
The \udq{} keywords can be of different types, \flow{} supports \emph{field},
\emph{well} and \emph{group} keywords\footnote{\eclipse{} also supports
connection, segment and aquifer variables.}. The field keywords are scalar,
whereas the well and group keywords are sets with values for every well/group.
The type of a \udq{} keyword is inferred from the name in the same manner as the
summary keywords, i.e. for this \udq{} keyword
\begin{deck}
UDQ
ASSIGN FU1 100 /
ASSIGN WU1 200 /
ASSIGN GU1 300 /
/
\end{deck}
we will define one scalar keyword \kw{FU1}, one well set \kw{WU1} and one group
set \kw{GU1}. The well sets will have one slot for each well in the model, it is
not possible to create a well set with only a subset of wells, but the well set
can have \emph{undefined} value for a subset of wells. The set maintains a
\inlinecode{is\_defined()} status for each element and most operations only
apply to the defined elements\footnote{The C++ implementation of the \udq{}
value set is the equivalent of \texttt{std::map<std::string,
std::optional<double>>}.}.
As indicated with \kw{ASSIGN WU1 200} you can assign a scalar value to a set
keyword, then all elements in the set will have the same value. Assuming we have
a model with wells OP1, OP2, WI and GI the \kw{WU1} will look like
\begin{code}
WU1 = {"OP1": 100, "OP2": 100, "WI": 100, "GI": 100}.
\end{code}
When defining a well \udq{} it is natural to refer to well summary variables, in
the example below we define \kw{WUBHP} which is the bottom hole pressure
for each well, \kw{WUOPR1} which is the oil production rate for a subset of
wells and \kw{WUOPR2} which is the oil production rate for well OP1 \emph{broadcasted to all wells}.
\begin{deck}
UDQ
DEFINE WUBHP WBHP /
DEFINE WUOPR1 WOPR 'OP*' /
DEFINE WUOPR2 WOPR OP1 /
/
\end{deck}
After evaluation these \udq{} values will be\footnote{The numerical values are
arbitrary, just to illustrate that they are \emph{defined}, in contrast to the
[ ] which is used to illustrate an \emph{undefined} value.}:
\begin{code}
WUBHP = {"OP1": 20, "OP2": 30, "WI": 10, "GI": 15}
WUOPR1 = {"OP1": 13, "OP2": 17, "WI": [ ], "GI": [ ]}
WUOPR2 = {"OP1": 13, "OP2": 13, "WI": 13, "GI": 13}
\end{code}
Observe how well variables like \kw{WBHP} and \kw{WOPR} can be qualified with a
wellname pattern. If no wellname is supplied the expression will be evaluated
for all wells, as for \kw{WUBHP}, for \kw{WUOPR1} the pattern 'OP*' will select
wells \{OP1, OP2\} and leave the injectors \{WI, GI\} undefined. For \kw{WUOPR2}
the well pattern 'OP1' specifies a well completely, i.e. this will be evaluated
as a scalar, and then the scalar value \inlinecode{WOPR:OP1 == 13} is
broadcasted to all the wells in \kw{WUOPR2}.
\udq{} sets with different sets of defined wells can be combined, in most cases
the operations will be applied to the intersection of all defined wells,
consider for example\label{udq_diff}:
\begin{deck}
UDQ
DEFINE WUBHP WBHP /
DEFINE WUTHP WTHP OP* /
DEFINE WUPDIFF WUBHP - WUTHP
/
\end{deck}
When these \udq{} statements are evaluated we will get:
\begin{code}
WUBHP = {"OP1": 20, "OP2": 30, "WI": 10, "GI": 15}
WUTHP = {"OP1": 13, "OP2": 17, "WI": [ ], "GI": [ ]}
WUPDIFF = {"OP1": 7, "OP2": 13, "WI": [ ], "GI": [ ]}
\end{code}
As we see the undefined property for wells GI and WI in \kw{WUTHP} is contagious
when the two expressions are combined with \inlinecode{WUPDIFF = WUBHP - WUTHP},
see however section \ref{udq_union_functions} for a collection of functions
which operate on the union of values.
When an undefined variable is output to the summary file it will get a value
given as item 3 of the \kw{UDQPARAM} keyword. Summary output is the \emph{only}
point where the undefined value can be dereferenced, the numerical value given
in \kw{UDQPARAM} will not be available either for \udq{} nor \kw{ACTIONX}
evaluations.
\section{Functions available in \udq{} defintions}
\label{udq_functions}
\flow{} supports all the \udq{} functions available in \eclipse{}, for the
future it would be a quite simple C++ task to extend the list of available
functions, although that will affect \eclipse{} compatibility.
\subsection{Ordinary binary functions}
The \udq{} framework supports all the ordinary arithmetic operators +,-,*,/ and
\^{} and the comparison operators $>, \ge, <, \le, \ne, ==$. For all of these
operations sets and scalars can be combined freely. When combining a scalar and
a set the scalar will be promoted to a set with all values equal, i.e. for
\begin{deck}
UDQ
ASSIGN WULIMIT 100 /
/
\end{deck}
the numerical value 100 will be broadcasted to all wells:
\begin{code}
WULIMIT = {"OP1": 100, "OP2": 100, "WI": 100, "GI": 100}.
\end{code}
In the case of set arguments the operations are only applied to the union of
values which are defined in both argument sets. The comparison operators produce
numerical 0 or 1 depending on the result of the comparison, the result from a
comparison operation can be used numerically in further computations. In the
following example \kw{FUWCNT} will be the number of wells producing with oil
production rate above 1000\footnote{Remember: 1000 has the units of the
deck, i.e. $\mathrm{stb/day}$ in FIELD units and $\mathrm{m^3/day}$ in metric
units.}.
\begin{deck}
UDQ
DEFINE FUWCNT SUM( WOPR > 1000 ) /
/
\end{deck}
\subsection{Functions over a set returning a scalar}
The \udq{} framework has several functions which iterate over all the defined
members of a set and return a scalar. In the example
\begin{deck}
UDQ
DEFINE FU1 SUM(WOPR 'OP*') /
/
\end{deck}
The scalar variable \kw{FU1} will be equal to the sum of oil production rates
for all wells matching the pattern \kw{OP*}, the wells with a name not matching
\kw{OP*} will not contribute to the sum. The complete list of functions iterating
over a set and returning a scalar are:
\begin{description}
\item[SUM] Sum all defined elements in the argument set and return a scalar.
\item[AVEA] The arithmetic average of the elements in the set.
\item[AVEG] The geometric average of the elements in the set.
\item[AVEH] The harmonic average of the elements in the set.
\item[MAX] The maximum element in the set.
\item[MIN] The minimum element in the set.
\item[NORM1] The $\mathrm{L^1}$ norm of the elements in the set.
\item[NORM2] The $\mathrm{L^2}$ norm of the elements in the set.
\item[NORMI] The $\mathrm{L^\infty}$ norm of the elements in the set.
\item[PROD] The product of all the elements in the set.
\end{description}
\subsection{Elemental functions}
There is a family of functions which take a vector or scalar as argument, run
through all the elements in the argument and return a result of the same shape
as the argument, where a function has been applied to all the defined elements.
Assume that the \kw{WU1} has the following value:
\begin{code}
WU1 = {"OP1": -2, "OP2": -1, "WI": 1, "GI": []},
\end{code}
then \kw{DEFINE WUABS ABS(WU1)} will give
\begin{code}
WUABS = {"OP1": 2, "OP2": 1, "WI": 1, "GI": []}.
\end{code}
The available elemental functions of this kind come in different categories:
\subsubsection*{Mathematical functions}
\begin{description}
\item[EXP] Return a new set where all defined elements have been exponentiated.
\item[ABS] Return a new set with the absolute value of all elements.
\item[LN] Return a new set with the \emph{natural logarithm} of all elements.
\item[LOG] Return a new set with $\log_{10}$ of all elements.
\item[NINT] Return a new set where all elements have been converted to the
nearest integer.
\end{description}
\subsubsection*{Sorting functions}
The \udq{} functionality supports functions \kw{SORTA} and \kw{SORTD} to sort a
set in ascending or descending order respectively. Observe that these functions
do not sort the sets in place - the udqset does not have any notion of ordering,
rather they create a permutation set with values 1,2,3, ... The following
combination of \udq{} and \kw{ACTIONX} will use the \kw{SORTD} function to close
the two wells with the highest watercut:
\begin{deck}
UDQ
DEFINE WUWCTS SORTD(WWCT OP*) /
/
\end{deck}
assuming the \kw{WWCT} looks like
\begin{code}
WWCT = {"OP1": 0.5, "OP2": 0.2, "OP3": 0.1, "OP4":0.7, "WI": 0, "GI": 0}
\end{code}
then the \kw{WUWCTS} set will look like
\begin{code}
WUWCTS = {"OP1": 2, "OP2": 3, "OP3": 4, "OP4":1 "WI": [], "GI": []}
\end{code}
When this is combined with the \kw{ACTIONX}(see chapter \ref{actionx})
\begin{code}
ACTIONX
CW /
WUWCTS <= 2 /
/
WELOPEN
'?' 'CLOSE' /
/
ENDACTIO
\end{code}
the two wells with highest watercut will be selected in the \inlinecode{WUWCTS
<= 2} statement and that will be expanded to \{OP4, OP1\} by the '?'
expression in the \kw{WELOPEN} keyword.
\subsubsection*{Random functions}
The \udq{} machinery has functionality to sample random numbers, there are one
set of random number functions which are seeded deterministically by item 1 of
\kw{UDQPARAMS} and an alternative set which is seeded by the clock. The random
number functions take a \udq{} variable as argument, that is only to ensure that
the shape of the result value is correct.
\begin{description}
\item[RANDN] Random numbers from distribution $N(0,1)$ seeded deterministically
by item 1 in \kw{UDQPARAMS}.
\item[RANDU] Random numbers from distribution $U(-1,1)$ seeded deterministically
by item 1 in \kw{UDQPARAMS}.
\item[RRNDN] Random numbers from distribution $N(0,1)$ seeded by the clock.
\item[RRNDU] Random numbers from distribution $U(-1,1)$ seeded by the clock.
\end{description}
Assuming the argument vector \kw{WU1} looks like
\begin{code}
WU1 = {"OP1": -2, "OP2": [], "WI": 1, "GI": []},
\end{code}
the result of \kw{DEFINE WURAND RANDU(WU1)} could be like
\begin{code}
WURAND = {"OP1": 0.576, "OP2": [], "WI": -0.132, "GI": []}.
\end{code}
\subsubsection*{Work with defined status}
The functions \kw{DEF}, \kw{UNDEF} and \kw{IDV} can be used to inspect the
defined/not defined status of the elements in a \udq{} set.
\begin{description}
\item[DEF] Return a set with value 1 for all defined elements.
\item[UNDEF] Return a set with value 1 for all undefined elements.
\item[IDV] Return a set with value 1 for all defined elements and value 0 for
all undefined elements.
\end{description}
Assuming the input argument
\begin{code}
WU1 = {"OP1": -2, "OP2": [], "WI": 1, "GI": []},
\end{code}
the \udq{} assignments
\begin{deck}
UDQ
DEFINE WUDEF DEF(WU1) /
DEFINE WUUNDEF UNDEF(WU1) /
DEFINE WUIDV IDV(WU1) /
/
\end{deck}
will produce:
\begin{code}
WUDEF = {"OP1": 1, "OP2": [], "WI": 1, "GI": []},
WUUNDEF = {"OP1": [], "OP2": 1, "WI": [], "GI": 1},
WUIDV = {"OP1": 1, "OP2": 0, "WI": 1, "GI": 0},
\end{code}
\subsection{Union functions}
\label{udq_union_functions}
There are a list of functions \kw{Uxxx} which operate on the union of the values
found in the two sets, i.e. a result is assigned if at at least one set has
defined value for this well/group.
\begin{description}
\item[UADD] Will add the items from the two sets.
\item[UMUL] Will multiply the items from the two sets.
\item[UMAX] The maximum value from the two sets.
\item[UMIN] The minumum value from the two sets.
\end{description}
In the case where only one of the sets has a defined value the operation will be
performed \emph{as if} the function \kw{Uxxx} is the identity function.
As an example consider the two sets:
\begin{code}
WU1 = {"OP1": 1, "OP2": [], "WI": 2, "GI": []},
WU2 = {"OP1": 6, "OP2": 5, "WI": [], "GI": []},
\end{code}
and the \udq{} expression \kw{DEFINE WUUADD WU1 UADD WU2}, then the resulting
set \kw{WUUADD} will be
\begin{code}
WUUADD = {"OP1": 7, "OP2": 5, "WI": 2, "GI": []}.
\end{code}
This in contrast to a normal $+$ which only operates on the intersection of the
two sets, only well OP1 would have a defined value in this case.
\section{Used as a control: UDA}
\label{uda}
Probably one of the most important uses of the \udq{} functionality is the
ability to use a \udq{} as control in e.g. the \kw{WCONINJE} keyword. In the
example below we calculate the produced liquid volume from a group of wells and
use that as injection target for a water injector:
\begin{deck}
UDQ
DEFINE FULPR (WOPR P* + WWPR P*) * 1.25 /
/
...
...
WCONINJE
WI 'WATER' 'OPEN' 'RATE' 'FULPR' /
/
\end{deck}
In the following insane example we distribute the current oil production rate
randomly among the producers and use that as target for the next timestep - do
not try this at home:
\begin{deck}
UDQ
-- Create a 0 / 1 mask with 0 for injectors and 1 for producers.
DEFINE WUPROD WOPR > 0 /
-- Create a vector of random numbers [0,1] for all producers
DEFINE WURAND 0.5 * (RANDU(WUPROD) + 1) * WUPROD /
-- Create a vector where all producers get a random fraction of
-- the current total oil production rate
DEFINE WUOPR FOPR * WURAND / SUM(WURAND) /
/
-- Need to have a well list or similar to select all producers for
-- the WCONPROD keyword.
WLIST
'P' 'ADD' ..... /
WCONPROD
'*P' 'OPEN' 'ORAT' 'WUOPR' /
/
\end{deck}
One point about this example is that the \udq{} variable \kw{WUOPR} which is
used as as control in the \kw{WCONPROD} is a well set, the lookup machinery will
automatically use the correct well index when assigning control value to a
particular well.
From an implementation point of view the \kw{UDA} functionality creates a
significant complexity, because the actual rate to use in the simulation must be
evaluated \emph{just in time}.
\section{\udq{} units}
\label{udq_units}
The \udq{} subcommand \kw{UNIT} can be used to assign a string which is used as
output unit when the \udq{} variable is output to the summary file. This is
\emph{only} a string and does not induce any unit conversion. All \udq{}
evaluations are in terms of the corre deck units - irrespective of the \kw{UNIT}
subcommand. Consider the following
\begin{deck}
RUNSPEC
FIELD
...
...
SCHEDULE
UDQ
DEFINE WUI WWIR - 100 /
/
\end{deck}
\begin{enumerate}
\item The simulation runs in SI units; hence the water injection rate is
calculated in $\mathrm{m^3/s}$.
\item As part of the summary evaluation the \inlinecode{SummaryState} will
contain the water injection rate converted to field units.
\item The \udq{} variable \kw{WUI} is evaluated as the water injection rate from
\inlinecode{SummaryState} subtracted numerical value 100, \emph{it is solely the users
responsability that the numerical value 100 represents water injection rate in
field units.}
\end{enumerate}
Observe that the units are complicated, and non intuitive for \kw{UDA} values.
The \kw{UDA} evaluation is based on the \inlinecode{SummaryState} class which is
in deck units, the controls determined by \kw{UDA} evaluation must therefor be
converted to SI units just when it is passed to the simulator. The initial
design ambition was to block the deck units at the IO boundary, keeping the
internals fully in SI. The \kw{UDA} concept is the exception which manages to
inject deck units quite far into the code.
\section{Implementation details}
The significant part of the UDQ implementation is in classes located in
\path{opm/input/eclipse/Schedule/UDQ}, in addition the restart output of
\udq{}/\kw{UDA} values is in \path{opm/output/eclipse/AggregateUDQData.cpp}.
Finally the \udq{} parser makes use of the type \inlinecode{RawString} to treat
literal ``/'' and ``*'' different from ordinary parsing where ``/'' signifies
end of line and ``*'' is either a default or part of a multiplier expression.
\subsection*{\inlinecode{UDQConfig}}
The class \inlinecode{UDQConfig} internalizes the parsing of the \udq{} keywords
from the input deck. The \inlinecode{UDQConfig} instance is time-versioned and
managed by the \inlinecode{ScheduleState} class. The \inlinecode{UDQConfig} is
immutable while the simulator is executing. The \inlinecode{UDQConfig} contains
two main classes \inlinecode{UDQDefine} and \inlinecode{UDQAssign} in addition
to book-keeping code to keep track of what type of expression a \udq{} keyword
is at the time. A significant part of the book-keeping is only required to be
able to output restart files in \eclipse{} format.
\subsection*{\inlinecode{UDQDefine} and \inlinecode{UDQASTNode}}
The \inlinecode{UDQDefine} manages a parsed \udq{} expresssion along with a
chunck of metadata. The parsed \udq{} expression is managed in an instance of
\inlinecode{UDQASTNode}. The \inlinecode{UDQASTNode} contains a parsed tree
representation of the \udq{} input expression. The parsing of \udq{} expressions
happens at input time, and for the rest of the simulation the
\inlinecode{UDQASTnode} instances are immutable.
Many scalar \udq{} types are defined in the file \path{UDQEenums.hpp} and in the
namespace \inlinecode{UDQ} there are many small utility functions to work with
these enums.
\subsection*{\inlinecode{SummaryState}}
\label{summarystate}
The \inlinecode{SummaryState} class is not part of the \udq{} implementation,
but it is a very important class for the \udq{} functionality. At the end of
every timestep the simulator will call the method \inlinecode{evalSummary} which
will call into opm-common and evaluate all summary variables and store them in a
\inlinecode{SummaryState} instance\footnote{Observe that during initialization
the \udq{} expressions are inspected, and we make sure that all summary
variables needed to evaulate \udq{} expressions are evaluated in the Summary
evaluation.}. The \inlinecode{SummaryState} class manages a set of maps with
well, group and field variables, when evaluating e.g. the \kw{WOPR} the results
will be stored in a two level map first indexed with keyword \kw{WOPR} and then
with well name. Afterwards the \udq{} layer can fetch values with
\inlinecode{SummaryState::get\_well\_var()}. The values in the
\inlinecode{SummaryState} have been converted to output units, this is important
for the \kw{UDA} evaluation.
At the end of every timestep the \inlinecode{UDQConfig::eval()} method is called
to evaluate all the \udq{} expressions, the evaluated values will end up in the
active \inlinecode{SummaryState} instance, i.e. for this \udq{}
\begin{deck}
UDQ
DEFINE FUOPR SUM(WOPR) /
DEFINE WUGWR WGPR / WWPR /
/
\end{deck}
we will get \inlinecode{SummaryState} entries for \kw{FUOPR} and \kw{WUGWR} for
\emph{all} wells in the model. These \inlinecode{SummaryState} values can then
be output to the summary file, be used when evaluating \kw{ACTIONX} keywords or
to evaluate \kw{UDA} control values.
In addition to the \inlinecode{SummaryState} variable there is an instance of
type \inlinecode{UDQState} which is updated runtime, the \inlinecode{UDQState}
instance holds on to the results of \udq{} evaluations with more context than
\inlinecode{SummaryState} and is used to output \udq{} and \kw{UDA} state to the
restart files. While evaluating the simulator will create a \kw{UDQContext}
variable which will manage both the \inlinecode{SummaryState},
\inlinecode{UDQState} and also some \udq{} parameters from the \kw{RUNSPEC}
section. The lifetime of the \kw{UDQContext} instance is only one \udq{}
evaluation.
While evaluating the \udq{} expressions the results will be instances of
\inlinecode{UDQSet} which is a small container class which keeps track of
well/group names and whether a value is defined or not. The \inlinecode{UDQSet}
class overrides the arithmetic operators like \inlinecode{UDQSet::operator+()}
so that expressions like \kw{2 * WOPR 'OP*'} can be easily evaluated in code.
\subsection*{Paralell awareness}
\label{udq_parallel}
The opm-common code where the \udq{} functionality is implemented is totally
unaware of parallel execution, so to be certain that this works for a parallel
simulator care must be taken. In flow this is handled as:
\begin{enumerate}
\item The \inlinecode{Schedule} class as a whole is identical on all
processes.
\item The state variables \inlinecode{UDQState} and \inlinecode{SummaryState}
are distributed so they are equal on all processes before the \udq{}
evaluation. This communication is performed in the simulator.
\end{enumerate}
The \udq{} evaluation is invoked from
\path{opm-simulators/ebos/eclgenericwriter.cc} function
\inlinecode{evalSummary()}.

View File

@@ -5,9 +5,9 @@
Module: opm-common
Description: Open Porous Media Initiative shared infrastructure
Version: 2023.04
Label: 2023.04
Version: 2021.10-rc2
Label: 2021.10-rc2
Maintainer: opm@opm-project.org
MaintainerName: OPM community
Url: http://opm-project.org
Depends: dune-common (>= 2.7)
Depends: dune-common

View File

@@ -1,194 +0,0 @@
// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
// vi: set et ts=4 sw=4 sts=4:
/*
This file is part of the Open Porous Media project (OPM).
OPM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
OPM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with OPM. If not, see <http://www.gnu.org/licenses/>.
Consult the COPYING file in the top-level source directory of this
module for the precise wording of the license and the list of
copyright holders.
*/
/*!
* \file
*
* \brief This is the unit test for the co2 brine PVT model
*
*/
#include "config.h"
#include <opm/material/fluidsystems/blackoilpvt/Co2GasPvt.hpp>
#include <opm/material/fluidsystems/blackoilpvt/BrineCo2Pvt.hpp>
#include <iostream>
template <class Co2Pvt>
double densityGas(const Co2Pvt& co2Pvt, const double p, const double T, const double Rv)
{
return co2Pvt.inverseFormationVolumeFactor(/*regionIdx=*/0,
T,
p,
Rv,
/*Rvw=*/0.0) * co2Pvt.gasReferenceDensity(0);
}
template <class BrinePvt>
double densityBrine(const BrinePvt& brinePvt, const double p, const double T, const double Rs)
{
double bo = brinePvt.inverseFormationVolumeFactor(/*regionIdx=*/0,
T,
p,
Rs);
return bo * (brinePvt.oilReferenceDensity(0) + Rs * brinePvt.gasReferenceDensity(0));
}
int main(int argc, char **argv)
{
bool help = false;
for (int i = 1; i < argc; ++i) {
std::string tmp = argv[i];
help = help || (tmp == "--h") || (tmp == "--help");
}
if (argc < 5 || help) {
std::cout << "USAGE:" << std::endl;
std::cout << "co2brinepvt <prop> <phase> <p> <T> <salinity> <rs> "<< std::endl;
std::cout << "prop = {density, invB, B, viscosity, rsSat, internalEnergy, enthalpy, diffusionCoefficient}" << std::endl;
std::cout << "phase = {CO2, brine}" << std::endl;
std::cout << "p: pressure in pascal" << std::endl;
std::cout << "T: temperature in kelvin" << std::endl;
std::cout << "salinity(optional): salt molality in mol/kg" << std::endl;
std::cout << "rs(optional): amount of dissolved CO2 in Brine in SM3/SM3" << std::endl;
std::cout << "OPTIONS:" << std::endl;
std::cout << "--h/--help Print help and exit." << std::endl;
std::cout << "DESCRIPTION:" << std::endl;
std::cout << "co2brinepvt computes PVT properties of a brine/co2 system " << std::endl;
std::cout << "for a given phase (oil or brine), pressure, temperature, salinity and rs." << std::endl;
std::cout << "The properties support are: density, the inverse phase formation volume factor (invB), viscosity, " << std::endl;
std::cout << "saturated dissolution factor (rsSat) " << std::endl;
std::cout << "See CO2STORE in the OPM manual for more details." << std::endl;
return EXIT_FAILURE;
}
std::string prop = argv[1];
std::string phase = argv[2];
double p = atof(argv[3]);
double T = atof(argv[4]);
double molality = 0.0;
double rs = 0.0;
double rv = 0.0; // only support 0.0 for now
if (argc > 5)
molality = atof(argv[5]);
if (argc > 6)
rs = atof(argv[6]);
const double MmNaCl = 58e-3; // molar mass of NaCl [kg/mol]
// convert to mass fraction
std::vector<double> salinity = {0.0};
if (molality > 0.0)
salinity[0] = 1 / ( 1 + 1 / (molality*MmNaCl));
Opm::BrineCo2Pvt<double> brineCo2Pvt(salinity);
Opm::Co2GasPvt<double> co2Pvt(salinity);
double value;
if (prop == "density") {
if (phase == "CO2") {
value = densityGas(co2Pvt, p, T, rv);
} else if (phase == "brine") {
value = densityBrine(brineCo2Pvt, p, T, rs);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
} else if (prop == "invB" || prop == "B") {
if (phase == "CO2") {
value = co2Pvt.inverseFormationVolumeFactor(/*regionIdx=*/0,
T,
p,
rv,
/*Rvw=*/0.0);
} else if (phase == "brine") {
value = brineCo2Pvt.inverseFormationVolumeFactor(/*regionIdx=*/0,
T,
p,
rs);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
if (prop == "B")
value = 1 / value;
} else if (prop == "viscosity") {
if (phase == "CO2") {
value = co2Pvt.viscosity(/*regionIdx=*/0,
T,
p,
rv,
/*Rvw=*/0.0);
} else if (phase == "brine") {
value = brineCo2Pvt.viscosity(/*regionIdx=*/0,
T,
p,
rs);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
} else if (prop == "rsSat") {
if (phase == "CO2") {
value = co2Pvt.saturatedWaterVaporizationFactor(/*regionIdx=*/0,
T,
p);
} else if (phase == "brine") {
value = brineCo2Pvt.saturatedGasDissolutionFactor(/*regionIdx=*/0,
T,
p);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
} else if (prop == "diffusionCoefficient") {
size_t comp_idx = 0; // not used
if (phase == "CO2") {
value = co2Pvt.diffusionCoefficient(T,p, comp_idx);
} else if (phase == "brine") {
value = brineCo2Pvt.diffusionCoefficient(T,p, comp_idx);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
} else if (prop == "internalEnergy") {
if (phase == "CO2") {
value = co2Pvt.internalEnergy(/*regionIdx=*/0 ,T,p, rv, 0.0);
} else if (phase == "brine") {
value = brineCo2Pvt.internalEnergy(/*regionIdx=*/0 ,T,p, rs);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
} else if (prop == "enthalpy") {
if (phase == "CO2") {
value = p / densityGas(co2Pvt, p, T, rv) + co2Pvt.internalEnergy(/*regionIdx=*/0 ,T,p, rv, 0.0);
} else if (phase == "brine") {
value = p / densityBrine(brineCo2Pvt, p, T, rs) + brineCo2Pvt.internalEnergy(/*regionIdx=*/0 ,T,p, rs);
} else {
throw std::runtime_error("phase " + phase + " not recognized. Use either CO2 or brine");
}
} else {
throw std::runtime_error("prop " + prop + " not recognized. "
+ "Use either density, visosity, invB, B, internalEnergy, enthalpy or diffusionCoefficient");
}
std::cout << value << std::endl;
return 0;
}

View File

@@ -18,7 +18,6 @@
*/
#include <filesystem>
#include <iostream>
#include <getopt.h>
#include <string.h>
@@ -32,6 +31,7 @@
#include <opm/io/eclipse/ESmry.hpp>
#include <opm/io/eclipse/EclUtil.hpp>
#include <opm/common/utility/FileSystem.hpp>
static void printHelp() {
@@ -91,36 +91,25 @@ int main(int argc, char **argv) {
auto lap0 = std::chrono::system_clock::now();
int num_esmry = argc-argOffset;
std::vector<bool> status(num_esmry, false);
#pragma omp parallel for
for (int f = 0; f < num_esmry; f ++){
std::filesystem::path inputFileName = argv[f + argOffset];
for (int f = argOffset; f < argc; f ++){
Opm::filesystem::path inputFileName = argv[f];
std::filesystem::path esmryFileName = inputFileName.parent_path() / inputFileName.stem();
Opm::filesystem::path esmryFileName = inputFileName.parent_path() / inputFileName.stem();
esmryFileName = esmryFileName += ".ESMRY";
if (Opm::EclIO::fileExists(esmryFileName) && (force))
remove (esmryFileName);
try {
Opm::EclIO::ESmry smry{ argv[f + argOffset] };
status[f] = smry.make_esmry_file();
if (! status[f]) {
std::cerr << "\n! Warning, smspec already have one esmry file, existing kept use option -f to replace this\n";
}
} catch (...) {
std::cerr << "\n! Warning, could not open summary file " << argv[f + argOffset] << '\n';
Opm::EclIO::ESmry smryFile(argv[f]);
if (!smryFile.make_esmry_file()){
std::cout << "\n! Warning, smspec already have one lod file, existing kept use option -f to replace this" << std::endl;
}
}
const auto n_converted = std::count(status.begin(), status.end(), true);
auto lap1 = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds1 = lap1-lap0;
std::cout << "\nruntime for creating " << n_converted << " ESMRY files: " << elapsed_seconds1.count() << " seconds\n" << std::endl;
std::cout << "\nruntime for creating " << (argc-argOffset) << " ESMRY files: " << elapsed_seconds1.count() << " seconds\n" << std::endl;
return 0;
}

View File

@@ -19,16 +19,14 @@
#include <opm/output/eclipse/EclipseIO.hpp>
#include <opm/input/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ParseContext.hpp>
#include <opm/parser/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Parser/Parser.hpp>
#include <opm/input/eclipse/Parser/ParseContext.hpp>
#include <opm/input/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Python/Python.hpp>
#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
#include <opm/input/eclipse/Schedule/Schedule.hpp>
#include <opm/input/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
#include <opm/parser/eclipse/Python/Python.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/Schedule/Schedule.hpp>
#include <opm/parser/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
#include <opm/common/OpmLog/OpmLog.hpp>
#include <opm/msim/msim.hpp>
@@ -53,8 +51,8 @@ int main(int /* argc */, char** argv) {
error_guard.terminate();
}
Opm::msim msim(state, schedule);
Opm::msim msim(state);
Opm::EclipseIO io(state, state.getInputGrid(), schedule, summary_config);
msim.run(io, false);
msim.run(schedule, io, false);
}

View File

@@ -24,11 +24,14 @@
#include <cstdlib>
#include <fmt/format.h>
#include <opm/input/eclipse/Parser/Parser.hpp>
#include <opm/input/eclipse/Parser/ParseContext.hpp>
#include <opm/input/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Parser/InputErrorAction.hpp>
#include <opm/input/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ParseContext.hpp>
#include <opm/parser/eclipse/Parser/ErrorGuard.hpp>
#include <opm/parser/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
#include <opm/parser/eclipse/EclipseState/Schedule/Schedule.hpp>
struct keyword {
@@ -55,10 +58,10 @@ std::vector<keyword> load_deck(const std::string& deck_file) {
std::vector<keyword> keywords;
/* Use the same default ParseContext as flow. */
parseContext.update(Opm::ParseContext::PARSE_RANDOM_SLASH, Opm::InputErrorAction::IGNORE);
parseContext.update(Opm::ParseContext::PARSE_MISSING_DIMS_KEYWORD, Opm::InputErrorAction::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_WELL, Opm::InputErrorAction::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_GROUP, Opm::InputErrorAction::WARN);
parseContext.update(Opm::ParseContext::PARSE_RANDOM_SLASH, Opm::InputError::IGNORE);
parseContext.update(Opm::ParseContext::PARSE_MISSING_DIMS_KEYWORD, Opm::InputError::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_WELL, Opm::InputError::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_GROUP, Opm::InputError::WARN);
auto deck = parser.parseFile(deck_file, parseContext, errors);
for (const auto& kw : deck) {

View File

@@ -21,15 +21,15 @@
#include <iomanip>
#include <chrono>
#include <opm/input/eclipse/Parser/Parser.hpp>
#include <opm/input/eclipse/Parser/ParseContext.hpp>
#include <opm/input/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Deck/Deck.hpp>
#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
#include <opm/input/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
#include <opm/input/eclipse/Schedule/Schedule.hpp>
#include <opm/input/eclipse/Python/Python.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ParseContext.hpp>
#include <opm/parser/eclipse/Parser/ErrorGuard.hpp>
#include <opm/parser/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/SummaryConfig/SummaryConfig.hpp>
#include <opm/parser/eclipse/EclipseState/Schedule/Schedule.hpp>
#include <opm/parser/eclipse/Python/Python.hpp>
#include <opm/common/OpmLog/OpmLog.hpp>
#include <opm/common/OpmLog/StreamLog.hpp>

View File

@@ -17,26 +17,24 @@
along with OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#include <filesystem>
#include <fstream>
#include <iostream>
#include <getopt.h>
#include <opm/input/eclipse/Deck/Deck.hpp>
#include <opm/input/eclipse/EclipseState/InitConfig/InitConfig.hpp>
#include <opm/input/eclipse/EclipseState/IOConfig/IOConfig.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/I.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/P.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/G.hpp>
#include <opm/input/eclipse/Parser/Parser.hpp>
#include <opm/input/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Parser/ParseContext.hpp>
#include <opm/input/eclipse/Parser/InputErrorAction.hpp>
#include <opm/common/utility/FileSystem.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/I.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/P.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/G.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ErrorGuard.hpp>
#include <opm/parser/eclipse/Parser/ParseContext.hpp>
#include <opm/parser/eclipse/Parser/InputErrorAction.hpp>
#include <opm/parser/eclipse/Deck/Deck.hpp>
namespace fs = std::filesystem;
namespace fs = Opm::filesystem;
Opm::Deck pack_deck( const char * deck_file, std::ostream& os) {
Opm::ParseContext parseContext(Opm::InputErrorAction::WARN);
Opm::ParseContext parseContext(Opm::InputError::WARN);
Opm::ErrorGuard errors;
Opm::Parser parser;
@@ -156,14 +154,16 @@ int main(int argc, char** argv) {
}
using IMPORT = Opm::ParserKeywords::IMPORT;
for (const auto& import_keyword : deck.get<IMPORT>()) {
for (std::size_t import_index = 0; import_index < deck.count<IMPORT>(); import_index++) {
const auto& import_keyword = deck.getKeyword<IMPORT>(import_index);
const auto& fname = import_keyword.getRecord(0).getItem<IMPORT::FILE>().get<std::string>(0);
copy_file(input_arg.parent_path(), fname, output_dir);
}
using PYACTION = Opm::ParserKeywords::PYACTION;
for (const auto& pyaction_keyword : deck.get<PYACTION>()) {
for (std::size_t pyaction_index = 0; pyaction_index < deck.count<PYACTION>(); pyaction_index++) {
const auto& pyaction_keyword = deck.getKeyword<PYACTION>(pyaction_index);
const auto& fname = pyaction_keyword.getRecord(1).getItem<PYACTION::FILENAME>().get<std::string>(0);
copy_file(input_arg.parent_path(), fname, output_dir);
}
@@ -171,7 +171,7 @@ int main(int argc, char** argv) {
using GDFILE = Opm::ParserKeywords::GDFILE;
if (deck.hasKeyword<GDFILE>()) {
const auto& gdfile_keyword = deck.get<GDFILE>().back();
const auto& gdfile_keyword = deck.getKeyword<GDFILE>();
const auto& fname = gdfile_keyword.getRecord(0).getItem<GDFILE::filename>().get<std::string>(0);
copy_file(input_arg.parent_path(), fname, output_dir);
}

View File

@@ -18,30 +18,28 @@
*/
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <getopt.h>
#include <fmt/format.h>
#include <unordered_set>
#include <utility>
#include <opm/input/eclipse/Deck/DeckKeyword.hpp>
#include <opm/input/eclipse/Units/UnitSystem.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/I.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/P.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/G.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/R.hpp>
#include <opm/input/eclipse/Parser/ParserKeywords/S.hpp>
#include <opm/input/eclipse/Parser/Parser.hpp>
#include <opm/input/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Parser/ParseContext.hpp>
#include <opm/input/eclipse/Parser/InputErrorAction.hpp>
#include <opm/input/eclipse/EclipseState/IOConfig/IOConfig.hpp>
#include <opm/input/eclipse/Deck/Deck.hpp>
#include <opm/input/eclipse/Deck/FileDeck.hpp>
#include <opm/parser/eclipse/Deck/DeckKeyword.hpp>
#include <opm/common/utility/FileSystem.hpp>
#include <opm/parser/eclipse/Units/UnitSystem.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/I.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/P.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/G.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/R.hpp>
#include <opm/parser/eclipse/Parser/ParserKeywords/S.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ErrorGuard.hpp>
#include <opm/parser/eclipse/Parser/ParseContext.hpp>
#include <opm/parser/eclipse/Parser/InputErrorAction.hpp>
#include <opm/parser/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/Deck/FileDeck.hpp>
namespace fs = std::filesystem;
namespace fs = Opm::filesystem;
const std::unordered_set<std::string> remove_from_solution = {"EQUIL", "PRESSURE", "SWAT", "SGAS"};
@@ -65,7 +63,7 @@ output the program will update the SOLUTION and SCHEDULE sections. All keywords
from the SOLUTION section will be cleared out(1) and a RESTART keyword will be
inserted. In the SCHEDULE section the program can either remove all keywords up
until the restart date, or alternatively insert SKIPREST immediately following
the SCHEDULE keyword.
the SCHEDULE keyword(2).
When creating the updated restart deck the program can either link to unmodified
include files with INCLUDE statements, create a copy of deck structure in an
@@ -78,35 +76,9 @@ Arguments:
1. The data file we are starting with.
2. The restart source; this can either be a basename with an optional path
prefix and a :N to restart from step N; alternatively you can point to an
existing restart file. If you point to an existing restart file the input
will be validated in several ways:
a) Unified/multiple files will be checked against the UNIFIN setting of
the deck.
b) Formatted/unformatted will be checked against the FMTIn setting of the
deck.
c) If a single file like /path/to/case/HISTORY.X0067 is given as argument the
:N notation to denote report step should not be used.
If the restart argument is given as the path to an existing file the content
of the RESTART keyword will be updated to contain the correct path from the
location of the restart deck to the location of the restart file. This path
awareness will be fooled if the restart deck is redirected from stdout to a
path different from cwd. If the restart argument is given as an absolute
filename the RESTART keyword will have an absolute path, if the restart
argument is a relative path the RESTART keyword will get a relative path -
although an absolute path will be used if the restart file and the output
deck have different roots. If the restart argument is given as a string not
pointing to an existing file it will be inserted verbatim in the restart
deck.
A restart step value of 0 is interpreted as a dry run - a deck which has not
been set up for restart will be written out.
2. The basename of the restart file - with an optional path prefix and a :N to
restart from step N(3). A restart step value of 0 is interpreted as a dry run
- a deck which has not been set up for restart will be written out.
3. Basename of the restart deck we create, can optionally contain a path prefix;
the path will be created if it does not already exist. This argument is
@@ -119,7 +91,7 @@ Options:
-s: Manipulate the SCHEDULE section by inserting a SKIPREST keyword immediately
following the SCHEDULE keyword. If the -s option is not used the SCHEDULE
section will be modified by removing all keywords until we reach the restart
date.
date. NB: Currently the -s option is required
-m: [share|inline|copy] The restart deck can reuse the unmodified include files
from the base case, this is mode 'share' and is the default. With mode
@@ -130,7 +102,7 @@ Options:
In the case of 'share' and 'copy' the correct path to include files will be
negotiated based on the path given to the output case in the third argument.
If the restart deck is passed to stdout the include files will be resolved
based on output in cwd.
based on output in cwd.
Example:
@@ -139,6 +111,14 @@ Example:
1: The program has a compiled list of keywords which will be retained in the
SOLUTION section. The current value of that list is: {}
2: Current version of the program *only* supports the SKIPREST option, and the
-s option is required.
3: The second argument is treated purely as a string and inserted verbatim into
the updated restart deck. In a future version we might interpret the second
argument as a file path and check the content and also do filesystem
manipulations from it.
)", keep_keywords);
std::cerr << help_text << std::endl;
@@ -150,29 +130,28 @@ Example:
struct Options {
struct options {
std::string input_deck;
std::string restart_base;
int restart_step;
std::optional<std::string> target_path;
std::optional<std::string> target_fname;
std::pair<std::string, int> restart;
std::optional<std::string> target;
Opm::FileDeck::OutputMode mode{Opm::FileDeck::OutputMode::SHARE};
bool skiprest{false};
};
Opm::Deck load_deck(const Options& opt) {
Opm::ParseContext parseContext(Opm::InputErrorAction::WARN);
Opm::FileDeck load_deck(const options& opt) {
Opm::ParseContext parseContext(Opm::InputError::WARN);
Opm::ErrorGuard errors;
Opm::Parser parser;
/* Use the same default ParseContext as flow. */
parseContext.update(Opm::ParseContext::PARSE_RANDOM_SLASH, Opm::InputErrorAction::IGNORE);
parseContext.update(Opm::ParseContext::PARSE_MISSING_DIMS_KEYWORD, Opm::InputErrorAction::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_WELL, Opm::InputErrorAction::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_GROUP, Opm::InputErrorAction::WARN);
return parser.parseFile(opt.input_deck, parseContext, errors);
parseContext.update(Opm::ParseContext::PARSE_RANDOM_SLASH, Opm::InputError::IGNORE);
parseContext.update(Opm::ParseContext::PARSE_MISSING_DIMS_KEYWORD, Opm::InputError::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_WELL, Opm::InputError::WARN);
parseContext.update(Opm::ParseContext::SUMMARY_UNKNOWN_GROUP, Opm::InputError::WARN);
auto deck = parser.parseFile(opt.input_deck, parseContext, errors);
return Opm::FileDeck{ deck };
}
@@ -190,86 +169,17 @@ Opm::FileDeck::OutputMode mode(const std::string& mode_arg) {
return Opm::FileDeck::OutputMode::INLINE;
}
std::optional<std::size_t> verify_extension(const std::string& extension, bool unified, bool formatted) {
if (unified) {
if (formatted) {
if (extension == ".FUNRST")
return std::nullopt;
print_help_and_exit("Deck has specified formatted unified input - expected restart extension: .FUNRST");
std::pair<std::string, std::size_t> split_restart(const std::string& restart_base) {
auto sep_pos = restart_base.rfind(':');
if (sep_pos == std::string::npos)
print_help_and_exit(fmt::format("Expected restart argument on the form: BASE:NUMBER - e.g. HISTORY:60"));
}
if (extension == ".UNRST")
return std::nullopt;
print_help_and_exit("Deck has expected unformatted unified input - expected restart extension: .UNRST");
}
std::size_t report_step;
if ((formatted && (extension[1] == 'F')) || (!formatted && (extension[1] == 'X'))) {
try {
report_step = std::stoi(extension.substr(2));
return report_step;
}
catch (...) {}
}
print_help_and_exit("Deck has specified multiple input files - expected restart extension: .Xnnnn / .Fnnnn");
return std::nullopt;
return std::make_pair(restart_base.substr(0, sep_pos), std::stoi(restart_base.substr(sep_pos + 1)));
}
bool same_mount(const fs::path& p1, const fs::path& p2) {
auto abs1 = fs::absolute(p1);
auto abs2 = fs::absolute(p2);
auto iter1 = abs1.begin(); iter1++;
auto iter2 = abs2.begin(); iter2++;
auto mnt1 = *iter1;
auto mnt2 = *iter2;
return (mnt1 == mnt2);
}
void update_restart_path(Options& opt, const std::string& restart_arg, const Opm::IOConfig& io_config) {
std::string base;
std::optional<std::size_t> rst_step;
auto sep_pos = restart_arg.rfind(':');
auto base_arg = restart_arg.substr(0, sep_pos);
if (fs::exists(base_arg)) {
auto unif = io_config.getUNIFIN();
auto fmt = io_config.getFMTIN();
auto path = fs::path(base_arg);
auto extension = path.extension();
rst_step = verify_extension(extension, unif, fmt);
if (path.is_absolute()) {
path.replace_extension();
base = path;
} else {
auto target_path = fs::current_path();
if (opt.target_path.has_value())
target_path = fs::path(opt.target_path.value());
if (same_mount(path, target_path))
base = fs::relative(path, target_path).replace_extension();
else
base = fs::canonical(fs::absolute(path)).replace_extension();
}
} else
base = base_arg;
if (!rst_step.has_value()) {
if (sep_pos == std::string::npos)
print_help_and_exit(fmt::format("Expected restart argument on the form: BASE:NUMBER - e.g. HISTORY:60"));
rst_step = std::stoi(restart_arg.substr(sep_pos + 1));
}
opt.restart_step = rst_step.value();
opt.restart_base = base;
}
std::pair<Options, std::string> load_options(int argc, char **argv) {
Options opt;
options load_options(int argc, char **argv) {
options opt;
while (true) {
int c;
c = getopt(argc, argv, "hm:s");
@@ -294,21 +204,11 @@ std::pair<Options, std::string> load_options(int argc, char **argv) {
print_help_and_exit();
opt.input_deck = argv[arg_offset];
std::string restart_arg = argv[arg_offset + 1];
opt.restart = split_restart(argv[arg_offset + 1]);
if ((argc - arg_offset) >= 3) {
auto target_arg = argv[arg_offset + 2];
if (fs::is_directory(target_arg)) {
opt.target_path = target_arg;
opt.target_fname = fs::path(opt.input_deck).filename();
} else {
auto target_path = fs::path( fs::absolute(target_arg) );
opt.target_path = fs::absolute(target_path.parent_path());
opt.target_fname = target_path.filename();
}
opt.target = argv[arg_offset + 2];
if (opt.mode == Opm::FileDeck::OutputMode::COPY) {
auto target = fs::path(target_arg).parent_path();
auto target = fs::path(opt.target.value()).parent_path();
if (fs::exists(target)) {
auto input = fs::path(opt.input_deck).parent_path();
if (fs::equivalent(target, input))
@@ -320,13 +220,13 @@ std::pair<Options, std::string> load_options(int argc, char **argv) {
print_help_and_exit("When writing output to stdout you must use inline|share mode");
}
return {opt, restart_arg};
return opt;
}
void update_solution(const Options& opt, Opm::FileDeck& file_deck)
void update_solution(const options& opt, Opm::FileDeck& file_deck)
{
if (opt.restart_step == 0)
if (opt.restart.second == 0)
return;
const auto solution = file_deck.find("SOLUTION");
@@ -337,33 +237,35 @@ void update_solution(const Options& opt, Opm::FileDeck& file_deck)
if (!summary.has_value())
print_help_and_exit(fmt::format("Could not find SUMMARY section in input deck: {}", opt.input_deck));
file_deck.rst_solution(opt.restart_base, opt.restart_step);
file_deck.rst_solution(opt.restart.first, opt.restart.second);
}
void update_schedule(const Options& opt, Opm::FileDeck& file_deck)
void update_schedule(const options& opt, Opm::FileDeck& file_deck)
{
if (opt.restart_step == 0)
if (opt.restart.second == 0)
return;
if (opt.skiprest)
file_deck.insert_skiprest();
else
file_deck.skip(opt.restart_step);
}
int main(int argc, char** argv) {
auto [options, restart_arg] = load_options(argc, argv);
auto deck = load_deck(options);
Opm::FileDeck file_deck(deck);
update_restart_path(options, restart_arg, Opm::IOConfig(deck));
auto options = load_options(argc, argv);
auto file_deck = load_deck(options);
update_solution(options, file_deck);
update_schedule(options, file_deck);
if (!options.target_path.has_value())
if (!options.target.has_value())
file_deck.dump_stdout(fs::current_path(), options.mode);
else
file_deck.dump( options.target_path.value(), options.target_fname.value(), options.mode);
else {
std::string target = options.target.value();
if (fs::is_directory(target))
file_deck.dump( fs::absolute(target), fs::path(options.input_deck).filename(), options.mode );
else {
auto target_path = fs::path( fs::absolute(options.target.value()) );
file_deck.dump( fs::absolute(target_path.parent_path()), target_path.filename(), options.mode );
}
}
}

View File

@@ -17,30 +17,24 @@
along with OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <chrono>
#include <sstream>
#include <opm/input/eclipse/Deck/Deck.hpp>
#include <opm/input/eclipse/EclipseState/EclipseState.hpp>
#include <opm/input/eclipse/Parser/ErrorGuard.hpp>
#include <opm/input/eclipse/Parser/InputErrorAction.hpp>
#include <opm/input/eclipse/Parser/Parser.hpp>
#include <opm/input/eclipse/Parser/ParseContext.hpp>
#include <opm/input/eclipse/Python/Python.hpp>
#include <opm/input/eclipse/Schedule/Schedule.hpp>
#include <opm/input/eclipse/Schedule/Well/Well.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ParseContext.hpp>
#include <opm/parser/eclipse/Parser/ErrorGuard.hpp>
#include <opm/parser/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/EclipseState.hpp>
#include <opm/parser/eclipse/EclipseState/Schedule/Schedule.hpp>
#include <opm/parser/eclipse/Python/Python.hpp>
#include <opm/common/OpmLog/OpmLog.hpp>
#include <opm/common/OpmLog/StreamLog.hpp>
#include <opm/common/OpmLog/LogUtil.hpp>
#include <opm/common/utility/FileSystem.hpp>
inline void createDot(const Opm::Schedule& schedule, const std::string& casename)
@@ -91,16 +85,15 @@ inline void createDot(const Opm::Schedule& schedule, const std::string& casename
}
os << "}\n";
std::cout << "complete." << std::endl;
std::cout << "Convert output to PDF with 'dot -Tpdf " << casename << ".gv > " << casename << ".pdf'\n" << std::endl;
}
inline Opm::Schedule loadSchedule(const std::string& deck_file)
{
Opm::ParseContext parseContext({{Opm::ParseContext::PARSE_RANDOM_SLASH, Opm::InputErrorAction::IGNORE},
{Opm::ParseContext::PARSE_MISSING_DIMS_KEYWORD, Opm::InputErrorAction::WARN},
{Opm::ParseContext::SUMMARY_UNKNOWN_WELL, Opm::InputErrorAction::WARN},
{Opm::ParseContext::SUMMARY_UNKNOWN_GROUP, Opm::InputErrorAction::WARN}});
Opm::ParseContext parseContext({{Opm::ParseContext::PARSE_RANDOM_SLASH, Opm::InputError::IGNORE},
{Opm::ParseContext::PARSE_MISSING_DIMS_KEYWORD, Opm::InputError::WARN},
{Opm::ParseContext::SUMMARY_UNKNOWN_WELL, Opm::InputError::WARN},
{Opm::ParseContext::SUMMARY_UNKNOWN_GROUP, Opm::InputError::WARN}});
Opm::ErrorGuard errors;
Opm::Parser parser;
auto python = std::make_shared<Opm::Python>();
@@ -130,7 +123,7 @@ int main(int argc, char** argv)
for (int iarg = 1; iarg < argc; iarg++) {
const std::string filename = argv[iarg];
const auto sched = loadSchedule(filename);
const auto casename = std::filesystem::path(filename).stem();
const auto casename = Opm::filesystem::path(filename).stem();
createDot(sched, casename);
}
} catch (const std::exception& e) {

View File

@@ -1,401 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
//##################################################################################################
#include "../CommonCode/cvfStructGrid.h"
#include "../LibCore/cvfBase.h"
// namespace caf
// {
// template <>
// void cvf::StructGridInterface::FaceEnum::setUp()
// {
// addItem( cvf::StructGridInterface::POS_I, "POS I", "" );
// addItem( cvf::StructGridInterface::NEG_I, "NEG I", "" );
// addItem( cvf::StructGridInterface::POS_J, "POS J", "" );
// addItem( cvf::StructGridInterface::NEG_J, "NEG J", "" );
// addItem( cvf::StructGridInterface::POS_K, "POS K", "" );
// addItem( cvf::StructGridInterface::NEG_K, "NEG K", "" );
// addItem( cvf::StructGridInterface::NO_FACE, "UnDef", "" );
// }
// } // namespace caf
namespace external
{
namespace cvf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
StructGridInterface::StructGridInterface()
{
m_characteristicCellSizeI = cvf::UNDEFINED_DOUBLE;
m_characteristicCellSizeJ = cvf::UNDEFINED_DOUBLE;
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;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridInterface::cellFaceVertexIndices( FaceType face, cvf::ubyte vertexIndices[4] )
{
//
// 7---------6
// /| /| |k
// / | / | | /j
// 4---------5 | |/
// | 3------|--2 *---i
// | / | /
// |/ |/
// 0---------1
if ( face == NEG_K )
{
vertexIndices[0] = 0;
vertexIndices[1] = 3;
vertexIndices[2] = 2;
vertexIndices[3] = 1;
}
else if ( face == POS_K )
{
vertexIndices[0] = 4;
vertexIndices[1] = 5;
vertexIndices[2] = 6;
vertexIndices[3] = 7;
}
else if ( face == NEG_J )
{
vertexIndices[0] = 0;
vertexIndices[1] = 1;
vertexIndices[2] = 5;
vertexIndices[3] = 4;
}
else if ( face == POS_I )
{
vertexIndices[0] = 1;
vertexIndices[1] = 2;
vertexIndices[2] = 6;
vertexIndices[3] = 5;
}
else if ( face == POS_J )
{
vertexIndices[0] = 3;
vertexIndices[1] = 7;
vertexIndices[2] = 6;
vertexIndices[3] = 2;
}
else if ( face == NEG_I )
{
vertexIndices[0] = 0;
vertexIndices[1] = 4;
vertexIndices[2] = 7;
vertexIndices[3] = 3;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::pair<ubyte, ubyte> StructGridInterface::edgeVertexIndices( FaceType face1, FaceType face2 )
{
// Return the two shared vertex indices between two faces
// The ordering is identical to the ordering in StructGridInterface::cellFaceVertexIndices
// Ensure face1 has the largest enum value
if ( face2 > face1 ) std::swap( face1, face2 );
if ( face1 == NEG_K )
{
if ( face2 == NEG_I ) return { 0, 3 };
if ( face2 == POS_I ) return { 2, 1 };
if ( face2 == NEG_J ) return { 1, 0 };
if ( face2 == POS_J ) return { 3, 2 };
}
if ( face1 == POS_K )
{
if ( face2 == NEG_I ) return { 7, 4 };
if ( face2 == POS_I ) return { 5, 6 };
if ( face2 == NEG_J ) return { 4, 5 };
if ( face2 == POS_J ) return { 6, 7 };
}
if ( face1 == NEG_J )
{
if ( face2 == NEG_I ) return { 4, 0 };
if ( face2 == POS_I ) return { 1, 5 };
}
if ( face1 == POS_J )
{
if ( face2 == NEG_I ) return { 3, 7 };
if ( face2 == POS_I ) return { 6, 2 };
}
return {};
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
StructGridInterface::FaceType StructGridInterface::oppositeFace( FaceType face )
{
FaceType opposite;
switch ( face )
{
case NEG_I:
opposite = POS_I;
break;
case POS_I:
opposite = NEG_I;
break;
case NEG_J:
opposite = POS_J;
break;
case POS_J:
opposite = NEG_J;
break;
case NEG_K:
opposite = POS_K;
break;
case POS_K:
opposite = NEG_K;
break;
default:
opposite = POS_I;
CVF_ASSERT( false );
}
return opposite;
}
//--------------------------------------------------------------------------------------------------
/// Return values are set to cvf::UNDEFINED_SIZE_T if the neighbor is in the negative area
//--------------------------------------------------------------------------------------------------
void StructGridInterface::neighborIJKAtCellFace( size_t i, size_t j, size_t k, FaceType face, size_t* ni, size_t* nj, size_t* nk )
{
*ni = i;
*nj = j;
*nk = k;
switch ( face )
{
case POS_I:
( *ni )++;
break;
case NEG_I:
if ( i > 0 )
( *ni )--;
else
( *ni ) = cvf::UNDEFINED_SIZE_T;
break;
case POS_J:
( *nj )++;
break;
case NEG_J:
if ( j > 0 )
( *nj )--;
else
( *nj ) = cvf::UNDEFINED_SIZE_T;
break;
case POS_K:
( *nk )++;
break;
case NEG_K:
if ( k > 0 )
( *nk )--;
else
( *nk ) = cvf::UNDEFINED_SIZE_T;
break;
default:
break;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
StructGridInterface::GridAxisType StructGridInterface::gridAxisFromFace( FaceType face )
{
GridAxisType axis = GridAxisType::NO_AXIS;
if ( face == cvf::StructGridInterface::POS_I || face == cvf::StructGridInterface::NEG_I )
{
axis = GridAxisType::AXIS_I;
}
else if ( face == cvf::StructGridInterface::POS_J || face == cvf::StructGridInterface::NEG_J )
{
axis = GridAxisType::AXIS_J;
}
else if ( face == cvf::StructGridInterface::POS_K || face == cvf::StructGridInterface::NEG_K )
{
axis = GridAxisType::AXIS_K;
}
return axis;
}
//--------------------------------------------------------------------------------------------------
/// Models with large absolute values for coordinate scalars will often end up with z-fighting due
/// to numerical limits in float used by OpenGL. displayModelOffset() is intended
// to be subtracted from a domain model coordinate when building geometry
//
// Used in StructGridGeometryGenerator::computeArrays()
//
// Vec3d domainModelCoord = ...
// Vec3d vizCoord = domainModelCoord - displayModelOffset();
//--------------------------------------------------------------------------------------------------
cvf::Vec3d StructGridInterface::displayModelOffset() const
{
return cvf::Vec3d::ZERO;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridInterface::characteristicCellSizes( double* iSize, double* jSize, double* kSize ) const
{
CVF_ASSERT( iSize && jSize && kSize );
if ( m_characteristicCellSizeI == cvf::UNDEFINED_DOUBLE || m_characteristicCellSizeJ == cvf::UNDEFINED_DOUBLE ||
m_characteristicCellSizeK == cvf::UNDEFINED_DOUBLE )
{
ubyte faceConnPosI[4];
cellFaceVertexIndices( StructGridInterface::POS_I, faceConnPosI );
ubyte faceConnNegI[4];
cellFaceVertexIndices( StructGridInterface::NEG_I, faceConnNegI );
ubyte faceConnPosJ[4];
cellFaceVertexIndices( StructGridInterface::POS_J, faceConnPosJ );
ubyte faceConnNegJ[4];
cellFaceVertexIndices( StructGridInterface::NEG_J, faceConnNegJ );
ubyte faceConnPosK[4];
cellFaceVertexIndices( StructGridInterface::POS_K, faceConnPosK );
ubyte faceConnNegK[4];
cellFaceVertexIndices( StructGridInterface::NEG_K, faceConnNegK );
double iLengthAccumulated = 0.0;
double jLengthAccumulated = 0.0;
double kLengthAccumulated = 0.0;
cvf::Vec3d cornerVerts[8];
size_t cellCount = 0;
size_t k;
for ( k = 0; k < cellCountK(); k++ )
{
size_t j;
for ( j = 0; j < cellCountJ(); j++ )
{
size_t i;
for ( i = 0; i < cellCountI(); i += 10 ) // NB! Evaluate every n-th cell
{
if ( isCellValid( i, j, k ) )
{
size_t cellIndex = cellIndexFromIJK( i, j, k );
cellCornerVertices( cellIndex, cornerVerts );
iLengthAccumulated +=
( cornerVerts[faceConnPosI[0]] - cornerVerts[faceConnNegI[0]] ).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[1]] - cornerVerts[faceConnNegI[3]] ).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[2]] - cornerVerts[faceConnNegI[2]] ).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[3]] - cornerVerts[faceConnNegI[1]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[0]] - cornerVerts[faceConnNegJ[0]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[1]] - cornerVerts[faceConnNegJ[3]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[2]] - cornerVerts[faceConnNegJ[2]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[3]] - cornerVerts[faceConnNegJ[1]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[0]] - cornerVerts[faceConnNegK[0]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[1]] - cornerVerts[faceConnNegK[3]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[2]] - cornerVerts[faceConnNegK[2]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[3]] - cornerVerts[faceConnNegK[1]] ).lengthSquared();
cellCount++;
}
}
}
}
double divisor = cellCount * 4.0;
if ( divisor > 0.0 )
{
m_characteristicCellSizeI = cvf::Math::sqrt( iLengthAccumulated / divisor );
m_characteristicCellSizeJ = cvf::Math::sqrt( jLengthAccumulated / divisor );
m_characteristicCellSizeK = cvf::Math::sqrt( kLengthAccumulated / divisor );
}
}
*iSize = m_characteristicCellSizeI;
*jSize = m_characteristicCellSizeJ;
*kSize = m_characteristicCellSizeK;
}
} // namespace cvf
} //namespace external

View File

@@ -1,135 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "../LibCore/cvfObject.h"
#include "../LibCore/cvfVector3.h"
#include <cstddef>
// #include "../cafPdmCore/cafAppEnum.h"
namespace external
{
namespace cvf
{
class CellFilterBase;
// Navneforslag
// StructGridGeometryGeneratorInterface
// Main purpose of this class is to define the interface to be used by geometry generators
class StructGridInterface : public Object
{
public:
enum FaceType
{
POS_I,
NEG_I,
POS_J,
NEG_J,
POS_K,
NEG_K,
NO_FACE
};
// typedef caf::AppEnum<StructGridInterface::FaceType> FaceEnum;
enum class GridAxisType
{
AXIS_I,
AXIS_J,
AXIS_K,
NO_AXIS
};
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 bool isCellValid( size_t i, size_t j, size_t k ) const = 0;
virtual cvf::Vec3d minCoordinate() const = 0;
virtual cvf::Vec3d maxCoordinate() const = 0;
void characteristicCellSizes( double* iSize, double* jSize, double* kSize ) const;
virtual cvf::Vec3d displayModelOffset() const;
virtual bool cellIJKNeighbor( size_t i, size_t j, size_t k, FaceType face, size_t* neighborCellIndex ) const = 0;
virtual size_t cellIndexFromIJK( size_t i, size_t j, size_t k ) const = 0;
virtual bool ijkFromCellIndex( size_t cellIndex, size_t* i, size_t* j, size_t* k ) const = 0;
virtual bool cellIJKFromCoordinate( const cvf::Vec3d& coord, size_t* i, size_t* j, size_t* k ) const = 0;
virtual void cellCornerVertices( size_t cellIndex, cvf::Vec3d vertices[8] ) const = 0;
virtual cvf::Vec3d cellCentroid( size_t cellIndex ) const = 0;
virtual void cellMinMaxCordinates( size_t cellIndex, cvf::Vec3d* minCoordinate, cvf::Vec3d* maxCoordinate ) const = 0;
virtual size_t gridPointIndexFromIJK( size_t i, size_t j, size_t k ) const = 0;
virtual cvf::Vec3d gridPointCoordinate( size_t i, size_t j, size_t k ) const = 0;
public:
static void cellFaceVertexIndices( FaceType face, cvf::ubyte vertexIndices[4] );
static FaceType oppositeFace( FaceType face );
static void neighborIJKAtCellFace( size_t i,
size_t j,
size_t k,
StructGridInterface::FaceType face,
size_t* ni,
size_t* nj,
size_t* nk );
static GridAxisType gridAxisFromFace( FaceType face );
static std::pair<ubyte, ubyte> edgeVertexIndices( cvf::StructGridInterface::FaceType face1,
cvf::StructGridInterface::FaceType face2 );
private:
mutable double m_characteristicCellSizeI;
mutable double m_characteristicCellSizeJ;
mutable double m_characteristicCellSizeK;
};
} // namespace cvf
} //namespace external

View File

@@ -1,153 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfObject.h"
#include "cvfValueArray.h"
#include <vector>
namespace external
{
namespace cvf {
//==================================================================================================
//
// Templated array designed for high performance and no overhead over C arrays.
//
//==================================================================================================
template <typename T>
class Array : public Object, public ValueArray<T>
{
public:
Array();
Array(const Array& other);
Array(const T* data, size_t size);
explicit Array(size_t size);
explicit Array(const ValueArray<T>& other);
explicit Array(const std::vector<T>& other);
~Array();
inline const T& operator[](size_t index) const;
inline T& operator[](size_t index);
Array& operator=(Array rhs);
void assign(const T* data, size_t size);
void assign(const std::vector<T>& data);
void resize(size_t size);
void clear();
inline virtual size_t size() const;
inline void set(size_t index, const T& val);
inline void setAll(const T& val);
inline void setConsecutive(const T& startVal);
inline const T& get(size_t index) const;
inline virtual T val(size_t index) const;
inline const T* ptr() const;
inline T* ptr();
inline const T* ptr(size_t index) const;
inline T* ptr(size_t index);
void setSharedPtr(T* data, size_t size);
void setPtr(T* data, size_t size);
void copyData(const T* source, size_t numElementsToCopy, size_t destIndex);
void copyData(const Array<T>& source, size_t numElementsToCopy, size_t destIndex, size_t sourceIndex);
template<typename U>
void copyConvertedData(const Array<U>& source, size_t numElementsToCopy, size_t destIndex, size_t sourceIndex);
template<typename U>
ref<Array<T> > extractElements(const Array<U>& elementIndices) const;
void toStdVector(std::vector<T>* vec) const;
size_t capacity() const;
void reserve(size_t capacity);
void squeeze();
void setSizeZero();
inline void add(const T& val);
T min(size_t* index = 0) const;
T max(size_t* index = 0) const;
void swap(Array& other);
// Basic iterator support to be able to utilize STL algorithms
public:
typedef T* iterator;
typedef const T* const_iterator;
inline iterator begin() { return m_data; }
inline iterator end() { return m_data + m_size; }
inline const_iterator begin() const { return m_data; }
inline const_iterator end() const { return m_data + m_size; }
private:
void ground();
private:
size_t m_size; ///< Number of elements/items in array
size_t m_capacity; ///< Size of the allocated buffer
T* m_data; ///< Array holding the actual data
bool m_sharedData; ///< True if the data member is shared with another object and cannot be changed
};
// Only works for simple types that don't require copy operators.
typedef Array<int> IntArray;
typedef Array<uint> UIntArray;
typedef Array<ushort> UShortArray;
typedef Array<ubyte> UByteArray;
typedef Array<float> FloatArray;
typedef Array<double> DoubleArray;
typedef Array<Vec2f> Vec2fArray;
typedef Array<Vec2d> Vec2dArray;
typedef Array<Vec3f> Vec3fArray;
typedef Array<Vec3d> Vec3dArray;
typedef Array<Vec4f> Vec4fArray;
typedef Array<Vec4d> Vec4dArray;
typedef Array<Color3ub> Color3ubArray;
typedef Array<Color3f> Color3fArray;
typedef Array<Color4ub> Color4ubArray;
}
} //namespace external
#include "cvfArray.inl"

View File

@@ -1,785 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
namespace external
{
namespace cvf {
//==================================================================================================
///
/// \class cvf::Array
/// \ingroup Core
///
/// Templated version of a simple array designed for high performance and no overhead over C arrays
/// in release (non-check builds).
///
/// Will only work on simple types and classes that do not rely on a constructor or
/// destructor (as they are not called).
///
//==================================================================================================
//--------------------------------------------------------------------------------------------------
/// Create an empty array
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::Array()
{
ground();
}
//--------------------------------------------------------------------------------------------------
/// Create an array with the given number of elements
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::Array(size_t size)
{
CVF_ASSERT(size > 0);
ground();
resize(size);
}
//--------------------------------------------------------------------------------------------------
/// Create the array and assign (copy) the given data
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::Array(const T* data, size_t size)
{
CVF_ASSERT(data);
CVF_ASSERT(size > 0);
ground();
assign(data, size);
}
//--------------------------------------------------------------------------------------------------
/// Create the array and assign (copy) the given data
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::Array(const Array& other)
: Object(), ValueArray<T>()
{
ground();
if (other.size() > 0)
{
assign(other.m_data, other.size());
}
}
//--------------------------------------------------------------------------------------------------
/// Explicit constructor to create the array and assign (copy) the passed value array
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::Array(const ValueArray<T>& other)
{
ground();
if (other.size() > 0)
{
resize(other.size());
size_t i;
for (i = 0; i < other.size(); i++)
{
set(i, other.val(i));
}
}
}
//--------------------------------------------------------------------------------------------------
/// Explicit constructor to create the array and assign (copy) the passed std::vector
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::Array(const std::vector<T>& other)
{
ground();
if (other.size() > 0)
{
assign(other);
}
}
//--------------------------------------------------------------------------------------------------
/// Init all members
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::ground()
{
m_size = 0;
m_data = NULL;
m_capacity = 0;
m_sharedData = false;
}
//--------------------------------------------------------------------------------------------------
/// Destructor. Deletes the data.
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>::~Array()
{
clear();
}
//--------------------------------------------------------------------------------------------------
/// Returns a const reference to the element at the given index.
//--------------------------------------------------------------------------------------------------
template <typename T>
inline const T& Array<T>::operator[] (size_t index) const
{
CVF_TIGHT_ASSERT(m_data);
CVF_TIGHT_ASSERT(index < m_size);
return m_data[index];
}
//--------------------------------------------------------------------------------------------------
/// Returns a modifiable reference to the element at the given index.
//--------------------------------------------------------------------------------------------------
template <typename T>
inline T& Array<T>::operator[] (size_t index)
{
CVF_TIGHT_ASSERT(m_data);
CVF_TIGHT_ASSERT(index < m_size);
return m_data[index];
}
//--------------------------------------------------------------------------------------------------
/// Assign (copy) the data in the given array
//--------------------------------------------------------------------------------------------------
template <typename T>
Array<T>& Array<T>::operator=(Array rhs)
{
CVF_TIGHT_ASSERT(!m_sharedData);
rhs.swap(*this);
return *this;
}
//--------------------------------------------------------------------------------------------------
/// Resize the array to the given size.
/// The current contents (data) will be kept (as much as possible). Any new elements will be unassigned.
/// Calling resize(0) is the same as clear().
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::resize(size_t size)
{
CVF_ASSERT(!m_sharedData);
if (size > 0)
{
if (m_data)
{
// Copy old data
T* pTmp = m_data;
m_data = new T[size];
size_t numToCopy = CVF_MIN(size, m_size);
cvf::System::memcpy(m_data, size*sizeof(T), pTmp, numToCopy*sizeof(T));
delete[] pTmp;
}
else
{
m_data = new T[size];
}
m_size = size;
m_capacity = size;
}
else
{
clear();
}
}
//--------------------------------------------------------------------------------------------------
/// Clear the array, freeing all memory (if not shared) and setting capacity and size to zero.
/// If the array was in shared mode, it will not be in shared mode anymore.
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::clear()
{
if (!m_sharedData)
{
delete[] m_data;
}
ground();
}
//--------------------------------------------------------------------------------------------------
/// Returns the number of elements in the array
//--------------------------------------------------------------------------------------------------
template <typename T>
inline size_t Array<T>::size() const
{
return m_size;
}
//--------------------------------------------------------------------------------------------------
/// Set the element at the given index. Index must be < size()
//--------------------------------------------------------------------------------------------------
template <typename T>
inline void Array<T>::set(size_t index, const T& val)
{
CVF_TIGHT_ASSERT(index < m_size);
m_data[index] = val;
}
//--------------------------------------------------------------------------------------------------
/// Set all elements in the array to the given value
//--------------------------------------------------------------------------------------------------
template <typename T>
inline void Array<T>::setAll(const T& val)
{
size_t i;
for (i = 0; i < m_size; i++)
{
set(i, val);
}
}
//--------------------------------------------------------------------------------------------------
/// Assign consecutive values to the elements in the array
///
/// Example: setConsecutive(2) on an array with size=3 gives: {2,3,4}
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::setConsecutive(const T& startValue)
{
T val = startValue;
size_t i;
for (i = 0; i < m_size; i++)
{
set(i, val++);
}
}
//--------------------------------------------------------------------------------------------------
/// Returns a const reference to the element at the given index
//--------------------------------------------------------------------------------------------------
template <typename T>
const T& cvf::Array<T>::get(size_t index) const
{
CVF_TIGHT_ASSERT(index < m_size);
return m_data[index];
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename T>
T cvf::Array<T>::val(size_t index) const
{
CVF_TIGHT_ASSERT(index < m_size);
return m_data[index];
}
//--------------------------------------------------------------------------------------------------
/// Returns a const native pointer to the array storing the data
//--------------------------------------------------------------------------------------------------
template <typename T>
inline const T* Array<T>::ptr() const
{
return m_data;
}
//--------------------------------------------------------------------------------------------------
/// Returns the native pointer to the array storing the data
//--------------------------------------------------------------------------------------------------
template <typename T>
inline T* Array<T>::ptr()
{
return m_data;
}
//--------------------------------------------------------------------------------------------------
/// Returns a const native pointer to the array storing the data
//--------------------------------------------------------------------------------------------------
template <typename T>
inline const T* Array<T>::ptr(size_t index) const
{
CVF_TIGHT_ASSERT(index < m_size);
return &m_data[index];
}
//--------------------------------------------------------------------------------------------------
/// Returns the native pointer to the array storing the data
//--------------------------------------------------------------------------------------------------
template <typename T>
inline T* Array<T>::ptr(size_t index)
{
CVF_TIGHT_ASSERT(index < m_size);
return &m_data[index];
}
//--------------------------------------------------------------------------------------------------
/// Data shared with another class. Will not delete on destruction.
///
/// Any method that reallocates data (resize, assign & setPtr) is not allowed and will assert
/// The only way to break the shared 'connection' is via clear()
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::setSharedPtr(T* data, size_t size)
{
CVF_ASSERT((data && size > 0) || (!data && size == 0));
clear();
m_data = data;
m_size = size;
m_sharedData = true;
}
//--------------------------------------------------------------------------------------------------
/// Set the data in the array to use the passed array.
///
/// This class takes ownership of the passed data.
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::setPtr(T* data, size_t size)
{
CVF_ASSERT((data && size > 0) || (!data && size == 0));
// Not allowed
// The only way to break the shared 'connection' is via clear()
CVF_ASSERT(!m_sharedData);
clear();
m_data = data;
m_size = size;
}
//--------------------------------------------------------------------------------------------------
/// Delete any current data and set from the given data pointer
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::assign(const T* data, size_t size)
{
CVF_ASSERT(data);
CVF_ASSERT(size > 0);
CVF_ASSERT(!m_sharedData);
clear();
resize(size);
// copy
cvf::System::memcpy(m_data, m_size*sizeof(T), data, size*sizeof(T));
}
//--------------------------------------------------------------------------------------------------
/// Delete any current data and set from the given data
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::assign(const std::vector<T>& data)
{
CVF_ASSERT(!m_sharedData);
clear();
size_t newSize = data.size();
if (newSize > 0)
{
resize(newSize);
cvf::System::memcpy(m_data, m_size*sizeof(T), &data[0], newSize*sizeof(T));
}
}
//--------------------------------------------------------------------------------------------------
/// Copy data into the array
///
/// \warning Must have enough room for the new data, meaning the array must be resize()'ed before use
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::copyData(const T* pSource, size_t numElementsToCopy, size_t destIndex)
{
CVF_ASSERT(pSource);
CVF_ASSERT(numElementsToCopy > 0);
CVF_ASSERT(destIndex < m_size);
CVF_ASSERT(destIndex + numElementsToCopy <= m_size);
cvf::System::memcpy(m_data + destIndex, (m_size - destIndex)*sizeof(T), pSource, numElementsToCopy*sizeof(T));
}
//--------------------------------------------------------------------------------------------------
/// Copy data into the array
///
/// \warning Must have enough room for the new data, meaning the array must be resize()'ed before use
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::copyData(const Array<T>& source, size_t numElementsToCopy, size_t destIndex, size_t sourceIndex)
{
CVF_ASSERT(numElementsToCopy > 0);
CVF_ASSERT(destIndex < m_size);
CVF_ASSERT(numElementsToCopy + destIndex <= m_size);
cvf::System::memcpy(m_data + destIndex, (m_size - destIndex)*sizeof(T), source.ptr() + sourceIndex, numElementsToCopy*sizeof(T));
}
//--------------------------------------------------------------------------------------------------
/// Copy data into this array with conversion.
/// Data in source array will be converted using static_cast
//--------------------------------------------------------------------------------------------------
template <typename T>
template <typename U>
void Array<T>::copyConvertedData(const Array<U>& source, size_t numElementsToCopy, size_t destIndex, size_t sourceIndex)
{
CVF_ASSERT(numElementsToCopy > 0);
CVF_ASSERT(destIndex < m_size);
CVF_ASSERT(numElementsToCopy + destIndex <= m_size);
size_t dst = destIndex;
size_t i;
for (i = sourceIndex; i < sourceIndex + numElementsToCopy; i++)
{
m_data[dst++] = static_cast<T>(source[i]);
}
}
//--------------------------------------------------------------------------------------------------
/// Returns an array containing the specified elements
///
/// Example:
/// <PRE>
/// this = {2.0, 5.5, 100.0}
/// elementIndices = { 0, 2, 1, 0, 2}
/// -> output = {2.0, 100.0, 5.5, 2.0, 100.0}
/// </PRE>
//--------------------------------------------------------------------------------------------------
template <typename T>
template <typename U>
ref<Array<T> > Array<T>::extractElements(const Array<U>& elementIndices) const
{
ref<Array<T> > arr = new Array<T>;
size_t numItems = elementIndices.size();
if (numItems > 0)
{
arr->resize(numItems);
size_t i;
for (i = 0; i < numItems; i++)
{
U idx = elementIndices[i];
arr->set(i, get(idx));
}
}
return arr;
}
//--------------------------------------------------------------------------------------------------
/// Copy the contents of the array to the given std::vector
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::toStdVector(std::vector<T>* vec) const
{
CVF_ASSERT(vec);
size_t numItems = size();
vec->resize(numItems);
size_t i;
for (i = 0; i < numItems; i++)
{
(*vec)[i] = (*this)[i];
}
}
//--------------------------------------------------------------------------------------------------
/// Get the current capacity of the array (the size of the buffer). This will return a number >= size(),
/// depending on if reserve() has been used or not.
/// If capacity() > size(), then add() is allowed on the array.
///
/// \sa
/// - reserve()
/// - add()
/// - squeeze()
/// - setSizeZero()
//--------------------------------------------------------------------------------------------------
template <typename T>
size_t Array<T>::capacity() const
{
return m_capacity;
}
//--------------------------------------------------------------------------------------------------
/// Reserve (allocate) at least the given number of items.
/// If capacity is less than the current buffer, nothing is done.
/// size() of the array is not changed.
///
/// \sa
/// - capacity()
/// - add()
/// - squeeze()
/// - setSizeZero()
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::reserve(size_t capacity)
{
CVF_ASSERT(!m_sharedData);
if ((capacity <= m_size) || (capacity <= m_capacity))
{
// Required capacity is less than current capacity, done!
return;
}
CVF_ASSERT(capacity > 0);
CVF_ASSERT(capacity > m_size);
if (m_data)
{
// Copy old data
T* pTmp = m_data;
m_data = new T[capacity];
m_capacity = capacity;
cvf::System::memcpy(m_data, capacity*sizeof(T), pTmp, m_size*sizeof(T));
delete[] pTmp;
}
else
{
// alloc
m_data = new T[capacity];
m_capacity = capacity;
}
CVF_ASSERT(m_size <= m_capacity);
}
//--------------------------------------------------------------------------------------------------
/// Realloc the array to the current size(). Removing any reserved memory created by reserve().
///
/// \sa
/// - reserve()
/// - capacity()
/// - add()
/// - setSizeZero()
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::squeeze()
{
CVF_ASSERT(!m_sharedData);
if (m_data && (m_size < m_capacity))
{
if (m_size > 0)
{
// Copy old data
T* pTmp = m_data;
m_data = new T[m_size];
cvf::System::memcpy(m_data, m_capacity*sizeof(T), pTmp, m_size*sizeof(T));
delete[] pTmp;
m_capacity = m_size;
}
else
{
clear();
}
}
}
//--------------------------------------------------------------------------------------------------
/// Set the size (number of items) in the array to zero, but keep the buffer. Items in the buffer
/// are not modified.
///
/// \sa
/// - reserve()
/// - capacity()
/// - add()
/// - squeeze()
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::setSizeZero()
{
CVF_TIGHT_ASSERT(!m_sharedData);
m_size = 0;
}
//--------------------------------------------------------------------------------------------------
/// Add an item to the array.
///
/// Note that this will not grow the array, so the array needs to be pre-allocated with reserve()
/// before calling this method. The method will assert if not enough space.
///
/// \sa
/// - reserve()
/// - capacity()
/// - squeeze()
/// - setSizeZero()
//--------------------------------------------------------------------------------------------------
template <typename T>
inline void Array<T>::add(const T& val)
{
CVF_TIGHT_ASSERT(!m_sharedData);
CVF_TIGHT_ASSERT(m_size < m_capacity);
m_data[m_size] = val;
m_size++;
}
//--------------------------------------------------------------------------------------------------
/// Get the min value and optionally the index of the (first) min value
/// Works only on arrays with types that implement comparison operators
/// Empty arrays will return std::numeric_limits<T>::max() and not modify index
//--------------------------------------------------------------------------------------------------
template <typename T>
T Array<T>::min(size_t* index) const
{
T minVal = std::numeric_limits<T>::max();
size_t i;
for (i = 0; i < m_size; i++)
{
if (m_data[i] < minVal)
{
minVal = m_data[i];
if (index)
{
*index = i;
}
}
}
return minVal;
}
//--------------------------------------------------------------------------------------------------
/// Get the min value and optionally the index of the (first) min value
/// Works only on arrays with types that implement comparison operators
/// Empty arrays will return std::numeric_limits<T>::max() and not modify index
//--------------------------------------------------------------------------------------------------
template <typename T>
T Array<T>::max(size_t* index) const
{
T maxVal = std::numeric_limits<T>::min();
size_t i;
for (i = 0; i < m_size; i++)
{
if (m_data[i] > maxVal)
{
maxVal = m_data[i];
if (index)
{
*index = i;
}
}
}
return maxVal;
}
//--------------------------------------------------------------------------------------------------
/// Exchanges the contents of the two arrays.
///
/// \param other Modifiable reference to the array that should have its contents swapped.
///
/// \warning Note that signature differs from normal practice. This is done to be
/// consistent with the signature of std::swap()
//--------------------------------------------------------------------------------------------------
template <typename T>
void Array<T>::swap(Array& other)
{
using std::swap;
swap(m_size, other.m_size);
swap(m_capacity, other.m_capacity);
swap(m_data, other.m_data);
swap(m_sharedData, other.m_sharedData);
}
} // namespace cvf
} //namespace external

View File

@@ -1,156 +0,0 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) Ceetron Solutions 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
namespace external {
namespace cvf {
//--------------------------------------------------------------------------------------------------
///
/// \class cvf::ArrayWrapperConst
/// \ingroup Core
///
/// A wrapper class for const access to make it possible to use different array types with
/// different element types in the same algorithms.
///
/// The implementation has a specialization for bare pointer arrays.
/// The reason for the bare pointer specialization is the [] access implementation
/// which is different. (*array)[] vs array[]
///
/// The convenience functions wrapArrayConst() are available to simplify wrapping of your data making it
/// possible to do:
/// myFunction (wrapArrayConst(myNodeArray), wrapArrayConst(myIndexArray), ...);
/// when calling a template function using ArrayWrapperConst's as input.
///
//--------------------------------------------------------------------------------------------------
template < typename ArrayType, typename ElmType >
class ArrayWrapperConst
{
public:
ArrayWrapperConst(const ArrayType* array, size_t size) : m_array(array), m_size(size) { }
inline size_t size() const { return m_size; }
inline const ElmType& operator[] (const size_t index) const { return (*m_array)[index]; }
private:
const ArrayType * m_array;
size_t m_size;
};
//--------------------------------------------------------------------------------------------------
/// Const bare-pointer array wrapper specialization
//--------------------------------------------------------------------------------------------------
template < typename ElmType >
class ArrayWrapperConst <const ElmType*, ElmType>
{
public:
ArrayWrapperConst(const ElmType* array, size_t size) : m_array(array), m_size(size) { }
inline size_t size() const { return m_size; }
inline const ElmType& operator[](const size_t index) const { return m_array[index]; }
private:
const ElmType * m_array;
size_t m_size;
};
#include "cvfArray.h"
#include <vector>
//--------------------------------------------------------------------------------------------------
/// const cvf::Array specialization
//--------------------------------------------------------------------------------------------------
template <typename ElmType>
inline const ArrayWrapperConst< const cvf::Array<ElmType>, ElmType > wrapArrayConst(const cvf::Array<ElmType>* array )
{
const ArrayWrapperConst<const cvf::Array<ElmType>, ElmType> warr(array, array->size());
return warr;
}
template <typename ElmType>
inline const ArrayWrapperConst< const cvf::Array<ElmType>, ElmType > wrapArrayConst( cvf::Array<ElmType>* array )
{
const ArrayWrapperConst<const cvf::Array<ElmType>, ElmType> warr(array, array->size());
return warr;
}
//--------------------------------------------------------------------------------------------------
/// const std::vector specialization
//--------------------------------------------------------------------------------------------------
template <typename ElmType>
inline const ArrayWrapperConst< const std::vector<ElmType>, ElmType > wrapArrayConst( const std::vector<ElmType>* array )
{
const ArrayWrapperConst< const std::vector<ElmType>, ElmType> warr(array, array->size());
return warr;
}
template <typename ElmType>
inline const ArrayWrapperConst< const std::vector<ElmType>, ElmType > wrapArrayConst( std::vector<ElmType>* array )
{
const ArrayWrapperConst< const std::vector<ElmType>, ElmType> warr(array, array->size());
return warr;
}
//--------------------------------------------------------------------------------------------------
/// const Bare-pointer specialization
//--------------------------------------------------------------------------------------------------
template <typename ElmType>
inline const ArrayWrapperConst< const ElmType*, ElmType > wrapArrayConst( const ElmType* array, size_t size )
{
const ArrayWrapperConst<const ElmType*, ElmType> warr(array, size);
return warr;
}
template <typename ElmType>
inline const ArrayWrapperConst< const ElmType*, ElmType > wrapArrayConst( ElmType* array, size_t size )
{
const ArrayWrapperConst<const ElmType*, ElmType> warr(array, size);
return warr;
}
}
} //namespace external

View File

@@ -1,478 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfAssert.h"
#include "cvfSystem.h"
#include <cstdlib>
#include <iostream>
#include <string>
#ifdef WIN32
#pragma warning (push)
#pragma warning (disable: 4668)
#include <windows.h>
#pragma warning (pop)
#include <io.h>
#include <signal.h>
#include <fcntl.h>
#endif
namespace external {
namespace cvf {
// User actions (interactive responses)
static const int USERACTION_CONTINUE = 0;
static const int USERACTION_DEBUGBREAK = 1;
static const int USERACTION_ABORT = 2;
//==================================================================================================
///
/// \class cvf::AssertHandler
/// \ingroup Core
///
/// Base class for assert handlers
///
//==================================================================================================
class AssertHandler
{
public:
virtual ~AssertHandler() {}
virtual Assert::FailAction handleAssert(const char* fileName, int lineNumber, const char* expr, const char* msg) = 0;
};
//==================================================================================================
///
/// \class cvf::AssertHandlerConsole
/// \ingroup Core
///
/// Assert handler for basic assert output to console
///
//==================================================================================================
class AssertHandlerConsole : public AssertHandler
{
public:
virtual Assert::FailAction handleAssert(const char* fileName, int lineNumber, const char* expr, const char* msg);
private:
static void reportToConsole(const char* fileName, int lineNumber, const char* expr, const char* msg);
static int askForUserActionUsingConsole();
#ifdef WIN32
static void winCreateConsoleAndRedirectIO(bool redirectInput);
#endif
};
//--------------------------------------------------------------------------------------------------
/// Show report of a failed assert in console and abort execution
///
/// On Windows, a console will be created if one doesn't exist (GUI applications)
//--------------------------------------------------------------------------------------------------
Assert::FailAction AssertHandlerConsole::handleAssert(const char* fileName, int lineNumber, const char* expr, const char* msg)
{
// Just shows assert message in console.
// Does the job on both Windows and Linux (creates a console on Windows if one doesn't exist)
reportToConsole(fileName, lineNumber, expr, msg);
#ifdef _MSC_VER
#if (_MSC_VER >= 1600)
if (::IsDebuggerPresent())
#endif
{
__debugbreak();
}
#endif
abort();
// Shouldn't really matter since we always abort
return Assert::CONTINUE;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AssertHandlerConsole::reportToConsole(const char* fileName, int lineNumber, const char* expr, const char* msg)
{
#ifdef WIN32
// Make sure we have a console (applicable to Windows GUI applications)
winCreateConsoleAndRedirectIO(false);
#endif
std::cerr << "Assertion failed:";
if (expr)
{
std::cerr << " (" << expr << ")";
}
if (msg)
{
std::cerr << " '" << msg << "'";
}
if (expr || msg)
{
std::cerr << ",";
}
std::cerr << " file " << fileName << ", line " << lineNumber << std::endl;
}
//--------------------------------------------------------------------------------------------------
/// Ask for user action using console input
///
/// \return One of the USERACTION_ constants
//--------------------------------------------------------------------------------------------------
int AssertHandlerConsole::askForUserActionUsingConsole()
{
#ifdef WIN32
// Make sure we have a console (applicable to Windows GUI applications)
// Also ensures that input is redirected
winCreateConsoleAndRedirectIO(true);
#endif
// Let abort be the default choice
#ifdef WIN32
std::cerr << "Choose action: [A]bort, [R]etry (debug) or [I]gnore: default [A]\n";
#else
std::cerr << "Choose action: [A]bort or [I]gnore: default [A]\n";
#endif
// Reset failstate, just in case.
std::cin.clear();
std::string line;
while (std::getline(std::cin, line))
{
int ch = 0;
if (!std::cin.fail() && line.length() == 1)
{
ch = tolower(line[0]);
}
if (ch == 'i')
{
return USERACTION_CONTINUE;
}
#ifdef WIN32
else if (ch == 'r')
{
return USERACTION_DEBUGBREAK;
}
#endif
else if (ch == 'a' || line.length() == 0)
{
return USERACTION_ABORT;
}
}
return USERACTION_ABORT;
}
//--------------------------------------------------------------------------------------------------
/// Creates a console and redirects I/O from/to it (Windows only)
///
/// \param redirectInput If true, input will also be redirected.
///
/// Function is useful for Windows GUI applications. Allocates a console if it doesn't exist and
/// then redirects output to the console. Also redirects input if \a redirectInput is true
//--------------------------------------------------------------------------------------------------
#ifdef WIN32
void AssertHandlerConsole::winCreateConsoleAndRedirectIO(bool redirectInput)
{
// 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();
bool redirStdOut = true;
bool redirStdErr = true;
bool redirStdIn = redirectInput;
if (redirStdOut)
{
HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
FILE* fp = _fdopen(fileDescriptor, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
}
if (redirStdErr)
{
HANDLE stdHandle = GetStdHandle(STD_ERROR_HANDLE);
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
FILE* fp = _fdopen(fileDescriptor, "w");
*stderr = *fp;
setvbuf(stderr, NULL, _IONBF, 0);
}
if (redirStdIn)
{
HANDLE stdHandle = GetStdHandle(STD_INPUT_HANDLE);
int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
FILE* fp = _fdopen(fileDescriptor, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);
}
// Make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well
std::ios::sync_with_stdio();
}
#endif
//==================================================================================================
///
/// \class cvf::AssertHandlerWinDialog
/// \ingroup Core
///
/// Assert handler for Windows, using a dialog with interaction
///
//==================================================================================================
#ifdef WIN32
class AssertHandlerWinDialog : public AssertHandler
{
public:
virtual Assert::FailAction handleAssert(const char* fileName, int lineNumber, const char* expr, const char* msg);
private:
static int handleUsingDialog(const char* fileName, int lineNumber, const char* expr, const char* msg);
#ifdef _DEBUG
static int handleUsingCrtDbgReport(const char* fileName, int lineNumber, const char* expr, const char* msg);
#endif
};
#endif
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
#ifdef WIN32
Assert::FailAction AssertHandlerWinDialog::handleAssert(const char* fileName, int lineNumber, const char* expr, const char* msg)
{
//int retVal = handleUsingCrtDbgReport(fileName, lineNumber, expr, msg);
int retVal = handleUsingDialog(fileName, lineNumber, expr, msg);
if (retVal == USERACTION_CONTINUE)
{
return Assert::CONTINUE;
}
else if (retVal == USERACTION_DEBUGBREAK)
{
return Assert::DEBUGBREAK;
}
else if (retVal == USERACTION_ABORT)
{
// From __crtMessageWindow() in response to user clicking abort button
// Note that it is better NOT to call abort() here, because the default implementation of abort() will call Watson
// raise abort signal
raise(SIGABRT);
// We usually won't get here, but it's possible that SIGABRT was ignored.
// So exit the program anyway.
_exit(3);
}
// Shouldn't be getting here
abort();
return Assert::CONTINUE;
}
#endif
//--------------------------------------------------------------------------------------------------
/// Shows message in interactive dialog and lets user choose how to proceed
///
/// \return Returns one of the USERACTION_ constants depending on which button the user chooses.
///
/// Compared to the handleUsingCrtDbgReport() function, this function will also work in release builds
/// As opposed to the handleUsingCrtDbgReport(), this function will not call abort, but will return
/// USERACTION_ABORT instead.
///
/// \todo Must add code to handle case where new assert is triggered while handling an assert
//--------------------------------------------------------------------------------------------------
#ifdef WIN32
int AssertHandlerWinDialog::handleUsingDialog(const char* fileName, int lineNumber, const char* expr, const char* msg)
{
char szMsgBuf[2048];
System::strcpy(szMsgBuf, sizeof(szMsgBuf), "Assertion failed\n");
System::strcat(szMsgBuf, sizeof(szMsgBuf), "\nFile: ");
if (fileName)
{
System::strcat(szMsgBuf, sizeof(szMsgBuf), fileName);
}
System::strcat(szMsgBuf, sizeof(szMsgBuf), "\nLine: ");
if (lineNumber >= 0)
{
char szLinNumBuf[20];
System::sprintf(szLinNumBuf, sizeof(szLinNumBuf), "%d", lineNumber);
System::strcat(szMsgBuf, sizeof(szMsgBuf), szLinNumBuf);
}
if (expr)
{
System::strcat(szMsgBuf, sizeof(szMsgBuf), "\n\n");
System::strcat(szMsgBuf, sizeof(szMsgBuf), "Expression: ");
System::strcat(szMsgBuf, sizeof(szMsgBuf), expr);
}
if (msg)
{
System::strcat(szMsgBuf, sizeof(szMsgBuf), "\n\n");
System::strcat(szMsgBuf, sizeof(szMsgBuf), msg);
}
System::strcat(szMsgBuf, sizeof(szMsgBuf), "\n\n(Press Retry to debug application)");
int retVal = ::MessageBoxA(NULL, szMsgBuf, "Assertion Failed", MB_TASKMODAL|MB_ICONHAND|MB_ABORTRETRYIGNORE|MB_SETFOREGROUND);
if (retVal == IDIGNORE) return USERACTION_CONTINUE;
else if (retVal == IDRETRY) return USERACTION_DEBUGBREAK;
else return USERACTION_ABORT;
}
#endif
//--------------------------------------------------------------------------------------------------
/// Wrapper function for the CRT _CrtDbgReport() function
///
/// This function never returns if the user chooses 'Abort'
/// Note that the underlying function is only available in debug builds
//--------------------------------------------------------------------------------------------------
#if defined WIN32 && defined _DEBUG
int AssertHandlerWinDialog::handleUsingCrtDbgReport(const char* fileName, int lineNumber, const char* expr, const char* msg)
{
// Create message combining expression and message
char szMsgBuf[2048];
szMsgBuf[0] = '\0';
if (expr)
{
System::strcat(szMsgBuf, sizeof(szMsgBuf), expr);
}
if (msg)
{
System::strcat(szMsgBuf, sizeof(szMsgBuf), "\n");
System::strcat(szMsgBuf, sizeof(szMsgBuf), msg);
}
int retVal = _CrtDbgReport(_CRT_ASSERT, fileName, lineNumber, NULL, szMsgBuf);
if (retVal == 0) return USERACTION_CONTINUE;
else if (retVal == 1) return USERACTION_DEBUGBREAK;
else return USERACTION_ABORT;
}
#endif
//==================================================================================================
///
/// \class cvf::Assert
/// \ingroup Core
///
/// Helper class to customize assert
///
//==================================================================================================
#ifdef WIN32
AssertHandler* Assert::sm_handler = new AssertHandlerWinDialog;
#else
AssertHandler* Assert::sm_handler = new AssertHandlerConsole;
#endif
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Assert::setReportMode(ReportMode reportMode)
{
#ifndef WIN32
if (reportMode == INTERACTIVE_DIALOG) return;
#endif
delete sm_handler;
sm_handler = NULL;
if (reportMode == CONSOLE)
{
sm_handler = new AssertHandlerConsole;
}
#ifdef WIN32
else if (reportMode == INTERACTIVE_DIALOG)
{
sm_handler = new AssertHandlerWinDialog;
}
#endif
}
//--------------------------------------------------------------------------------------------------
/// Show report of a failed assert
///
/// If assertions are configured to be interactive, a message box will be shown on Windows and
/// the user may opt to ignore or trigger debugging.
/// On Linux, or if interactive asserts are disabled, the application will terminate.
///
/// \todo Add handling of cases where we get another assert while processing the first one AND
/// asserts from multiple threads.
//--------------------------------------------------------------------------------------------------
Assert::FailAction Assert::reportFailedAssert(const char* fileName, int lineNumber, const char* expr, const char* msg)
{
if (sm_handler)
{
return sm_handler->handleAssert(fileName, lineNumber, expr, msg);
}
else
{
abort();
return CONTINUE;
}
}
} // namespace cvf
} //namespace external

View File

@@ -1,107 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
namespace external {
namespace cvf {
// Forward of base class for assert handlers
class AssertHandler;
//==================================================================================================
//
// Helper class to customize assert behavior
//
//==================================================================================================
class Assert
{
public:
enum ReportMode
{
CONSOLE, // Report asserts to console only and then abort. (default mode for Linux)
INTERACTIVE_DIALOG // Show message in dialog and ask for user action (Windows only, default mode on Windows)
};
enum FailAction
{
CONTINUE, // Continue execution
DEBUGBREAK // Execution should be stopped and debugger should be triggered (currently windows only)
};
public:
static void setReportMode(ReportMode reportMode);
static FailAction reportFailedAssert(const char* fileName, int lineNumber, const char* expr, const char* msg);
private:
static AssertHandler* sm_handler;
};
} // cvf
// Define to trigger debug trap for use with assert macros
// Currently only useful and in action on windows
#ifdef WIN32
#define CVF_DEBUGTRAP() __debugbreak()
#else
#define CVF_DEBUGTRAP() ((void)0)
#endif
// Define our assert macros
#if CVF_ENABLE_ASSERTS == 1
# define CVF_ASSERT(expr) (void)( (!!(expr)) || (cvf::Assert::CONTINUE == cvf::Assert::reportFailedAssert(__FILE__, __LINE__, #expr, NULL)) || (CVF_DEBUGTRAP(), 0) )
# define CVF_ASSERT_MSG(expr, msg) (void)( (!!(expr)) || (cvf::Assert::CONTINUE == cvf::Assert::reportFailedAssert(__FILE__, __LINE__, #expr, (msg))) || (CVF_DEBUGTRAP(), 0) )
# define CVF_FAIL_MSG(msg) (void)( (cvf::Assert::CONTINUE == cvf::Assert::reportFailedAssert(__FILE__, __LINE__, NULL, (msg))) || (CVF_DEBUGTRAP(), 0) )
#else
# define CVF_ASSERT(expr) ((void)0)
# define CVF_ASSERT_MSG(expr, msg) ((void)0)
# define CVF_FAIL_MSG(msg) ((void)0)
#endif
#if CVF_ENABLE_TIGHT_ASSERTS == 1 && CVF_ENABLE_ASSERTS == 1
# define CVF_TIGHT_ASSERT(expr) CVF_ASSERT(expr)
# define CVF_TIGHT_ASSERT_MSG(expr, msg) CVF_ASSERT_MSG(expr, msg)
#else
# define CVF_TIGHT_ASSERT(expr) ((void)0)
# define CVF_TIGHT_ASSERT_MSG(expr, msg) ((void)0)
#endif
} //namespace external

View File

@@ -1,175 +0,0 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) 2014 Ceetron Solutions 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 <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
//##################################################################################################
#include "cvfAtomicCounter.h"
namespace external {
// Some older GCC version do not support atomics, we have seen this for RHEL5
#if defined(CVF_ATOMIC_COUNTER_CLASS_EXISTS)
namespace cvf {
#ifdef WIN32
#pragma warning (push)
#pragma warning (disable: 4668)
#include <windows.h>
#pragma warning (pop)
AtomicCounter::AtomicCounter(int initialValue)
: m_counter(initialValue)
{
}
AtomicCounter::~AtomicCounter()
{
}
AtomicCounter::operator int () const
{
return m_counter;
}
int AtomicCounter::operator ++ () // prefix
{
return InterlockedIncrement(&m_counter);
}
int AtomicCounter::operator ++ (int) // postfix
{
int result = InterlockedIncrement(&m_counter);
return --result;
}
int AtomicCounter::operator -- () // prefix
{
return InterlockedDecrement(&m_counter);
}
int AtomicCounter::operator -- (int) // postfix
{
int result = InterlockedDecrement(&m_counter);
return ++result;
}
#elif defined(CVF_IOS) || defined(CVF_OSX)
AtomicCounter::AtomicCounter(int initialValue)
: m_counter(initialValue)
{
}
AtomicCounter::~AtomicCounter()
{
}
AtomicCounter::operator int () const
{
return m_counter;
}
int AtomicCounter::operator ++ () // prefix
{
return OSAtomicIncrement32(&m_counter);
}
int AtomicCounter::operator ++ (int) // postfix
{
int result = OSAtomicIncrement32(&m_counter);
return --result;
}
int AtomicCounter::operator -- () // prefix
{
return OSAtomicDecrement32(&m_counter);
}
int AtomicCounter::operator -- (int) // postfix
{
int result = OSAtomicDecrement32(&m_counter);
return ++result;
}
#elif defined(CVF_GCC_DEFINED)
AtomicCounter::AtomicCounter(int initialValue)
: m_counter(initialValue)
{
}
AtomicCounter::~AtomicCounter()
{
}
AtomicCounter::operator int () const
{
return m_counter;
}
int AtomicCounter::operator ++ () // prefix
{
return __sync_add_and_fetch(&m_counter, 1);
}
int AtomicCounter::operator ++ (int) // postfix
{
return __sync_fetch_and_add(&m_counter, 1);
}
int AtomicCounter::operator -- () // prefix
{
return __sync_sub_and_fetch(&m_counter, 1);
}
int AtomicCounter::operator -- (int) // postfix
{
return __sync_fetch_and_sub(&m_counter, 1);
}
#endif
} // namespace cvf
#endif // CVF_ATOMICS_COMPILED
} //namespace external

View File

@@ -1,94 +0,0 @@
//##################################################################################################
//
// Custom Visualization Core library
// Copyright (C) 2014 Ceetron Solutions 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
namespace external {
#ifdef WIN32
#define CVF_ATOMIC_COUNTER_CLASS_EXISTS
#elif defined(CVF_IOS) || defined(CVF_OSX)
#include <libkern/OSAtomic.h>
#define CVF_ATOMIC_COUNTER_CLASS_EXISTS
#elif defined __GNUC__
#define CVF_GCC_DEFINED
#define CVF_ATOMIC_COUNTER_CLASS_EXISTS
#endif
#if defined(CVF_ATOMIC_COUNTER_CLASS_EXISTS)
namespace cvf {
// Inspired by Poco
class AtomicCounter
{
public:
explicit AtomicCounter(int initialValue);
~AtomicCounter();
operator int () const;
int operator ++ (); // prefix
int operator ++ (int); // postfix
int operator -- (); // prefix
int operator -- (int); // postfix
private:
CVF_DISABLE_COPY_AND_ASSIGN(AtomicCounter);
#ifdef WIN32
typedef volatile long ImplType;
#elif defined(CVF_IOS) || defined(CVF_OSX)
typedef int32_t ImplType;
#else
typedef int ImplType;
#endif
ImplType m_counter;
};
} // namespace cvf
#endif
} //namespace external

View File

@@ -1,133 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
// #if !defined(WIN32) && !defined(CVF_LINUX) && !defined(CVF_IOS) && !defined(CVF_OSX) && !defined(CVF_ANDROID)
// #error No platform defined
// #endif
// Global include file with definitions useful for all library files
// Disable some annoying warnings so we can compile with warning level Wall
#ifdef _MSC_VER
// 4512 'class' : assignment operator could not be generated : Due to problems with classes with reference member variables (e.g. VertexCompactor)
// 4514 unreferenced inline/local function has been removed
// 4625 copy constructor could not be generated because a base class copy constructor is inaccessible
// 4626 assignment operator could not be generated because a base class assignment operator is inaccessible
// 4640 'staticInstance' : construction of local static object is not thread-safe -> used by singletons. To be revisited.
// 4710 function 'func_name' not inlined
// 4711 function 'func_name' selected for automatic inline expansion
// 4738 storing 32-bit float result in memory, possible loss of performance
// 4820 'bytes' bytes padding added after construct 'member_name'
#pragma warning (disable: 4512 4514 4625 4626 4640 4710 4711 4738 4820)
#if (_MSC_VER >= 1600)
// VS2010 and newer
// 4986 'operator new[]': exception specification does not match previous declaration
#pragma warning (disable: 4986)
#endif
#endif
// 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__)
#endif
// Helper macro to disable (ignore) compiler warnings on GCC
// The needed pragma is only available in GCC for versions 4.2.x and above
#if defined(__GNUC__) && (CVF_GCC_VER >= 40200)
#define CVF_DO_PRAGMA(x) _Pragma(#x)
#define CVF_GCC_DIAGNOSTIC_IGNORE(OPTION_STRING) CVF_DO_PRAGMA(GCC diagnostic ignored OPTION_STRING)
#else
#define CVF_GCC_DIAGNOSTIC_IGNORE(OPTION_STRING)
#endif
#if defined(CVF_LINUX) || defined(CVF_IOS) || defined(CVF_OSX) || defined(CVF_ANDROID)
// Used by int64_t on *nix below
#include <stdint.h>
#endif
// Brings in size_t and definition of NULL
#include <cstddef>
namespace external {
// Added due to conflict between std::min/max and define in Windows.h
#define CVF_MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#define CVF_MAX(X, Y) ((X) > (Y) ? (X) : (Y))
// Macro for avoiding "unused parameter" warnings
// The bottom one is the best alternative, but unfortunately doesn't work on VS2010
#ifdef WIN32
#define CVF_UNUSED(EXPR) (void)(EXPR);
#else
#define CVF_UNUSED(EXPR) (void)sizeof(EXPR);
#endif
// Macro to disable the copy constructor and assignment operator
// Should be used in the private section of a class
#define CVF_DISABLE_COPY_AND_ASSIGN(CLASS_NAME) \
CLASS_NAME(const CLASS_NAME&); \
void operator=(const CLASS_NAME&)
/// Ceetron Visualization Framework namespace
namespace cvf {
typedef unsigned char ubyte;
typedef unsigned short ushort;
typedef unsigned int uint;
// 64bit integer support via the int64 type
#ifdef WIN32
typedef __int64 int64;
#elif defined(CVF_LINUX) || defined(CVF_IOS) || defined(CVF_OSX) || defined(CVF_ANDROID)
typedef int64_t int64;
#endif
}
} //namespace external
#include "cvfConfigCore.h"
#include "cvfVersion.h"
#include "cvfAssert.h"

View File

@@ -1,59 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfString.h"
#include "cvfArray.h"
namespace external {
namespace cvf {
//==================================================================================================
//
// Base64 encoding and decoding for representing binary data in an ASCII string
//
//==================================================================================================
class Base64
{
public:
static std::string encode(const cvf::UByteArray& data);
static cvf::ref<cvf::UByteArray> decode(const std::string& encodedData);
};
}
} //namespace external

View File

@@ -1,172 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfCharArray.h"
#include "cvfSystem.h"
#include <sstream>
#include <iomanip>
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::CharArray
/// \ingroup Core
///
/// 8 bit zero terminated char array.
///
/// Behind the scenes, the array always has a 0 termination sentinel.
//==================================================================================================
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CharArray::CharArray()
{
m_data.push_back('\0');
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CharArray::CharArray(size_t size, char c)
{
resize(size);
size_t i;
for (i = 0; i < size; i++)
{
m_data[i] = c;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CharArray::CharArray(const char* str)
{
size_t numChars = System::strlen(str);
resize(numChars);
size_t i;
for (i = 0; i < numChars; i++)
{
m_data[i] = str[i];
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
char& CharArray::operator[](size_t i)
{
CVF_TIGHT_ASSERT(i < m_data.size() - 1);
return m_data[i];
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
const char& CharArray::operator[](size_t i) const
{
CVF_TIGHT_ASSERT(i < m_data.size() - 1);
return m_data[i];
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CharArray::resize(size_t size)
{
m_data.resize(size + 1, '\0');
m_data[size] = '\0';
}
//--------------------------------------------------------------------------------------------------
/// Add a character to the array. Array grows if necessary.
//--------------------------------------------------------------------------------------------------
void CharArray::push_back(char c)
{
CVF_TIGHT_ASSERT(m_data.size() > 0);
m_data[m_data.size() - 1] = c;
m_data.push_back('\0');
}
//--------------------------------------------------------------------------------------------------
/// Get the size of the character array.
///
/// Note that this is not necessarily the length of the contained string. In order to get the string
/// length, you must call System::strlen().
//--------------------------------------------------------------------------------------------------
size_t CharArray::size() const
{
CVF_TIGHT_ASSERT(m_data.size() > 0);
return m_data.size() - 1;
}
//--------------------------------------------------------------------------------------------------
/// Get a const char* pointer to the string
//--------------------------------------------------------------------------------------------------
const char* CharArray::ptr() const
{
CVF_ASSERT(m_data.size() > 0);
CVF_ASSERT(m_data[m_data.size() - 1] == '\0');
return &m_data[0];
}
//--------------------------------------------------------------------------------------------------
/// Get a const char* pointer to the string
//--------------------------------------------------------------------------------------------------
char* CharArray::ptr()
{
CVF_ASSERT(m_data.size() > 0);
CVF_ASSERT(m_data[m_data.size() - 1] == '\0');
return &m_data[0];
}
} // namespace cvf
} //namespace external

View File

@@ -1,75 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include <vector>
namespace external {
namespace cvf {
//==================================================================================================
//
// 8 bit zero terminated char array
//
//==================================================================================================
class CharArray
{
public:
CharArray();
CharArray(size_t size, char c);
explicit CharArray(const char* str);
char& operator[](size_t i);
const char& operator[](size_t i) const;
void resize(size_t size);
void push_back(char c);
size_t size() const;
const char* ptr() const;
char* ptr();
private:
std::vector<char> m_data;
};
}
} //namespace external

View File

@@ -1,85 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
namespace external {
namespace cvf {
//==================================================================================================
//
//
//
//==================================================================================================
class CodeLocation
{
public:
CodeLocation();
CodeLocation(const char* fileName, const char* functionName, int lineNumber);
CodeLocation(const CodeLocation& other);
const CodeLocation& operator=(CodeLocation rhs);
const char* fileName() const;
const char* shortFileName() const;
const char* functionName() const;
int lineNumber() const;
void swap(CodeLocation& other);
private:
const char* m_fileName;
const char* m_functionName;
int m_lineNumber;
};
#if defined(_MSC_VER)
#define CVF_CODELOC_FUNCNAME __FUNCSIG__
#elif defined(__GNUC__)
#define CVF_CODELOC_FUNCNAME __PRETTY_FUNCTION__
#else
#define CVF_CODELOC_FUNCNAME ""
#endif
#define CVF_CODE_LOCATION ::cvf::CodeLocation(__FILE__, CVF_CODELOC_FUNCNAME, __LINE__)
} // cvf
} //namespace external

View File

@@ -1,102 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfObject.h"
#include "cvfMath.h"
#include <vector>
#include <algorithm>
namespace external {
namespace cvf {
//==================================================================================================
//
// A collection class for reference counted objects (that derive from Object)
//
//==================================================================================================
template<typename T>
class Collection
{
public:
Collection();
Collection(const Collection& other);
explicit Collection(const std::vector< ref<T> >& vector);
Collection& operator=(Collection rhs);
Collection& operator=(const std::vector< ref<T> >& vector);
const ref<T>& operator[](size_t index) const;
ref<T>& operator[](size_t index);
void push_back(T* data);
const T* at(size_t index) const;
T* at(size_t index);
void resize(size_t size);
size_t size() const;
void reserve(size_t capacity);
size_t capacity() const;
void clear();
bool empty() const;
bool contains(const T* data) const;
size_t indexOf(const T* data) const;
void erase(const T* data);
void eraseAt(size_t index);
void swap(Collection& other);
// Iterator support
public:
typedef typename std::vector<ref<T> >::iterator iterator;
typedef typename std::vector<ref<T> >::const_iterator const_iterator;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
private:
std::vector<ref<T> > m_vector;
};
}
} //namespace external
#include "cvfCollection.inl"

View File

@@ -1,334 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::Collection
/// \ingroup Core
///
/// A collection class for reference counted objects (that derive from Object).
///
/// The class add a reference to all objects when added to the array, and releases them when removed
/// from the array.
///
/// The class exposes the same public interface as a std::vector, so see the STL documentation
/// for documentation on most of the methods.
///
//==================================================================================================
//--------------------------------------------------------------------------------------------------
/// Default constructor. Create an empty collection
//--------------------------------------------------------------------------------------------------
template<typename T>
Collection<T>::Collection()
{
}
//--------------------------------------------------------------------------------------------------
/// Copy constructor
//--------------------------------------------------------------------------------------------------
template<typename T>
Collection<T>::Collection(const Collection& other)
: m_vector(other.m_vector)
{
}
//--------------------------------------------------------------------------------------------------
/// Create a collection and copy the contents from the passed collection
//--------------------------------------------------------------------------------------------------
template<typename T>
Collection<T>::Collection(const std::vector< ref<T> >& vector)
: m_vector(vector)
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
Collection<T>& Collection<T>::operator=(Collection rhs)
{
rhs.swap(*this);
return *this;
}
//--------------------------------------------------------------------------------------------------
/// Set the collection to contain the same elements as the passed collection
//--------------------------------------------------------------------------------------------------
template<typename T>
Collection<T>& Collection<T>::operator=(const std::vector< ref<T> >& vector)
{
m_vector = vector;
return *this;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
const ref<T>& Collection<T>::operator[](size_t index) const
{
return m_vector[index];
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
ref<T>& Collection<T>::operator[](size_t index)
{
return m_vector[index];
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::push_back(T* data)
{
m_vector.push_back(data);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
const T* Collection<T>::at(size_t index) const
{
return m_vector[index].p();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
T* Collection<T>::at(size_t index)
{
return m_vector[index].p();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::resize(size_t size)
{
m_vector.resize(size);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
size_t Collection<T>::size() const
{
return m_vector.size();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::reserve(size_t capacity)
{
m_vector.reserve(capacity);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
size_t Collection<T>::capacity() const
{
return m_vector.capacity();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::clear()
{
m_vector.clear();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
bool Collection<T>::empty() const
{
return m_vector.empty();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
bool Collection<T>::contains(const T* data) const
{
if (std::find(m_vector.begin(), m_vector.end(), data) != m_vector.end())
{
return true;
}
else
{
return false;
}
}
//--------------------------------------------------------------------------------------------------
/// Find index of the first occurence of the specified element
///
/// Returns UNDEFINED_SIZE_T if element could not be found
//--------------------------------------------------------------------------------------------------
template<typename T>
size_t Collection<T>::indexOf(const T* data) const
{
typename std::vector<ref<T> >::const_iterator it = std::find(m_vector.begin(), m_vector.end(), data);
if (it != m_vector.end())
{
return static_cast<size_t>(it - m_vector.begin());
}
else
{
return UNDEFINED_SIZE_T;
}
}
//--------------------------------------------------------------------------------------------------
/// Erase the specified element
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::erase(const T* data)
{
typename std::vector<ref<T> >::iterator it = std::find(m_vector.begin(), m_vector.end(), data);
if (it != m_vector.end())
{
m_vector.erase(it);
}
}
//--------------------------------------------------------------------------------------------------
/// Erase the element at the specified index
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::eraseAt(size_t index)
{
CVF_ASSERT(index < m_vector.size());
// Cast may have to be to std::vector<T>::difference_type
m_vector.erase(m_vector.begin() + static_cast<ptrdiff_t>(index));
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename T>
void Collection<T>::swap(Collection& other)
{
m_vector.swap(other.m_vector);
}
//--------------------------------------------------------------------------------------------------
/// Return iterator to beginning
//--------------------------------------------------------------------------------------------------
template<typename T>
typename Collection<T>::iterator Collection<T>::begin()
{
return m_vector.begin();
}
//--------------------------------------------------------------------------------------------------
/// Return iterator to end
//--------------------------------------------------------------------------------------------------
template<typename T>
typename Collection<T>::iterator Collection<T>::end()
{
return m_vector.end();
}
//--------------------------------------------------------------------------------------------------
/// Return const iterator to beginning
//--------------------------------------------------------------------------------------------------
template<typename T>
typename Collection<T>::const_iterator Collection<T>::begin() const
{
return m_vector.begin();
}
//--------------------------------------------------------------------------------------------------
/// Return const iterator to end
//--------------------------------------------------------------------------------------------------
template<typename T>
typename Collection<T>::const_iterator Collection<T>::end() const
{
return m_vector.end();
}
} // namespace cvf
} //namespace external

View File

@@ -1,186 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
namespace external {
namespace cvf {
// Forward declarations
class Color3ub;
//==================================================================================================
//
// Abstract base class for RGB colors
//
//==================================================================================================
class Color3
{
public:
enum ColorIdent
{
RED, ///< Pure red (255, 0, 0)
GREEN, ///< Pure greed (0, 255, 0)
BLUE, ///< Pure blue (0, 0, 255)
YELLOW, ///< Yellow (255, 255, 0)
CYAN, ///< Cyan (0, 255, 255)
MAGENTA, ///< Magenta (255, 0, 255)
WHITE, ///< White
BLACK, ///< Black
LIGHT_GRAY, ///< Light gray (192, 192, 192)
GRAY, ///< Gray (128, 128, 128)
DARK_GRAY, ///< Dark gray (64, 64, 64)
BROWN, ///< Brown (165, 42, 42)
CRIMSON, ///< Crimson (220, 20, 60)
DARK_BLUE, ///< Dark blue (0, 0, 139)
DARK_YELLOW, ///< Dark yellow (139, 139, 0)
DARK_CYAN, ///< Dark cyan (0, 139, 139)
DARK_GREEN, ///< Dark green (0, 100, 0)
DARK_MAGENTA, ///< Dark magenta (139, 0, 139)
DARK_ORANGE, ///< Dark orange (255, 140, 0)
DARK_RED, ///< Dark red (139, 0, 0)
DARK_VIOLET, ///< Dark violet (148, 0, 211)
DEEP_PINK, ///< Deep pink (255, 20, 147)
FOREST_GREEN, ///< Forest green (34, 139, 34)
GOLD, ///< Gold (255, 215, 0)
GREEN_YELLOW, ///< Green yellow (173, 255, 47)
INDIGO, ///< Indigo (75, 0, 130)
OLIVE, ///< Olive (128, 128, 0)
ORANGE, ///< Orange (255, 165, 0)
ORANGE_RED, ///< Orange red (255, 69, 0)
ORCHID, ///< Orchid (218, 112, 214)
PINK, ///< Pink (255, 192, 203)
PURPLE, ///< Purple (128, 0, 128)
SEA_GREEN, ///< Sea green (46, 139, 87)
SKY_BLUE, ///< Sky blue (135, 206, 235)
VIOLET, ///< Violet (238, 130, 238)
YELLOW_GREEN, ///< Yellow green (154, 205, 50)
CEETRON ///< Ceetron Color (81, 134, 148)
};
};
//==================================================================================================
//
// Floating point RGB colors
//
//==================================================================================================
class Color3f : public Color3
{
public:
Color3f();
Color3f(float r, float g, float b);
Color3f(const Color3f& other);
Color3f(ColorIdent colorIdent);
explicit Color3f(const Color3ub& other);
Color3f& operator=(const Color3f& rhs);
Color3f& operator=(ColorIdent colorIdent);
bool operator==(const Color3f& rhs) const;
bool operator!=(const Color3f& rhs) const;
const float& r() const { return m_rgb[0]; } ///< Returns the red color component
const float& g() const { return m_rgb[1]; } ///< Returns the green color component
const float& b() const { return m_rgb[2]; } ///< Returns the blue color component
float& r() { return m_rgb[0]; } ///< Get modifiable reference to the red color component, used for setting the component.
float& g() { return m_rgb[1]; } ///< Get modifiable reference to the green color component, used for setting the component
float& b() { return m_rgb[2]; } ///< Get modifiable reference to the blue color component, used for setting the component
void set(float r, float g, float b);
bool isValid() const;
const float* ptr() const;
ubyte rByte() const;
ubyte gByte() const;
ubyte bByte() const;
static Color3f fromByteColor(ubyte r, ubyte g, ubyte b);
friend bool operator < (const Color3f& color1, const Color3f& color2);
private:
float m_rgb[3];
};
bool operator < (const Color3f& color1, const Color3f& color2);
//==================================================================================================
//
// Unsigned byte RGB colors
//
//==================================================================================================
class Color3ub : public Color3
{
public:
Color3ub();
Color3ub(ubyte r, ubyte g, ubyte b);
Color3ub(const Color3ub& other);
Color3ub(ColorIdent colorIdent);
explicit Color3ub(const Color3f& other);
Color3ub& operator=(const Color3ub& rhs);
Color3ub& operator=(ColorIdent colorIdent);
bool operator==(const Color3ub& rhs) const;
bool operator!=(const Color3ub& rhs) const;
ubyte r() const { return m_rgb[0]; } ///< Returns the red color component
ubyte g() const { return m_rgb[1]; } ///< Returns the green color component
ubyte b() const { return m_rgb[2]; } ///< Returns the blue color component
ubyte& r() { return m_rgb[0]; } ///< Get modifiable reference to the red color component.
ubyte& g() { return m_rgb[1]; } ///< Get modifiable reference to the green color component.
ubyte& b() { return m_rgb[2]; } ///< Get modifiable reference to the blue color component.
void set(ubyte r, ubyte g, ubyte b);
const ubyte* ptr() const;
private:
ubyte m_rgb[3];
};
}
} //namespace external

View File

@@ -1,128 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfColor3.h"
namespace external {
namespace cvf {
class Color4ub;
//==================================================================================================
//
// Class for RGBA colors
//
//==================================================================================================
class Color4f
{
public:
Color4f();
Color4f(float r, float g, float b, float alpha);
Color4f(const Color4f& other);
Color4f(const Color3f& rgbColor, float alpha);
explicit Color4f(const Color3f& rgbColor);
explicit Color4f(Color3::ColorIdent colorIdent);
explicit Color4f(const Color4ub& other);
Color4f& operator=(const Color4f& rhs);
bool operator==(const Color4f& rhs) const;
bool operator!=(const Color4f& rhs) const;
const float& r() const { return m_rgba[0]; } ///< Returns the red color component
const float& g() const { return m_rgba[1]; } ///< Returns the green color component
const float& b() const { return m_rgba[2]; } ///< Returns the blue color component
const float& a() const { return m_rgba[3]; } ///< Returns the alpha component
float& r() { return m_rgba[0]; } ///< Get modifiable reference to the red color component, used for setting the component.
float& g() { return m_rgba[1]; } ///< Get modifiable reference to the green color component, used for setting the component
float& b() { return m_rgba[2]; } ///< Get modifiable reference to the blue color component, used for setting the component
float& a() { return m_rgba[3]; } ///< Get modifiable reference to the alpha component, used for setting the component
void set(float r, float g, float b, float alpha);
void set(const Color3f& rgbColor, float alpha);
void set(const Color3f& rgbColor);
bool isValid() const;
const float* ptr() const;
Color3f toColor3f() const;
private:
float m_rgba[4];
};
//==================================================================================================
//
// Unsigned byte RGBA colors
//
//==================================================================================================
class Color4ub
{
public:
Color4ub();
Color4ub(ubyte r, ubyte g, ubyte b, ubyte a);
Color4ub(const Color4ub& other);
Color4ub(const Color3ub& rgbColor, ubyte a);
explicit Color4ub(const Color3ub& rgbColor);
explicit Color4ub(Color3::ColorIdent colorIdent);
explicit Color4ub(const Color4f& other);
Color4ub& operator=(const Color4ub& rhs);
bool operator==(const Color4ub& rhs) const;
bool operator!=(const Color4ub& rhs) const;
ubyte r() const { return m_rgba[0]; } ///< Returns the red color component
ubyte g() const { return m_rgba[1]; } ///< Returns the green color component
ubyte b() const { return m_rgba[2]; } ///< Returns the blue color component
ubyte a() const { return m_rgba[3]; } ///< Returns the alpha component
ubyte& r() { return m_rgba[0]; } ///< Get modifiable reference to the red color component.
ubyte& g() { return m_rgba[1]; } ///< Get modifiable reference to the green color component.
ubyte& b() { return m_rgba[2]; } ///< Get modifiable reference to the blue color component.
ubyte& a() { return m_rgba[3]; } ///< Get modifiable reference to the alpha component.
void set(ubyte r, ubyte g, ubyte b, ubyte a);
const ubyte* ptr() const;
private:
ubyte m_rgba[4];
};
}
} //namespace external

View File

@@ -1,78 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
namespace external {
// Define this one to tell windows.h to not define min() and max() as macros
#if defined WIN32 && !defined NOMINMAX
#define NOMINMAX
#endif
// Used to keep track of all instances of classes derived from Object.
// Can be used to detect memory leaks in combination with the static member
// functions: Object::activeObjectInstances() and Object::dumpActiveObjectInstances()
// 0 - disable tracking of active object instances
// 1 - track active instances in debug builds
// 2 - track active instances in BOTH debug and release builds
#ifndef CVF_TRACK_ACTIVE_OBJECT_INSTANCES
#define CVF_TRACK_ACTIVE_OBJECT_INSTANCES 0
#endif
// Behavior of assert macros
// In debug builds, all asserts are in action, including tight asserts
// In release builds, tight asserts are disabled by default. Normal asserts are still in action (including CVF_FAIL_...)
#ifndef CVF_ENABLE_ASSERTS
#define CVF_ENABLE_ASSERTS 1
#endif
#ifndef CVF_ENABLE_TIGHT_ASSERTS
#ifdef _DEBUG
#define CVF_ENABLE_TIGHT_ASSERTS 1
#else
#define CVF_ENABLE_TIGHT_ASSERTS 0
#endif
#endif
} //namespace external

View File

@@ -1,87 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfString.h"
namespace external {
namespace cvf {
class Timer;
//=================================================================================================
//
// Timer class
//
//=================================================================================================
class DebugTimer
{
public:
enum OperationMode
{
NORMAL, ///< Normal operation
DISABLED ///< Disables all functionality in the class
};
public:
DebugTimer(const char* prefix, OperationMode operationMode = NORMAL);
~DebugTimer();
void restart(const char* msg = NULL);
void reportTime(const char* msg = NULL);
void reportTimeMS(const char* msg = NULL);
void reportLapTime(const char* msg = NULL);
void reportLapTimeMS(const char* msg = NULL);
void echoMessage(const char* format, ...);
private:
String makeMessageStartString(const char* msg);
private:
Timer* m_timer; ///< The actual timer object to use
String* m_prefix; ///< String to prefix all output
int m_messageCount; ///< Counts number of messages returned
CVF_DISABLE_COPY_AND_ASSIGN(DebugTimer);
};
}
} //namespace external

View File

@@ -1,77 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
namespace external {
namespace cvf {
//=================================================================================================
//
// Flags class
//
//=================================================================================================
template<typename FlagEnum>
class Flags
{
public:
inline Flags();
inline Flags(const Flags& other);
inline Flags(FlagEnum flag);
inline Flags& operator=(const Flags& rhs);
inline Flags& operator=(FlagEnum flag);
inline Flags& operator|=(const Flags& rhs);
inline Flags operator|(const Flags& rhs) const;
inline Flags& operator&=(const Flags& rhs);
inline Flags operator&(const Flags& rhs) const;
inline bool operator==(const Flags& rhs) const;
inline bool operator==(int rhs) const;
inline bool operator!=(const Flags& rhs) const;
inline bool operator!=(int rhs) const;
inline bool testFlag(FlagEnum flag) const;
private:
int m_bitfield;
};
}
} //namespace external
#include "cvfFlags.inl"

View File

@@ -1,198 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::Flags
/// \ingroup Core
///
/// The Flags class provides a type-safe way of storing OR-combinations of enum values
///
//==================================================================================================
//--------------------------------------------------------------------------------------------------
/// Default constructor
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>::Flags()
: m_bitfield(0)
{
}
//--------------------------------------------------------------------------------------------------
/// Copy constructor
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>::Flags(const Flags& other)
: m_bitfield(other.m_bitfield)
{
}
//--------------------------------------------------------------------------------------------------
/// Constructor with initialization
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>::Flags(FlagEnum flag)
: m_bitfield(flag)
{
}
//--------------------------------------------------------------------------------------------------
/// Assignment operator
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>& Flags<FlagEnum>::operator=(const Flags& rhs)
{
m_bitfield = rhs.m_bitfield;
return *this;
}
//--------------------------------------------------------------------------------------------------
/// Assignment operator
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>& Flags<FlagEnum>::operator=(FlagEnum flag)
{
m_bitfield = flag;
return *this;
}
//--------------------------------------------------------------------------------------------------
/// Performs a bitwise OR operation with rhs and stores the result in this Flags object.
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>& Flags<FlagEnum>::operator|=(const Flags& rhs)
{
m_bitfield |= rhs.m_bitfield;
return *this;
}
//--------------------------------------------------------------------------------------------------
/// Performs a bitwise OR operation with rhs and returns new object
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum> Flags<FlagEnum>::operator|(const Flags& rhs) const
{
Flags ret(*this);
return (ret |= rhs);
}
//--------------------------------------------------------------------------------------------------
/// Performs a bitwise AND operation with rhs and stores the result in this Flags object.
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum>& Flags<FlagEnum>::operator&=(const Flags& rhs)
{
m_bitfield &= rhs.m_bitfield;
return *this;
}
//--------------------------------------------------------------------------------------------------
/// Performs a bitwise AND operation with rhs and returns new object
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline Flags<FlagEnum> Flags<FlagEnum>::operator&(const Flags& rhs) const
{
Flags ret(*this);
return (ret &= rhs);
}
//--------------------------------------------------------------------------------------------------
/// Comparison operator, equality
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline bool Flags<FlagEnum>::operator==(const Flags& rhs) const
{
return m_bitfield == rhs.m_bitfield;
}
//--------------------------------------------------------------------------------------------------
/// Comparison operator, equality
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline bool Flags<FlagEnum>::operator==(int rhs) const
{
return m_bitfield == rhs;
}
//--------------------------------------------------------------------------------------------------
/// Comparison operator, not equal
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline bool Flags<FlagEnum>::operator!=(const Flags& rhs) const
{
return m_bitfield != rhs.m_bitfield;
}
//--------------------------------------------------------------------------------------------------
/// Comparison operator, not equal
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline bool Flags<FlagEnum>::operator!=(int rhs) const
{
return m_bitfield != rhs;
}
//--------------------------------------------------------------------------------------------------
/// Return true only if ALL bits in flag are set
//--------------------------------------------------------------------------------------------------
template<typename FlagEnum>
inline bool Flags<FlagEnum>::testFlag(FlagEnum flag) const
{
return ((m_bitfield & flag) == flag);
}
} // namespace cvf
} //namespace external

View File

@@ -1,73 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::FunctorRange
/// \ingroup Core
///
/// Implements an iteration range for use with our functors.
/// The class is designed to be compatible with TBB's blocked_range class with regards to
/// the functor's requirements
///
//==================================================================================================
template <typename T>
class FunctorRange
{
public:
FunctorRange(T beginIndex, T endIndex)
: m_beginIndex(beginIndex), m_endIndex(endIndex) {}
inline T begin() const { return m_beginIndex; } ///< The first index included in the range
inline T end() const { return m_endIndex; } ///< Index one past last the last index to be included in the range
private:
T m_beginIndex; // The first index to be included in the iteration.
T m_endIndex; // The index one past the last index to be included in the iteration
};
} // cvf
} //namespace external

View File

@@ -1,74 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
// Doxygen module definition
/// \ingroup VizFramework
/// @{
/// \defgroup Core Core module
/// @}
/// \defgroup VizFramework Framework Basis
// Intentionally on top to be included first
#include "cvfBase.h"
#include "cvfArray.h"
#include "cvfAssert.h"
#include "cvfBase64.h"
#include "cvfCharArray.h"
#include "cvfCollection.h"
#include "cvfColor3.h"
#include "cvfColor4.h"
#include "cvfDebugTimer.h"
#include "cvfFlags.h"
#include "cvfFunctorRange.h"
#include "cvfLogger.h"
#include "cvfMath.h"
#include "cvfMatrix4.h"
#include "cvfObject.h"
#include "cvfPlane.h"
#include "cvfRect.h"
#include "cvfQuat.h"
#include "cvfString.h"
#include "cvfSystem.h"
#include "cvfTBBControl.h"
#include "cvfTimer.h"
#include "cvfTrace.h"
#include "cvfVector2.h"
#include "cvfVector3.h"
#include "cvfVector4.h"
#include "cvfVersion.h"

View File

@@ -1,64 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfObject.h"
namespace external {
namespace cvf {
class LogEvent;
//==================================================================================================
//
// Interface for log destinations
//
//==================================================================================================
class LogDestination : public Object
{
public:
virtual void log(const LogEvent& logEvent) = 0;
};
} // cvf
} //namespace external

View File

@@ -1,114 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfObject.h"
#include "cvfString.h"
#include "cvfCodeLocation.h"
namespace external {
namespace cvf {
class LogEvent;
class LogDestination;
//==================================================================================================
//
// Logger class
//
//==================================================================================================
class Logger : public Object
{
public:
enum Level
{
LL_ERROR = 1,
LL_WARNING,
LL_INFO,
LL_DEBUG
};
public:
Logger(const String& loggerName, int logLevel, LogDestination* logDestination);
~Logger();
const String& name() const;
int level() const;
void setLevel(int logLevel);
LogDestination* destination();
void setDestination(LogDestination* logDestination);
void error(const String& message);
void error(const String& message, const CodeLocation& location);
void warning(const String& message);
void warning(const String& message, const CodeLocation& location);
void info(const String& message);
void info(const String& message, const CodeLocation& location);
void debug(const String& message, const CodeLocation& location);
bool isErrorEnabled() const { return m_logLevel >= LL_ERROR; }
bool isWarningEnabled() const { return m_logLevel >= LL_WARNING; }
bool isInfoEnabled() const { return m_logLevel >= LL_INFO; }
bool isDebugEnabled() const { return m_logLevel >= LL_DEBUG; }
private:
void log(const String& message, Logger::Level messageLevel, const CodeLocation& location);
private:
String m_name; // Logger name
int m_logLevel; // Logging level, all messages with a level less than or equal to this level will be logged
ref<LogDestination> m_destination;
CVF_DISABLE_COPY_AND_ASSIGN(Logger);
};
// Helper macros for writing log messages to a logger
#define CVF_LOG_ERROR(theLogger, theMessage) if ((theLogger)->isErrorEnabled()) { (theLogger)->error((theMessage), CVF_CODE_LOCATION); }
#define CVF_LOG_WARNING(theLogger, theMessage) if ((theLogger)->isWarningEnabled()) { (theLogger)->warning((theMessage), CVF_CODE_LOCATION); }
#define CVF_LOG_INFO(theLogger, theMessage) if ((theLogger)->isInfoEnabled()) { (theLogger)->info((theMessage), CVF_CODE_LOCATION); }
#define CVF_LOG_DEBUG(theLogger, theMessage) if ((theLogger)->isDebugEnabled()) { (theLogger)->debug((theMessage), CVF_CODE_LOCATION); }
} // cvf
} //namespace external

View File

@@ -1,341 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfMath.h"
#include <cmath>
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::Math
/// \ingroup Core
///
/// Static class providing basic math operations
///
//==================================================================================================
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::toRadians(float degrees)
{
return degrees*PI_F/180.0f;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::toRadians(double degrees)
{
return degrees*PI_D/180.0;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::toDegrees(float radians)
{
return radians*180.0f/PI_F;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::toDegrees(double radians)
{
return radians*180.0/PI_D;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::cos(double val)
{
return ::cos(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::cos(float val)
{
return ::cosf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::acos(double val)
{
return ::acos(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::acos(float val)
{
return ::acosf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::sin(double val)
{
return ::sin(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::sin(float val)
{
return ::sinf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::asin(double val)
{
return ::asin(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::asin(float val)
{
return ::asinf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::tan(double val)
{
return ::tan(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::tan(float val)
{
return ::tanf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::atan(double val)
{
return ::atan(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::atan(float val)
{
return ::atanf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::sqrt(double val)
{
return ::sqrt(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::sqrt(float val)
{
return ::sqrtf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::floor(double val)
{
return ::floor(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::floor(float val)
{
return ::floorf(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Math::ceil(double val)
{
return ::ceil(val);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float Math::ceil(float val)
{
return ::ceilf(val);
}
//--------------------------------------------------------------------------------------------------
/// Returns the floating-point remainder of x / y
//--------------------------------------------------------------------------------------------------
double Math::fmod(double x, double y)
{
return ::fmod(x, y);
}
//--------------------------------------------------------------------------------------------------
/// Returns the floating-point remainder of x / y
//--------------------------------------------------------------------------------------------------
float Math::fmod(float x, float y)
{
return ::fmodf(x, y);
}
//--------------------------------------------------------------------------------------------------
/// Returns true if the number is a power of 2
///
/// The number 0 is not considered a power of 2.
//--------------------------------------------------------------------------------------------------
bool Math::isPow2(uint number)
{
// From Bit Twiddling Hacks
// http://graphics.stanford.edu/~seander/bithacks.html
return (number && !(number & (number - 1)));
}
//--------------------------------------------------------------------------------------------------
/// Round up to the next highest power of 2
///
/// If the number is already a power of 2 this function will return the same value
/// If number if out of range (greater than 2147483648) we cannot represent the next power of 2 and 0 is returned
//--------------------------------------------------------------------------------------------------
uint Math::roundUpPow2(uint number)
{
// From Bit Twiddling Hacks
// http://graphics.stanford.edu/~seander/bithacks.html
if (number == 0)
{
// Handle edge case where number is 0, algo returns 0, which isn't a power of 2;
return 1;
}
if (number > 2147483648u)
{
// Input is too large, we cannot represent the next power of two
return 0;
}
number--;
number |= number >> 1;
number |= number >> 2;
number |= number >> 4;
number |= number >> 8;
number |= number >> 16;
number++;
return number;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Math::isUndefined(double val)
{
if (val < UNDEFINED_DOUBLE_THRESHOLD)
{
return false;
}
else
{
return true;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Math::isUndefined(float val)
{
if (val < UNDEFINED_FLOAT_THRESHOLD)
{
return false;
}
else
{
return true;
}
}
} // namespace cvf
} //namespace external

View File

@@ -1,117 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
namespace external {
namespace cvf {
//==================================================================================================
//
// Static class providing basic math operations
//
//==================================================================================================
class Math
{
public:
static float toRadians(float degrees);
static double toRadians(double degrees);
static float toDegrees(float radians);
static double toDegrees(double radians);
static double cos(double val);
static float cos(float val);
static double acos(double val);
static float acos(float val);
static double sin(double val);
static float sin(float val);
static double asin(double val);
static float asin(float val);
static double tan(double val);
static float tan(float val);
static double atan(double val);
static float atan(float val);
static double sqrt(double val);
static float sqrt(float val);
static double floor(double val);
static float floor(float val);
static double ceil(double val);
static float ceil(float val);
static double fmod(double x, double y);
static float fmod(float x, float y);
static bool isPow2(uint number);
static uint roundUpPow2(uint number);
static bool isUndefined(double val);
static bool isUndefined(float val);
template<typename T> static bool valueInRange(T val, T min, T max);
template<typename T> static T clamp(T val, T minVal, T maxVal);
template<typename T> static inline T abs(const T& val);
template<typename T> static int sign(const T& val);
};
const float PI_F = 3.14159265f;
const double PI_D = 3.14159265358979323846;
const float ONE_THIRD_F = 1.0f/3.0f;
const double ONE_THIRD_D = 1.0/3.0;
const double SQRT2_F = 1.41421356f; // sqrt(2)
const double SQRT2_D = 1.41421356237309504880; // sqrt(2)
const double SQRT1_2_F = 0.70710678f; // 1/sqrt(2)
const double SQRT1_2_D = 0.70710678118654752440; // 1/sqrt(2)
const int UNDEFINED_INT = 2147483647;
const uint UNDEFINED_UINT = static_cast<uint>(-1); // 4294967295u
const size_t UNDEFINED_SIZE_T = static_cast<size_t>(-1);// 18446744073709551615u
const double UNDEFINED_DOUBLE = 1.7976931348623158e+308;
const double UNDEFINED_DOUBLE_THRESHOLD = 1.00e+308;
const float UNDEFINED_FLOAT = 3.402823466e+38f;
const float UNDEFINED_FLOAT_THRESHOLD = 2.99e+38f;
} // namespace cvf
} //namespace external
#include "cvfMath.inl"

View File

@@ -1,108 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
namespace external {
namespace cvf {
//--------------------------------------------------------------------------------------------------
/// Check if a value is within the specified range, inclusive.
///
/// \return Returns true if \a val >= \a min and \a val <= \a max.
//--------------------------------------------------------------------------------------------------
template<typename T>
bool Math::valueInRange(T val, T minVal, T maxVal)
{
CVF_ASSERT(minVal <= maxVal);
if (val >= minVal && val <= maxVal)
{
return true;
}
else
{
return false;
}
}
//--------------------------------------------------------------------------------------------------
/// Clamp a value within an inclusive range.
///
/// \return The clamped value
//--------------------------------------------------------------------------------------------------
template<typename T>
T Math::clamp(T val, T minVal, T maxVal)
{
CVF_ASSERT(minVal <= maxVal);
if (val >= minVal && val <= maxVal)
{
return val;
}
else if (val > maxVal)
{
return maxVal;
}
else
{
return minVal;
}
}
//--------------------------------------------------------------------------------------------------
/// Returns the absolute value of val
//--------------------------------------------------------------------------------------------------
template<typename T>
T Math::abs(const T& val)
{
return val >= 0 ? val : -val;
}
//--------------------------------------------------------------------------------------------------
/// Returns the sign of val
//--------------------------------------------------------------------------------------------------
template<typename T>
int Math::sign(const T& val)
{
return val < 0 ? -1 : 1;
}
} // namespace cvf
} //namespace external

View File

@@ -1,110 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfSystem.h"
#include "cvfVector3.h"
namespace external {
namespace cvf {
//==================================================================================================
//
// Template matrix class for 3x3 matrices
//
//==================================================================================================
template<typename S>
class Matrix3
{
public:
Matrix3();
Matrix3(const Matrix3& other);
Matrix3(S m00, S m01, S m02, S m10, S m11, S m12, S m20, S m21, S m22);
template<typename T>
explicit Matrix3(const Matrix3<T>& other);
inline Matrix3& operator=(const Matrix3& rhs);
bool equals(const Matrix3& mat) const;
bool operator==(const Matrix3& rhs) const;
bool operator!=(const Matrix3& rhs) const;
void multiply(const Matrix3& mat);
const Matrix3 operator*(const Matrix3& rhs) const;
void setIdentity();
bool isIdentity() const;
void setZero();
bool isZero() const;
inline void setRowCol(int row, int col, S value);
inline S rowCol(int row, int col) const;
inline S& operator()(int row, int col);
inline S operator()(int row, int col) const;
bool invert();
const Matrix3 getInverted(bool* pInvertible = NULL) const;
S determinant() const;
void transpose();
inline const S* ptr() const;
static Matrix3 fromRotation(Vector3<S> axis, S angle);
public:
static const Matrix3 IDENTITY; ///< Identity matrix
static const Matrix3 ZERO; ///< Matrix with all zeros
private:
// Constants for accessing our internal array using standard matrix notation
static const int e00 = 0; static const int e01 = 3; static const int e02 = 6;
static const int e10 = 1; static const int e11 = 4; static const int e12 = 7;
static const int e20 = 2; static const int e21 = 5; static const int e22 = 8;
private:
S m_v[9];
};
typedef Matrix3<float> Mat3f;
typedef Matrix3<double> Mat3d;
}
} //namespace external
#include "cvfMatrix3.inl"

View File

@@ -1,487 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::Matrix3
/// \ingroup Core
///
/// Matrices are stored internally as a one dimensional array for performance reasons.
///
/// The internal indices into the 1D array are as follows:
///
/// <PRE>
/// | m00 m01 m02 | | 0 3 6 |
/// | m10 m11 m12 | | 1 4 7 |
/// | m20 m21 m22 | | 2 5 18 |
/// </PRE>
///
/// See description of Matrix4 for more details on storage
///
//==================================================================================================
template<typename S> Matrix3<S> const Matrix3<S>::IDENTITY;
template<typename S> Matrix3<S> const Matrix3<S>::ZERO(0, 0, 0, 0, 0, 0, 0, 0, 0);
//----------------------------------------------------------------------------------------------------
/// Default constructor. Initializes matrix to identity
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix3<S>::Matrix3()
{
setIdentity();
}
//----------------------------------------------------------------------------------------------------
/// Copy constructor
//----------------------------------------------------------------------------------------------------
template <typename S>
inline Matrix3<S>::Matrix3(const Matrix3& other)
{
System::memcpy(m_v, sizeof(m_v), other.m_v, sizeof(other.m_v));
}
//----------------------------------------------------------------------------------------------------
/// Constructor with explicit initialization of all matrix elements.
///
/// The value of the parameter \a mrc will be placed in row r and column c of the matrix, eg m12
/// goes into row 1, column 2.
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix3<S>::Matrix3(S m00, S m01, S m02, S m10, S m11, S m12, S m20, S m21, S m22)
{
m_v[e00] = m00;
m_v[e10] = m10;
m_v[e20] = m20;
m_v[e01] = m01;
m_v[e11] = m11;
m_v[e21] = m21;
m_v[e02] = m02;
m_v[e12] = m12;
m_v[e22] = m22;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template<typename S>
template<typename T>
Matrix3<S>::Matrix3(const Matrix3<T>& other)
{
m_v[e00] = static_cast<S>(other.rowCol(0, 0));
m_v[e01] = static_cast<S>(other.rowCol(0, 1));
m_v[e02] = static_cast<S>(other.rowCol(0, 2));
m_v[e10] = static_cast<S>(other.rowCol(1, 0));
m_v[e11] = static_cast<S>(other.rowCol(1, 1));
m_v[e12] = static_cast<S>(other.rowCol(1, 2));
m_v[e20] = static_cast<S>(other.rowCol(2, 0));
m_v[e21] = static_cast<S>(other.rowCol(2, 1));
m_v[e22] = static_cast<S>(other.rowCol(2, 2));
}
//----------------------------------------------------------------------------------------------------
/// Assignment operator
//----------------------------------------------------------------------------------------------------
template <typename S>
inline Matrix3<S>& Matrix3<S>::operator=(const Matrix3& obj)
{
System::memcpy(m_v, sizeof(m_v), obj.m_v, sizeof(obj.m_v));
return *this;
}
//----------------------------------------------------------------------------------------------------
/// Check if matrices are equal using exact comparisons.
//----------------------------------------------------------------------------------------------------
template<typename S>
bool Matrix3<S>::equals(const Matrix3& mat) const
{
for (int i = 0; i < 9; i++)
{
if (m_v[i] != mat.m_v[i]) return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
/// Comparison operator. Checks for equality using exact comparisons.
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix3<S>::operator==(const Matrix3& rhs) const
{
return this->equals(rhs);
}
//----------------------------------------------------------------------------------------------------
/// Comparison operator. Checks for not equal using exact comparisons.
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix3<S>::operator!=(const Matrix3& rhs) const
{
int i;
for (i = 0; i < 9; i++)
{
if (m_v[i] != rhs.m_v[i]) return true;
}
return false;
}
//--------------------------------------------------------------------------------------------------
/// Multiplies this matrix M with the matrix \a mat, M = M*mat
//--------------------------------------------------------------------------------------------------
template<typename S>
void Matrix3<S>::multiply(const Matrix3& mat)
{
*this = (*this)*mat;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const Matrix3<S> Matrix3<S>::operator*(const Matrix3& rhs) const
{
Matrix3 m;
int r;
for (r = 0; r < 3; r++)
{
int c;
for (c = 0; c < 3; c++)
{
S val = 0;
int a;
for (a = 0; a < 3; a++)
{
val += rowCol(r, a)*rhs.rowCol(a, c);
}
m.setRowCol(r, c, val);
}
}
return m;
}
//----------------------------------------------------------------------------------------------------
/// Sets this matrix to identity
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix3<S>::setIdentity()
{
m_v[0] = 1;
m_v[1] = 0;
m_v[2] = 0;
m_v[3] = 0;
m_v[4] = 1;
m_v[5] = 0;
m_v[6] = 0;
m_v[7] = 0;
m_v[8] = 1;
}
//----------------------------------------------------------------------------------------------------
/// Check if this matrix is identity using exact comparisons
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix3<S>::isIdentity() const
{
if (m_v[0] != 1) return false;
if (m_v[1] != 0) return false;
if (m_v[2] != 0) return false;
if (m_v[3] != 0) return false;
if (m_v[4] != 1) return false;
if (m_v[5] != 0) return false;
if (m_v[6] != 0) return false;
if (m_v[7] != 0) return false;
if (m_v[8] != 1) return false;
return true;
}
//----------------------------------------------------------------------------------------------------
/// Set all matrix elements to 0
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix3<S>::setZero()
{
m_v[0] = 0;
m_v[1] = 0;
m_v[2] = 0;
m_v[3] = 0;
m_v[4] = 0;
m_v[5] = 0;
m_v[6] = 0;
m_v[7] = 0;
m_v[8] = 0;
}
//----------------------------------------------------------------------------------------------------
/// Returns true if all elements of the matrix are 0. Uses exact comparison.
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix3<S>::isZero() const
{
if (m_v[0] != 0) return false;
if (m_v[1] != 0) return false;
if (m_v[2] != 0) return false;
if (m_v[3] != 0) return false;
if (m_v[4] != 0) return false;
if (m_v[5] != 0) return false;
if (m_v[6] != 0) return false;
if (m_v[7] != 0) return false;
if (m_v[8] != 0) return false;
return true;
}
//----------------------------------------------------------------------------------------------------
/// Set the matrix element at the specified row and column
//----------------------------------------------------------------------------------------------------
template <typename S>
inline void Matrix3<S>::setRowCol(int row, int col, S value)
{
CVF_TIGHT_ASSERT(row >= 0 && row < 3);
CVF_TIGHT_ASSERT(col >= 0 && col < 3);
m_v[3*col + row] = value;
}
//----------------------------------------------------------------------------------------------------
/// Get the matrix element at the specified row and column
//----------------------------------------------------------------------------------------------------
template <typename S>
inline S Matrix3<S>::rowCol(int row, int col) const
{
CVF_TIGHT_ASSERT(row >= 0 && row < 3);
CVF_TIGHT_ASSERT(col >= 0 && col < 3);
return m_v[3*col + row];
}
//--------------------------------------------------------------------------------------------------
/// Get modifiable reference to the the matrix element at the specified row and column
//--------------------------------------------------------------------------------------------------
template <typename S>
inline S& Matrix3<S>::operator()(int row, int col)
{
CVF_TIGHT_ASSERT(row >= 0 && row < 3);
CVF_TIGHT_ASSERT(col >= 0 && col < 3);
return m_v[3*col + row];
}
//--------------------------------------------------------------------------------------------------
/// Get the matrix element at the specified row and column
//--------------------------------------------------------------------------------------------------
template <typename S>
inline S Matrix3<S>::operator()(int row, int col) const
{
CVF_TIGHT_ASSERT(row >= 0 && row < 3);
CVF_TIGHT_ASSERT(col >= 0 && col < 3);
return m_v[3*col + row];
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix3<S>::invert()
{
// Use double internally here
double m00 = static_cast<double>(m_v[e00]);
double m10 = static_cast<double>(m_v[e10]);
double m20 = static_cast<double>(m_v[e20]);
double m01 = static_cast<double>(m_v[e01]);
double m11 = static_cast<double>(m_v[e11]);
double m21 = static_cast<double>(m_v[e21]);
double m02 = static_cast<double>(m_v[e02]);
double m12 = static_cast<double>(m_v[e12]);
double m22 = static_cast<double>(m_v[e22]);
double det = m00*m11*m22 + m01*m12*m20 + m02*m10*m21 - m00*m12*m21 - m01*m10*m22 - m02*m11*m20;
if (Math::abs(det) > std::numeric_limits<double>::epsilon())
{
double invDet = 1/det;
m_v[e00] = static_cast<S>( (m11*m22 - m12*m21) * invDet );
m_v[e01] = static_cast<S>( (m02*m21 - m01*m22) * invDet );
m_v[e02] = static_cast<S>( (m01*m12 - m02*m11) * invDet );
m_v[e10] = static_cast<S>( (m12*m20 - m10*m22) * invDet );
m_v[e11] = static_cast<S>( (m00*m22 - m02*m20) * invDet );
m_v[e12] = static_cast<S>( (m02*m10 - m00*m12) * invDet );
m_v[e20] = static_cast<S>( (m10*m21 - m11*m20) * invDet );
m_v[e21] = static_cast<S>( (m01*m20 - m00*m21) * invDet );
m_v[e22] = static_cast<S>( (m00*m11 - m01*m10) * invDet );
return true;
}
else
{
return false;
}
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const Matrix3<S> Matrix3<S>::getInverted(bool* pInvertible) const
{
Matrix3 m(*this);
if (m.invert())
{
if (pInvertible) *pInvertible = true;
}
else
{
if (pInvertible) *pInvertible = false;
m.setZero();
}
return m;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
S Matrix3<S>::determinant() const
{
S det = m_v[e00]*m_v[e11]*m_v[e22] +
m_v[e01]*m_v[e12]*m_v[e20] +
m_v[e02]*m_v[e10]*m_v[e21] -
m_v[e00]*m_v[e12]*m_v[e21] -
m_v[e01]*m_v[e10]*m_v[e22] -
m_v[e02]*m_v[e11]*m_v[e20];
return det;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
void Matrix3<S>::transpose()
{
S tmp;
int i, j;
for (i = 0; i < 3; i++)
{
for (j = i + 1; j < 3; j++)
{
tmp = m_v[j + 3*i];
m_v[j + 3*i] = m_v[3*j + i];
m_v[3*j + i] = tmp;
}
}
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const S* Matrix3<S>::ptr() const
{
return m_v;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix3<S> Matrix3<S>::fromRotation(Vector3<S> axis, S angle)
{
axis.normalize();
S rcos = Math::cos(angle);
S rsin = Math::sin(angle);
Matrix3 m;
m.m_v[e00] = rcos + axis.x()*axis.x()*(1 - rcos);
m.m_v[e10] = axis.z() * rsin + axis.y()*axis.x()*(1 - rcos);
m.m_v[e20] = -axis.y() * rsin + axis.z()*axis.x()*(1 - rcos);
m.m_v[e01] = -axis.z() * rsin + axis.x()*axis.y()*(1 - rcos);
m.m_v[e11] = rcos + axis.y()*axis.y()*(1 - rcos);
m.m_v[e21] = axis.x() * rsin + axis.z()*axis.y()*(1 - rcos);
m.m_v[e02] = axis.y() * rsin + axis.x()*axis.z()*(1 - rcos);
m.m_v[e12] = -axis.x() * rsin + axis.y()*axis.z()*(1 - rcos);
m.m_v[e22] = rcos + axis.z()*axis.z()*(1 - rcos);
return m;
}
}
} //namespace external

View File

@@ -1,143 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include "cvfSystem.h"
#include "cvfVector3.h"
#include "cvfVector4.h"
#include "cvfMatrix3.h"
namespace external {
namespace cvf {
//==================================================================================================
//
// Template matrix class for 4x4 matrices
//
//==================================================================================================
template<typename S>
class Matrix4
{
public:
Matrix4();
Matrix4(const Matrix4& other);
Matrix4(S m00, S m01, S m02, S m03, S m10, S m11, S m12, S m13, S m20, S m21, S m22, S m23, S m30, S m31, S m32, S m33);
explicit Matrix4(const Matrix3<S>& other);
template<typename T>
explicit Matrix4(const Matrix4<T>& other);
inline Matrix4& operator=(const Matrix4& rhs);
bool equals(const Matrix4& mat) const;
bool operator==(const Matrix4& rhs) const;
bool operator!=(const Matrix4& rhs) const;
void multiply(const Matrix4& mat);
const Matrix4 operator*(const Matrix4& rhs) const;
const Vector4<S> operator*(const Vector4<S>& rhs) const;
void setIdentity();
bool isIdentity() const;
void setZero();
bool isZero() const;
inline void setRowCol(int row, int col, S value);
inline S rowCol(int row, int col) const;
inline S& operator()(int row, int col);
inline S operator()(int row, int col) const;
void setRow(int row, const Vector4<S>& vector);
Vector4<S> row(int row) const;
void setCol(int column, const Vector4<S>& vector);
Vector4<S> col(int column) const;
template<typename T>
void set(const Matrix4<T>& mat);
Vector3<S> translation() const;
void setTranslation(const Vector3<S>& trans);
void translatePreMultiply(const Vector3<S>& trans);
void translatePostMultiply(const Vector3<S>& trans);
bool invert();
const Matrix4 getInverted(bool* pInvertible = NULL) const;
S determinant() const;
void transpose();
const Matrix4 getTransposed() const;
void setFromMatrix3(const Matrix3<S>& mat3);
Matrix3<S> toMatrix3() const;
void toMatrix3(Matrix3<S>* mat3) const;
inline const S* ptr() const;
static Matrix4 fromTranslation(const Vector3<S>& trans);
static Matrix4 fromScaling(const Vector3<S>& scale);
static Matrix4 fromRotation(Vector3<S> axis, S angle);
static Matrix4 fromCoordSystemAxes(const Vector3<S>* xAxis, const Vector3<S>* yAxis, const Vector3<S>* zAxis);
public:
static const Matrix4 IDENTITY; ///< Identity matrix
static const Matrix4 ZERO; ///< Matrix with all zeros
private:
// Constants for accessing our internal array using standard matrix notation
static const int e00 = 0; static const int e01 = 4; static const int e02 = 8; static const int e03 = 12;
static const int e10 = 1; static const int e11 = 5; static const int e12 = 9; static const int e13 = 13;
static const int e20 = 2; static const int e21 = 6; static const int e22 = 10; static const int e23 = 14;
static const int e30 = 3; static const int e31 = 7; static const int e32 = 11; static const int e33 = 15;
private:
S m_v[16];
};
template<typename S>
Vector4<S> operator*(const Matrix4<S>& m, const Vector4<S>& v);
typedef Matrix4<float> Mat4f;
typedef Matrix4<double> Mat4d;
}
} //namespace external
#include "cvfMatrix4.inl"

View File

@@ -1,938 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::Matrix4
/// \ingroup Core
///
/// Matrices are stored internally as a one dimensional array for performance reasons.
///
/// The internal indices into the 1D array are as follows:
///
/// <PRE>
/// | m00 m01 m02 m03 | | 0 4 8 12 |
/// | m10 m11 m12 m13 | | 1 5 9 13 |
/// | m20 m21 m22 m23 | | 2 6 10 14 |
/// | m30 m31 m32 m33 | | 3 7 11 15 |
/// </PRE>
///
/// This is consistent with the way matrices are represented in %OpenGL.
/// To exemplify, translation values are stored in elements 12,13,14; see figure below
///
/// <PRE>
/// | 1 0 0 Tx |
/// | 0 1 0 Ty |
/// | 0 0 1 Tz |
/// | 0 0 0 1 |
/// </PRE>
///
/// From the %OpenGL red book (page 68) v' = M*v
///
/// <PRE>
/// | X'| | 1 0 0 Tx | | X |
/// | Y'| | 0 1 0 Ty | | Y |
/// | Z'| = | 0 0 1 Tz | * | Z |
/// | 1 | | 0 0 0 1 | | 1 |
/// </PRE>
///
/// Beware when porting code that uses C style double array indexing. In this case, the first
/// index given will corrspond to the columnd, eg M[3][0] = Tx, M[3][1] = Ty, M[3][2] = Tz
///
/// To ease accessing the internal 1D array in implementations, the private eij constants can be used.
/// These are consistent with the normal row column ordering, so that e02 accesses the element
/// in the first row and the third column.
///
//==================================================================================================
template<typename S> Matrix4<S> const Matrix4<S>::IDENTITY;
template<typename S> Matrix4<S> const Matrix4<S>::ZERO(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
//----------------------------------------------------------------------------------------------------
/// Default constructor. Initializes matrix to identity
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix4<S>::Matrix4()
{
setIdentity();
}
//----------------------------------------------------------------------------------------------------
/// Copy constructor
//----------------------------------------------------------------------------------------------------
template <typename S>
inline Matrix4<S>::Matrix4(const Matrix4& other)
{
System::memcpy(m_v, sizeof(m_v), other.m_v, sizeof(other.m_v));
}
//----------------------------------------------------------------------------------------------------
/// Constructor with explicit initialization of all matrix elements.
///
/// The value of the parameter \a mrc will be placed in row r and column c of the matrix, eg m23
/// goes into row 2, column 3.
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix4<S>::Matrix4(S m00, S m01, S m02, S m03, S m10, S m11, S m12, S m13, S m20, S m21, S m22, S m23, S m30, S m31, S m32, S m33)
{
m_v[e00] = m00;
m_v[e10] = m10;
m_v[e20] = m20;
m_v[e30] = m30;
m_v[e01] = m01;
m_v[e11] = m11;
m_v[e21] = m21;
m_v[e31] = m31;
m_v[e02] = m02;
m_v[e12] = m12;
m_v[e22] = m22;
m_v[e32] = m32;
m_v[e03] = m03;
m_v[e13] = m13;
m_v[e23] = m23;
m_v[e33] = m33;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename S>
Matrix4<S>::Matrix4(const Matrix3<S>& other)
{
setFromMatrix3(other);
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template<typename S>
template<typename T>
Matrix4<S>::Matrix4(const Matrix4<T>& other)
{
m_v[e00] = static_cast<S>(other.rowCol(0, 0));
m_v[e10] = static_cast<S>(other.rowCol(1, 0));
m_v[e20] = static_cast<S>(other.rowCol(2, 0));
m_v[e30] = static_cast<S>(other.rowCol(3, 0));
m_v[e01] = static_cast<S>(other.rowCol(0, 1));
m_v[e11] = static_cast<S>(other.rowCol(1, 1));
m_v[e21] = static_cast<S>(other.rowCol(2, 1));
m_v[e31] = static_cast<S>(other.rowCol(3, 1));
m_v[e02] = static_cast<S>(other.rowCol(0, 2));
m_v[e12] = static_cast<S>(other.rowCol(1, 2));
m_v[e22] = static_cast<S>(other.rowCol(2, 2));
m_v[e32] = static_cast<S>(other.rowCol(3, 2));
m_v[e03] = static_cast<S>(other.rowCol(0, 3));
m_v[e13] = static_cast<S>(other.rowCol(1, 3));
m_v[e23] = static_cast<S>(other.rowCol(2, 3));
m_v[e33] = static_cast<S>(other.rowCol(3, 3));
}
//----------------------------------------------------------------------------------------------------
/// Assignment operator
//----------------------------------------------------------------------------------------------------
template <typename S>
inline Matrix4<S>& Matrix4<S>::operator=(const Matrix4& obj)
{
System::memcpy(m_v, sizeof(m_v), obj.m_v, sizeof(obj.m_v));
return *this;
}
//----------------------------------------------------------------------------------------------------
/// Check if matrices are equal using exact comparisons.
//----------------------------------------------------------------------------------------------------
template<typename S>
bool Matrix4<S>::equals(const Matrix4& mat) const
{
for (int i = 0; i < 16; i++)
{
if (m_v[i] != mat.m_v[i]) return false;
}
return true;
}
//----------------------------------------------------------------------------------------------------
/// Comparison operator. Checks for equality using exact comparisons.
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix4<S>::operator==(const Matrix4& rhs) const
{
return this->equals(rhs);
}
//----------------------------------------------------------------------------------------------------
/// Comparison operator. Checks for not equal using exact comparisons.
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix4<S>::operator!=(const Matrix4& rhs) const
{
int i;
for (i = 0; i < 16; i++)
{
if (m_v[i] != rhs.m_v[i]) return true;
}
return false;
}
//--------------------------------------------------------------------------------------------------
/// Multiplies this matrix M with the matrix \a mat, M = M*mat
//--------------------------------------------------------------------------------------------------
template<typename S>
void Matrix4<S>::multiply(const Matrix4& mat)
{
*this = (*this)*mat;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const Matrix4<S> Matrix4<S>::operator*(const Matrix4& rhs) const
{
Matrix4 m;
m.m_v[e00] = m_v[e00] * rhs.m_v[e00] + m_v[e01] * rhs.m_v[e10] + m_v[e02] * rhs.m_v[e20] + m_v[e03] * rhs.m_v[e30];
m.m_v[e01] = m_v[e00] * rhs.m_v[e01] + m_v[e01] * rhs.m_v[e11] + m_v[e02] * rhs.m_v[e21] + m_v[e03] * rhs.m_v[e31];
m.m_v[e02] = m_v[e00] * rhs.m_v[e02] + m_v[e01] * rhs.m_v[e12] + m_v[e02] * rhs.m_v[e22] + m_v[e03] * rhs.m_v[e32];
m.m_v[e03] = m_v[e00] * rhs.m_v[e03] + m_v[e01] * rhs.m_v[e13] + m_v[e02] * rhs.m_v[e23] + m_v[e03] * rhs.m_v[e33];
m.m_v[e10] = m_v[e10] * rhs.m_v[e00] + m_v[e11] * rhs.m_v[e10] + m_v[e12] * rhs.m_v[e20] + m_v[e13] * rhs.m_v[e30];
m.m_v[e11] = m_v[e10] * rhs.m_v[e01] + m_v[e11] * rhs.m_v[e11] + m_v[e12] * rhs.m_v[e21] + m_v[e13] * rhs.m_v[e31];
m.m_v[e12] = m_v[e10] * rhs.m_v[e02] + m_v[e11] * rhs.m_v[e12] + m_v[e12] * rhs.m_v[e22] + m_v[e13] * rhs.m_v[e32];
m.m_v[e13] = m_v[e10] * rhs.m_v[e03] + m_v[e11] * rhs.m_v[e13] + m_v[e12] * rhs.m_v[e23] + m_v[e13] * rhs.m_v[e33];
m.m_v[e20] = m_v[e20] * rhs.m_v[e00] + m_v[e21] * rhs.m_v[e10] + m_v[e22] * rhs.m_v[e20] + m_v[e23] * rhs.m_v[e30];
m.m_v[e21] = m_v[e20] * rhs.m_v[e01] + m_v[e21] * rhs.m_v[e11] + m_v[e22] * rhs.m_v[e21] + m_v[e23] * rhs.m_v[e31];
m.m_v[e22] = m_v[e20] * rhs.m_v[e02] + m_v[e21] * rhs.m_v[e12] + m_v[e22] * rhs.m_v[e22] + m_v[e23] * rhs.m_v[e32];
m.m_v[e23] = m_v[e20] * rhs.m_v[e03] + m_v[e21] * rhs.m_v[e13] + m_v[e22] * rhs.m_v[e23] + m_v[e23] * rhs.m_v[e33];
m.m_v[e30] = m_v[e30] * rhs.m_v[e00] + m_v[e31] * rhs.m_v[e10] + m_v[e32] * rhs.m_v[e20] + m_v[e33] * rhs.m_v[e30];
m.m_v[e31] = m_v[e30] * rhs.m_v[e01] + m_v[e31] * rhs.m_v[e11] + m_v[e32] * rhs.m_v[e21] + m_v[e33] * rhs.m_v[e31];
m.m_v[e32] = m_v[e30] * rhs.m_v[e02] + m_v[e31] * rhs.m_v[e12] + m_v[e32] * rhs.m_v[e22] + m_v[e33] * rhs.m_v[e32];
m.m_v[e33] = m_v[e30] * rhs.m_v[e03] + m_v[e31] * rhs.m_v[e13] + m_v[e32] * rhs.m_v[e23] + m_v[e33] * rhs.m_v[e33];
return m;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const Vector4<S> Matrix4<S>::operator*(const Vector4<S>& rhs) const
{
return Vector4<S>(m_v[e00]*rhs.x() + m_v[e01]*rhs.y() + m_v[e02]*rhs.z() + m_v[e03]*rhs.w(),
m_v[e10]*rhs.x() + m_v[e11]*rhs.y() + m_v[e12]*rhs.z() + m_v[e13]*rhs.w(),
m_v[e20]*rhs.x() + m_v[e21]*rhs.y() + m_v[e22]*rhs.z() + m_v[e23]*rhs.w(),
m_v[e30]*rhs.x() + m_v[e31]*rhs.y() + m_v[e32]*rhs.z() + m_v[e33]*rhs.w());
}
//----------------------------------------------------------------------------------------------------
/// Sets this matrix to identity
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::setIdentity()
{
m_v[0] = 1;
m_v[1] = 0;
m_v[2] = 0;
m_v[3] = 0;
m_v[4] = 0;
m_v[5] = 1;
m_v[6] = 0;
m_v[7] = 0;
m_v[8] = 0;
m_v[9] = 0;
m_v[10] = 1;
m_v[11] = 0;
m_v[12] = 0;
m_v[13] = 0;
m_v[14] = 0;
m_v[15] = 1;
}
//----------------------------------------------------------------------------------------------------
/// Check if this matrix is identity using exact comparisons
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix4<S>::isIdentity() const
{
if (m_v[0] != 1) return false;
if (m_v[1] != 0) return false;
if (m_v[2] != 0) return false;
if (m_v[3] != 0) return false;
if (m_v[4] != 0) return false;
if (m_v[5] != 1) return false;
if (m_v[6] != 0) return false;
if (m_v[7] != 0) return false;
if (m_v[8] != 0) return false;
if (m_v[9] != 0) return false;
if (m_v[10] != 1) return false;
if (m_v[11] != 0) return false;
if (m_v[12] != 0) return false;
if (m_v[13] != 0) return false;
if (m_v[14] != 0) return false;
if (m_v[15] != 1) return false;
return true;
}
//----------------------------------------------------------------------------------------------------
/// Set all matrix elements to 0
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::setZero()
{
m_v[0] = 0;
m_v[1] = 0;
m_v[2] = 0;
m_v[3] = 0;
m_v[4] = 0;
m_v[5] = 0;
m_v[6] = 0;
m_v[7] = 0;
m_v[8] = 0;
m_v[9] = 0;
m_v[10] = 0;
m_v[11] = 0;
m_v[12] = 0;
m_v[13] = 0;
m_v[14] = 0;
m_v[15] = 0;
}
//----------------------------------------------------------------------------------------------------
/// Returns true if all elements of the matrix are 0. Uses exact comparison.
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix4<S>::isZero() const
{
if (m_v[0] != 0) return false;
if (m_v[1] != 0) return false;
if (m_v[2] != 0) return false;
if (m_v[3] != 0) return false;
if (m_v[4] != 0) return false;
if (m_v[5] != 0) return false;
if (m_v[6] != 0) return false;
if (m_v[7] != 0) return false;
if (m_v[8] != 0) return false;
if (m_v[9] != 0) return false;
if (m_v[10] != 0) return false;
if (m_v[11] != 0) return false;
if (m_v[12] != 0) return false;
if (m_v[13] != 0) return false;
if (m_v[14] != 0) return false;
if (m_v[15] != 0) return false;
return true;
}
//----------------------------------------------------------------------------------------------------
/// Set the matrix element at the specified row and column
//----------------------------------------------------------------------------------------------------
template <typename S>
inline void Matrix4<S>::setRowCol(int row, int col, S value)
{
CVF_TIGHT_ASSERT(row >= 0 && row < 4);
CVF_TIGHT_ASSERT(col >= 0 && col < 4);
m_v[4*col + row] = value;
}
//----------------------------------------------------------------------------------------------------
/// Get the matrix element at the specified row and column
//----------------------------------------------------------------------------------------------------
template <typename S>
inline S Matrix4<S>::rowCol(int row, int col) const
{
CVF_TIGHT_ASSERT(row >= 0 && row < 4);
CVF_TIGHT_ASSERT(col >= 0 && col < 4);
return m_v[4*col + row];
}
//--------------------------------------------------------------------------------------------------
/// Get modifiable reference to the the matrix element at the specified row and column
//--------------------------------------------------------------------------------------------------
template <typename S>
inline S& Matrix4<S>::operator()(int row, int col)
{
CVF_TIGHT_ASSERT(row >= 0 && row < 4);
CVF_TIGHT_ASSERT(col >= 0 && col < 4);
return m_v[4*col + row];
}
//--------------------------------------------------------------------------------------------------
/// Get the matrix element at the specified row and column
//--------------------------------------------------------------------------------------------------
template <typename S>
inline S Matrix4<S>::operator()(int row, int col) const
{
CVF_TIGHT_ASSERT(row >= 0 && row < 4);
CVF_TIGHT_ASSERT(col >= 0 && col < 4);
return m_v[4*col + row];
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::setRow(int row, const Vector4<S>& vector)
{
CVF_TIGHT_ASSERT(row >= 0 && row < 4);
m_v[row] = vector.x();
m_v[row + 4] = vector.y();
m_v[row + 8] = vector.z();
m_v[row + 12] = vector.w();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
Vector4<S> Matrix4<S>::row(int row) const
{
CVF_TIGHT_ASSERT(row >= 0 && row < 4);
return Vector4<S>(m_v[row], m_v[row + 4], m_v[row + 8], m_v[row + 12]);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::setCol(int column, const Vector4<S>& vector)
{
CVF_TIGHT_ASSERT(column >= 0 && column < 4);
m_v[4*column] = vector.x();
m_v[4*column + 1] = vector.y();
m_v[4*column + 2] = vector.z();
m_v[4*column + 3] = vector.w();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
Vector4<S> Matrix4<S>::col(int column) const
{
CVF_TIGHT_ASSERT(column >= 0 && column < 4);
return Vector4<S>(m_v[4*column], m_v[4*column + 1], m_v[4*column + 2], m_v[4*column + 3]);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename S>
template<typename T>
void Matrix4<S>::set(const Matrix4<T>& mat)
{
const T* matPtr = mat.ptr();
for (int i = 0; i < 16; i++)
{
m_v[i] = static_cast<S>(matPtr[i]);
}
}
//----------------------------------------------------------------------------------------------------
/// Extracts the translation part of the transformation matrix
//----------------------------------------------------------------------------------------------------
template <typename S>
Vector3<S> Matrix4<S>::translation() const
{
return Vector3<S>(m_v[e03], m_v[e13], m_v[e23]);
}
//----------------------------------------------------------------------------------------------------
/// Sets the translation transformation part of the matrix
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::setTranslation(const Vector3<S>& trans)
{
m_v[e03] = trans.x();
m_v[e13] = trans.y();
m_v[e23] = trans.z();
}
//----------------------------------------------------------------------------------------------------
/// Adds translation by pre-multiplying the matrix with a matrix containing the specified translation
///
/// Adds translation to this (transformation) matrix by pre-multiplying the current matrix M with
/// a matrix T containing only the specified translation.
/// Calling this function has the effect of doing the multiplication M' = T x M
///
/// \param trans Specifies the X, Y and Z components of the translation.
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::translatePreMultiply(const Vector3<S>& trans)
{
m_v[e00] += trans.x()*m_v[e30];
m_v[e01] += trans.x()*m_v[e31];
m_v[e02] += trans.x()*m_v[e32];
m_v[e03] += trans.x()*m_v[e33];
m_v[e10] += trans.y()*m_v[e30];
m_v[e11] += trans.y()*m_v[e31];
m_v[e12] += trans.y()*m_v[e32];
m_v[e13] += trans.y()*m_v[e33];
m_v[e20] += trans.z()*m_v[e30];
m_v[e21] += trans.z()*m_v[e31];
m_v[e22] += trans.z()*m_v[e32];
m_v[e23] += trans.z()*m_v[e33];
}
//----------------------------------------------------------------------------------------------------
/// Adds translation by post-multiplying the matrix with a matrix containing the specified translation
///
/// Adds translation to this (transformation) matrix by post-multiplying the current matrix M with
/// a matrix T containing only the specified translation.
/// Calling this function has the effect of doing the multiplication M' = M x T
///
/// \param trans Specifies the X, Y and Z coordinates of the translation.
//----------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::translatePostMultiply(const Vector3<S>& trans)
{
m_v[e03] += trans.x()*m_v[e00] + trans.y()*m_v[e01] + trans.z()*m_v[e02];
m_v[e13] += trans.x()*m_v[e10] + trans.y()*m_v[e11] + trans.z()*m_v[e12];
m_v[e23] += trans.x()*m_v[e20] + trans.y()*m_v[e21] + trans.z()*m_v[e22];
m_v[e33] += trans.x()*m_v[e30] + trans.y()*m_v[e31] + trans.z()*m_v[e32];
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
bool Matrix4<S>::invert()
{
// Use double internally here
const double m00 = static_cast<double>(m_v[e00]);
const double m10 = static_cast<double>(m_v[e10]);
const double m20 = static_cast<double>(m_v[e20]);
const double m30 = static_cast<double>(m_v[e30]);
const double m01 = static_cast<double>(m_v[e01]);
const double m11 = static_cast<double>(m_v[e11]);
const double m21 = static_cast<double>(m_v[e21]);
const double m31 = static_cast<double>(m_v[e31]);
const double m02 = static_cast<double>(m_v[e02]);
const double m12 = static_cast<double>(m_v[e12]);
const double m22 = static_cast<double>(m_v[e22]);
const double m32 = static_cast<double>(m_v[e32]);
const double m03 = static_cast<double>(m_v[e03]);
const double m13 = static_cast<double>(m_v[e13]);
const double m23 = static_cast<double>(m_v[e23]);
const double m33 = static_cast<double>(m_v[e33]);
const double s0 = m00 * m11 - m01 * m10;
const double s1 = m00 * m12 - m02 * m10;
const double s2 = m00 * m13 - m03 * m10;
const double s3 = m01 * m12 - m02 * m11;
const double s4 = m01 * m13 - m03 * m11;
const double s5 = m02 * m13 - m03 * m12;
const double c5 = m22 * m33 - m23 * m32;
const double c4 = m21 * m33 - m23 * m31;
const double c3 = m21 * m32 - m22 * m31;
const double c2 = m20 * m33 - m23 * m30;
const double c1 = m20 * m32 - m22 * m30;
const double c0 = m20 * m31 - m21 * m30;
const double det = s0*c5 - s1*c4 + s2*c3 + s3*c2 - s4*c1 + s5*c0;
if (Math::abs(det) > std::numeric_limits<double>::epsilon())
{
const double invDet = 1/det;
m_v[e00] = static_cast<S>( ( m11 * c5 - m12 * c4 + m13 * c3 ) * invDet );
m_v[e10] = static_cast<S>( ( - m10 * c5 + m12 * c2 - m13 * c1 ) * invDet );
m_v[e20] = static_cast<S>( ( m10 * c4 - m11 * c2 + m13 * c0 ) * invDet );
m_v[e30] = static_cast<S>( ( - m10 * c3 + m11 * c1 - m12 * c0 ) * invDet );
m_v[e01] = static_cast<S>( ( - m01 * c5 + m02 * c4 - m03 * c3 ) * invDet );
m_v[e11] = static_cast<S>( ( m00 * c5 - m02 * c2 + m03 * c1 ) * invDet );
m_v[e21] = static_cast<S>( ( - m00 * c4 + m01 * c2 - m03 * c0 ) * invDet );
m_v[e31] = static_cast<S>( ( m00 * c3 - m01 * c1 + m02 * c0 ) * invDet );
m_v[e02] = static_cast<S>( ( m31 * s5 - m32 * s4 + m33 * s3 ) * invDet );
m_v[e12] = static_cast<S>( ( - m30 * s5 + m32 * s2 - m33 * s1 ) * invDet );
m_v[e22] = static_cast<S>( ( m30 * s4 - m31 * s2 + m33 * s0 ) * invDet );
m_v[e32] = static_cast<S>( ( - m30 * s3 + m31 * s1 - m32 * s0 ) * invDet );
m_v[e03] = static_cast<S>( ( - m21 * s5 + m22 * s4 - m23 * s3 ) * invDet );
m_v[e13] = static_cast<S>( ( m20 * s5 - m22 * s2 + m23 * s1 ) * invDet );
m_v[e23] = static_cast<S>( ( - m20 * s4 + m21 * s2 - m23 * s0 ) * invDet );
m_v[e33] = static_cast<S>( ( m20 * s3 - m21 * s1 + m22 * s0 ) * invDet );
return true;
}
else
{
return false;
}
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const Matrix4<S> Matrix4<S>::getInverted(bool* pInvertible) const
{
Matrix4 m(*this);
if (m.invert())
{
if (pInvertible) *pInvertible = true;
}
else
{
if (pInvertible) *pInvertible = false;
m.setZero();
}
return m;
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
S Matrix4<S>::determinant() const
{
// Consider using double precision for the intermediate calculations here
// Haven't seen any direct need for it yet, but good old GLview API did that
const S a0 = m_v[e00]*m_v[e11] - m_v[e01]*m_v[e10];
const S a1 = m_v[e00]*m_v[e12] - m_v[e02]*m_v[e10];
const S a2 = m_v[e00]*m_v[e13] - m_v[e03]*m_v[e10];
const S a3 = m_v[e01]*m_v[e12] - m_v[e02]*m_v[e11];
const S a4 = m_v[e01]*m_v[e13] - m_v[e03]*m_v[e11];
const S a5 = m_v[e02]*m_v[e13] - m_v[e03]*m_v[e12];
const S b0 = m_v[e20]*m_v[e31] - m_v[e21]*m_v[e30];
const S b1 = m_v[e20]*m_v[e32] - m_v[e22]*m_v[e30];
const S b2 = m_v[e20]*m_v[e33] - m_v[e23]*m_v[e30];
const S b3 = m_v[e21]*m_v[e32] - m_v[e22]*m_v[e31];
const S b4 = m_v[e21]*m_v[e33] - m_v[e23]*m_v[e31];
const S b5 = m_v[e22]*m_v[e33] - m_v[e23]*m_v[e32];
return (a0*b5 - a1*b4 + a2*b3 + a3*b2 - a4*b1 + a5*b0);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
void Matrix4<S>::transpose()
{
S tmp;
int i, j;
for (i = 0; i < 4; i++)
{
for (j = i + 1; j < 4; j++)
{
tmp = m_v[j + 4*i];
m_v[j + 4*i] = m_v[4*j + i];
m_v[4*j + i] = tmp;
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template <typename S>
const Matrix4<S> Matrix4<S>::getTransposed() const
{
Matrix4 m(*this);
m.transpose();
return m;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename S>
void Matrix4<S>::setFromMatrix3(const Matrix3<S>& mat3)
{
m_v[e00] = mat3.rowCol(0, 0);
m_v[e01] = mat3.rowCol(0, 1);
m_v[e02] = mat3.rowCol(0, 2);
m_v[e03] = 0;
m_v[e10] = mat3.rowCol(1, 0);
m_v[e11] = mat3.rowCol(1, 1);
m_v[e12] = mat3.rowCol(1, 2);
m_v[e13] = 0;
m_v[e20] = mat3.rowCol(2, 0);
m_v[e21] = mat3.rowCol(2, 1);
m_v[e22] = mat3.rowCol(2, 2);
m_v[e23] = 0;
m_v[e30] = 0;
m_v[e31] = 0;
m_v[e32] = 0;
m_v[e33] = 1;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename S>
Matrix3<S> Matrix4<S>::toMatrix3() const
{
return Matrix3<S>(m_v[e00], m_v[e01], m_v[e02],
m_v[e10], m_v[e11], m_v[e12],
m_v[e20], m_v[e21], m_v[e22]);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<typename S>
void Matrix4<S>::toMatrix3(Matrix3<S>* mat3) const
{
CVF_ASSERT(mat3);
mat3->setRowCol(0, 0, m_v[e00]);
mat3->setRowCol(0, 1, m_v[e01]);
mat3->setRowCol(0, 2, m_v[e02]);
mat3->setRowCol(1, 0, m_v[e10]);
mat3->setRowCol(1, 1, m_v[e11]);
mat3->setRowCol(1, 2, m_v[e12]);
mat3->setRowCol(2, 0, m_v[e20]);
mat3->setRowCol(2, 1, m_v[e21]);
mat3->setRowCol(2, 2, m_v[e22]);
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
const S* Matrix4<S>::ptr() const
{
return m_v;
}
//----------------------------------------------------------------------------------------------------
/// Static member function that creates a transformation matrix containing only translation
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix4<S> Matrix4<S>::fromTranslation(const Vector3<S>& trans)
{
return Matrix4(1, 0, 0, trans.x(),
0, 1, 0, trans.y(),
0, 0, 1, trans.z(),
0, 0, 0, 1);
}
//----------------------------------------------------------------------------------------------------
/// Static member function that creates a transformation matrix containing only scaling
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix4<S> Matrix4<S>::fromScaling(const Vector3<S>& scale)
{
return Matrix4(scale.x(), 0, 0, 0,
0, scale.y(), 0, 0,
0, 0, scale.z(), 0,
0, 0, 0, 1);
}
//----------------------------------------------------------------------------------------------------
///
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix4<S> Matrix4<S>::fromRotation(Vector3<S> axis, S angle)
{
axis.normalize();
S rcos = Math::cos(angle);
S rsin = Math::sin(angle);
Matrix4 m;
m.m_v[e00] = rcos + axis.x()*axis.x()*(1 - rcos);
m.m_v[e10] = axis.z() * rsin + axis.y()*axis.x()*(1 - rcos);
m.m_v[e20] = -axis.y() * rsin + axis.z()*axis.x()*(1 - rcos);
m.m_v[e01] = -axis.z() * rsin + axis.x()*axis.y()*(1 - rcos);
m.m_v[e11] = rcos + axis.y()*axis.y()*(1 - rcos);
m.m_v[e21] = axis.x() * rsin + axis.z()*axis.y()*(1 - rcos);
m.m_v[e02] = axis.y() * rsin + axis.x()*axis.z()*(1 - rcos);
m.m_v[e12] = -axis.x() * rsin + axis.y()*axis.z()*(1 - rcos);
m.m_v[e22] = rcos + axis.z()*axis.z()*(1 - rcos);
return m;
}
//----------------------------------------------------------------------------------------------------
/// Create a rotation matrix that will align the global X, Y and Z axes with the specified axes.
///
/// Note that at least one axis must be specified and all specified axes must be normalized.
/// If two or three axes are specified, they must be orthogonal to each other.
///
/// \param xAxis Orientation of x axis
/// \param yAxis Orientation of y axis
/// \param zAxis Orientation of z axis
//----------------------------------------------------------------------------------------------------
template <typename S>
Matrix4<S> Matrix4<S>::fromCoordSystemAxes(const Vector3<S>* xAxis, const Vector3<S>* yAxis, const Vector3<S>* zAxis)
{
Vector3<S> x(0, 0, 0);
Vector3<S> y(0, 0, 0);
Vector3<S> z(0, 0, 0);
if (xAxis && yAxis && zAxis)
{
x = *xAxis;
y = *yAxis;
z = *zAxis;
}
else if (xAxis && yAxis)
{
x = *xAxis;
y = *yAxis;
z = x ^ y;
}
else if (xAxis && zAxis)
{
x = *xAxis;
z = *zAxis;
y = z ^ x;
}
else if (yAxis && zAxis)
{
y = *yAxis;
z = *zAxis;
x = y ^ z;
}
else if (xAxis)
{
xAxis->createOrthonormalBasis(0, &x, &y, &z);
}
else if (yAxis)
{
yAxis->createOrthonormalBasis(1, &x, &y, &z);
}
else if (zAxis)
{
zAxis->createOrthonormalBasis(2, &x, &y, &z);
}
else
{
CVF_FAIL_MSG("Must specify at least one axis");
}
Matrix4 m;
m.setIdentity();
m.setCol(0, Vector4<S>(x, 0));
m.setCol(1, Vector4<S>(y, 0));
m.setCol(2, Vector4<S>(z, 0));
return m;
}
//--------------------------------------------------------------------------------------------------
/// Post multiplication: matrix * column vector
///
/// v' = M*v
//--------------------------------------------------------------------------------------------------
template<typename S>
cvf::Vector4<S> operator*(const cvf::Matrix4<S>& m, const cvf::Vector4<S>& v)
{
cvf::Vector4<S> vec(
v.x()*m.rowCol(0,0) + v.y()*m.rowCol(0,1) + v.z()*m.rowCol(0,2) + v.w()*m.rowCol(0,3),
v.x()*m.rowCol(1,0) + v.y()*m.rowCol(1,1) + v.z()*m.rowCol(1,2) + v.w()*m.rowCol(1,3),
v.x()*m.rowCol(2,0) + v.y()*m.rowCol(2,1) + v.z()*m.rowCol(2,2) + v.w()*m.rowCol(2,3),
v.x()*m.rowCol(3,0) + v.y()*m.rowCol(3,1) + v.z()*m.rowCol(3,2) + v.w()*m.rowCol(3,3)
);
return vec;
}
}
} //namespace external

View File

@@ -1,124 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// for more details.
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfObject.h"
#include "cvfTrace.h"
#include <map>
namespace external {
namespace cvf {
//==================================================================================================
///
/// \class cvf::Object
/// \ingroup Core
///
/// Base class for all reference counted objects
///
/// Very often used in conjunction with the ref<> class (smart pointer) which wraps the
/// reference counting. Thus direct use of addRef() and release() is seldom needed.
///
/// The copy constructor and assignment operator is disabled by default so you will get compiler errors
/// instead of unexpected behavior if you pass objects (that derive from Object) by value or assign objects.
//==================================================================================================
//--------------------------------------------------------------------------------------------------
/// Get the set of currently active/allocated object instances
///
/// Note that unless the define CVF_TRACK_ACTIVE_OBJECT_INSTANCES is set to 1, this function
/// will always return an empty set.
//--------------------------------------------------------------------------------------------------
std::set<Object*>* Object::activeObjectInstances()
{
static std::set<Object*>* sl_activeObjects = NULL;
if (!sl_activeObjects)
{
sl_activeObjects = new std::set<Object*>;
}
return sl_activeObjects;
}
//--------------------------------------------------------------------------------------------------
/// Dump list of active object instances using Trace class
///
/// Currently this function utilizes RTTI and typeid to get the class names.
/// Data on active instances will only be present if CVF_TRACK_ACTIVE_OBJECT_INSTANCES is defined
//--------------------------------------------------------------------------------------------------
void Object::dumpActiveObjectInstances()
{
Trace::show("Dumping active object instances:");
std::set<Object*>* objInstances = Object::activeObjectInstances();
size_t numInstances = objInstances->size();
#if ((CVF_TRACK_ACTIVE_OBJECT_INSTANCES >= 1 && defined(_DEBUG)) || CVF_TRACK_ACTIVE_OBJECT_INSTANCES == 2)
// Use a map to count the number of occurences of each class
std::map<std::string, int> occurences;
std::set<Object*>::iterator it;
for (it = objInstances->begin(); it != objInstances->end(); ++it)
{
Object* obj = *it;
const type_info& typeInfo = typeid(*obj);
const char* className = typeInfo.name();
if (occurences.find(className) != occurences.end())
{
occurences[className] += 1;
}
else
{
occurences[className] = 1;
}
}
if (occurences.size() > 0)
{
std::map<std::string, int>::iterator it;
for (it = occurences.begin(); it != occurences.end(); ++it)
{
Trace::show("%6d instances of: %s", it->second, it->first.data());
}
}
#else
Trace::show(" Tracking of active instances not enabled!");
#endif
Trace::show("Total number of active object instances: %d", numInstances);
}
} // namespace cvf
} //namespace external

View File

@@ -1,200 +0,0 @@
//##################################################################################################
//
// 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 <<http://www.gnu.org/licenses/gpl.html>>
// 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 <<http://www.gnu.org/licenses/lgpl-2.1.html>>
// for more details.
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include "cvfSystem.h"
#include <set>
#include "cvfAtomicCounter.h"
namespace external {
#if !defined(CVF_ATOMIC_COUNTER_CLASS_EXISTS) && !defined(CVF_USE_NON_THREADSAFE_REFERENCE_COUNT)
#error No support for atomics. Define CVF_USE_NON_THREADSAFE_REFERENCE_COUNT to be able to compile
#endif
namespace cvf {
//==================================================================================================
//
// Base class for all reference counted objects
//
//==================================================================================================
class Object
{
public:
inline Object();
inline virtual ~Object();
inline int addRef() const;
inline int release() const;
inline int refCount() const;
// Helpers for debugging, see the CVF_TRACK_ACTIVE_OBJECT_INSTANCES define
static std::set<Object*>* activeObjectInstances();
static void dumpActiveObjectInstances();
private:
#if defined(CVF_USE_NON_THREADSAFE_REFERENCE_COUNT)
mutable int m_refCount;
#elif defined(CVF_ATOMIC_COUNTER_CLASS_EXISTS)
mutable AtomicCounter m_refCount;
#else
#error No support for atomics. Define CVF_USE_NON_THREADSAFE_REFERENCE_COUNT to be able to compile
#endif
CVF_DISABLE_COPY_AND_ASSIGN(Object);
};
//==================================================================================================
//
// Smart pointer class
//
//==================================================================================================
template <typename T>
class ref
{
public:
ref(T* object = NULL);
ref(const ref& other);
template<typename T2> ref(const ref<T2>& other);
~ref();
ref& operator=(T* rhs);
ref& operator=(ref rhs);
template<typename T2> ref& operator=(const ref<T2>& rhs);
inline T* operator->();
inline const T* operator->() const;
inline T& operator*();
inline const T& operator*() const;
inline T* p();
inline const T* p() const;
inline bool isNull() const;
inline bool notNull() const;
bool operator<(const ref& rhs) const;
void swap(ref& other);
private:
T* m_object;
};
/// \relates cvf::ref
/// @{
template<typename T1, typename T2> inline bool operator==(const ref<T1>& a, const ref<T2>& b) { return a.p() == b.p(); } ///< Returns true if the internal pointers of refs \a a and \a b are equal.
template<typename T1, typename T2> inline bool operator!=(const ref<T1>& a, const ref<T2>& b) { return a.p() != b.p(); } ///< Returns true if the internal pointers of refs \a a and \a b are different.
template<typename T1, typename T2> inline bool operator==(const ref<T1>& a, T2* b) { return a.p() == b; } ///< Returns true if the internal pointer of ref \a a is equal to the naked pointer \a b.
template<typename T1, typename T2> inline bool operator!=(const ref<T1>& a, T2* b) { return a.p() != b; } ///< Returns true if the internal pointer of ref \a a is different from the naked pointer \a b.
template<typename T1, typename T2> inline bool operator==(T1* a, const ref<T2>& b) { return a == b.p(); } ///< Returns true if the naked pointer \a a is equal to the internal pointer of ref \a b.
template<typename T1, typename T2> inline bool operator!=(T1* a, const ref<T2>& b) { return a != b.p(); } ///< Returns true if the naked pointer \a a is different from the internal pointer of ref \a b.
/// Swap contents of \a a and \a b. Matches signature of std::swap().
/// \todo Need to investigate which STL algorithms actually utilize the swap() function.
template<typename T> inline void swap(ref<T>& a, ref<T>& b) { a.swap(b); }
/// @}
//==================================================================================================
//
// Smart pointer class for const pointers
//
//==================================================================================================
template <typename T>
class cref
{
public:
cref(const T* object = NULL);
cref(const cref& other);
template<typename T2> cref(const cref<T2>& other);
~cref();
cref& operator=(const T* rhs);
cref& operator=(cref rhs);
template<typename T2> cref& operator=(const cref<T2>& rhs);
inline const T* operator->() const;
inline const T& operator*() const;
inline const T* p() const;
inline bool isNull() const;
inline bool notNull() const;
bool operator<(const cref& rhs) const;
void swap(cref& other);
private:
const T* m_object;
};
/// \relates cvf::cref
/// @{
template<typename T1, typename T2> inline bool operator==(const cref<T1>& a, const cref<T2>& b) { return a.p() == b.p(); } ///< Returns true if the internal pointers of refs \a a and \a b are equal.
template<typename T1, typename T2> inline bool operator!=(const cref<T1>& a, const cref<T2>& b) { return a.p() != b.p(); } ///< Returns true if the internal pointers of refs \a a and \a b are different.
template<typename T1, typename T2> inline bool operator==(const cref<T1>& a, T2* b) { return a.p() == b; } ///< Returns true if the internal pointer of ref \a a is equal to the naked pointer \a b.
template<typename T1, typename T2> inline bool operator!=(const cref<T1>& a, T2* b) { return a.p() != b; } ///< Returns true if the internal pointer of ref \a a is different from the naked pointer \a b.
template<typename T1, typename T2> inline bool operator==(T1* a, const cref<T2>& b) { return a == b.p(); } ///< Returns true if the naked pointer \a a is equal to the internal pointer of ref \a b.
template<typename T1, typename T2> inline bool operator!=(T1* a, const cref<T2>& b) { return a != b.p(); } ///< Returns true if the naked pointer \a a is different from the internal pointer of ref \a b.
//==================================================================================================
//
// Creation of smart pointers.
//
//==================================================================================================
template<typename T, class... Args>
ref<T> make_ref(Args&&... args);
template<typename T, class... Args>
cref<T> make_cref(Args&&... args);
/// @}
}
} //namespace external
#include "cvfObject.inl"

Some files were not shown because too many files have changed in this diff Show More